repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
ShNadi/OkCupid-project
|
[
"5eca6571e5c2a65c9cc185fadd24b0724a3cbb1b"
] |
[
"src/classifiers.py"
] |
[
"from sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom imblearn.pipeline import Pipeline\nfrom sklearn.linear_model import LogisticRegression\nimport matplotlib.pyplot as plt\nplt.rc(\"font\", size=10)\nimport itertools\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.pipeline import FeatureUnion\nfrom sklearn import preprocessing\nimport matplotlib\nimport pandas as pd\n\n\n# plot confusion matrix\ndef plot_confusion_matrix(cm, folder, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0])\n , range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.savefig(\"../data/output/\"+ folder + \"/ConfusionMatrix.png\")\n plt.close()\n\n\n# Show most informative words in logistic regression classifier\ndef show_most_informative_features(vectorizer, clf, folder, n=50):\n feature_names = vectorizer.get_feature_names()\n coefs_with_fns = sorted(zip(clf.coef_[0], feature_names))\n top = zip(coefs_with_fns[:n], coefs_with_fns[:-(n + 1):-1])\n for (coef_1, fn_1), (coef_2, fn_2) in top:\n with open(r\"../data/output/\"+ folder+\"/FeatureImportance.txt\", 'a+') as output:\n output.write(\"\\t%.4f\\t%-15s\\t\\t%.4f\\t%-15s\\n\" % (coef_1, fn_1, coef_2, fn_2))\n\n\n# Text classification by Logistic regression(Bag of words)\ndef logistic_text(clean_text, target):\n\n X_train, X_val, y_train, y_val = train_test_split(clean_text['clean_text'], target['isced'], stratify=target, test_size = 0.25, random_state=0)\n\n clf_text = Pipeline([('vec', CountVectorizer(max_df=0.60, max_features=200000, stop_words='english', binary=True, lowercase=True, ngram_range=(1, 2))),\n ('clf', LogisticRegression(random_state=0, max_iter=10000, solver='lbfgs', penalty='l2', class_weight='balanced'))])\n clf_text.fit(X_train, y_train)\n\n predictions_t = clf_text.predict(X_val)\n\n print(\"Final Accuracy for Logistic: %s\"% accuracy_score(y_val, predictions_t))\n cm = confusion_matrix(y_val, predictions_t)\n print(classification_report(y_val, predictions_t))\n with open (r\"../data/output/BagOfWords/classificationReport.txt\", 'a+') as output:\n output.write(classification_report(y_val, predictions_t))\n\n plot_confusion_matrix(cm, folder=\"BagOfWords\", classes=[0, 1], normalize=False,\n title='Confusion Matrix')\n\n # Show most informative words\n show_most_informative_features(clf_text.get_params()['vec'], clf_text.get_params()['clf'], n=50,\n folder=\"BagOfWords\")\n print(\"Outputs are written in 'data/output/BagOfWords' folder.\\n\")\n\n\n\n# The Logistic regression(Text+ Language features)\ndef logistic_text_lingustic(text_meta, target):\n\n X_train, X_val, y_train, y_val = train_test_split(text_meta, target['isced'], stratify=target, test_size = 0.25,\n random_state=0)\n\n cols = text_meta.loc[:, text_meta.columns != 'clean_text'].columns\n\n get_text_data = FunctionTransformer(lambda x: x['clean_text'], validate=False)\n get_numeric_data = FunctionTransformer(lambda x: x[cols], validate=False)\n\n process_and_join_features = Pipeline([\n ('features', FeatureUnion([\n ('numeric_features', Pipeline([\n ('selector', get_numeric_data),\n ('scaler', preprocessing.StandardScaler())\n\n ])),\n ('text_features', Pipeline([\n ('selector', get_text_data),\n ('vec', CountVectorizer(binary=False, ngram_range=(1, 2), lowercase=True))\n ]))\n ])),\n ('clf',\n LogisticRegression(random_state=0, max_iter=10000, solver='lbfgs', penalty='l2', class_weight='balanced'))\n ])\n\n # merge vectorized text data and scaled numeric data\n process_and_join_features.fit(X_train, y_train)\n predictions_tm = process_and_join_features.predict(X_val)\n\n print(\"Final Accuracy for Logistic: %s\" % accuracy_score(y_val, predictions_tm))\n cm = confusion_matrix(y_val, predictions_tm)\n print(classification_report(y_val, predictions_tm))\n\n with open(r\"../data/output/TextLinguistic/classificationReport.txt\", 'a+') as output:\n output.write(classification_report(y_val, predictions_tm))\n\n plot_confusion_matrix(cm, folder=\"TextLinguistic\", classes=[0, 1], normalize=False,\n title='Confusion Matrix')\n\n show_most_informative_features(\n process_and_join_features.get_params()['features'].get_params()['text_features'].get_params()['vec'],\n process_and_join_features.get_params()['clf'], n=50, folder='TextLinguistic')\n\n print(\"Outputs are written in 'data/output/TextLinguistic' folder.\\n\")\n\n\n# The Logistic regression (LIWC only)\ndef logistic_liwc(liwc, target):\n X_train, X_val, y_train, y_val = train_test_split(liwc, target['isced'], stratify=target, test_size=0.25,\n random_state=0)\n\n\n scaler = preprocessing.StandardScaler()\n Xl_train_scaled = scaler.fit_transform(X_train)\n Xl_val_scaled = scaler.transform(X_val)\n\n LogisticRegr = LogisticRegression(random_state=0, max_iter=10000, solver='lbfgs', penalty='l2',\n class_weight='balanced')\n LogisticRegr.fit(Xl_train_scaled, y_train)\n predictions = LogisticRegr.predict(Xl_val_scaled)\n\n print(\"Final Accuracy for Logistic: %s\" % accuracy_score(y_val, predictions))\n\n cm = confusion_matrix(y_val, predictions)\n plot_confusion_matrix(cm, folder=\"Liwc\", classes=[0, 1], normalize=False,\n title='Confusion Matrix')\n\n print(classification_report(y_val, predictions))\n with open(r\"../data/output/Liwc/classificationReport.txt\", 'a+') as out:\n out.write(classification_report(y_val, predictions))\n\n\n # Plot feature importance for Liwc\n coef_liwc = pd.Series(LogisticRegr.coef_[0], index=liwc.columns)\n\n imp_coef_liwc = coef_liwc.sort_values()\n matplotlib.rcParams['figure.figsize'] = (8.0, 15.0)\n imp_coef_liwc.plot(kind=\"barh\")\n plt.title(\"Feature importance \")\n plt.savefig(\"../data/output/liwc/FeatureImportance.png\")\n plt.show()\n\n\n# The Logistic regression (Bag of words + LIWC)\ndef logistic_text_liwc(liwc_text, target):\n X_train, X_val, y_train, y_val = train_test_split(liwc_text, target['isced'], stratify=target, test_size=0.25,\n random_state=0)\n\n cols = liwc_text.loc[:, liwc_text.columns != 'clean_text'].columns\n\n get_text_data = FunctionTransformer(lambda x: x['clean_text'], validate=False)\n get_numeric_data = FunctionTransformer(lambda x: x[cols], validate=False)\n\n process_and_join_features = Pipeline([\n ('features', FeatureUnion([\n ('numeric_features', Pipeline([\n ('selector', get_numeric_data),\n ('scaler', preprocessing.StandardScaler())\n\n ])),\n ('text_features', Pipeline([\n ('selector', get_text_data),\n ('vec', CountVectorizer(binary=False, ngram_range=(1, 2), lowercase=True))\n\n ]))\n ])),\n (\n 'clf', LogisticRegression(random_state=0, max_iter=5000, solver='lbfgs', penalty='l2', class_weight='balanced'))\n ])\n\n\n # merge vectorized text data and scaled numeric data\n process_and_join_features.fit(X_train, y_train)\n predictions_lt = process_and_join_features.predict(X_val)\n\n print(\"Final Accuracy for Logistic: %s\" % accuracy_score(y_val, predictions_lt))\n cm = confusion_matrix(y_val, predictions_lt)\n plt.figure()\n plot_confusion_matrix(cm, folder=\"TextLiwc\", classes=[0, 1], normalize=False,\n title='Confusion Matrix')\n print(classification_report(y_val, predictions_lt))\n with open(r\"../data/output/TextLiwc/classificationReport.txt\", 'a+') as out:\n out.write(classification_report(y_val, predictions_lt))\n\n\n # Write_most_informative_features\n n = 1000\n fnames = dict(process_and_join_features.named_steps['features'].transformer_list).get('text_features').named_steps[\n 'vec'].get_feature_names()\n k = liwc_text.columns.tolist()\n k.remove(k[93])\n names = k + fnames\n dd = pd.DataFrame(columns=names)\n feature_names = dd.columns\n clff = process_and_join_features['clf']\n coefs_with_fns = sorted(zip(clff.coef_[0], feature_names))\n top = zip(coefs_with_fns[:n], coefs_with_fns[:-(n + 1):-1])\n for (coef_1, fn_1), (coef_2, fn_2) in top:\n with open(r\"../data/output/TextLiwc/FeatureImportance.txt\", \"a\") as output:\n output.write(\"\\t%.4f\\t%-15s\\t\\t%.4f\\t%-15s\\n\" % (coef_1, fn_1, coef_2, fn_2))\n\n"
] |
[
[
"matplotlib.pyplot.imshow",
"pandas.Series",
"matplotlib.pyplot.rc",
"sklearn.metrics.confusion_matrix",
"pandas.DataFrame",
"sklearn.metrics.classification_report",
"matplotlib.pyplot.tight_layout",
"sklearn.feature_extraction.text.CountVectorizer",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.savefig",
"sklearn.preprocessing.StandardScaler",
"matplotlib.pyplot.show",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"sklearn.linear_model.LogisticRegression",
"sklearn.preprocessing.FunctionTransformer",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.yticks",
"sklearn.metrics.accuracy_score"
]
] |
littlefisherfisher/models
|
[
"11fd89c0b45853e2ca99b86bf1638d5e8fbd9d34"
] |
[
"mobilenetv3/train.py"
] |
[
"import oneflow.experimental as flow\nimport argparse\nimport numpy as np\nimport os\nimport time\n\nfrom models.mobilenetv3 import mobilenet_v3_small\nfrom utils.ofrecord_data_utils import OFRecordDataLoader\n\n\ndef _parse_args():\n parser = argparse.ArgumentParser(\"flags for train mobilenetv3\")\n parser.add_argument(\n \"--save_checkpoint_path\",\n type=str,\n default=\"./checkpoints\",\n help=\"save checkpoint root dir\",\n )\n parser.add_argument(\n \"--load_checkpoint\", type=str, default=\"\", help=\"load checkpoint\"\n )\n parser.add_argument(\n \"--ofrecord_path\", type=str, default=\"./ofrecord\", help=\"dataset path\"\n )\n # training hyper-parameters\n parser.add_argument(\n \"--learning_rate\", type=float, default=0.001, help=\"learning rate\"\n )\n parser.add_argument(\"--mom\", type=float, default=0.9, help=\"momentum\")\n parser.add_argument(\"--epochs\", type=int, default=100, help=\"training epochs\")\n parser.add_argument(\n \"--train_batch_size\", type=int, default=32, help=\"train batch size\"\n )\n parser.add_argument(\"--val_batch_size\", type=int, default=32, help=\"val batch size\")\n\n return parser.parse_args()\n\n\ndef main(args):\n flow.enable_eager_execution()\n flow.InitEagerGlobalSession()\n\n train_data_loader = OFRecordDataLoader(\n ofrecord_root=args.ofrecord_path,\n mode=\"train\",\n dataset_size=9469,\n batch_size=args.train_batch_size,\n )\n\n val_data_loader = OFRecordDataLoader(\n ofrecord_root=args.ofrecord_path,\n mode=\"val\",\n dataset_size=3925,\n batch_size=args.val_batch_size,\n )\n\n # oneflow init\n start_t = time.time()\n mobilenetv3_module = mobilenet_v3_small()\n if args.load_checkpoint != \"\":\n print(\"load_checkpoint >>>>>>>>> \", args.load_checkpoint)\n mobilenetv3_module.load_state_dict(flow.load(args.load_checkpoint))\n\n end_t = time.time()\n print(\"init time : {}\".format(end_t - start_t))\n\n of_cross_entropy = flow.nn.CrossEntropyLoss()\n\n mobilenetv3_module.to(\"cuda\")\n of_cross_entropy.to(\"cuda\")\n\n of_sgd = flow.optim.SGD(\n mobilenetv3_module.parameters(), lr=args.learning_rate, momentum=args.mom\n )\n\n of_losses = []\n all_samples = len(val_data_loader) * args.val_batch_size\n print_interval = 100\n\n for epoch in range(args.epochs):\n mobilenetv3_module.train()\n\n for b in range(len(train_data_loader)):\n image, label = train_data_loader.get_batch()\n\n # oneflow train\n start_t = time.time()\n image = image.to(\"cuda\")\n label = label.to(\"cuda\")\n logits = mobilenetv3_module(image)\n loss = of_cross_entropy(logits, label)\n loss.backward()\n of_sgd.step()\n of_sgd.zero_grad()\n end_t = time.time()\n if b % print_interval == 0:\n l = loss.numpy()[0]\n of_losses.append(l)\n print(\n \"epoch {} train iter {} oneflow loss {}, train time : {}\".format(\n epoch, b, l, end_t - start_t\n )\n )\n\n print(\"epoch %d train done, start validation\" % epoch)\n\n mobilenetv3_module.eval()\n correct_of = 0.0\n for b in range(len(val_data_loader)):\n image, label = val_data_loader.get_batch()\n\n start_t = time.time()\n image = image.to(\"cuda\")\n with flow.no_grad():\n logits = mobilenetv3_module(image)\n predictions = logits.softmax()\n of_predictions = predictions.numpy()\n clsidxs = np.argmax(of_predictions, axis=1)\n\n label_nd = label.numpy()\n for i in range(args.val_batch_size):\n if clsidxs[i] == label_nd[i]:\n correct_of += 1\n end_t = time.time()\n\n print(\"epoch %d, oneflow top1 val acc: %f\" % (epoch, correct_of / all_samples))\n\n flow.save(\n mobilenetv3_module.state_dict(),\n os.path.join(\n args.save_checkpoint_path,\n \"epoch_%d_val_acc_%f\" % (epoch, correct_of / all_samples),\n ),\n )\n\n writer = open(\"of_losses.txt\", \"w\")\n for o in of_losses:\n writer.write(\"%f\\n\" % o)\n writer.close()\n\n\nif __name__ == \"__main__\":\n args = _parse_args()\n main(args)\n"
] |
[
[
"numpy.argmax"
]
] |
joshuadeng/torchrec
|
[
"4b525a1132db70da09e52839bb87575e523bf7b2"
] |
[
"torchrec/distributed/tests/test_train_pipeline.py"
] |
[
"#!/usr/bin/env python3\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport os\nimport unittest\nfrom dataclasses import dataclass\nfrom typing import Tuple, List, Optional, Dict\n\nimport torch\nimport torch.distributed as dist\nfrom torch import nn, optim\nfrom torchrec.distributed import DistributedModelParallel\nfrom torchrec.distributed.embedding_types import EmbeddingComputeKernel\nfrom torchrec.distributed.embedding_types import (\n SparseFeaturesList,\n)\nfrom torchrec.distributed.embeddingbag import (\n ShardedEmbeddingBagCollection,\n EmbeddingBagCollectionSharder,\n)\nfrom torchrec.distributed.tests.test_model import (\n TestSparseNN,\n ModelInput,\n TestEBCSharder,\n)\nfrom torchrec.distributed.train_pipeline import (\n TrainPipelineBase,\n TrainPipelineSparseDist,\n)\nfrom torchrec.distributed.types import (\n Awaitable,\n ParameterSharding,\n ShardedModuleContext,\n ShardingEnv,\n)\nfrom torchrec.distributed.types import (\n ShardingType,\n)\nfrom torchrec.modules.embedding_configs import EmbeddingBagConfig\nfrom torchrec.modules.embedding_modules import EmbeddingBagCollection\nfrom torchrec.optim.keyed import KeyedOptimizerWrapper\nfrom torchrec.sparse.jagged_tensor import KeyedJaggedTensor\nfrom torchrec.tests.utils import get_free_port, init_distributed_single_host\nfrom torchrec.types import Pipelineable\n\n\nclass TestShardedEmbeddingBagCollection(ShardedEmbeddingBagCollection):\n def input_dist(\n self,\n ctx: ShardedModuleContext,\n features: KeyedJaggedTensor,\n ) -> Awaitable[SparseFeaturesList]:\n return super().input_dist(ctx, features)\n\n\nclass TestCustomEBCSharder(EmbeddingBagCollectionSharder[EmbeddingBagCollection]):\n def shard(\n self,\n module: EmbeddingBagCollection,\n params: Dict[str, ParameterSharding],\n env: ShardingEnv,\n device: Optional[torch.device] = None,\n ) -> TestShardedEmbeddingBagCollection:\n return TestShardedEmbeddingBagCollection(\n module, params, env, self.fused_params, device\n )\n\n def sharding_types(self, compute_device_type: str) -> List[str]:\n return [\n ShardingType.TABLE_WISE.value,\n ]\n\n def compute_kernels(\n self, sharding_type: str, compute_device_type: str\n ) -> List[str]:\n return [EmbeddingComputeKernel.DENSE.value]\n\n\n@dataclass\nclass ModelInputSimple(Pipelineable):\n float_features: torch.Tensor\n label: torch.Tensor\n\n def to(self, device: torch.device, non_blocking: bool) -> \"ModelInputSimple\":\n return ModelInputSimple(\n float_features=self.float_features.to(\n device=device, non_blocking=non_blocking\n ),\n label=self.label.to(device=device, non_blocking=non_blocking),\n )\n\n def record_stream(self, stream: torch.cuda.streams.Stream) -> None:\n self.float_features.record_stream(stream)\n self.label.record_stream(stream)\n\n\nclass TestModule(nn.Module):\n def __init__(self) -> None:\n super().__init__()\n self.model = nn.Linear(10, 1)\n self.loss_fn = nn.BCEWithLogitsLoss()\n\n def forward(\n self, model_input: ModelInputSimple\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n pred = self.model(model_input.float_features)\n loss = self.loss_fn(pred, model_input.label)\n return (loss, pred)\n\n\nclass TrainPipelineBaseTest(unittest.TestCase):\n def setUp(self) -> None:\n self.device = torch.device(\"cuda:0\")\n\n # pyre-fixme[56]: Pyre was not able to infer the type of argument\n @unittest.skipIf(\n torch.cuda.device_count() <= 1,\n \"Not enough GPUs, this test requires at least two GPUs\",\n )\n def test_equal_to_non_pipelined(self) -> None:\n model_cpu = TestModule()\n model_gpu = TestModule().to(self.device)\n model_gpu.load_state_dict(model_cpu.state_dict())\n optimizer_cpu = optim.SGD(model_cpu.model.parameters(), lr=0.01)\n optimizer_gpu = optim.SGD(model_gpu.model.parameters(), lr=0.01)\n data = [\n ModelInputSimple(\n float_features=torch.rand((10,)),\n label=torch.randint(2, (1,), dtype=torch.float32),\n )\n for b in range(5)\n ]\n dataloader = iter(data)\n pipeline = TrainPipelineBase(model_gpu, optimizer_gpu, self.device)\n\n for example in data[:-1]:\n optimizer_cpu.zero_grad()\n loss, pred = model_cpu(example)\n loss.backward()\n optimizer_cpu.step()\n\n pred_gpu = pipeline.progress(dataloader)\n\n self.assertEquals(pred_gpu.device, self.device)\n self.assertTrue(torch.isclose(pred_gpu.cpu(), pred))\n\n\nclass TrainPipelineSparseDistTest(unittest.TestCase):\n def setUp(self) -> None:\n os.environ[\"MASTER_ADDR\"] = str(\"localhost\")\n os.environ[\"MASTER_PORT\"] = str(get_free_port())\n if not dist.is_initialized():\n self.pg = init_distributed_single_host(backend=\"gloo\", rank=0, world_size=1)\n else:\n self.pg = dist.group.WORLD\n\n num_features = 4\n num_weighted_features = 2\n\n self.tables = [\n EmbeddingBagConfig(\n num_embeddings=(i + 1) * 100,\n embedding_dim=(i + 1) * 4,\n name=\"table_\" + str(i),\n feature_names=[\"feature_\" + str(i)],\n )\n for i in range(num_features)\n ]\n self.weighted_tables = [\n EmbeddingBagConfig(\n num_embeddings=(i + 1) * 100,\n embedding_dim=(i + 1) * 4,\n name=\"weighted_table_\" + str(i),\n feature_names=[\"weighted_feature_\" + str(i)],\n )\n for i in range(num_weighted_features)\n ]\n\n self.device = torch.device(\"cuda:0\")\n\n def _test_move_cpu_gpu_helper(\n self, distributed_model: DistributedModelParallel\n ) -> None:\n model_cpu = TestSparseNN(\n tables=self.tables, weighted_tables=self.weighted_tables\n )\n optimizer_cpu = optim.SGD(model_cpu.parameters(), lr=0.1)\n optimizer_distributed = KeyedOptimizerWrapper(\n dict(distributed_model.named_parameters()),\n lambda params: optim.SGD(params, lr=0.1),\n )\n pipeline = TrainPipelineSparseDist(\n distributed_model, optimizer_distributed, self.device\n )\n\n data = [\n ModelInput.generate(\n tables=self.tables,\n weighted_tables=self.weighted_tables,\n batch_size=1,\n world_size=1,\n num_float_features=10,\n )[0]\n for i in range(5)\n ]\n dataloader = iter(data)\n\n for example in data[:-2]:\n optimizer_cpu.zero_grad()\n loss, pred = model_cpu(example)\n loss.backward()\n optimizer_cpu.step()\n\n pred_gpu = pipeline.progress(dataloader)\n\n self.assertEquals(pred_gpu.device, self.device)\n self.assertEquals(pred_gpu.cpu().size(), pred.size())\n self.assertEquals(len(pipeline._pipelined_modules), 2)\n\n # pyre-fixme[56]: Pyre was not able to infer the type of argument\n @unittest.skipIf(\n torch.cuda.device_count() <= 1,\n \"Not enough GPUs, this test requires at least two GPUs\",\n )\n def test_move_cpu_gpu(self) -> None:\n unsharded_model = TestSparseNN(\n tables=self.tables,\n weighted_tables=self.weighted_tables,\n dense_device=self.device,\n sparse_device=torch.device(\"meta\"),\n )\n distributed_model = DistributedModelParallel(\n unsharded_model,\n env=ShardingEnv.from_process_group(self.pg),\n init_data_parallel=False,\n device=self.device,\n # pyre-ignore [6]\n sharders=[\n TestEBCSharder(\n sharding_type=ShardingType.TABLE_WISE.value,\n kernel_type=EmbeddingComputeKernel.DENSE.value,\n )\n ],\n )\n self._test_move_cpu_gpu_helper(distributed_model)\n\n # pyre-fixme[56]: Pyre was not able to infer the type of argument\n @unittest.skipIf(\n torch.cuda.device_count() <= 1,\n \"Not enough GPUs, this test requires at least two GPUs\",\n )\n def test_pipelining(self) -> None:\n unsharded_model = TestSparseNN(\n tables=self.tables,\n weighted_tables=self.weighted_tables,\n dense_device=self.device,\n sparse_device=torch.device(\"meta\"),\n )\n distributed_model = DistributedModelParallel(\n unsharded_model,\n env=ShardingEnv.from_process_group(self.pg),\n init_data_parallel=False,\n device=self.device,\n # pyre-fixme [6]\n sharders=[TestCustomEBCSharder()],\n )\n self._test_move_cpu_gpu_helper(distributed_model)\n"
] |
[
[
"torch.randint",
"torch.distributed.is_initialized",
"torch.nn.Linear",
"torch.nn.BCEWithLogitsLoss",
"torch.rand",
"torch.optim.SGD",
"torch.device",
"torch.cuda.device_count"
]
] |
ElementAI/synbols
|
[
"618a171a0b21e8700582636af48a293185c20fc8"
] |
[
"synbols/drawing.py"
] |
[
"import os\nfrom glob import glob\n\nimport cairo\nimport numpy as np\nfrom PIL import Image as PILImage\n\n\ndef draw_symbol(ctxt, attributes):\n \"\"\"Core function drawing the characters as described in `attributes`\n\n Args:\n ctxt: cairo context to draw the image\n attributes: Object of type Symbol\n\n Returns:\n extent: rectangle containing the text in the coordinate of the context\n extent_main_char: rectangle containing the central character \\\n in the coordinate of the context\n \"\"\"\n # attributes.background.draw(ctxt)\n\n attributes.foreground.set_as_source(ctxt)\n\n weight = cairo.FontWeight.BOLD if attributes.is_bold else cairo.FontWeight.NORMAL\n slant = cairo.FontSlant.OBLIQUE if attributes.is_slant else cairo.FontSlant.NORMAL\n char = attributes.char\n\n ctxt.set_font_size(1)\n ctxt.select_font_face(attributes.font, cairo.FONT_SLANT_NORMAL, weight)\n\n extent = ctxt.text_extents(char)\n # normalize font size\n font_size = attributes.scale / max(extent.width, extent.height, 0.1)\n ctxt.set_font_size(font_size)\n\n font_matrix = ctxt.get_font_matrix()\n\n # set slant to normal and perform it manually.\n # There seems to be some issues with system italic\n if slant != cairo.FONT_SLANT_NORMAL:\n font_matrix = font_matrix.multiply(cairo.Matrix(1, 0.2, 0.0, 1))\n\n font_matrix.rotate(attributes.rotation)\n ctxt.set_font_matrix(font_matrix)\n\n extent = ctxt.text_extents(char)\n\n translate = (np.array(attributes.translation) + 1.0) / 2.0\n translate *= np.array((1 - extent.width, 1 - extent.height))\n ctxt.translate(-extent.x_bearing, -extent.y_bearing)\n ctxt.translate(translate[0], translate[1])\n\n ctxt.show_text(char)\n\n ctxt.clip()\n ctxt.paint()\n\n # TODO verify that the extent is the final extent\n # and not the one before translate\n return extent, None\n\n\nclass Pattern(object):\n \"\"\"Base class for all patterns\"\"\"\n\n def surface(self, width, height):\n surface, ctxt = _make_surface(width, height)\n self.draw(ctxt)\n return surface\n\n def draw(self, ctxt):\n ctxt.rectangle(0, 0, 1, 1) # Rectangle(x0, y0, x1, y1)\n self.set_as_source(ctxt)\n ctxt.fill()\n\n def set_as_source(self, ctxt):\n raise NotImplementedError()\n\n def attribute_dict(self):\n return {\"style\": self.__class__.__name__}\n\n\nclass RandomPattern(Pattern):\n \"\"\"Base class for patterns using a seed.\"\"\"\n\n def attribute_dict(self):\n return {\"style\": self.__class__.__name__, \"seed\": self.seed}\n\n\nclass NoPattern(Pattern):\n def draw(self, ctxt):\n pass\n\n def set_as_source(self, ctxt):\n ctxt.set_source_rgba(1, 1, 1, 0)\n\n\nclass SolidColor(Pattern):\n \"\"\"Uses fixed color to render pattern.\"\"\"\n\n def __init__(self, color=None):\n self.color = color\n\n def draw(self, ctxt):\n self.set_as_source(ctxt)\n ctxt.paint()\n\n def set_as_source(self, ctxt):\n ctxt.set_source_rgb(*self.color)\n\n\n# There is a plan to make to color sampler a bit more fancy.\ndef color_sampler(rng=np.random, brightness_range=(0, 1)):\n def sampler():\n b_delta = brightness_range[1] - brightness_range[0]\n return rng.rand(3) * b_delta + brightness_range[0]\n\n return sampler\n\n\nclass Gradient(RandomPattern):\n \"\"\"Uses linear or radial graidents to render patterns.\"\"\"\n\n def __init__(self, alpha=1, types=(\"radial\", \"linear\"), random_color=None, seed=None):\n self.random_color = random_color\n self.seed = seed\n self.rng = np.random.RandomState(self.seed)\n\n self.types = types\n self.alpha = alpha\n\n def set_as_source(self, ctxt):\n pat = _random_pattern(self.alpha, self.random_color, rng=self.rng, patern_types=self.types)\n ctxt.set_source(pat)\n\n\nclass MultiGradient(RandomPattern):\n \"\"\"Renders multiple gradient patterns at with transparency.\"\"\"\n\n def __init__(self, alpha=0.5, n_gradients=2, types=(\"radial\", \"linear\"), random_color=None, seed=None):\n\n self.random_color = random_color\n self.seed = seed\n self.types = types\n self.alpha = alpha\n self.n_gradients = n_gradients\n\n def draw(self, ctxt):\n rng = np.random.RandomState(self.seed)\n for i in range(self.n_gradients):\n if i == 0:\n alpha = self.alpha\n else:\n alpha = self.alpha\n pat = _random_pattern(alpha, self.random_color, rng=rng, patern_types=self.types)\n ctxt.rectangle(0, 0, 1, 1) # Rectangle(x0, y0, x1, y1)\n ctxt.set_source(pat)\n ctxt.fill()\n\n def set_as_source(self, ctxt):\n raise NotImplementedError()\n\n\ndef _random_pattern(alpha=0.8, random_color=None, patern_types=(\"linear\", \"radial\"), rng=np.random):\n \"\"\"\"Select a random pattern with either radial or linear gradient.\"\"\"\n if random_color is None:\n random_color = color_sampler(rng)\n pattern_type = rng.choice(patern_types)\n\n # TODO have the locations dependant on the symbol position\n # or in general have a more intelligent design\n if pattern_type == \"linear\":\n x1, y1 = rng.rand(2)\n theta = rng.rand() * 2 * np.pi\n r = rng.randn() * 0.2 + 1\n x2 = x1 + r * np.cos(theta)\n y2 = y1 + r * np.sin(theta)\n pat = cairo.LinearGradient(x1, y1, x2, y2)\n elif pattern_type == \"radial\":\n x1, y1, x2, y2 = rng.rand(4)\n pat = cairo.RadialGradient(x1, y1, 2, x2, y2, 0.1)\n else:\n raise Exception(\"unknown pattern type %s\" % pattern_type)\n\n r, g, b = random_color()\n pat.add_color_stop_rgba(1, r, g, b, alpha)\n r, g, b = random_color()\n pat.add_color_stop_rgba(0.5, r, g, b, alpha)\n r, g, b = random_color()\n pat.add_color_stop_rgba(0, r, g, b, alpha)\n return pat\n\n\nclass Camouflage(RandomPattern):\n def __init__(\n self, stroke_length=0.4, stroke_width=0.05, stroke_angle=np.pi / 4, stroke_noise=0.02, n_stroke=500, seed=None\n ):\n self.seed = seed\n self.stroke_length = stroke_length\n self.stroke_width = stroke_width\n self.n_stroke = n_stroke\n self.stroke_angle = stroke_angle\n self.stroke_noise = stroke_noise\n\n def draw(self, ctxt):\n stroke_vector = self.stroke_length * np.array([np.cos(self.stroke_angle), np.sin(self.stroke_angle)])\n rng = np.random.RandomState(self.seed)\n for i in range(self.n_stroke):\n start = (rng.rand(2) * 1.6 - 0.3) * (1 - stroke_vector)\n stop = start + stroke_vector + rng.randn(2) * self.stroke_noise\n ctxt.move_to(*start)\n ctxt.line_to(*stop)\n ctxt.set_line_width(self.stroke_width)\n\n b, g, r = rng.rand(3)\n\n ctxt.set_source_rgba(b, g, r, 0.8)\n ctxt.stroke()\n\n def set_as_source(self, ctxt):\n surface = ctxt.get_group_target()\n width, height = surface.get_width(), surface.get_height()\n source_surface = self.surface(width, height)\n ctxt.set_source_surface(source_surface)\n\n def to_json(self):\n pass\n\n\nclass ImagePattern(RandomPattern):\n \"\"\"Uses natural images to render patterns.\n\n Args:\n root : str, Base path to search for images.\n rotation: float, Maximum random rotation in radian, default 0.\n translation: float, Maximum random translation in proportion, default 1.\n crop: bool, Whether to take a random crop of the image or not, default True.\n min_crop_size: float, Crop's minimal proportion from the image, default 0.2.\n seed : Optional[int], Random seed to use for transformation, default to None\n \"\"\"\n\n def __init__(self, root=\"/images\", rotation=0, translation=0.0, crop=True, min_crop_size=0.2, seed=None):\n # TODO more extensions\n self._path = glob(os.path.join(root, \"**\", \"*.*\"), recursive=True)\n self._path = list(filter(lambda p: os.path.splitext(p)[1] in (\".jpg\", \".png\", \".gif\"), self._path))\n self.rotation = rotation\n self.translation = translation\n self.crop = crop\n self.seed = seed\n self.min_crop_size = min_crop_size\n self.rng = np.random.RandomState(self.seed)\n\n def _rotate_and_translate(self, im, rotation, translation):\n \"\"\"Randomly rotate and translate the image.\"\"\"\n w, h = im.size\n rot = np.rad2deg(rotation) * ((self.rng.rand() - 0.5) * 2)\n translation_x = w * translation * ((self.rng.rand() - 0.5) * 2)\n translation_y = h * translation * ((self.rng.rand() - 0.5) * 2)\n return im.rotate(rot, translate=(translation_x, translation_y))\n\n def _random_crop(self, im, min_crop_size):\n \"\"\"Randomly crop the image with a minimal crop size of `min_crop_size`% of the image.\"\"\"\n w, h = im.size\n min_crop_size_x = int(min_crop_size * w)\n min_crop_size_y = int(min_crop_size * h)\n crop_x2 = self.rng.randint(min_crop_size_x + 1, w)\n crop_y2 = self.rng.randint(min_crop_size_y + 1, h)\n x1 = self.rng.randint(0, crop_x2 - min_crop_size_x)\n y1 = self.rng.randint(0, crop_y2 - min_crop_size_y)\n return im.crop((x1, y1, crop_x2, crop_y2))\n\n def draw(self, ctxt):\n self.set_as_source(ctxt)\n ctxt.paint()\n\n def set_as_source(self, ctxt):\n surface = ctxt.get_group_target()\n width, height = surface.get_width(), surface.get_height()\n im = PILImage.open(self.rng.choice(self._path, 1).item()).convert(\"RGB\")\n im = self._rotate_and_translate(im, self.rotation, self.translation)\n # Generate a crop with a least 10% of the image in it.\n if self.crop:\n im = self._random_crop(im, min_crop_size=self.min_crop_size)\n im = im.resize((width, height))\n ctxt.set_source_surface(_from_pil(im))\n\n\ndef _surface_to_array(surface):\n \"\"\"Converts a cairo.ImageSurface object to a numpy array.\"\"\"\n buf = surface.get_data()\n img = np.ndarray(shape=(surface.get_height(), surface.get_width(), 4), dtype=np.uint8, buffer=buf)\n return img[:, :, :3]\n\n\ndef _make_surface(width, height):\n \"\"\"Creates a cairo.ImageSurface and cairo.Context.\"\"\"\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)\n scale = min(width, height)\n surface.set_device_scale(scale, scale)\n ctxt = cairo.Context(surface)\n return surface, ctxt\n\n\ndef _image_transform(img, inverse_color, pixel_noise_scale, is_gray, max_contrast, rng, symbols=()):\n \"\"\"Basic array transformation of the image.\"\"\"\n img = img.astype(np.float32) / 256.0\n\n if is_gray:\n img = np.mean(img, axis=2, keepdims=True)\n\n if inverse_color:\n img = 1 - img\n\n if max_contrast:\n mn, mx = np.min(img), np.max(img)\n\n if mx - mn > 0:\n img = (img - mn) / (mx - mn)\n else:\n if len(symbols) > 0:\n print(\"Font %s yields empty image\" % symbols[0].font)\n\n img += rng.randn(*img.shape) * pixel_noise_scale\n img = np.clip(img, 0.0, 1.0)\n\n return (img * 255).astype(np.uint8)\n\n\ndef _from_pil(im, alpha=1.0, format=cairo.FORMAT_ARGB32):\n \"\"\"Convert a PIL Image to a Cairo surface.\n\n Args:\n im: Pillow Image\n alpha: 0..1 alpha to add to non-alpha images\n format: Pixel format for output surface\n\n Returns: a cairo.ImageSurface object\n \"\"\"\n assert format in (cairo.FORMAT_RGB24, cairo.FORMAT_ARGB32), f\"Unsupported pixel format: {format}\"\n if \"A\" not in im.getbands():\n im.putalpha(int(alpha * 256.0))\n arr = bytearray(im.tobytes(\"raw\", \"BGRa\"))\n surface = cairo.ImageSurface.create_for_data(arr, format, im.width, im.height)\n surface.set_device_scale(im.width, im.height)\n return surface\n\n\nclass Image:\n \"\"\"High level class for genrating an image with symbols, based on attributes.\n\n Attributes:\n symbols: a list of objects of type Symbol\n resolution: a pair of integer describing the resolution of the image.\\\n Defaults to (32, 32).\n background: an object of type Pattern for rendering the background \\\n of the image. Defaults to NoPattern.\n inverse_color: Boolean, specifying if the colors should be inverted. \\\n Defaults to False.\n pixel_noise_scale: The standard deviation of the pixel noise. \\\n Defaults to 0.01.\n max_contrast: Boolean, specifying if the image contrast should \\\n be maximized after rendering. If True, the \\\n pixel values will be linearly map to range [0, 1] within an image. \\\n Defaults to True.\n seed: The random seed of an image. For the same seed, \\\n the same image will be rendered. Defaults to None.\n \"\"\"\n\n def __init__(\n self,\n symbols,\n resolution=(32, 32),\n background=NoPattern(),\n inverse_color=False,\n pixel_noise_scale=0.01,\n is_gray=False,\n max_contrast=True,\n seed=None,\n ):\n self.symbols = symbols\n self.resolution = resolution\n self.inverse_color = inverse_color\n self.pixel_noise_scale = pixel_noise_scale\n self.background = background\n self.is_gray = is_gray\n self.max_contrast = max_contrast\n self.seed = seed\n\n def make_mask(self):\n mask_list = []\n for symbol in self.symbols:\n mask_list.append(symbol.make_mask(self.resolution))\n return np.concatenate(mask_list, axis=2)\n\n def make_image(self):\n surface, ctxt = _make_surface(*self.resolution)\n self.background.draw(ctxt)\n for symbol in self.symbols:\n ctxt.save()\n symbol.draw(ctxt)\n ctxt.restore()\n img = _surface_to_array(surface)\n rng = np.random.RandomState(self.seed)\n return _image_transform(\n img, self.inverse_color, self.pixel_noise_scale, self.is_gray, self.max_contrast, rng, self.symbols\n )\n\n def attribute_dict(self):\n symbols = [symbol.attribute_dict() for symbol in self.symbols]\n data = dict(\n resolution=self.resolution,\n pixel_noise_scale=self.pixel_noise_scale,\n seed=self.seed,\n background=self.background.attribute_dict(),\n inverse_color=int(self.inverse_color),\n )\n data.update(symbols[0]) # hack to allow flatten access\n data[\"symbols\"] = symbols\n\n return data\n\n def add_symbol(self, symbol):\n self.symbols.append(symbol)\n\n\nclass Symbol:\n \"\"\"Class containing attributes describing each symbol\n\n Attributes:\n alphabet: Object of type Alphabet\n char: string of 1 or more characters in the image\n font: string describing the font used to draw characters\n foreground: object of type Pattern, \\\n used for the foreground of the symbol\n is_slant: bool describing if char is italic or not\n is_bold: bool describing if char is bold or not\n rotation: float, rotation angle of the text\n scale: float, scale of the text. A scale of 1 will have the \\\n longest extent of the symbol cover the whole image.\n translation: relative (x, y) translation of the text. \\\n A translation in the range [-1, 1] will ensure that the\n symbol fits entirely in the image. Note if the scale i\n \"\"\"\n\n def __init__(self, alphabet, char, font, foreground, is_slant, is_bold, rotation, scale, translation):\n self.alphabet = alphabet\n self.char = char\n self.font = font\n self.is_bold = is_bold\n self.is_slant = is_slant\n self.foreground = foreground\n self.rotation = rotation\n self.scale = scale\n self.translation = translation\n\n def draw(self, ctxt):\n draw_symbol(ctxt, self)\n\n def make_mask(self, resolution):\n \"\"\"Creates a grey scale image\n corresponding to the mask of the symbol.\n \"\"\"\n fg = self.foreground\n self.foreground = SolidColor((1, 1, 1))\n surface, ctxt = _make_surface(*resolution)\n draw_symbol(ctxt, self)\n self.foreground = fg\n img = _surface_to_array(surface)\n return np.mean(img, axis=2, keepdims=True).astype(np.uint8)\n\n def attribute_dict(self):\n \"\"\"Returns a dict of all attributes of the symbol.\"\"\"\n return dict(\n alphabet=self.alphabet.name,\n char=self.char,\n font=self.font,\n is_bold=str(self.is_bold),\n is_slant=str(self.is_slant),\n scale=self.scale,\n translation=self.translation,\n rotation=self.rotation,\n foreground=self.foreground.attribute_dict(),\n )\n"
] |
[
[
"numpy.clip",
"numpy.min",
"numpy.cos",
"numpy.rad2deg",
"numpy.sin",
"numpy.concatenate",
"numpy.max",
"numpy.mean",
"numpy.array",
"numpy.random.RandomState"
]
] |
GBERESEARCH/optionvisualizer
|
[
"98830c478f7edbacb18f30d679ee4010c7ed7fe6"
] |
[
"optionvisualizer/simple_payoffs.py"
] |
[
"\"\"\"\nOne and Two Option Payoffs\n\n\"\"\"\nimport numpy as np\nfrom optionvisualizer.multi_payoffs import MultiPayoff\nfrom optionvisualizer.option_formulas import Option\n# pylint: disable=invalid-name\n\nclass SimplePayoff():\n \"\"\"\n Calculate One and Two Option payoffs - Call / Put / Spread / Straddle etc.\n\n \"\"\"\n\n @staticmethod\n def call(params):\n \"\"\"\n Displays the graph of the call.\n\n Parameters\n ----------\n params : Dict\n S : Float\n Underlying Stock Price. The default is 100.\n K : Float\n Strike Price of option 1. The default is 100.\n T : Float\n Time to Maturity. The default is 0.25 (3 months).\n r : Float\n Interest Rate. The default is 0.05 (5%).\n q : Float\n Dividend Yield. The default is 0.\n sigma : Float\n Implied Volatility. The default is 0.2 (20%).\n direction : Str\n Whether the payoff is long or short. The default is 'long'.\n value : Bool\n Whether to show the current value as well as the terminal\n payoff. The default is False.\n mpl_style : Str\n Matplotlib style template for 2D risk charts and payoffs.\n The default is 'seaborn-darkgrid'.\n\n Returns\n -------\n payoff: Terminal payoff value less initial cost; Array\n payoff2: Current payoff value less initial cost (optional); Array\n title: Description of payoff; Str\n Runs method to graph using Matplotlib.\n\n \"\"\"\n\n params['opt_dict'] = {\n 'legs':1,\n 'S':params['S'],\n 'K1':params['K'],\n 'T1':params['T'],\n 'r':params['r'],\n 'q':params['q'],\n 'sigma':params['sigma'],\n 'option1':'call'\n }\n\n # Calculate option prices\n option_legs = Option.return_options(\n opt_dict=params['opt_dict'], params=params)\n\n # Create payoff based on direction\n if params['direction'] == 'long':\n payoff = option_legs['C1'] - option_legs['C1_0']\n title = 'Long Call'\n if params['value']:\n payoff2 = option_legs['C1_G'] - option_legs['C1_0']\n else:\n payoff2 = None\n\n if params['direction'] == 'short':\n payoff = -option_legs['C1'] + option_legs['C1_0']\n title = 'Short Call'\n if params['value']:\n payoff2 = -option_legs['C1_G'] + option_legs['C1_0']\n else:\n payoff2 = None\n\n params['payoff_dict'] = {\n 'S':params['S'],\n 'SA':option_legs['SA'],\n 'payoff':payoff,\n 'title':title,\n 'payoff2':payoff2,\n 'size2d':params['size2d'],\n 'mpl_style':params['mpl_style']\n }\n\n # Visualize payoff\n MultiPayoff.vis_payoff(\n payoff_dict=params['payoff_dict'], params=params)\n\n\n @staticmethod\n def put(params):\n \"\"\"\n Displays the graph of the put.\n\n Parameters\n ----------\n params : Dict\n S : Float\n Underlying Stock Price. The default is 100.\n K : Float\n Strike Price of option 1. The default is 100.\n T : Float\n Time to Maturity. The default is 0.25 (3 months).\n r : Float\n Interest Rate. The default is 0.05 (5%).\n q : Float\n Dividend Yield. The default is 0.\n sigma : Float\n Implied Volatility. The default is 0.2 (20%).\n direction : Str\n Whether the payoff is long or short. The default is 'long'.\n value : Bool\n Whether to show the current value as well as the terminal\n payoff. The default is False.\n mpl_style : Str\n Matplotlib style template for 2D risk charts and payoffs.\n The default is 'seaborn-darkgrid'.\n\n Returns\n -------\n payoff: Terminal payoff value less initial cost; Array\n payoff2: Current payoff value less initial cost (optional); Array\n title: Description of payoff; Str\n Runs method to graph using Matplotlib.\n\n \"\"\"\n\n params['opt_dict'] = {\n 'legs':1,\n 'S':params['S'],\n 'K1':params['K'],\n 'T1':params['T'],\n 'r':params['r'],\n 'q':params['q'],\n 'sigma':params['sigma'],\n 'option1':'put'\n }\n\n # Calculate option prices\n option_legs = Option.return_options(\n opt_dict=params['opt_dict'], params=params)\n\n # Create payoff based on direction\n if params['direction'] == 'long':\n payoff = option_legs['C1'] - option_legs['C1_0']\n title = 'Long Put'\n if params['value']:\n payoff2 = option_legs['C1_G'] - option_legs['C1_0']\n else:\n payoff2 = None\n\n if params['direction'] == 'short':\n payoff = -option_legs['C1'] + option_legs['C1_0']\n title = 'Short Put'\n if params['value']:\n payoff2 = -option_legs['C1_G'] + option_legs['C1_0']\n else:\n payoff2 = None\n\n params['payoff_dict'] = {\n 'S':params['S'],\n 'SA':option_legs['SA'],\n 'payoff':payoff,\n 'title':title,\n 'payoff2':payoff2,\n 'size2d':params['size2d'],\n 'mpl_style':params['mpl_style']\n }\n\n # Visualize payoff\n MultiPayoff.vis_payoff(\n payoff_dict=params['payoff_dict'], params=params)\n\n\n @staticmethod\n def stock(params):\n \"\"\"\n Displays the graph of the underlying.\n\n Parameters\n ----------\n S : Float\n Underlying Stock Price. The default is 100.\n direction : Str\n Whether the payoff is long or short. The default is 'long'.\n mpl_style : Str\n Matplotlib style template for 2D risk charts and payoffs.\n The default is 'seaborn-darkgrid'.\n\n Returns\n -------\n payoff: Terminal payoff value less initial cost; Array\n title: Description of payoff; Str\n Runs method to graph using Matplotlib.\n\n \"\"\"\n\n # Define strike range\n SA = np.linspace(0.75 * params['S'], 1.25 * params['S'], 1000)\n\n # Create payoff based on option type\n if params['direction'] == 'long':\n payoff = SA - params['S']\n title = 'Long Stock'\n\n if params['direction'] == 'short':\n payoff = params['S'] - SA\n title = 'Short Stock'\n\n params['payoff_dict'] = {\n 'S':params['S'],\n 'SA':SA,\n 'payoff':payoff,\n 'title':title,\n 'payoff2':None,\n 'size2d':params['size2d'],\n 'mpl_style':params['mpl_style']\n }\n\n # Visualize payoff\n MultiPayoff.vis_payoff(\n payoff_dict=params['payoff_dict'], params=params)\n\n\n @staticmethod\n def forward(params):\n \"\"\"\n Displays the graph of the synthetic forward strategy:\n Long one ATM call\n Short one ATM put\n\n Parameters\n ----------\n S : Float\n Underlying Stock Price. The default is 100.\n T : Float\n Time to Maturity. The default is 0.25 (3 months).\n r : Float\n Interest Rate. The default is 0.05 (5%).\n q : Float\n Dividend Yield. The default is 0.\n sigma : Float\n Implied Volatility. The default is 0.2 (20%).\n direction : Str\n Whether the payoff is long or short. The default is 'long'.\n cash : Bool\n Whether to discount to present value. The default is False.\n mpl_style : Str\n Matplotlib style template for 2D risk charts and payoffs.\n The default is 'seaborn-darkgrid'.\n\n Returns\n -------\n payoff: Terminal payoff value less initial cost; Array\n payoff2: Current payoff value less initial cost (optional); Array\n title: Description of payoff; Str\n Runs method to graph using Matplotlib.\n\n \"\"\"\n\n params['opt_dict'] = {\n 'legs':2,\n 'S':params['S'],\n 'K1':params['S'],\n 'T1':params['T'],\n 'K2':params['S'],\n 'T2':params['T'],\n 'r':params['r'],\n 'q':params['q'],\n 'sigma':params['sigma'],\n 'option1':'call',\n 'option2':'put'\n }\n\n # Calculate option prices\n option_legs = Option.return_options(\n opt_dict=params['opt_dict'], params=params)\n\n # Whether to discount the payoff\n if params['cash']:\n pv = np.exp(-params['r'] * params['T'])\n else:\n pv = 1\n\n # Create payoff based on option type\n if params['direction'] == 'long':\n payoff = ((option_legs['C1'] - option_legs['C2']\n - option_legs['C1_0'] + option_legs['C2_0'])\n * pv)\n title = 'Long Forward'\n\n if params['direction'] == 'short':\n payoff = ((-option_legs['C1'] + option_legs['C2']\n + option_legs['C1_0'] - option_legs['C2_0'])\n * pv)\n title = 'Short Forward'\n\n params['payoff_dict'] = {\n 'S':params['S'],\n 'SA':option_legs['SA'],\n 'payoff':payoff,\n 'title':title,\n 'payoff2':None,\n 'size2d':params['size2d'],\n 'mpl_style':params['mpl_style']\n }\n\n # Visualize payoff\n MultiPayoff.vis_payoff(\n payoff_dict=params['payoff_dict'], params=params)\n\n\n @staticmethod\n def collar(params):\n \"\"\"\n Displays the graph of the collar strategy:\n Long one OTM put\n Short one OTM call\n\n Parameters\n ----------\n S : Float\n Underlying Stock Price. The default is 100.\n K1 : Float\n Strike Price of option 1. The default is 98.\n K2 : Float\n Strike Price of option 2. The default is 102.\n T : Float\n Time to Maturity. The default is 0.25 (3 months).\n r : Float\n Interest Rate. The default is 0.05 (5%).\n q : Float\n Dividend Yield. The default is 0.\n sigma : Float\n Implied Volatility. The default is 0.2 (20%).\n direction : Str\n Whether the payoff is long or short. The default is 'long'.\n value : Bool\n Whether to show the current value as well as the terminal\n payoff. The default is False.\n mpl_style : Str\n Matplotlib style template for 2D risk charts and payoffs.\n The default is 'seaborn-darkgrid'.\n\n Returns\n -------\n payoff: Terminal payoff value less initial cost; Array\n payoff2: Current payoff value less initial cost (optional); Array\n title: Description of payoff; Str\n Runs method to graph using Matplotlib.\n\n \"\"\"\n\n params['opt_dict'] = {\n 'legs':2,\n 'S':params['S'],\n 'K1':params['K1'],\n 'T1':params['T'],\n 'K2':params['K2'],\n 'T2':params['T'],\n 'r':params['r'],\n 'q':params['q'],\n 'sigma':params['sigma'],\n 'option1':'put',\n 'option2':'call'\n }\n\n # Calculate option prices\n option_legs = Option.return_options(\n opt_dict=params['opt_dict'], params=params)\n\n # Create payoff based on option type\n if params['direction'] == 'long':\n payoff = (option_legs['SA'] - params['S']\n + option_legs['C1'] - option_legs['C2']\n - option_legs['C1_0'] + option_legs['C2_0'])\n title = 'Long Collar'\n\n if params['value']:\n payoff2 = (option_legs['SA'] - params['S']\n + option_legs['C1_G'] - option_legs['C2_G']\n - option_legs['C1_0'] + option_legs['C2_0'])\n else:\n payoff2 = None\n\n if params['direction'] == 'short':\n payoff = (-option_legs['SA'] + params['S']\n - option_legs['C1'] + option_legs['C2']\n + option_legs['C1_0'] - option_legs['C2_0'])\n title = 'Short Collar'\n\n if params['value']:\n payoff2 = (-option_legs['SA'] + params['S']\n - option_legs['C1_G'] + option_legs['C2_G']\n + option_legs['C1_0'] - option_legs['C2_0'])\n else:\n payoff2 = None\n\n params['payoff_dict'] = {\n 'S':params['S'],\n 'SA':option_legs['SA'],\n 'payoff':payoff,\n 'title':title,\n 'payoff2':payoff2,\n 'size2d':params['size2d'],\n 'mpl_style':params['mpl_style']\n }\n\n # Visualize payoff\n MultiPayoff.vis_payoff(\n payoff_dict=params['payoff_dict'], params=params)\n\n\n @staticmethod\n def spread(params):\n \"\"\"\n Displays the graph of the spread strategy:\n Long one ITM option\n Short one OTM option\n\n Parameters\n ----------\n S : Float\n Underlying Stock Price. The default is 100.\n K1 : Float\n Strike Price of option 1. The default is 95.\n K2 : Float\n Strike Price of option 2. The default is 105.\n T : Float\n Time to Maturity. The default is 0.25 (3 months).\n r : Float\n Interest Rate. The default is 0.05 (5%).\n q : Float\n Dividend Yield. The default is 0.\n sigma : Float\n Implied Volatility. The default is 0.2 (20%).\n option : Str\n Option type, Put or Call. The default is 'call'\n direction : Str\n Whether the payoff is long or short. The default is 'long'.\n value : Bool\n Whether to show the current value as well as the terminal\n payoff. The default is False.\n mpl_style : Str\n Matplotlib style template for 2D risk charts and payoffs.\n The default is 'seaborn-darkgrid'.\n\n Returns\n -------\n payoff: Terminal payoff value less initial cost; Array\n payoff2: Current payoff value less initial cost (optional); Array\n title: Description of payoff; Str\n Runs method to graph using Matplotlib.\n\n\n \"\"\"\n\n params['opt_dict'] = {\n 'legs':2,\n 'S':params['S'],\n 'K1':params['K1'],\n 'T1':params['T'],\n 'K2':params['K2'],\n 'T2':params['T'],\n 'r':params['r'],\n 'q':params['q'],\n 'sigma':params['sigma'],\n 'option1':params['option'],\n 'option2':params['option']\n }\n\n # Calculate option prices\n option_legs = Option.return_options(\n opt_dict=params['opt_dict'], params=params)\n\n # Create payoff based on option type\n if params['direction'] == 'long':\n payoff = (option_legs['C1'] - option_legs['C2']\n - option_legs['C1_0'] + option_legs['C2_0'])\n if params['value']:\n payoff2 = (option_legs['C1_G'] - option_legs['C2_G']\n - option_legs['C1_0'] + option_legs['C2_0'])\n else:\n payoff2 = None\n\n if params['direction'] == 'short':\n payoff = (-option_legs['C1'] + option_legs['C2']\n + option_legs['C1_0'] - option_legs['C2_0'])\n if params['value']:\n payoff2 = (-option_legs['C1_G'] + option_legs['C2_G']\n + option_legs['C1_0'] - option_legs['C2_0'])\n else:\n payoff2 = None\n\n # Create title based on option type and direction\n if params['option'] == 'call' and params['direction'] == 'long':\n title = 'Bull Call Spread'\n if params['option'] == 'put' and params['direction'] == 'long':\n title = 'Bull Put Spread'\n if params['option'] == 'call' and params['direction'] == 'short':\n title = 'Bear Call Spread'\n if params['option'] == 'put' and params['direction'] == 'short':\n title = 'Bear Put Spread'\n\n params['payoff_dict'] = {\n 'S':params['S'],\n 'SA':option_legs['SA'],\n 'payoff':payoff,\n 'title':title,\n 'payoff2':payoff2,\n 'size2d':params['size2d'],\n 'mpl_style':params['mpl_style']\n }\n\n # Visualize payoff\n MultiPayoff.vis_payoff(\n payoff_dict=params['payoff_dict'], params=params)\n\n\n @staticmethod\n def backspread(params):\n \"\"\"\n Displays the graph of the backspread strategy:\n Short one ITM option\n Long ratio * OTM options\n\n Parameters\n ----------\n S : Float\n Underlying Stock Price. The default is 100.\n K1 : Float\n Strike Price of option 1. The default is 95.\n K2 : Float\n Strike Price of option 2. The default is 105.\n T : Float\n Time to Maturity. The default is 0.25 (3 months).\n r : Float\n Interest Rate. The default is 0.05 (5%).\n q : Float\n Dividend Yield. The default is 0.\n sigma : Float\n Implied Volatility. The default is 0.2 (20%).\n option : Str\n Option type, Put or Call. The default is 'call'\n ratio : Int\n Multiple of OTM options to be sold for ITM purchased. The\n default is 2.\n value : Bool\n Whether to show the current value as well as the terminal\n payoff. The default is False.\n mpl_style : Str\n Matplotlib style template for 2D risk charts and payoffs.\n The default is 'seaborn-darkgrid'.\n\n Returns\n -------\n payoff: Terminal payoff value less initial cost; Array\n payoff2: Current payoff value less initial cost (optional); Array\n title: Description of payoff; Str\n Runs method to graph using Matplotlib.\n\n \"\"\"\n\n params['opt_dict'] = {\n 'legs':2,\n 'S':params['S'],\n 'K1':params['K1'],\n 'T1':params['T'],\n 'K2':params['K2'],\n 'T2':params['T'],\n 'r':params['r'],\n 'q':params['q'],\n 'sigma':params['sigma'],\n 'option1':params['option'],\n 'option2':params['option']\n }\n\n # Calculate option prices\n option_legs = Option.return_options(\n opt_dict=params['opt_dict'], params=params)\n\n # Create payoff based on option type\n if params['option'] == 'call':\n title = 'Call Backspread'\n payoff = (-option_legs['C1'] + (params['ratio']\n * option_legs['C2'])\n + option_legs['C1_0'] - (params['ratio']\n * option_legs['C2_0']))\n if params['value']:\n payoff2 = (-option_legs['C1_G'] + (params['ratio']\n * option_legs['C2_G'])\n + option_legs['C1_0'] - (params['ratio']\n * option_legs['C2_0']))\n else:\n payoff2 = None\n\n if params['option'] == 'put':\n payoff = (params['ratio'] * option_legs['C1']\n - option_legs['C2']\n - params['ratio'] * option_legs['C1_0']\n + option_legs['C2_0'])\n title = 'Put Backspread'\n if params['value']:\n payoff2 = (params['ratio'] * option_legs['C1_G']\n - option_legs['C2_G']\n - params['ratio'] * option_legs['C1_0']\n + option_legs['C2_0'])\n else:\n payoff2 = None\n\n params['payoff_dict'] = {\n 'S':params['S'],\n 'SA':option_legs['SA'],\n 'payoff':payoff,\n 'title':title,\n 'payoff2':payoff2,\n 'size2d':params['size2d'],\n 'mpl_style':params['mpl_style']\n }\n\n # Visualize payoff\n MultiPayoff.vis_payoff(\n payoff_dict=params['payoff_dict'], params=params)\n\n\n @staticmethod\n def ratio_vertical_spread(params):\n \"\"\"\n Displays the graph of the ratio vertical spread strategy:\n Long one ITM option\n Short ratio * OTM options\n\n Parameters\n ----------\n S : Float\n Underlying Stock Price. The default is 100.\n K1 : Float\n Strike Price of option 1. The default is 95.\n K2 : Float\n Strike Price of option 2. The default is 105.\n T : Float\n Time to Maturity. The default is 0.25 (3 months).\n r : Float\n Interest Rate. The default is 0.05 (5%).\n q : Float\n Dividend Yield. The default is 0.\n sigma : Float\n Implied Volatility. The default is 0.2 (20%).\n option : Str\n Option type, Put or Call. The default is 'call'\n ratio : Int\n Multiple of OTM options to be sold for ITM purchased. The\n default is 2.\n direction : Str\n Whether the payoff is long or short. The default is 'long'.\n value : Bool\n Whether to show the current value as well as the terminal\n payoff. The default is False.\n mpl_style : Str\n Matplotlib style template for 2D risk charts and payoffs.\n The default is 'seaborn-darkgrid'.\n\n Returns\n -------\n payoff: Terminal payoff value less initial cost; Array\n payoff2: Current payoff value less initial cost (optional); Array\n title: Description of payoff; Str\n Runs method to graph using Matplotlib.\n\n \"\"\"\n\n params['opt_dict'] = {\n 'legs':2,\n 'S':params['S'],\n 'K1':params['K1'],\n 'T1':params['T'],\n 'K2':params['K2'],\n 'T2':params['T'],\n 'r':params['r'],\n 'q':params['q'],\n 'sigma':params['sigma'],\n 'option1':params['option'],\n 'option2':params['option']\n }\n\n # Calculate option prices\n option_legs = Option.return_options(\n opt_dict=params['opt_dict'], params=params)\n\n # Create payoff based on option type\n if params['option'] == 'call':\n title = 'Call Ratio Vertical Spread'\n payoff = (option_legs['C1']\n - params['ratio'] * option_legs['C2']\n - option_legs['C1_0']\n + params['ratio'] * option_legs['C2_0'])\n if params['value']:\n payoff2 = (option_legs['C1_G']\n - params['ratio'] * option_legs['C2_G']\n - option_legs['C1_0']\n + params['ratio'] * option_legs['C2_0'])\n else:\n payoff2 = None\n\n if params['option'] == 'put':\n title = 'Put Ratio Vertical Spread'\n payoff = (-params['ratio'] * option_legs['C1']\n + option_legs['C2']\n + params['ratio'] * option_legs['C1_0']\n - option_legs['C2_0'])\n if params['value']:\n payoff2 = (-params['ratio'] * option_legs['C1_G']\n + option_legs['C2_G']\n + params['ratio'] * option_legs['C1_0']\n - option_legs['C2_0'])\n else:\n payoff2 = None\n\n params['payoff_dict'] = {\n 'S':params['S'],\n 'SA':option_legs['SA'],\n 'payoff':payoff,\n 'title':title,\n 'payoff2':payoff2,\n 'size2d':params['size2d'],\n 'mpl_style':params['mpl_style']\n }\n\n # Visualize payoff\n MultiPayoff.vis_payoff(\n payoff_dict=params['payoff_dict'], params=params)\n\n\n @staticmethod\n def straddle(params):\n \"\"\"\n Displays the graph of the straddle strategy:\n Long one ATM put\n Long one ATM call\n\n Parameters\n ----------\n S : Float\n Underlying Stock Price. The default is 100.\n K : Float\n Strike Price of options 1 and 2. The default is 100.\n T : Float\n Time to Maturity. The default is 0.25 (3 months).\n r : Float\n Interest Rate. The default is 0.05 (5%).\n q : Float\n Dividend Yield. The default is 0.\n sigma : Float\n Implied Volatility. The default is 0.2 (20%).\n direction : Str\n Whether the payoff is long or short. The default is 'long'.\n value : Bool\n Whether to show the current value as well as the terminal\n payoff. The default is False.\n mpl_style : Str\n Matplotlib style template for 2D risk charts and payoffs.\n The default is 'seaborn-darkgrid'.\n\n Returns\n -------\n payoff: Terminal payoff value less initial cost; Array\n payoff2: Current payoff value less initial cost (optional); Array\n title: Description of payoff; Str\n Runs method to graph using Matplotlib.\n\n \"\"\"\n\n params['opt_dict'] = {\n 'legs':2,\n 'S':params['S'],\n 'K1':params['K'],\n 'T1':params['T'],\n 'K2':params['K'],\n 'T2':params['T'],\n 'r':params['r'],\n 'q':params['q'],\n 'sigma':params['sigma'],\n 'option1':'put',\n 'option2':'call'\n }\n\n # Calculate option prices\n option_legs = Option.return_options(\n opt_dict=params['opt_dict'], params=params)\n\n # Create payoff based on direction\n if params['direction'] == 'long':\n payoff = (option_legs['C1'] + option_legs['C2']\n - option_legs['C1_0'] - option_legs['C2_0'])\n title = 'Long Straddle'\n if params['value']:\n payoff2 = (option_legs['C1_G'] + option_legs['C2_G']\n - option_legs['C1_0'] - option_legs['C2_0'])\n else:\n payoff2 = None\n\n if params['direction'] == 'short':\n payoff = (-option_legs['C1'] - option_legs['C2']\n + option_legs['C1_0'] + option_legs['C2_0'])\n title = 'Short Straddle'\n if params['value']:\n payoff2 = (-option_legs['C1_G'] - option_legs['C2_G']\n + option_legs['C1_0'] + option_legs['C2_0'])\n else:\n payoff2 = None\n\n params['payoff_dict'] = {\n 'S':params['S'],\n 'SA':option_legs['SA'],\n 'payoff':payoff,\n 'title':title,\n 'payoff2':payoff2,\n 'size2d':params['size2d'],\n 'mpl_style':params['mpl_style']\n }\n\n # Visualize payoff\n MultiPayoff.vis_payoff(\n payoff_dict=params['payoff_dict'], params=params)\n\n\n @staticmethod\n def strangle(params):\n \"\"\"\n Displays the graph of the strangle strategy:\n Long one OTM put\n Long one OTM call\n\n Parameters\n ----------\n S : Float\n Underlying Stock Price. The default is 100.\n K1 : Float\n Strike Price of option 1. The default is 95.\n K2 : Float\n Strike Price of option 2. The default is 105.\n T : Float\n Time to Maturity. The default is 0.25 (3 months).\n r : Float\n Interest Rate. The default is 0.05 (5%).\n q : Float\n Dividend Yield. The default is 0.\n sigma : Float\n Implied Volatility. The default is 0.2 (20%).\n direction : Str\n Whether the payoff is long or short. The default is 'long'.\n value : Bool\n Whether to show the current value as well as the terminal\n payoff. The default is False.\n mpl_style : Str\n Matplotlib style template for 2D risk charts and payoffs.\n The default is 'seaborn-darkgrid'.\n\n Returns\n -------\n payoff: Terminal payoff value less initial cost; Array\n payoff2: Current payoff value less initial cost (optional); Array\n title: Description of payoff; Str\n Runs method to graph using Matplotlib.\n\n \"\"\"\n\n params['opt_dict'] = {\n 'legs':2,\n 'S':params['S'],\n 'K1':params['K1'],\n 'T1':params['T'],\n 'K2':params['K2'],\n 'T2':params['T'],\n 'r':params['r'],\n 'q':params['q'],\n 'sigma':params['sigma'],\n 'option1':'put',\n 'option2':'call'\n }\n\n # Calculate option prices\n option_legs = Option.return_options(\n opt_dict=params['opt_dict'], params=params)\n\n # Create payoff based on direction\n if params['direction'] == 'long':\n payoff = (option_legs['C1'] + option_legs['C2']\n - option_legs['C1_0'] - option_legs['C2_0'])\n title = 'Long Strangle'\n if params['value']:\n payoff2 = (option_legs['C1_G'] + option_legs['C2_G']\n - option_legs['C1_0'] - option_legs['C2_0'])\n else:\n payoff2 = None\n\n if params['direction'] == 'short':\n payoff = (-option_legs['C1'] - option_legs['C2']\n + option_legs['C1_0'] + option_legs['C2_0'])\n title = 'Short Strangle'\n if params['value']:\n payoff2 = (-option_legs['C1_G'] - option_legs['C2_G']\n + option_legs['C1_0'] + option_legs['C2_0'])\n else:\n payoff2 = None\n\n params['payoff_dict'] = {\n 'S':params['S'],\n 'SA':option_legs['SA'],\n 'payoff':payoff,\n 'title':title,\n 'payoff2':payoff2,\n 'size2d':params['size2d'],\n 'mpl_style':params['mpl_style']\n }\n\n # Visualize payoff\n MultiPayoff.vis_payoff(\n payoff_dict=params['payoff_dict'], params=params)\n"
] |
[
[
"numpy.exp",
"numpy.linspace"
]
] |
leonardohcl/Nature-Inspired-Computing-Algorithms
|
[
"7227a6516c746b248e861b4c582672cff1864229"
] |
[
"project_1_task_1.py"
] |
[
"# encoding: utf-8\n\nfrom BinaryString import BinaryString\nfrom InputMethods import readIntMin, readIntInterval, readFloatInterval, readIntInterval, readOption, readFloat, secondsToString\nfrom NatureInspiredAlgorithms import geneticAlgorithm\nimport matplotlib.pyplot as plt\nimport time\nimport math\nfrom random import random, randint\nfrom copy import deepcopy\n\n#DEFINIÇÃO DE CONSTANTES E VARIÁVEIS GLOBAIS\nzero = BinaryString([1,1,1,1,0,1,1,0,1,1,1,1])\nwithElitism = False\nshouldCrossover = False\ncrossoverProbability = 0\ncrossoverRangeStart = 0\ncrossoverRangeEnd = zero.size - 1\nshouldMutate = False\nmutationProbability = 0\n#-------------------------------------------------------\n\n#DEFINIÇÃO DE FUNÇÕES\n\n#Calculo da aptidão da população\ndef fitnessCalculation(population):\n\tfitnessList = []\n\tbestFitness = 0\n\tbestIndex = 0\n\tfor i in range(len(population)):\n\t\tfitnessList.append(zero.size - BinaryString.hammingDistance(zero,population[i]))\n\t\tif fitnessList[i] >= bestFitness:\n\t\t\tbestFitness = fitnessList[i]\n\t\t\tbestIndex = i\n\treturn [fitnessList, bestIndex]\n\n#Função que retorna o indicie da melhor aptidão de uma lista de fitness\ndef getBestFitnessIndex(fitnessList):\n\tbestFitness = 0\n\tbestIndex = 0\n\tfor i in range(len(fitnessList)):\t\t\n\t\tif fitnessList[i] >= bestFitness:\n\t\t\tbestFitness = fitnessList[i]\n\t\t\tbestIndex = i\n\treturn bestIndex\n\n#Seleção por roleta\ndef rouletteWheelSelection(population, fitnessList):\n\tif(len(population) != len(fitnessList)):\n\t\traise Exception(\"Population and fitness list must be the same length\")\n\n\twheelSections = []\n\tselectedGenes = []\n\tnewPopulation = []\n\ttotalFitness = sum(fitnessList)\n\n\tfor i in range(len(fitnessList)):\n\t\t#Definição das seções da roda \n\t\twheelSections.append(360*fitnessList[i] / float(totalFitness))\n\t\t#Sorteio do individuo para nova população\n\t\tselectedGenes.append(random() * 360)\n\t\t#Ajuste dos valores para obter valores entre 0 e 360\n\t\tif i > 0:\n\t\t\twheelSections[i] = wheelSections[i-1] + wheelSections[i]\n\t\n\t#Substituicao dos individuos pelos sorteados\n\tfor i in range(len(selectedGenes)):\n\t\tj = 0\n\t\twhile j < len(wheelSections) and wheelSections[j] <= selectedGenes[i]:\n\t\t\tj+=1\n\t\tnewPopulation.append(deepcopy(population[j]))\n\n\t#Caso o elitismo esteja habilitado, preserva o melhor gene na primeira posição\n\tif withElitism:\n\t\tbestIndex = getBestFitnessIndex(fitnessList)\n\t\tnewPopulation[0] = population[bestIndex]\n\n\treturn newPopulation\n\n#Crossover dois a dois\ndef crossover2by2(population, fitnessList):\n\t#Retorna a população sem alteração caso não deva fazer o crossover\n\tif not shouldCrossover:\n\t\treturn population\n\n\tnewPopulation = population\n\t#Para cada 2 individuos da população faça\n\tfor i in range(0, len(population), 2):\n\t\t#Verifica se deve aplicar crossover para o par\n\t\tshould = random() <= crossoverProbability\n\t\tif should:\n\t\t\t#Se sim, gera um ponto e cruza os indivíduos\n\t\t\tpoint = randint(crossoverRangeStart, crossoverRangeEnd)\n\t\t\t[newPopulation[i], newPopulation[i+1]] = BinaryString.crossover(population[i],population[i+1],point)\n\treturn newPopulation\n\n#Mutação simple um a um\ndef mutate(population):\n\t#Retorna a população sem alteração caso não deva ocorrer mutação\n\tif not shouldMutate:\n\t\treturn population\n\n\t#Se o elitismo estiver habilitado não aplica a mutação para o melhor indivíduo\n\tif withElitism:\n\t\t[fitnessList, bestIndex] = fitnessCalculation(population)\n\t\t#Para cada individuo da população faça\n\t\tfor i in range(len(population)):\n\t\t\tif i != bestIndex:\n\t\t\t\t#Aplica a função de mutação com a probabilidade dada\n\t\t\t\tpopulation[i].mutate(mutationProbability)\n\telse:\t\t\n\t\t#Para cada individuo da população faça\n\t\tfor i in range(len(population)):\n\t\t\t#Aplica a função de mutação com a probabilidade dada\n\t\t\tpopulation[i].mutate(mutationProbability)\t\n\n\treturn population\n\n#Verificação de objetivo atingido\ndef equalsZero(fitnessList, bestIndex):\n\tif (fitnessList[bestIndex] == 12):\n\t\treturn True\n\treturn False\n\n#Retorna a melhor aptidão de uma comparação\ndef newFitnessIsBetter(fitness, newFitness):\n\tif newFitness > fitness:\n\t\treturn True\n\treturn False\n#-------------------------------------------------------\n\n#INICIO DA EXECUÇÃO\nprint(\"\\nReconhecimento de padroes com algoritmo genetico\")\nprint(\"------------------------------------------------\")\nprint(\"Aproximar ao maximo a figura 0, representado por [111101101111].\")\n\npopSize = 1\nwhile popSize % 2 == 1:\n\tpopSize = readIntMin('Tamanho da populacao: ', 1)\n\tif popSize % 2 == 1:\n\t\tprint('Populacao deve ser de tamanho par para aplicar o crossover 2 por 2!')\n\nwithElitism = readOption('\\nDeseja que a selecao permita o elitismo? (s/n)\\n','s','n')\n\nshouldCrossover = readOption('\\nDeseja que ocorra crossover dos individuos? (s/n)\\n','s','n')\t\t\n\nif shouldCrossover:\n\tcrossoverProbability = readFloatInterval('Probabilidade de ocorrer o crossover: ', 0, 1)\n\n\tcrossoverRangeStart = readIntInterval('Inicio do intervalo de indices que podem ser selecionados para o crossover: ', 0, zero.size - 1)\n\t\n\tcrossoverRangeEnd = readIntInterval('Fim do intervalo de indices que podem ser selecionados para o crossover: ', crossoverRangeStart, zero.size - 1)\nelse:\n\tcrossoverRangeStart = 0\n\tcrossoverRangeEnd = zero.size - 1\n\tcrossoverProbability = 0\n\nshouldMutate = readOption('\\nDeseja que ocorram mutacoes nos individuos? (s/n)\\n','s','n')\n\nif shouldMutate:\n\tmutationProbability = readFloatInterval(\"Probabilidade de mutacao dos individuos: \", 0, 1)\nelse:\n\tmutationProbability = 0\n\t\t\nmaxIt = readIntMin('\\nNumero maximo de iteracoes do algoritmo: ', 1)\n\nmultipleExecutions = readOption('\\nDeseja executar diversas vezes com esse parametros para obter estatisticas? (s/n)\\n','s','n')\n\nif multipleExecutions:\n\tn = readIntMin('Numero de execucoes do algoritmo: ', 1)\n\titCountList = []\n\titFitnnesList = []\n\titAvgBestFitnessList = []\n\tdidtnMakeIt = 0\n\tprint('\\nExecutando...')\n\tnextPoint = 0\t\n\tstart = time.time()\n\tfor i in range(n):\t\t\t\n\t\tpopulation = []\n\t\tfor j in range(popSize):\n\t\t\tpopulation.append(BinaryString.newRandom(zero.size))\n\n\t\t[population, bestGene, bestFitness, lastFitnessList, lastBestGeneIndex, generationCount, avgFitnessList, bestFitnessList] = geneticAlgorithm(population, maxIt, rouletteWheelSelection, crossover2by2, mutate, fitnessCalculation, equalsZero, newFitnessIsBetter)\n\n\t\tif bestFitness != 12:\n\t\t\tdidtnMakeIt += 1\t\t\t\t\n\t\t\n\t\titAvgBestFitnessList.append(sum(bestFitnessList)/len(bestFitnessList))\n\t\titFitnnesList.append(bestFitness)\n\t\titCountList.append(generationCount)\n\n\t\tprct = float(i)/n\n\t\tif(prct >= nextPoint):\n\t\t\tpointTime = time.time()\t\t\t\t\t\t\n\t\t\tprint('['+secondsToString(pointTime - start)+'] - '+str(100*prct)+'%')\n\t\t\tnextPoint += 0.1\n\n\tend = time.time()\n\telapsed = end - start\n\tprint('['+secondsToString(elapsed)+'] - Finalizado\\n')\n\n\tavgItCount = float(sum(itCountList))/len(itCountList)\n\tavgItFitness = sum(itFitnnesList)/len(itFitnnesList)\n\n\tdevItFitness = 0\n\tdevItCount = 0\n\tfor i in range(len(itFitnnesList)):\n\t\tdevItFitness += (itFitnnesList[i] - avgItFitness)**2\n\t\tdevItCount += (itCountList[i] - avgItCount)**2\n\t\n\tdevItFitness = math.sqrt(devItFitness/len(itFitnnesList))\n\tdevItCount = math.sqrt(devItCount/len(itCountList))\n\n\n\tprint('\\nMedia de iteracoes para cada execucao: '+str(avgItCount))\n\tprint('Desvio padrao de iteracoes para cada execucao: '+str(devItCount))\n\tprint('\\nMedia de aptidao para cada execucao: '+str(avgItFitness))\n\tprint('Desvio padrao de aptidao para cada execucao: '+str(devItFitness))\n\n\tprint('\\nExecucoes que pararam por atingir o maximo de iteracoes: '+str(didtnMakeIt) + ' de '+str(n))\n\n\t\n\tplotGraphs = readOption('\\nDeseja ver o grafico da quantidade de iteracoes para cada execucao? (s/n)\\n','s','n')\n\n\tif plotGraphs:\n\t\tx = range(len(itCountList))\n\t\tmean = len(x) * [avgItCount]\n\t\tplt.bar(x,itCountList)\n\t\tplt.plot(x,mean, 'r-', label=\"Mean\")\n\t\tplt.ylabel('Iterations')\n\t\tplt.xlabel('Execution')\n\t\tplt.legend()\n\t\tplt.show()\n\n\tplotGraphs = readOption('\\nDeseja ver o grafico do fitness para cada execucao? (s/n)\\n','s','n')\n\n\tif plotGraphs:\n\t\tx = range(len(itFitnnesList))\n\t\tmeanArray = len(x) * [avgItFitness]\n\t\tplt.plot(x,itFitnnesList, label=\"Best fitness this iteration\")\n\t\tplt.plot(x,itAvgBestFitnessList, label=\"Average fitness this iteration\")\n\t\tplt.ylabel('Fitness')\n\t\tplt.xlabel('Execution')\n\t\tplt.legend()\n\t\tplt.show()\nelse:\n\tpopulation = []\n\tfor i in range(popSize):\n\t\tpopulation.append(BinaryString.newRandom(zero.size))\n\n\tprint('\\nExecutando...')\n\tstart = time.time()\n\t[population, bestGene, bestFitness, lastFitnessList, lastBestGeneIndex, generationCount, avgFitnessList, bestFitnessList] = geneticAlgorithm(population, maxIt, rouletteWheelSelection, crossover2by2, mutate, fitnessCalculation, equalsZero, newFitnessIsBetter)\n\tend = time.time()\n\telapsed = (end - start)*1000\n\tprint('Finalizado em '+str(elapsed)+'ms\\n')\n\tprint('Geracoes executadas: '+str(generationCount))\n\tprint('Melhor resultado encontrado: '+ bestGene.toString()+' - Fitness: '+ str(bestFitness))\n\n\tprintResults = readOption('\\nDeseja ver a ultima geracao do algoritmo? (s/n)\\n','s','n')\n\n\tif printResults:\n\t\tprint('\\nPopulacao final: ')\n\t\tfor i in range(len(population)):\n\t\t\tprint('['+population[i].toString() + '] - Fitness: '+ str(lastFitnessList[i]))\n\t\tprint('Melhor gene:\\n[' + population[lastBestGeneIndex].toString() +'] - Fitness:'+ str(lastFitnessList[lastBestGeneIndex]))\n\n\tplotGraphs = readOption('\\nDeseja ver o grafico com a media de desempenho e o melhor desempenho de cada geracao? (s/n)\\n','s','n')\n\n\tif plotGraphs:\n\t\tx = range(len(avgFitnessList))\n\t\tplt.plot(x,avgFitnessList, label=\"Average fitness\")\n\t\tplt.plot(x,bestFitnessList, label=\"Best fitness\")\n\t\tplt.ylabel('Fitness')\n\t\tplt.xlabel('Generation')\n\t\tplt.legend()\n\t\tplt.show()\n\nprint('\\nFinalizando script...')\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
xxxnell/how-do-vits-work
|
[
"dbe209871315e7b86d6fe2d7b90592d3ca23fb14"
] |
[
"models/pit.py"
] |
[
"\"\"\"\nThis model is based on the implementation of https://github.com/lucidrains/vit-pytorch.\n\"\"\"\nfrom math import sqrt\n\nimport torch\nfrom torch import nn\n\nfrom einops import rearrange\n\nfrom models.layers import Lambda\nfrom models.embeddings import ConvEmbedding, CLSToken, AbsPosEmbedding\nfrom models.attentions import Transformer\n\n\nclass DepthwiseConv2d(nn.Module):\n\n def __init__(self, dim_in, dim_out, kernel_size, padding, stride, bias=True):\n super().__init__()\n self.net = nn.Sequential(\n nn.Conv2d(dim_in, dim_out,\n kernel_size=kernel_size, padding=padding, groups=dim_in, stride=stride, bias=bias),\n # nn.Conv2d(dim_out, dim_out, kernel_size=1, bias=bias)\n )\n\n def forward(self, x):\n return self.net(x)\n\n\nclass Pool(nn.Module):\n\n def __init__(self, dim_in, dim_out):\n super().__init__()\n self.cls_ff = nn.Linear(dim_in, dim_out)\n self.downsample = DepthwiseConv2d(dim_in, dim_out, kernel_size=3, stride=2, padding=1)\n\n def forward(self, x):\n cls_token, spat_tokens = x[:, :1], x[:, 1:]\n _, s, _ = spat_tokens.shape\n h, w = int(sqrt(s)), int(sqrt(s))\n\n cls_token = self.cls_ff(cls_token)\n\n spat_tokens = rearrange(spat_tokens, 'b (h w) c -> b c h w', h=h, w=w)\n spat_tokens = self.downsample(spat_tokens)\n spat_tokens = rearrange(spat_tokens, 'b c h w -> b (h w) c')\n\n return torch.cat((cls_token, spat_tokens), dim=1)\n\n\nclass PiT(nn.Module):\n\n def __init__(self, *,\n image_size, patch_size, num_classes, dims, depths, heads, dims_head, dims_mlp,\n channel=3, dropout=0.0, emb_dropout=0.0, sd=0.0, stride=None,\n embedding=None, classifier=None,\n name=\"pit\"):\n super().__init__()\n self.name = name\n\n if len(depths) != 3:\n msg = \"`depths` must be a tuple of integers with len of 3, \" + \\\n \"specifying the number of blocks before each downsizing.\"\n raise Exception(msg)\n dims = self._to_tuple(dims, len(depths))\n dims = (dims[0], *dims) # (stem_dim, *stage_dims)\n heads = self._to_tuple(heads, len(depths))\n dims_head = self._to_tuple(dims_head, len(depths))\n dims_mlp = self._to_tuple(dims_mlp, len(depths))\n idxs = [[j for j in range(sum(depths[:i]), sum(depths[:i + 1]))] for i in range(len(depths))]\n sds = [[sd * j / (sum(depths) - 1) for j in js] for js in idxs]\n pools = [False] + [True] * (len(depths) - 1)\n\n self.embedding = nn.Sequential(\n ConvEmbedding(patch_size, dims[0], channel=channel, stride=stride),\n CLSToken(dims[0]),\n AbsPosEmbedding(image_size, patch_size, dims[0], stride=stride),\n nn.Dropout(emb_dropout) if emb_dropout > 0.0 else nn.Identity()\n ) if embedding is None else embedding\n\n self.transformers = []\n for i in range(len(depths)):\n if pools[i]:\n self.transformers.append(Pool(dims[i], dims[i+1]))\n for j in range(depths[i]):\n self.transformers.append(\n Transformer(dims[i+1],\n heads=heads[i], dim_head=dims_head[i], dim_mlp=dims_mlp[i],\n dropout=dropout, sd=sds[i][j])\n )\n self.transformers = nn.Sequential(*self.transformers)\n\n self.classifier = nn.Sequential(\n Lambda(lambda x: x[:, 0]),\n nn.LayerNorm(dims[-1]),\n nn.Linear(dims[-1], num_classes)\n ) if classifier is None else classifier\n\n def forward(self, x):\n x = self.embedding(x)\n x = self.transformers(x)\n x = self.classifier(x)\n\n return x\n\n @staticmethod\n def _to_tuple(v, l):\n return v if isinstance(v, tuple) or isinstance(v, list) else (v,) * l\n\n\ndef tiny(num_classes=1000, name=\"pit_ti\",\n image_size=224, patch_size=16, channel=3, stride=8,\n dims=(64, 128, 256), depths=(2, 6, 4), heads=(2, 4, 8), dims_head=(32, 32, 32),\n dims_mlp=(256, 512, 1024), dropout=0.0, emb_dropout=0.0, sd=0.0,\n **block_kwargs):\n return PiT(\n image_size=image_size, patch_size=patch_size, channel=channel, stride=stride,\n num_classes=num_classes, depths=depths,\n dims=dims, heads=heads, dims_head=dims_head,\n dims_mlp=dims_mlp, dropout=dropout, emb_dropout=emb_dropout, sd=sd,\n name=name, **block_kwargs\n )\n\n\ndef xsmall(num_classes=1000, name=\"pit_xs\",\n image_size=224, patch_size=16, channel=3, stride=8,\n dims=(96, 192, 384), depths=(2, 6, 4), heads=(2, 4, 8), dims_head=(48, 48, 48),\n dims_mlp=(384, 768, 1024), dropout=0.0, emb_dropout=0.0, sd=0.0,\n **block_kwargs):\n return PiT(\n image_size=image_size, patch_size=patch_size, channel=channel, stride=stride,\n num_classes=num_classes, depths=depths,\n dims=dims, heads=heads, dims_head=dims_head,\n dims_mlp=dims_mlp, dropout=dropout, emb_dropout=emb_dropout, sd=sd,\n name=name, **block_kwargs\n )\n\n\ndef small(num_classes=1000, name=\"pit_s\",\n image_size=224, patch_size=16, channel=3, stride=8,\n dims=(144, 288, 576), depths=(2, 6, 4), heads=(3, 6, 12), dims_head=(48, 48, 48),\n dims_mlp=(576, 1152, 2304), dropout=0.0, emb_dropout=0.0, sd=0.0,\n **block_kwargs):\n return PiT(\n image_size=image_size, patch_size=patch_size, channel=channel, stride=stride,\n num_classes=num_classes, depths=depths,\n dims=dims, heads=heads, dims_head=dims_head,\n dims_mlp=dims_mlp, dropout=dropout, emb_dropout=emb_dropout, sd=sd,\n name=name, **block_kwargs\n )\n\n\ndef base(num_classes=1000, name=\"pit_base\",\n image_size=224, patch_size=16, channel=3, stride=7,\n dims=(256, 512, 1024), depths=(3, 6, 4), heads=(4, 8, 16), dims_head=(64, 64, 64),\n dims_mlp=(256, 512, 1024), dropout=0.0, emb_dropout=0.0, sd=0.0,\n **block_kwargs):\n return PiT(\n image_size=image_size, patch_size=patch_size, channel=channel, stride=stride,\n num_classes=num_classes, depths=depths,\n dims=dims, heads=heads, dims_head=dims_head,\n dims_mlp=dims_mlp, dropout=dropout, emb_dropout=emb_dropout, sd=sd,\n name=name, **block_kwargs\n )\n"
] |
[
[
"torch.nn.Sequential",
"torch.nn.Dropout",
"torch.cat",
"torch.nn.Conv2d",
"torch.nn.LayerNorm",
"torch.nn.Linear",
"torch.nn.Identity"
]
] |
auesro/ABRS
|
[
"980ec3e225021a6d1566d51fe0e3a03443233d9f"
] |
[
"ST_image_to_ST_feature_batch.py"
] |
[
"# extract ST Features from ST images (dim reduction)\r\n\r\nimport numpy as np\r\nimport scipy\r\nfrom scipy import ndimage\r\nfrom scipy import misc\r\nimport pickle\r\nimport time\r\nimport matplotlib.pyplot as plt\r\nimport cv2\r\nimport os\r\nimport natsort\r\n\r\nfrom ABRS_modules import discrete_radon_transform\r\nfrom ABRS_modules import subplot_images\r\n\r\ndef project_to_basis_fun (dirPathInput,dirPathU,dirPathOutput,numbFiles):\r\n\r\n \r\n UDirPathFileName = dirPathU + '\\\\' + 'USVdictTrainingSet_ST_Gr33a_dust_th0_10_averSubT2_binVar';normalizeByMax = 0;\r\n\r\n\r\n with open(UDirPathFileName, \"rb\") as f:\r\n USVdict = pickle.load(f)\r\n\r\n U=USVdict['U'];\r\n \r\n fileList = natsort.natsorted(os.listdir(dirPathInput),reverse=False) #on 12/10/2018 #pip install natsort\r\n\r\n featureMat = np.zeros((30,numbFiles*50));\r\n posMat = np.zeros((2,numbFiles*50));\r\n maxMovementMat = np.zeros((1,numbFiles*50));\r\n \r\n ind = 0;\r\n\r\n for fl in range(0, numbFiles, 1):\r\n\r\n inputFileName = fileList[fl];\r\n print (inputFileName);\r\n\r\n fileDirPathInputName = dirPathInput + '\\\\' + inputFileName; #fir Win\r\n #fileDirPathInputName = dirPathInput + '/' + inputFileName; # for Mac\r\n\r\n with open(fileDirPathInputName, \"rb\") as f:\r\n dictST = pickle.load(f)\r\n \r\n sMRecSp = dictST[\"sMRecSp\"]; \r\n sMRec = sMRecSp.todense(); #from scipy\r\n sMRec = np.nan_to_num(sMRec);\r\n\r\n dictPosRec = dictST[\"dictPosRec\"];\r\n xPosRec = dictPosRec[\"xPosRec\"];\r\n yPosRec = dictPosRec[\"yPosRec\"];\r\n\r\n maxMovementRec = dictST[\"maxMovementRec\"];\r\n\r\n for i in range(0, sMRec.shape[0]):\r\n\r\n imST = np.reshape(sMRec[i,:],(80,80));\r\n imR = discrete_radon_transform(imST, 80);\r\n F = np.fft.fft(imR,axis = 0);\r\n FF = np.fft.fft(np.absolute(F),axis = 1);\r\n aFF = np.absolute(FF);\r\n if normalizeByMax == 1:\r\n naFF = aFF/np.max(np.max(aFF));\r\n if normalizeByMax == 0:\r\n naFF = aFF;\r\n naFFNZ = np.nan_to_num(naFF);\r\n\r\n vecFF = np.reshape(np.absolute(naFFNZ),(80*80,1));\r\n\r\n for dim in range(0,30):\r\n\r\n Udim = U[:,dim];\r\n\r\n prDim = np.dot(Udim,vecFF);prDim = prDim[0];\r\n \r\n featureMat[dim,ind] = prDim;\r\n\r\n posMat[0,ind] = xPosRec[i];\r\n posMat[1,ind] = yPosRec[i];\r\n\r\n maxMovementMat[0,ind] = maxMovementRec[i];\r\n\r\n ind = ind +1;\r\n \r\n STF_30_posXY_dict = {\"featureMat\" : featureMat, \"posMat\" : posMat, \"maxMovementMat\" : maxMovementMat};\r\n \r\n outputFileName = 'STF_30_posXY_dict' + inputFileName[5:];\r\n\r\n newPath = dirPathOutput + '\\\\' + outputFileName;\r\n \r\n with open(newPath, \"wb\") as f:\r\n pickle.dump(STF_30_posXY_dict, f)\r\n \r\n return STF_30_posXY_dict \r\n\r\n\r\nnumbFiles=720; #number of sMRec files in ST image folders #crimson data in Data_demo\r\n\r\n#pathToABRSfolder = 'INSERT PATH TO ABRS FOLDER HERE'\r\npathToABRSfolder = 'C:\\\\Users\\\\ravbar\\\\Desktop\\\\ABRS_GH_out'\r\n\r\nfirstFolder = 0; \r\n\r\ndirPathInput = pathToABRSfolder + '\\\\Data_demo\\\\ST' #ST image folder; contains subfolders with ST images\r\n\r\ndirPathU = pathToABRSfolder + '\\\\Filters'; # path to Filters (basis from SVD training; U matrix)\r\n\r\ndirPathOutput = pathToABRSfolder + '\\\\Data\\\\ST_features' # output folder where feature files will be written \r\n\r\nSTFolderList = os.listdir(dirPathInput);\r\nsz = np.shape(STFolderList);sizeSTFolder = sz[0];\r\n\r\nfor fld in range(firstFolder, sizeSTFolder):\r\n\r\n currentSTFolder = STFolderList[fld];\r\n\r\n dirPathInputSTfolder = dirPathInput + '\\\\' + currentSTFolder;\r\n\r\n checkIfFolder = os.path.isdir(dirPathInputSTfolder);\r\n\r\n if checkIfFolder == True:\r\n \r\n STF_30_posXY_dict = project_to_basis_fun (dirPathInputSTfolder,dirPathU,dirPathOutput,numbFiles) \r\n\r\n#imB=U[:,4].reshape(80,80);plt.matshow(imB[5:75,5:75], interpolation=None, aspect='auto');plt.show()\r\n"
] |
[
[
"numpy.dot",
"numpy.absolute",
"numpy.fft.fft",
"numpy.reshape",
"numpy.nan_to_num",
"numpy.max",
"numpy.shape",
"numpy.zeros"
]
] |
eliaswalyba/2021-deep-learning-gift-course
|
[
"c17c4370f0d1032ce7c3ea559f331c7318abba9a"
] |
[
"exercises/03-object-detection/03-Pedestrian-Counting/src/utils.py"
] |
[
"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport tensorflow as tf\r\n\r\ndef run_inference_for_single_image(image, graph):\r\n \"\"\"Computes the prediction of the object detection on a single image\r\n\r\n Parameters:\r\n image (np.array): An image in shape [height, width, 3]\r\n\tgraph: a graph object from TensorFlow\r\n\r\n Returns:\r\n dict: a dict containing the number of detections, their classes, boxes and scores\r\n\r\n \"\"\"\r\n\r\n with graph.as_default():\r\n with tf.Session() as sess:\r\n # Get handles to input and output tensors\r\n ops = tf.get_default_graph().get_operations()\r\n all_tensor_names = {output.name for op in ops for output in op.outputs}\r\n tensor_dict = {}\r\n for key in ['num_detections', 'detection_boxes', 'detection_scores',\r\n 'detection_classes', 'detection_masks']:\r\n tensor_name = key + ':0'\r\n if tensor_name in all_tensor_names:\r\n tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(tensor_name)\r\n if 'detection_masks' in tensor_dict:\r\n # The following processing is only for single image\r\n detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])\r\n detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])\r\n # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.\r\n real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)\r\n detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])\r\n detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])\r\n detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(\r\n detection_masks, detection_boxes, image.shape[0], image.shape[1])\r\n detection_masks_reframed = tf.cast(\r\n tf.greater(detection_masks_reframed, 0.5), tf.uint8)\r\n # Follow the convention by adding back the batch dimension\r\n tensor_dict['detection_masks'] = tf.expand_dims(\r\n detection_masks_reframed, 0)\r\n image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')\r\n \r\n # Run inference\r\n output_dict = sess.run(tensor_dict,\r\n feed_dict={image_tensor: np.expand_dims(image, 0)})\r\n\r\n # all outputs are float32 numpy arrays, so convert types as appropriate\r\n output_dict['num_detections'] = int(output_dict['num_detections'][0])\r\n output_dict['detection_classes'] = output_dict[\r\n 'detection_classes'][0].astype(np.uint8)\r\n output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\r\n output_dict['detection_scores'] = output_dict['detection_scores'][0]\r\n if 'detection_masks' in output_dict:\r\n output_dict['detection_masks'] = output_dict['detection_masks'][0]\r\n return output_dict\r\n"
] |
[
[
"numpy.expand_dims",
"tensorflow.greater",
"tensorflow.slice",
"tensorflow.cast",
"tensorflow.expand_dims",
"tensorflow.squeeze",
"tensorflow.Session",
"tensorflow.get_default_graph"
]
] |
akshaybahadur21/BigDL
|
[
"55b60e2a62d89ae62d706833e3bcf8d2674d6eea"
] |
[
"python/nano/src/bigdl/nano/pytorch/runtime_binding/onnxrt_inference.py"
] |
[
"#\n# Copyright 2016 The BigDL Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom pytorch_lightning import LightningModule\nimport torch\nfrom torch.utils.data import DataLoader\nfrom bigdl.nano.pytorch.lightning import LightningModuleFromTorch\nimport onnxruntime as ort\nimport onnx\nfrom functools import partial, wraps\nimport warnings\nimport torch\nimport math\nimport numpy as np\nimport inspect\n\n\nONNXRT_BINDED_COMPONENTS = ['_ortsess_up_to_date',\n '_ortsess',\n '_onnx_graph',\n '_build_ortsess',\n 'update_ortsess',\n '_forward_onnx',\n 'to_quantized_onnx'\n ]\n\n\n# internal function to build an ortsess\ndef _build_ortsess(self,\n input_sample=None,\n file_path=\"model.onnx\",\n sess_options=None,\n **kwargs):\n '''\n Internal function to build a ortsess and bind to the lightningmodule.\n\n :param input_sample: torch.Tensor or a list for the model tracing.\n :param file_path: The path to save onnx model file.\n :param sess_options: ortsess options in ort.SessionOptions type\n :param **kwargs: will be passed to torch.onnx.export function.\n '''\n\n # quantized model will not be supported\n if \"_quantized_model\" in dir(self):\n self._quantized_model = None\n self._quantized_model_up_to_date = False\n\n if input_sample is None and self.example_input_array is not None:\n input_sample = self.example_input_array # use internal example_input_array\n else:\n self.example_input_array = input_sample # set example_input_array for future usage\n\n assert input_sample is not None,\\\n 'You should set either input_sample or self.example_input_array'\n\n dynamic_axes = {}\n for forward_arg in self._forward_args:\n dynamic_axes[forward_arg] = {0: 'batch_size'} # set all dim0 to be dynamic\n dynamic_axes['output'] = {0: 'batch_size'}\n\n default_onnx_export_args = {'export_params': True,\n 'opset_version': 11, # version = 11 by default\n 'do_constant_folding': True,\n 'input_names': self._forward_args,\n 'output_names': ['output'], # TODO: only support single output\n 'dynamic_axes': dynamic_axes}\n default_onnx_export_args.update(kwargs)\n\n torch.onnx.export(self,\n input_sample,\n file_path,\n **default_onnx_export_args)\n\n self._ortsess = ort.InferenceSession(file_path, sess_options=sess_options)\n self._onnx_graph = onnx.load(file_path)\n self._ortsess_up_to_date = True\n\n\n# external method to update(& rebuild) ortsess\ndef update_ortsess(self,\n input_sample=None,\n file_path=\"model.onnx\",\n sess_options=None,\n **kwargs):\n '''\n Update the onnxruntime session options and rebuild the session.\n Users may also want to call this method before `inference(..., onnx=True`)`\n to avoid implicit building.\n\n :param input_sample: torch.Tensor for the model tracing.\n :param file_path: The path to save onnx model file.\n :param sess_options: ortsess options in ort.SessionOptions type.\n :param **kwargs: will be passed to torch.onnx.export function.\n '''\n self._build_ortsess(input_sample=input_sample,\n file_path=file_path,\n sess_options=sess_options,\n **kwargs)\n\n\n# on_fit_start (LightningModule method overwrite)\ndef _onnx_on_fit_start(self):\n self._ortsess_up_to_date = False\n self._ortsess = None\n self._quantized_ortsess_up_to_date = False\n self._default_ortsess_inference_quantize = False\n self._quantized_ortsess = None\n self.exit_onnx()\n\n\ndef _onnx_on_train(self, mode=True):\n self.exit_onnx()\n self._ortsess_up_to_date = False\n self._ortsess = None\n self._quantized_ortsess_up_to_date = False\n self._default_ortsess_inference_quantize = False\n self._quantized_ortsess = None\n\n\ndef to_quantized_onnx(self, file_path):\n if self._quantized_ortsess_up_to_date:\n onnx.save(self._q_onnx_model, file_path)\n else:\n raise RuntimeError(\"Please run trainer.quantize again since \"\n \"the quantized onnxruntime session is out-of-date.\")\n\n\ndef _forward_onnx(self, *args):\n ort_inputs = {}\n for i, ort_input_item in enumerate(args):\n if isinstance(ort_input_item, torch.Tensor):\n ort_input_item = ort_input_item.numpy()\n ort_inputs[self._forward_args[i]] = ort_input_item\n ort_outs = self._ortsess.run(None, ort_inputs)\n return torch.from_numpy(ort_outs[0])\n\n\ndef _forward_onnx_quantized(self, *args):\n ort_inputs = {}\n for i, ort_input_item in enumerate(args):\n if isinstance(ort_input_item, torch.Tensor):\n ort_input_item = ort_input_item.numpy()\n ort_inputs[self._forward_args[i]] = ort_input_item\n ort_outs = self._quantized_ortsess.run(None, ort_inputs)\n return torch.from_numpy(ort_outs[0])\n\n\ndef eval_onnx(self, input_sample=None, file_path=\"model.onnx\",\n sess_options=None, quantize=None, **kwargs):\n '''\n This method change the `forward` method to an onnxruntime backed forwarding.\n\n >>> model.eval_onnx(quantize=True/False)\n >>> pred = model(x) # onnxruntime forwarding\n >>> model.exit_onnx()\n\n :param input_sample: (optional) a torch dataloader, torch.Tensor or a\n list of them for the model tracing.\n :param file_path: (optional) The path to save onnx model file.\n :param sess_options: (optional) ortsess options in ort.SessionOptions type.\n :param quantize: Bool, state if we need to use quantized onnxruntime session.\n :param **kwargs: (optional) will be passed to torch.onnx.export function.\n '''\n # build ortsess\n quantize = quantize if quantize is not None else self._default_ortsess_inference_quantize\n if quantize:\n assert self._quantized_ortsess_up_to_date, \\\n \"Please run trainer.quantize again since the, \" \\\n \"quantized onnxruntime session is out-of-date.\"\n else:\n # change to eval mode\n self.eval()\n # get input_sample\n if isinstance(input_sample, DataLoader):\n input_sample = tuple(next(iter(input_sample))[:-1])\n if input_sample is None and self.example_input_array:\n input_sample = self.example_input_array\n if input_sample is None and self.trainer is None:\n raise RuntimeError(\"You must specify an input_sample or call `Trainer.fit` \"\n \"on the model first to use `eval_onnx`\")\n if input_sample is None and self.trainer.train_dataloader:\n input_sample = tuple(next(iter(self.trainer.train_dataloader))[:-1])\n if input_sample is None and self.trainer.datamodule:\n input_sample = tuple(next(iter(self.trainer.datamodule.train_dataloader()))[:-1])\n assert input_sample is not None,\\\n \"You must state an input_sample or fit on the model to use `eval_onnx`.\"\n self._build_ortsess(input_sample=input_sample,\n file_path=file_path,\n sess_options=sess_options,\n **kwargs)\n\n if quantize:\n self.forward = self._forward_onnx_quantized\n else:\n self.forward = self._forward_onnx\n\n\ndef exit_onnx(self):\n self.forward = self._torch_forward\n\n\ndef bind_onnxrt_methods(pl_model: LightningModule, q_onnx_model=None, sess_options=None):\n # class type check\n # assert isinstance(pl_model, LightningModule),\\\n # f\"onnxruntime support is only valid for a LightningModule, but found a {type(pl_model)}.\"\n\n if q_onnx_model:\n onnx.save(q_onnx_model, \"_model_quantized_cache.onnx\")\n pl_model._q_onnx_model = q_onnx_model\n pl_model._quantized_ortsess = ort.InferenceSession(\"_model_quantized_cache.onnx\",\n sess_options=sess_options)\n pl_model._quantized_ortsess_up_to_date = True\n pl_model._default_ortsess_inference_quantize = True\n\n # if all needed method has been binded, return the same model\n if set(ONNXRT_BINDED_COMPONENTS) <= set(dir(pl_model)):\n return pl_model\n\n # check conflicts\n for component in ONNXRT_BINDED_COMPONENTS:\n if component in dir(pl_model):\n warnings.warn(f\"{component} method/property will be replaced. You may rename your\"\n \" customized attributes or methods and call `Trainer.compile again `\"\n \"to avoid being overwrite.\")\n\n # additional attributes\n pl_model._ortsess_up_to_date = False # indicate if we need to build ortsess again\n pl_model._ortsess = None # ortsess instance\n pl_model._default_ortsess_inference_quantize = False\n pl_model._onnx_graph = None # onnx graph for quantization\n if isinstance(pl_model, LightningModuleFromTorch): # forward param list for compiled model\n pl_model._forward_args = inspect.getfullargspec(pl_model.model.forward).args[1:]\n else: # forward param list\n pl_model._forward_args = inspect.getfullargspec(pl_model.forward).args[1:]\n\n # additional methods\n pl_model._build_ortsess = partial(_build_ortsess, pl_model)\n pl_model.update_ortsess = partial(update_ortsess, pl_model)\n pl_model._onnx_on_fit_start = partial(_onnx_on_fit_start, pl_model)\n pl_model.eval_onnx = partial(eval_onnx, pl_model)\n pl_model._forward_onnx = partial(_forward_onnx, pl_model)\n pl_model.exit_onnx = partial(exit_onnx, pl_model)\n pl_model._onnx_on_train = partial(_onnx_on_train, pl_model)\n pl_model._forward_onnx_quantized = partial(_forward_onnx_quantized, pl_model)\n pl_model.to_quantized_onnx = partial(to_quantized_onnx, pl_model)\n\n return pl_model\n"
] |
[
[
"torch.onnx.export",
"torch.from_numpy"
]
] |
WenRichard/EasyTransfer
|
[
"6909238c45b5708968f955b7d971a79b25434597"
] |
[
"scripts/天池大赛专区/convert_csv_to_tfrecords.py"
] |
[
"import tensorflow as tf\nfrom easytransfer import base_model\nfrom easytransfer.datasets import CSVReader, TFRecordWriter\nfrom easytransfer import preprocessors\n\nclass FinetuneSerialization(base_model):\n def __init__(self, **kwargs):\n super(FinetuneSerialization, self).__init__(**kwargs)\n\n def build_logits(self, features, mode=None):\n preprocessor = preprocessors.get_preprocessor(self.config.tokenizer_name_or_path)\n input_ids, input_mask, segment_ids, label_ids = preprocessor(features)\n return input_ids, input_mask, segment_ids, label_ids\n\n def build_predictions(self, predict_output):\n input_ids, input_mask, segment_ids, label_ids = predict_output\n ret_dict = {\n \"input_ids\": input_ids,\n \"input_mask\": input_mask,\n \"segment_ids\": segment_ids,\n \"label_id\": label_ids,\n }\n return ret_dict\n\n\ndef main(_):\n app = FinetuneSerialization()\n\n reader = CSVReader(input_glob=app.preprocess_input_fp,\n is_training=False,\n input_schema=app.input_schema,\n batch_size=app.preprocess_batch_size)\n\n writer = TFRecordWriter(output_glob=app.preprocess_output_fp,\n output_schema=app.output_schema)\n\n app.run_preprocess(reader=reader, writer=writer)\n\nif __name__ == \"__main__\":\n tf.app.run()\n"
] |
[
[
"tensorflow.app.run"
]
] |
constantinpape/ome-zarr-py
|
[
"715f44d2519b6d71f1b79aabfef3fc8287bc87e2"
] |
[
"ome_zarr/reader.py"
] |
[
"\"\"\"Reading logic for ome-zarr.\"\"\"\n\nimport logging\nimport math\nfrom abc import ABC\nfrom typing import Any, Dict, Iterator, List, Optional, Type, Union, cast\n\nimport dask.array as da\nimport numpy as np\nfrom dask import delayed\nfrom vispy.color import Colormap\n\nfrom .io import ZarrLocation\nfrom .types import JSONDict\n\nLOGGER = logging.getLogger(\"ome_zarr.reader\")\n\n\nclass Node:\n \"\"\"Container for a representation of the binary data somewhere in the data\n hierarchy.\"\"\"\n\n def __init__(\n self,\n zarr: ZarrLocation,\n root: Union[\"Node\", \"Reader\", List[ZarrLocation]],\n visibility: bool = True,\n plate_labels: bool = False,\n ):\n self.zarr = zarr\n self.root = root\n self.seen: List[ZarrLocation] = []\n if isinstance(root, Node) or isinstance(root, Reader):\n self.seen = root.seen\n else:\n self.seen = cast(List[ZarrLocation], root)\n self.__visible = visibility\n\n # Likely to be updated by specs\n self.metadata: JSONDict = dict()\n self.data: List[da.core.Array] = list()\n self.specs: List[Spec] = []\n self.pre_nodes: List[Node] = []\n self.post_nodes: List[Node] = []\n\n # TODO: this should be some form of plugin infra over subclasses\n if Labels.matches(zarr):\n self.specs.append(Labels(self))\n if Label.matches(zarr):\n self.specs.append(Label(self))\n if Multiscales.matches(zarr):\n self.specs.append(Multiscales(self))\n if OMERO.matches(zarr):\n self.specs.append(OMERO(self))\n if plate_labels:\n self.specs.append(PlateLabels(self))\n elif Plate.matches(zarr):\n self.specs.append(Plate(self))\n self.add(zarr, plate_labels=True)\n if Well.matches(zarr):\n self.specs.append(Well(self))\n\n @property\n def visible(self) -> bool:\n \"\"\"True if this node should be displayed by default.\n\n An invisible node may have been requested by the instrument, by the\n user, or by the ome_zarr library after determining that this node\n is lower priority, e.g. to prevent too many nodes from being shown\n at once.\n \"\"\"\n return self.__visible\n\n @visible.setter\n def visible(self, visibility: bool) -> bool:\n \"\"\"\n Set the visibility for this node, returning the previous value.\n\n A change of the visibility will propagate to all subnodes.\n \"\"\"\n old = self.__visible\n if old != visibility:\n self.__visible = visibility\n for node in self.pre_nodes + self.post_nodes:\n node.visible = visibility\n return old\n\n def load(self, spec_type: Type[\"Spec\"]) -> Optional[\"Spec\"]:\n for spec in self.specs:\n if isinstance(spec, spec_type):\n return spec\n return None\n\n def add(\n self,\n zarr: ZarrLocation,\n prepend: bool = False,\n visibility: Optional[bool] = None,\n plate_labels: bool = False,\n ) -> \"Optional[Node]\":\n \"\"\"Create a child node if this location has not yet been seen.\n\n Newly created nodes may be considered higher or lower priority than\n the current node, and may be set to invisible if necessary.\n\n :param zarr: Location in the node hierarchy to be added\n :param prepend: Whether the newly created node should be given higher\n priority than the current node, defaults to False\n :param visibility: Allows setting the node (and therefore layer)\n as deactivated for initial display or if None the value of the\n current node will be propagated to the new node, defaults to None\n :return: Newly created node if this is the first time it has been\n encountered; None if the node has already been processed.\n \"\"\"\n\n if zarr in self.seen and not plate_labels:\n LOGGER.debug(f\"already seen {zarr}; stopping recursion\")\n return None\n\n if visibility is None:\n visibility = self.visible\n\n self.seen.append(zarr)\n node = Node(zarr, self, visibility=visibility, plate_labels=plate_labels)\n if prepend:\n self.pre_nodes.append(node)\n else:\n self.post_nodes.append(node)\n\n return node\n\n def write_metadata(self, metadata: JSONDict) -> None:\n for spec in self.specs:\n metadata.update(self.zarr.root_attrs)\n\n def __repr__(self) -> str:\n suffix = \"\"\n if not self.visible:\n suffix += \" (hidden)\"\n return f\"{self.zarr}{suffix}\"\n\n\nclass Spec(ABC):\n \"\"\"Base class for specifications that can be implemented by groups or arrays within\n the hierarchy.\n\n Multiple subclasses may apply.\n \"\"\"\n\n @staticmethod\n def matches(zarr: ZarrLocation) -> bool:\n raise NotImplementedError()\n\n def __init__(self, node: Node) -> None:\n self.node = node\n self.zarr = node.zarr\n LOGGER.debug(f\"treating {self.zarr} as {self.__class__.__name__}\")\n for k, v in self.zarr.root_attrs.items():\n LOGGER.info(\"root_attr: %s\", k)\n LOGGER.debug(v)\n\n def lookup(self, key: str, default: Any) -> Any:\n return self.zarr.root_attrs.get(key, default)\n\n\nclass Labels(Spec):\n \"\"\"Relatively small specification for the well-known \"labels\" group which only\n contains the name of subgroups which should be loaded as labeled images.\"\"\"\n\n @staticmethod\n def matches(zarr: ZarrLocation) -> bool:\n \"\"\"Does the Zarr Image group also include a /labels sub-group?\"\"\"\n # TODO: also check for \"labels\" entry and perhaps version?\n return bool(\"labels\" in zarr.root_attrs)\n\n def __init__(self, node: Node) -> None:\n super().__init__(node)\n label_names = self.lookup(\"labels\", [])\n for name in label_names:\n child_zarr = self.zarr.create(name)\n if child_zarr.exists():\n node.add(child_zarr)\n\n\nclass Label(Spec):\n \"\"\"An additional aspect to a multiscale image is that it can be a labeled image, in\n which each discrete pixel value represents a separate object.\"\"\"\n\n @staticmethod\n def matches(zarr: ZarrLocation) -> bool:\n \"\"\"If label-specific metadata is present, then return true.\"\"\"\n return bool(\"image-label\" in zarr.root_attrs)\n\n def __init__(self, node: Node) -> None:\n super().__init__(node)\n\n image_label = self.lookup(\"image-label\", {})\n\n image = image_label.get(\"source\", {}).get(\"image\", None)\n parent_zarr = None\n if image:\n # This is an ome mask, load the image\n parent_zarr = self.zarr.create(image)\n if parent_zarr.exists():\n LOGGER.debug(f\"delegating to parent image: {parent_zarr}\")\n node.add(parent_zarr, prepend=True, visibility=False)\n else:\n parent_zarr = None\n if parent_zarr is None:\n LOGGER.warn(f\"no parent found for {self}: {image}\")\n\n # Metadata: TODO move to a class\n colors: Dict[Union[int, bool], List[float]] = {}\n color_list = image_label.get(\"colors\", [])\n if color_list:\n for color in color_list:\n try:\n label_value = color[\"label-value\"]\n rgba = color.get(\"rgba\", None)\n if rgba:\n rgba = [x / 255 for x in rgba]\n\n if isinstance(label_value, bool) or isinstance(label_value, int):\n colors[label_value] = rgba\n else:\n raise Exception(\"not bool or int\")\n\n except Exception as e:\n LOGGER.error(f\"invalid color - {color}: {e}\")\n\n properties: Dict[int, Dict[str, str]] = {}\n props_list = image_label.get(\"properties\", [])\n if props_list:\n for props in props_list:\n label_val = props[\"label-value\"]\n properties[label_val] = dict(props)\n del properties[label_val][\"label-value\"]\n\n # TODO: a metadata transform should be provided by specific impls.\n name = self.zarr.basename()\n node.metadata.update(\n {\n \"visible\": node.visible,\n \"name\": name,\n \"color\": colors,\n \"metadata\": {\"image\": self.lookup(\"image\", {}), \"path\": name},\n }\n )\n if properties:\n node.metadata.update({\"properties\": properties})\n\n\nclass Multiscales(Spec):\n @staticmethod\n def matches(zarr: ZarrLocation) -> bool:\n \"\"\"is multiscales metadata present?\"\"\"\n if zarr.zgroup:\n if \"multiscales\" in zarr.root_attrs:\n return True\n return False\n\n def __init__(self, node: Node) -> None:\n super().__init__(node)\n\n try:\n multiscales = self.lookup(\"multiscales\", [])\n version = multiscales[0].get(\"version\", \"0.1\")\n datasets = multiscales[0][\"datasets\"]\n datasets = [d[\"path\"] for d in datasets]\n self.datasets: List[str] = datasets\n LOGGER.info(\"datasets %s\", datasets)\n except Exception as e:\n LOGGER.error(f\"failed to parse multiscale metadata: {e}\")\n return # EARLY EXIT\n\n for resolution in self.datasets:\n # data.shape is (t, c, z, y, x) by convention\n data: da.core.Array = self.array(resolution, version)\n chunk_sizes = [\n str(c[0]) + (\" (+ %s)\" % c[-1] if c[-1] != c[0] else \"\")\n for c in data.chunks\n ]\n LOGGER.info(\"resolution: %s\", resolution)\n LOGGER.info(\" - shape (t, c, z, y, x) = %s\", data.shape)\n LOGGER.info(\" - chunks = %s\", chunk_sizes)\n LOGGER.info(\" - dtype = %s\", data.dtype)\n node.data.append(data)\n\n # Load possible node data\n child_zarr = self.zarr.create(\"labels\")\n if child_zarr.exists():\n node.add(child_zarr, visibility=False)\n\n def array(self, resolution: str, version: str) -> da.core.Array:\n nested = version != \"0.1\"\n # data.shape is (t, c, z, y, x) by convention\n return self.zarr.load(resolution, nested)\n\n\nclass OMERO(Spec):\n @staticmethod\n def matches(zarr: ZarrLocation) -> bool:\n return bool(\"omero\" in zarr.root_attrs)\n\n def __init__(self, node: Node) -> None:\n super().__init__(node)\n # TODO: start checking metadata version\n self.image_data = self.lookup(\"omero\", {})\n\n try:\n model = \"unknown\"\n rdefs = self.image_data.get(\"rdefs\", {})\n if rdefs:\n model = rdefs.get(\"model\", \"unset\")\n\n channels = self.image_data.get(\"channels\", None)\n if channels is None:\n return # EARLY EXIT\n\n try:\n len(channels)\n except Exception:\n LOGGER.warn(f\"error counting channels: {channels}\")\n return # EARLY EXIT\n\n colormaps = []\n contrast_limits: Optional[List[Optional[Any]]] = [None for x in channels]\n names: List[str] = [(\"channel_%d\" % idx) for idx, ch in enumerate(channels)]\n visibles: List[bool] = [True for x in channels]\n\n for idx, ch in enumerate(channels):\n # 'FF0000' -> [1, 0, 0]\n\n color = ch.get(\"color\", None)\n if color is not None:\n rgb = [(int(color[i : i + 2], 16) / 255) for i in range(0, 6, 2)]\n # TODO: make this value an enumeration\n if model == \"greyscale\":\n rgb = [1, 1, 1]\n colormaps.append(Colormap([[0, 0, 0], rgb]))\n\n label = ch.get(\"label\", None)\n if label is not None:\n names[idx] = label\n\n visible = ch.get(\"active\", None)\n if visible is not None:\n visibles[idx] = visible and node.visible\n\n window = ch.get(\"window\", None)\n if window is not None:\n start = window.get(\"start\", None)\n end = window.get(\"end\", None)\n if start is None or end is None:\n # Disable contrast limits settings if one is missing\n contrast_limits = None\n elif contrast_limits is not None:\n contrast_limits[idx] = [start, end]\n\n node.metadata[\"name\"] = names\n node.metadata[\"visible\"] = visibles\n node.metadata[\"contrast_limits\"] = contrast_limits\n node.metadata[\"colormap\"] = colormaps\n\n except Exception as e:\n LOGGER.error(f\"failed to parse metadata: {e}\")\n\n\nclass Well(Spec):\n @staticmethod\n def matches(zarr: ZarrLocation) -> bool:\n return bool(\"well\" in zarr.root_attrs)\n\n def __init__(self, node: Node) -> None:\n super().__init__(node)\n self.well_data = self.lookup(\"well\", {})\n LOGGER.info(\"well_data: %s\", self.well_data)\n\n image_paths = [image[\"path\"] for image in self.well_data.get(\"images\")]\n field_count = len(image_paths)\n column_count = math.ceil(math.sqrt(field_count))\n row_count = math.ceil(field_count / column_count)\n\n # Use first Field for rendering settings, shape etc.\n image_zarr = self.zarr.create(image_paths[0])\n image_node = Node(image_zarr, node)\n level = 0 # load full resolution image\n numpy_type = image_node.data[level].dtype\n img_shape = image_node.data[level].shape\n\n # stitch full-resolution images into a grid\n def get_field(tile_name: str) -> np.ndarray:\n \"\"\"tile_name is 'row,col'\"\"\"\n row, col = (int(n) for n in tile_name.split(\",\"))\n field_index = (column_count * row) + col\n path = f\"{field_index}/{level}\"\n LOGGER.debug(f\"LOADING tile... {path}\")\n try:\n data = self.zarr.load(path)\n except ValueError:\n LOGGER.error(f\"Failed to load {path}\")\n data = np.zeros(img_shape, dtype=numpy_type)\n return data\n\n lazy_reader = delayed(get_field)\n\n def get_lazy_well() -> da.Array:\n lazy_rows = []\n # For level 0, return whole image for each tile\n for row in range(row_count):\n lazy_row: List[da.Array] = []\n for col in range(column_count):\n tile_name = f\"{row},{col}\"\n LOGGER.debug(f\"creating lazy_reader. row:{row} col:{col}\")\n lazy_tile = da.from_delayed(\n lazy_reader(tile_name), shape=img_shape, dtype=numpy_type\n )\n lazy_row.append(lazy_tile)\n lazy_rows.append(da.concatenate(lazy_row, axis=4))\n return da.concatenate(lazy_rows, axis=3)\n\n node.data = [get_lazy_well()]\n node.metadata = image_node.metadata\n\n\nclass Plate(Spec):\n @staticmethod\n def matches(zarr: ZarrLocation) -> bool:\n return bool(\"plate\" in zarr.root_attrs)\n\n def __init__(self, node: Node) -> None:\n super().__init__(node)\n self.get_pyramid_lazy(node)\n\n def get_pyramid_lazy(self, node: Node) -> None:\n \"\"\"\n Return a pyramid of dask data, where the highest resolution is the\n stitched full-resolution images.\n \"\"\"\n self.plate_data = self.lookup(\"plate\", {})\n LOGGER.info(\"plate_data\", self.plate_data)\n self.rows = self.plate_data.get(\"rows\")\n self.columns = self.plate_data.get(\"columns\")\n self.acquisitions = self.plate_data.get(\"acquisitions\")\n self.first_field = \"0\"\n self.row_names = [row[\"name\"] for row in self.rows]\n self.col_names = [col[\"name\"] for col in self.columns]\n\n self.well_paths = [well[\"path\"] for well in self.plate_data.get(\"wells\")]\n self.well_paths.sort()\n\n self.run = \"\"\n # TEMP - support acquisition path in plate/acq/row/col hierarchy\n # remove when we don't want to support dev versions of ome-zarr plate data\n if len(self.acquisitions) > 0:\n self.run = self.acquisitions[0].get(\"path\", \"\")\n if len(self.run) > 0 and not self.run.endswith(\"/\"):\n self.run = self.run + \"/\"\n\n self.row_count = len(self.rows)\n self.column_count = len(self.columns)\n # Get the first image...\n path = f\"{self.well_paths[0]}/{self.first_field}\"\n image_zarr = self.zarr.create(path)\n image_node = Node(image_zarr, node)\n\n self.numpy_type = self.get_numpy_type(image_node)\n img_shape = image_node.data[0].shape\n\n img_pyramid_shapes = [d.shape for d in image_node.data]\n\n LOGGER.debug(\"img_pyramid_shapes\", img_pyramid_shapes)\n\n size_y = img_shape[3]\n size_x = img_shape[4]\n\n # FIXME - if only returning a single stiched plate (not a pyramid)\n # need to decide optimal size. E.g. longest side < 1500\n TARGET_SIZE = 1500\n plate_width = self.column_count * size_x\n plate_height = self.row_count * size_y\n longest_side = max(plate_width, plate_height)\n target_level = 0\n for level, shape in enumerate(img_pyramid_shapes):\n plate_width = self.column_count * shape[-1]\n plate_height = self.row_count * shape[-2]\n longest_side = max(plate_width, plate_height)\n target_level = level\n if longest_side <= TARGET_SIZE:\n break\n\n LOGGER.debug(\"target_level\", target_level)\n\n pyramid = []\n\n # This should create a pyramid of levels, but causes seg faults!\n # for level in range(5):\n for level in [target_level]:\n\n tile_shape = img_pyramid_shapes[level]\n lazy_plate = self.get_stitched_grid(level, tile_shape)\n pyramid.append(lazy_plate)\n\n # Set the node.data to be pyramid view of the plate\n node.data = pyramid\n # Use the first image's metadata for viewing the whole Plate\n node.metadata = image_node.metadata\n\n # \"metadata\" dict gets added to each 'plate' layer in napari\n node.metadata.update({\"metadata\": {\"plate\": self.plate_data}})\n\n def get_numpy_type(self, image_node: Node) -> np.dtype:\n return image_node.data[0].dtype\n\n def get_tile_path(self, level: int, row: int, col: int) -> str:\n return (\n f\"{self.run}{self.row_names[row]}/\"\n f\"{self.col_names[col]}/{self.first_field}/{level}\"\n )\n\n def get_stitched_grid(self, level: int, tile_shape: tuple) -> da.core.Array:\n def get_tile(tile_name: str) -> np.ndarray:\n \"\"\"tile_name is 'level,z,c,t,row,col'\"\"\"\n row, col = (int(n) for n in tile_name.split(\",\"))\n path = self.get_tile_path(level, row, col)\n LOGGER.debug(f\"LOADING tile... {path}\")\n\n try:\n data = self.zarr.load(path)\n except ValueError:\n LOGGER.error(f\"Failed to load {path}\")\n data = np.zeros(tile_shape, dtype=self.numpy_type)\n return data\n\n lazy_reader = delayed(get_tile)\n\n lazy_rows = []\n # For level 0, return whole image for each tile\n for row in range(self.row_count):\n lazy_row: List[da.Array] = []\n for col in range(self.column_count):\n tile_name = f\"{row},{col}\"\n lazy_tile = da.from_delayed(\n lazy_reader(tile_name), shape=tile_shape, dtype=self.numpy_type\n )\n lazy_row.append(lazy_tile)\n lazy_rows.append(da.concatenate(lazy_row, axis=4))\n return da.concatenate(lazy_rows, axis=3)\n\n\nclass PlateLabels(Plate):\n def get_tile_path(self, level: int, row: int, col: int) -> str:\n \"\"\"251.zarr/A/1/0/labels/0/3/\"\"\"\n path = (\n f\"{self.row_names[row]}/{self.col_names[col]}/\"\n f\"{self.first_field}/labels/0/{level}\"\n )\n return path\n\n def get_pyramid_lazy(self, node: Node) -> None:\n super().get_pyramid_lazy(node)\n # pyramid data may be multi-channel, but we only have 1 labels channel\n node.data[0] = node.data[0][:, 0:1, :, :, :]\n # remove image metadata\n node.metadata = {}\n\n # combine 'properties' from each image\n # from https://github.com/ome/ome-zarr-py/pull/61/\n properties: Dict[int, Dict[str, Any]] = {}\n for row in self.row_names:\n for col in self.col_names:\n path = f\"{row}/{col}/{self.first_field}/labels/0/.zattrs\"\n labels_json = self.zarr.get_json(path).get(\"image-label\", {})\n # NB: assume that 'label_val' is unique across all images\n props_list = labels_json.get(\"properties\", [])\n if props_list:\n for props in props_list:\n label_val = props[\"label-value\"]\n properties[label_val] = dict(props)\n del properties[label_val][\"label-value\"]\n node.metadata[\"properties\"] = properties\n\n def get_numpy_type(self, image_node: Node) -> np.dtype:\n # FIXME - don't assume Well A1 is valid\n path = self.get_tile_path(0, 0, 0)\n label_zarr = self.zarr.load(path)\n return label_zarr.dtype\n\n\nclass Reader:\n \"\"\"Parses the given Zarr instance into a collection of Nodes properly ordered\n depending on context.\n\n Depending on the starting point, metadata may be followed up or down the Zarr\n hierarchy.\n \"\"\"\n\n def __init__(self, zarr: ZarrLocation) -> None:\n assert zarr.exists()\n self.zarr = zarr\n self.seen: List[ZarrLocation] = [zarr]\n\n def __call__(self) -> Iterator[Node]:\n node = Node(self.zarr, self)\n if node.specs: # Something has matched\n\n LOGGER.debug(f\"treating {self.zarr} as ome-zarr\")\n yield from self.descend(node)\n\n # TODO: API thoughts for the Spec type\n # - ask for recursion or not\n # - ask for \"provides data\", \"overrides data\"\n\n elif self.zarr.zarray: # Nothing has matched\n LOGGER.debug(f\"treating {self.zarr} as raw zarr\")\n node.data.append(self.zarr.load())\n yield node\n\n else:\n LOGGER.debug(f\"ignoring {self.zarr}\")\n # yield nothing\n\n def descend(self, node: Node, depth: int = 0) -> Iterator[Node]:\n\n for pre_node in node.pre_nodes:\n yield from self.descend(pre_node, depth + 1)\n\n LOGGER.debug(f\"returning {node}\")\n yield node\n\n for post_node in node.post_nodes:\n yield from self.descend(post_node, depth + 1)\n"
] |
[
[
"numpy.zeros"
]
] |
danich1/annorxiver
|
[
"8fab17e1c3ebce7b9e3fc54ea64585b37d9b3825"
] |
[
"biorxiv/publication_delay_experiment/02_publication_delay_experiment_figure_exploration.py"
] |
[
"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:light\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.9.1+dev\n# kernelspec:\n# display_name: Python [conda env:annorxiver]\n# language: python\n# name: conda-env-annorxiver-py\n# ---\n\n# # Measure the Difference between Preprint-Published similarity and Published Articles\n\n# This notebook measures the time delay that results from the peer review process. Two plots are generated: one that depict the average publication time delay as changes are demanded from the peer review process and the other that depicts the added time delay as preprints have to undergo multiple versions to be published.\n\n# +\nfrom datetime import timedelta\nimport random\nfrom pathlib import Path\n\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom matplotlib.patches import ConnectionPatch\nimport numpy as np\nimport pandas as pd\nimport plotnine as p9\nimport requests\nfrom scipy.spatial.distance import cdist\nfrom scipy.stats import linregress\nimport seaborn as sns\nfrom sklearn.linear_model import LogisticRegressionCV\nimport tqdm\n\nfrom mizani.breaks import date_breaks\nfrom mizani.formatters import timedelta_format\n\nimport warnings\n\nmpl.rcParams[\"figure.dpi\"] = 600\nmpl.rcParams[\"font.size\"] = 12\nmpl.rcParams[\"font.family\"] = \"Arial\"\nwarnings.filterwarnings(\"ignore\")\n# -\n\n# # Load the Document Distances\n\npublished_date_distances = pd.read_csv(\n \"output/preprint_published_distances.tsv\", sep=\"\\t\"\n)\nfor col in [\"preprint_date\", \"published_date\"]:\n published_date_distances[col] = pd.to_datetime(published_date_distances[col])\npublished_date_distances[\"time_to_published\"] = pd.to_timedelta(\n published_date_distances[\"time_to_published\"]\n)\nprint(published_date_distances.shape)\npublished_date_distances.head()\n\npublished_date_distances[\"days_to_published\"] = published_date_distances[\n \"time_to_published\"\n].dt.days\n\nremove_negative_time_to_published = True\nif remove_negative_time_to_published:\n published_date_distances = published_date_distances[\n published_date_distances[\"days_to_published\"] >= 0\n ]\n\n# # Construct Scatter Plot of Date vs Version Count\n\n# Preprints are delayed on an average of 51 days for each new version posted onto bioRxiv. This section regresses preprint's version counts against the time it takes to have a preprint published. A scatter and square bin plot are generated below.\n\n# +\n# Get smoothed linear regression line\nx = published_date_distances.version_count.values.tolist()\n\ny = published_date_distances.time_to_published.apply(\n lambda x: x / timedelta(days=1)\n).tolist()\n\nxseq_2 = np.linspace(np.min(x), np.max(x), 80)\n\nresults_2 = linregress(x, y)\nprint(results_2)\n# -\n\nx_line = np.array(\n [\n published_date_distances[\"version_count\"].min(),\n published_date_distances[\"version_count\"].max(),\n ]\n)\ny_line = x_line * results_2.slope + results_2.intercept\n\ng = (\n p9.ggplot(\n published_date_distances,\n p9.aes(x=\"factor(version_count)\", y=\"time_to_published\"),\n )\n + p9.geom_boxplot(fill=\"#a6cee3\")\n + p9.geom_line(\n mapping=p9.aes(x=\"version_count\", y=\"time_to_published\"),\n stat=\"smooth\",\n method=\"lm\",\n linetype=\"dashed\",\n se=False,\n alpha=1,\n size=0.7,\n inherit_aes=False,\n )\n + p9.scale_y_timedelta(labels=timedelta_format(\"d\"))\n + p9.annotate(\n \"text\",\n x=9,\n y=timedelta(days=1470),\n label=f\"Y={results_2.slope:.2f}*X+{results_2.intercept:.2f}\",\n )\n + p9.labs(x=\"# of Preprint Versions\", y=\"Time Elapsed Until Preprint is Published\")\n + p9.theme_seaborn(context=\"paper\", style=\"ticks\", font=\"Arial\", font_scale=1.3)\n)\n# g.save(\"output/version_count_vs_publication_time.svg\", dpi=500)\n# g.save(\"output/version_count_vs_publication_time.png\", dpi=500)\nprint(g)\n\nplt.figure(figsize=(8, 5))\ng = sns.boxenplot(\n x=\"version_count\",\n y=\"days_to_published\",\n data=published_date_distances,\n scale=\"linear\",\n palette=\"YlGnBu\",\n)\n_ = g.set_ylabel(\"Time Elapsed Until Preprint is Published (Days)\")\n_ = g.set_xlabel(\"# of Preprint Versions\")\n_ = g.plot(x_line - 1, y_line, \"--k\")\n_ = g.annotate(f\"Y={results_2.slope:.2f}*X+{results_2.intercept:.2f}\", (7, 1470))\n\nplt.figure(figsize=(8, 5))\ng = sns.violinplot(\n x=\"version_count\",\n y=\"days_to_published\",\n data=published_date_distances,\n cut=0,\n scale=\"width\",\n palette=\"YlGnBu\",\n)\n_ = g.set_ylabel(\"Time Elapsed Until Preprint is Published (Days)\")\n_ = g.set_xlabel(\"# of Preprint Versions\")\n_ = g.plot(x_line - 1, y_line, \"--k\")\n_ = g.annotate(f\"Y={results_2.slope:.2f}*X+{results_2.intercept:.2f}\", (7, 1470))\n_ = g.set_xlim(-0.5, 11.5)\n_ = g.set_ylim(0, g.get_ylim()[1])\nplt.savefig(\"output/version_count_vs_publication_time_violin_rerun.svg\")\nplt.savefig(\"output/version_count_vs_publication_time_violin_rerun.png\")\n\n# +\nsns.set_theme(style=\"white\", rc={\"axes.facecolor\": (0, 0, 0, 0)})\n\nbw_adjust = 0.5\n\ng = sns.FacetGrid(\n published_date_distances,\n col=\"version_count\",\n hue=\"version_count\",\n aspect=0.1,\n height=5,\n palette=\"YlGnBu\",\n)\n\n# Draw the densities in a few steps\ng = g.map(\n sns.kdeplot,\n \"days_to_published\",\n vertical=True,\n bw_adjust=bw_adjust,\n clip_on=False,\n fill=True,\n alpha=1,\n linewidth=1.5,\n)\n\ng = g.map(\n sns.kdeplot,\n \"days_to_published\",\n clip_on=False,\n color=\"w\",\n lw=2,\n bw_adjust=bw_adjust,\n vertical=True,\n)\ng = g.map(plt.axvline, x=0, lw=2, clip_on=False)\n\n# reorder so right side is lower than left\nfor i, ax in enumerate(g.axes[0]):\n ax.set_zorder(ax.zorder - i)\n\n\n# Define and use a simple function to label the plot in axes coordinates\ndef label(x, color, label):\n ax = plt.gca()\n ax.text(\n 0.03,\n 0,\n label,\n fontweight=\"bold\",\n color=color,\n ha=\"left\",\n va=\"center\",\n transform=ax.transAxes,\n )\n\n\n_ = g.map(label, \"days_to_published\")\n\n_ = g.set_ylabels(\"Time Elapsed Until Preprint is Published (Days)\")\n_ = g.set_xlabels(\"\")\n\nxyA = (0, y_line[0])\nxyB = (0, y_line[1])\naxA = g.axes[0][0]\naxB = g.axes[0][-1]\nline = ConnectionPatch(\n xyA=xyA,\n coordsA=axA.transData,\n xyB=xyB,\n coordsB=axB.transData,\n linestyle=\"--\",\n color=\"k\",\n)\n_ = g.fig.add_artist(line)\n\n# Set the subplots to overlap\n_ = g.fig.subplots_adjust(wspace=-0.7)\n\n# Remove axes details that don't play well with overlap\n_ = g.set_titles(\"\")\n_ = g.set(xticks=[])\n_ = g.despine(bottom=True, left=True)\n\n# +\nsns.set_theme(style=\"white\", rc={\"axes.facecolor\": (0, 0, 0, 0)})\n\ng = sns.FacetGrid(\n published_date_distances,\n row=\"version_count\",\n hue=\"version_count\",\n aspect=12,\n height=0.8,\n palette=\"YlGnBu\",\n)\n\n# Draw the densities in a few steps\ng.map(\n sns.kdeplot,\n \"days_to_published\",\n bw_adjust=0.5,\n clip_on=False,\n fill=True,\n alpha=1,\n linewidth=1.5,\n)\ng.map(\n sns.kdeplot,\n \"days_to_published\",\n clip_on=False,\n color=\"w\",\n lw=2,\n bw_adjust=0.5,\n)\ng.map(plt.axhline, y=0, lw=2, clip_on=False)\n\n\n# Define and use a simple function to label the plot in axes coordinates\ndef label(x, color, label):\n ax = plt.gca()\n ax.text(\n 0,\n 0.2,\n label,\n fontweight=\"bold\",\n color=color,\n ha=\"left\",\n va=\"center\",\n transform=ax.transAxes,\n )\n\n\ng.map(label, \"days_to_published\")\n\n# g.set_xlabels(\"Diversity (1 - gini coefficient)\")\n\n# Set the subplots to overlap\ng.fig.subplots_adjust(hspace=-0.7)\n\n# Remove axes details that don't play well with overlap\ng.set_titles(\"\")\ng.set(yticks=[])\ng.despine(bottom=True, left=True)\n# -\n\ng = sns.lmplot(\n x=\"version_count\",\n y=\"days_to_published\",\n data=published_date_distances,\n x_bins=np.unique(x),\n palette=\"YlGnBu\",\n)\n_ = g.set_ylabels(\"Time Elapsed Until Preprint is Published (Days)\")\n_ = g.set_xlabels(\"# of Preprint Versions\")\n_ = g.axes[0][0].annotate(\n f\"Y={results_2.slope:.2f}*X+{results_2.intercept:.2f}\", (2, 700)\n)\n_ = g.axes[0][0].set_xlim(0.5, 12.5)\n_ = g.axes[0][0].set_ylim(0, g.axes[0][0].get_ylim()[1])\n\n# # Construct Scatter Plot of Date vs Document Distances\n\n# Preprints are delayed on an average of 17 days as changes are demanded from the peer-review process. This section regresses a preprint's document distance against the time it takes to have a preprint published. A scatter and square bin plot are generated below.\n\n\n# +\n# Get smoothed linear regression line\n# Removed negative time here\nx = published_date_distances.doc_distances.values.tolist()\n\ny = published_date_distances.time_to_published.apply(\n lambda x: x / timedelta(days=1)\n).tolist()\n\nxseq_2 = np.linspace(np.min(x), np.max(x), 80)\n\nresults_2 = linregress(x, y)\nprint(results_2)\n# -\n\ng = (\n p9.ggplot(\n published_date_distances, p9.aes(y=\"time_to_published\", x=\"doc_distances\")\n )\n + p9.geom_point()\n + p9.geom_line(\n stat=\"smooth\", method=\"lm\", linetype=\"dashed\", se=False, alpha=0.9, size=0.6\n )\n + p9.scale_y_timedelta(labels=timedelta_format(\"d\"))\n + p9.annotate(\n \"text\",\n x=10,\n y=timedelta(days=1450),\n label=f\"Y={results_2.slope:.2f}*X+{results_2.intercept:.2f}\",\n )\n + p9.labs(\n x=\"Euclidean Distance of Preprints First and Final Versions\",\n y=\"Time Elapsed Until Preprint is Published\",\n )\n + p9.theme_seaborn(context=\"paper\", style=\"ticks\", font=\"Arial\", font_scale=1.3)\n)\nprint(g)\n\ng = (\n p9.ggplot(\n published_date_distances, p9.aes(x=\"doc_distances\", y=\"time_to_published\")\n )\n + p9.geom_bin2d(bins=100)\n + p9.scale_fill_distiller(\n trans=\"log\", direction=-1, type=\"seq\", palette=\"YlGnBu\", name=\"log(count)\"\n )\n + p9.geom_line(\n stat=\"smooth\", method=\"lm\", linetype=\"dashed\", se=False, alpha=1, size=0.7\n )\n + p9.scale_y_timedelta(labels=timedelta_format(\"d\"))\n + p9.annotate(\n \"text\",\n x=7.5,\n y=timedelta(days=1490),\n label=f\"Y={results_2.slope:.2f}*X+{results_2.intercept:.2f}\",\n )\n + p9.labs(\n x=\"Euclidean Distance of Preprint-Published Versions\",\n y=\"Time Elapsed Until Preprint is Published\",\n legend=\"log(count)\",\n )\n)\nprint(g)\n\n# # Hex grid options\n# A couple hex grid options just to see what they look like\n\nx_line = np.array(\n [\n published_date_distances[\"doc_distances\"].min(),\n published_date_distances[\"doc_distances\"].max(),\n ]\n)\ny_line = x_line * results_2.slope + results_2.intercept\n\nplt.figure(figsize=(7, 5))\nax = plt.hexbin(\n published_date_distances[\"doc_distances\"],\n published_date_distances[\"days_to_published\"],\n gridsize=50,\n cmap=\"YlGnBu_r\",\n norm=mpl.colors.LogNorm(),\n mincnt=1,\n linewidths=(0.15,)\n # edgecolors=None\n)\nplt.xlim([0, 12])\nplt.ylim([0, 1800])\nax = plt.gca()\nax.plot(x_line, y_line, \"--k\")\nax.annotate(\n f\"Y={results_2.slope:.2f}*X+{results_2.intercept:.2f}\",\n (6, 1490),\n)\n_ = ax.set_xlabel(\"Euclidean Distance of Preprint-Published Versions\")\n_ = ax.set_ylabel(\"Time Elapsed Until Preprint is Published (Days)\")\ncbar = plt.colorbar()\n_ = cbar.ax.set_ylabel(\"count\", rotation=270)\nplt.savefig(\"output/article_distance_vs_publication_time_hex.svg\")\nplt.savefig(\"output/article_distance_vs_publication_time_hex.png\")\n\nplt.figure(figsize=(6, 5))\nax = plt.hexbin(\n published_date_distances[\"doc_distances\"],\n published_date_distances[\"days_to_published\"],\n gridsize=50,\n cmap=\"YlGnBu_r\",\n norm=mpl.colors.LogNorm(),\n mincnt=1,\n edgecolors=None,\n)\nplt.xlim([0, 12])\nplt.ylim([0, 1800])\nax = plt.gca()\nax.plot(x_line, y_line, \"--k\")\nax.annotate(\n f\"Y={results_2.slope:.2f}*X+{results_2.intercept:.2f}\",\n (6, 1490),\n)\n_ = ax.set_xlabel(\"Euclidean Distance of Preprint-Published Versions\")\n_ = ax.set_ylabel(\"Time Elapsed Until Preprint is Published (Days)\")\ncbar = plt.colorbar()\n_ = cbar.ax.set_ylabel(\"count\", rotation=270)\n\n# +\nhexplot = sns.jointplot(\n x=\"doc_distances\",\n y=\"days_to_published\",\n data=published_date_distances,\n kind=\"hex\",\n joint_kws={\"cmap\": \"YlGnBu_r\", \"mincnt\": 1},\n norm=mpl.colors.LogNorm(),\n height=8,\n)\nhexplot.set_axis_labels(\n xlabel=\"Euclidian Distance of Preprint-Published Versions\",\n ylabel=\"Time Elapsed Until Preprint is Published (Days)\",\n)\n\nhexplot.ax_joint.plot(x_line, y_line, \"--k\")\nhexplot.ax_joint.annotate(\n f\"Y={results_2.slope:.2f}*X+{results_2.intercept:.2f}\",\n (6, 1490),\n)\n# shrink fig so cbar is visible\nplt.subplots_adjust(left=0.2, right=0.8, top=0.8, bottom=0.2)\n# make new ax object for the cbar\ncbar_ax = hexplot.fig.add_axes([0.85, 0.25, 0.05, 0.4]) # x, y, width, height\nplt.colorbar(cax=cbar_ax)\n_ = cbar_ax.set_ylabel(\"count\", rotation=270)\n\n# +\nhexplot = sns.jointplot(\n x=\"doc_distances\",\n y=\"days_to_published\",\n data=published_date_distances,\n kind=\"hex\",\n joint_kws={\"cmap\": \"YlGnBu_r\", \"mincnt\": 1, \"edgecolors\": None},\n norm=mpl.colors.LogNorm(),\n height=8,\n)\n\nhexplot.set_axis_labels(\n xlabel=\"Euclidian Distance of Preprint-Published Versions\",\n ylabel=\"Time Elapsed Until Preprint is Published (Days)\",\n)\n\nhexplot.ax_joint.plot(x_line, y_line, \"--k\")\nhexplot.ax_joint.annotate(\n f\"Y={results_2.slope:.2f}*X+{results_2.intercept:.2f}\",\n (6, 1490),\n)\n# shrink fig so cbar is visible\nplt.subplots_adjust(left=0.2, right=0.8, top=0.8, bottom=0.2)\n# make new ax object for the cbar\ncbar_ax = hexplot.fig.add_axes([0.85, 0.25, 0.05, 0.4]) # x, y, width, height\nplt.colorbar(cax=cbar_ax)\n_ = cbar_ax.set_ylabel(\"count\", rotation=270)\n"
] |
[
[
"matplotlib.pyplot.gca",
"pandas.read_csv",
"pandas.to_datetime",
"matplotlib.colors.LogNorm",
"numpy.min",
"numpy.unique",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.colorbar",
"scipy.stats.linregress",
"matplotlib.pyplot.xlim",
"numpy.max",
"matplotlib.patches.ConnectionPatch",
"matplotlib.pyplot.subplots_adjust",
"pandas.to_timedelta",
"matplotlib.pyplot.figure"
]
] |
yuvalot/ml_final_project
|
[
"fefb67c92504ceeb7999e49daa8a8aa5a60f1c61"
] |
[
"src/ml_final_project/optimizers/improved_lookahead.py"
] |
[
"import tensorflow as tf\r\nfrom tensorflow_addons.utils import types\r\nfrom typeguard import typechecked\r\n\r\n\r\nclass ImprovedLookahead(tf.keras.optimizers.Optimizer):\r\n \"\"\"This class allows to extend optimizers with the lookahead mechanism - with the addition of the momentum concept.\r\n The mechanism is proposed by Michael R. Zhang et.al in the paper\r\n [Lookahead Optimizer: k steps forward, 1 step back]\r\n (https://arxiv.org/abs/1907.08610v1). The optimizer iteratively updates two\r\n sets of weights: the search directions for weights are chosen by the inner\r\n optimizer, while the \"slow weights\" are updated each `k` steps based on the\r\n directions of the \"fast weights\" and the two sets of weights are\r\n synchronized. This method improves the learning stability and lowers the\r\n variance of its inner optimizer.\r\n\r\n Example of usage:\r\n ```python\r\n opt = tf.keras.optimizers.SGD(learning_rate)\r\n opt = ImprovedLookahead(opt)\r\n ```\r\n \"\"\"\r\n\r\n @typechecked\r\n def __init__(\r\n self,\r\n optimizer: types.Optimizer,\r\n sync_period: int = 6,\r\n slow_step_size: types.FloatTensorLike = 0.5,\r\n momentum=0.5,\r\n name: str = \"ImprovedLookahead\",\r\n **kwargs,\r\n ):\r\n r\"\"\"Wrap optimizer with the lookahead mechanism.\r\n Args:\r\n optimizer: The original optimizer that will be used to compute\r\n and apply the gradients.\r\n sync_period: An integer. The synchronization period of lookahead.\r\n Enable lookahead mechanism by setting it with a positive value.\r\n slow_step_size: A floating point value.\r\n The ratio for updating the slow weights.\r\n momentum: A floating point hyperparameter that control how history is being expressed in the current step.\r\n Affects only the slow step learning.\r\n Defaults to 0.5, i.e., vanilla gradient\r\n name: Optional name for the operations created when applying\r\n gradients. Defaults to \"Lookahead\".\r\n **kwargs: keyword arguments. Allowed to be {`clipnorm`,\r\n `clipvalue`, `lr`, `decay`}. `clipnorm` is clip gradients\r\n by norm; `clipvalue` is clip gradients by value, `decay` is\r\n included for backward compatibility to allow time inverse\r\n decay of learning rate. `lr` is included for backward\r\n compatibility, recommended to use `learning_rate` instead.\r\n \"\"\"\r\n super().__init__(name, **kwargs)\r\n\r\n if isinstance(optimizer, str):\r\n optimizer = tf.keras.optimizers.get(optimizer)\r\n if not isinstance(optimizer, tf.keras.optimizers.Optimizer):\r\n raise TypeError(\r\n \"optimizer is not an object of tf.keras.optimizers.Optimizer\"\r\n )\r\n\r\n self._optimizer = optimizer\r\n self._set_hyper(\"sync_period\", sync_period)\r\n self._set_hyper(\"slow_step_size\", slow_step_size)\r\n self._initialized = False\r\n self._track_trackable(self._optimizer, \"lh_base_optimizer\")\r\n # modified code:\r\n self.momentum = momentum\r\n self.last_delta_weight = {}\r\n ###\r\n\r\n def _create_slots(self, var_list):\r\n self._optimizer._create_slots(\r\n var_list=var_list\r\n ) # pylint: disable=protected-access\r\n for var in var_list:\r\n self.add_slot(var, \"slow\", initializer=var)\r\n # modified code:\r\n self.last_delta_weight[str(var.shape)] = 0\r\n ###\r\n\r\n def _create_hypers(self):\r\n self._optimizer._create_hypers() # pylint: disable=protected-access\r\n\r\n def _prepare(self, var_list):\r\n return self._optimizer._prepare(\r\n var_list=var_list\r\n ) # pylint: disable=protected-access\r\n\r\n def apply_gradients(self, grads_and_vars, name=None, **kwargs):\r\n self._optimizer._iterations = (\r\n self.iterations\r\n ) # pylint: disable=protected-access\r\n return super().apply_gradients(grads_and_vars, name, **kwargs)\r\n\r\n def _look_ahead_op(self, var):\r\n var_dtype = var.dtype.base_dtype\r\n slow_var = self.get_slot(var, \"slow\")\r\n local_step = tf.cast(self.iterations + 1, tf.dtypes.int64)\r\n sync_period = self._get_hyper(\"sync_period\", tf.dtypes.int64)\r\n slow_step_size = self._get_hyper(\"slow_step_size\", var_dtype)\r\n # original code:\r\n # step_back = slow_var + slow_step_size * (var - slow_var)\r\n ###\r\n # modified code:\r\n weight_delta = slow_step_size * (var - slow_var)\r\n step_back = slow_var + weight_delta + self.momentum * self.last_delta_weight[str(weight_delta.shape)]\r\n self.last_delta_weight[str(weight_delta.shape)] = weight_delta\r\n ###\r\n sync_cond = tf.equal(\r\n tf.math.floordiv(local_step, sync_period) * sync_period, local_step\r\n )\r\n with tf.control_dependencies([step_back]):\r\n slow_update = slow_var.assign(\r\n tf.where(sync_cond, step_back, slow_var), use_locking=self._use_locking\r\n )\r\n var_update = var.assign(\r\n tf.where(sync_cond, step_back, var), use_locking=self._use_locking\r\n )\r\n return tf.group(slow_update, var_update)\r\n\r\n @property\r\n def weights(self):\r\n return self._weights + self._optimizer.weights\r\n\r\n def _resource_apply_dense(self, grad, var):\r\n train_op = self._optimizer._resource_apply_dense(\r\n grad, var\r\n ) # pylint: disable=protected-access\r\n with tf.control_dependencies([train_op]):\r\n look_ahead_op = self._look_ahead_op(var)\r\n return tf.group(train_op, look_ahead_op)\r\n\r\n def _resource_apply_sparse(self, grad, var, indices):\r\n train_op = (\r\n self._optimizer._resource_apply_sparse( # pylint: disable=protected-access\r\n grad, var, indices\r\n )\r\n )\r\n with tf.control_dependencies([train_op]):\r\n look_ahead_op = self._look_ahead_op(var)\r\n return tf.group(train_op, look_ahead_op)\r\n\r\n def get_config(self):\r\n config = {\r\n \"optimizer\": tf.keras.optimizers.serialize(self._optimizer),\r\n \"sync_period\": self._serialize_hyperparameter(\"sync_period\"),\r\n \"slow_step_size\": self._serialize_hyperparameter(\"slow_step_size\"),\r\n }\r\n base_config = super().get_config()\r\n return {**base_config, **config}\r\n\r\n @property\r\n def learning_rate(self):\r\n return self._optimizer._get_hyper(\"learning_rate\")\r\n\r\n @learning_rate.setter\r\n def learning_rate(self, learning_rate):\r\n self._optimizer._set_hyper(\"learning_rate\", learning_rate)\r\n\r\n @property\r\n def lr(self):\r\n return self.learning_rate\r\n\r\n @lr.setter\r\n def lr(self, lr):\r\n self.learning_rate = lr\r\n\r\n @classmethod\r\n def from_config(cls, config, custom_objects=None):\r\n optimizer = tf.keras.optimizers.deserialize(\r\n config.pop(\"optimizer\"), custom_objects=custom_objects\r\n )\r\n return cls(optimizer, **config)\r\n"
] |
[
[
"tensorflow.control_dependencies",
"tensorflow.cast",
"tensorflow.keras.optimizers.get",
"tensorflow.math.floordiv",
"tensorflow.where",
"tensorflow.group",
"tensorflow.keras.optimizers.serialize"
]
] |
hboisgibault/KeyphraseVectorizers
|
[
"37816e6496c15db891182e5148ecbc9d4e585934"
] |
[
"keyphrase_vectorizers/keyphrase_tfidf_vectorizer.py"
] |
[
"\"\"\"\n.. _spaCy pipeline: https://spacy.io/models\n.. _stopwords available in NLTK: https://github.com/nltk/nltk_data/blob/gh-pages/packages/corpora/stopwords.zip\n.. _POS-tags: https://github.com/explosion/spaCy/blob/master/spacy/glossary.py\n.. _regex pattern: https://docs.python.org/3/library/re.html#regular-expression-syntax\n.. _spaCy part-of-speech tags: https://github.com/explosion/spaCy/blob/master/spacy/glossary.py\n\"\"\"\n\nimport warnings\nfrom typing import List\n\nimport numpy as np\nimport psutil\nfrom sklearn.exceptions import NotFittedError\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.utils.validation import FLOAT_DTYPES\n\nfrom keyphrase_vectorizers.keyphrase_count_vectorizer import KeyphraseCountVectorizer\n\n\nclass KeyphraseTfidfVectorizer(KeyphraseCountVectorizer):\n \"\"\"\n KeyphraseTfidfVectorizer\n\n KeyphraseTfidfVectorizer converts a collection of text documents to a normalized tf or tf-idf document-token matrix.\n The tokens are keyphrases that are extracted from the text documents based on their part-of-speech tags.\n The matrix rows indicate the documents and columns indicate the unique keyphrases.\n Each cell represents the tf or tf-idf value, depending on the parameter settings.\n The part-of-speech pattern of keyphrases can be defined by the ``pos_pattern`` parameter.\n By default, keyphrases are extracted, that have 0 or more adjectives, followed by 1 or more nouns.\n A list of extracted keyphrases matching the defined part-of-speech pattern can be returned after fitting via :class:`get_feature_names_out()`.\n\n Attention:\n If the vectorizer is used for languages other than English, the ``spacy_pipeline`` and ``stop_words`` parameters\n must be customized accordingly.\n Additionally, the ``pos_pattern`` parameter has to be customized as the `spaCy part-of-speech tags`_ differ between languages.\n Without customizing, the words will be tagged with wrong part-of-speech tags and no stopwords will be considered.\n\n Tf means term-frequency while tf-idf means term-frequency times inverse document-frequency.\n This is a common term weighting scheme in information retrieval,\n that has also found good use in document classification.\n\n The goal of using tf-idf instead of the raw frequencies of occurrence of a token in a given document\n is to scale down the impact of tokens that occur very frequently in a given corpus and that are hence empirically less\n informative than features that occur in a small fraction of the training corpus.\n\n The formula that is used to compute the tf-idf for a term t of a document d in a document set is\n tf-idf(t, d) = tf(t, d) * idf(t), and the idf is computed as idf(t) = log [ n / df(t) ] + 1 (if ``smooth_idf=False``),\n where n is the total number of documents in the document set and df(t) is the document frequency of t;\n the document frequency is the number of documents in the document set that contain the term t.\n The effect of adding \"1\" to the idf in the equation above is that terms with zero idf, i.e., terms\n that occur in all documents in a training set, will not be entirely ignored.\n (Note that the idf formula above differs from the standard textbook\n notation that defines the idf as idf(t) = log [ n / (df(t) + 1) ]).\n\n If ``smooth_idf=True`` (the default), the constant \"1\" is added to the numerator and denominator of the idf as\n if an extra document was seen containing every term in the collection exactly once, which prevents\n zero divisions: idf(t) = log [ (1 + n) / (1 + df(t)) ] + 1.\n\n Furthermore, the formulas used to compute tf and idf depend on parameter settings that correspond to\n the SMART notation used in IR as follows:\n\n Tf is \"n\" (natural) by default, \"l\" (logarithmic) when ``sublinear_tf=True``.\n Idf is \"t\" when use_idf is given, \"n\" (none) otherwise.\n Normalization is \"c\" (cosine) when ``norm='l2'``, \"n\" (none) when ``norm=None``.\n\n Parameters\n ----------\n spacy_pipeline : str, default='en_core_web_sm'\n The name of the `spaCy pipeline`_, used to tag the parts-of-speech in the text. Standard is the 'en' pipeline.\n\n pos_pattern : str, default='<J.*>*<N.*>+'\n The `regex pattern`_ of `POS-tags`_ used to extract a sequence of POS-tagged tokens from the text.\n Standard is to only select keyphrases that have 0 or more adjectives, followed by 1 or more nouns.\n\n stop_words : str, default='english'\n Language of stopwords to remove from the document, e.g. 'english'.\n Supported options are `stopwords available in NLTK`_.\n Removes unwanted stopwords from keyphrases if 'stop_words' is not None.\n\n lowercase : bool, default=True\n Whether the returned keyphrases should be converted to lowercase.\n\n workers :int, default=1\n How many workers to use for spaCy part-of-speech tagging.\n If set to -1, use all available worker threads of the machine.\n spaCy uses the specified number of cores to tag documents with part-of-speech.\n Depending on the platform, starting many processes with multiprocessing can add a lot of overhead.\n In particular, the default start method spawn used in macOS/OS X (as of Python 3.8) and in Windows can be slow.\n Therefore, carefully consider whether this option is really necessary.\n\n max_df : int, default=None\n During fitting ignore keyphrases that have a document frequency strictly higher than the given threshold.\n\n min_df : int, default=None\n During fitting ignore keyphrases that have a document frequency strictly lower than the given threshold.\n This value is also called cut-off in the literature.\n\n binary : bool, default=False\n If True, all non zero counts are set to 1.\n This is useful for discrete probabilistic models that model binary events rather than integer counts.\n\n dtype : type, default=np.int64\n Type of the matrix returned by fit_transform() or transform().\n\n norm : {'l1', 'l2'}, default='l2'\n Each output row will have unit norm, either:\n - 'l2': Sum of squares of vector elements is 1. The cosine similarity between two vectors is their dot product when l2 norm has been applied.\n - 'l1': Sum of absolute values of vector elements is 1.\n\n use_idf : bool, default=True\n Enable inverse-document-frequency reweighting. If False, idf(t) = 1.\n\n smooth_idf : bool, default=True\n Smooth idf weights by adding one to document frequencies, as if an\n extra document was seen containing every term in the collection\n exactly once. Prevents zero divisions.\n\n sublinear_tf : bool, default=False\n Apply sublinear tf scaling, i.e. replace tf with 1 + log(tf).\n\n \"\"\"\n\n def __init__(self, spacy_pipeline: str = 'en_core_web_sm', pos_pattern: str = '<J.*>*<N.*>+',\n stop_words: str = 'english',\n lowercase: bool = True, workers: int = 1, max_df: int = None, min_df: int = None,\n binary: bool = False,\n dtype: np.dtype = np.float64, norm: str = \"l2\",\n use_idf: bool = True, smooth_idf: bool = True,\n sublinear_tf: bool = False):\n\n # triggers a parameter validation\n if not isinstance(workers, int):\n raise ValueError(\n \"'workers' parameter must be of type int\"\n )\n\n if (workers < -1) or (workers > psutil.cpu_count(logical=True)) or (workers == 0):\n raise ValueError(\n \"'workers' parameter value cannot be 0 and must be between -1 and \" + str(\n psutil.cpu_count(logical=True))\n )\n\n self.spacy_pipeline = spacy_pipeline\n self.pos_pattern = pos_pattern\n self.stop_words = stop_words\n self.lowercase = lowercase\n self.workers = workers\n self.max_df = max_df\n self.min_df = min_df\n self.binary = binary\n self.dtype = dtype\n self.norm = norm\n self.use_idf = use_idf\n self.smooth_idf = smooth_idf\n self.sublinear_tf = sublinear_tf\n\n self._tfidf = TfidfTransformer(norm=self.norm, use_idf=self.use_idf, smooth_idf=self.smooth_idf,\n sublinear_tf=self.sublinear_tf)\n\n super().__init__(spacy_pipeline=self.spacy_pipeline, pos_pattern=self.pos_pattern, stop_words=self.stop_words,\n lowercase=self.lowercase, workers=self.workers, max_df=self.max_df,\n min_df=self.min_df, binary=self.binary,\n dtype=self.dtype)\n\n def _check_params(self):\n \"\"\"\n Validate dtype parameter.\n \"\"\"\n\n if self.dtype not in FLOAT_DTYPES:\n warnings.warn(\n \"Only {} 'dtype' should be used. {} 'dtype' will \"\n \"be converted to np.float64.\".format(FLOAT_DTYPES, self.dtype),\n UserWarning,\n )\n\n def fit(self, raw_documents: List[str]) -> object:\n \"\"\"Learn the keyphrases that match the defined part-of-speech pattern and idf from the list of raw documents.\n\n Parameters\n ----------\n raw_documents : iterable\n An iterable of strings.\n\n Returns\n -------\n self : object\n Fitted vectorizer.\n \"\"\"\n\n self._check_params()\n X = super().fit_transform(raw_documents)\n self._tfidf.fit(X)\n return self\n\n def fit_transform(self, raw_documents: List[str]) -> List[List[float]]:\n \"\"\"\n Learn the keyphrases that match the defined part-of-speech pattern and idf from the list of raw documents.\n Then return document-keyphrase matrix.\n This is equivalent to fit followed by transform, but more efficiently implemented.\n\n Parameters\n ----------\n raw_documents : iterable\n An iterable of strings.\n\n Returns\n -------\n X : sparse matrix of (n_samples, n_features)\n Tf-idf-weighted document-keyphrase matrix.\n \"\"\"\n\n self._check_params()\n X = super().fit_transform(raw_documents)\n self._tfidf.fit(X)\n # X is already a transformed view of raw_documents so\n # we set copy to False\n return self._tfidf.transform(X, copy=False)\n\n def transform(self, raw_documents: List[str]) -> List[List[float]]:\n \"\"\"\n Transform documents to document-keyphrase matrix.\n Uses the keyphrases and document frequencies (df) learned by fit (or fit_transform).\n\n Parameters\n ----------\n raw_documents : iterable\n An iterable of strings.\n\n Returns\n -------\n X : sparse matrix of (n_samples, n_features)\n Tf-idf-weighted document-keyphrase matrix.\n \"\"\"\n\n # triggers a parameter validation\n if not hasattr(self, 'keyphrases'):\n raise NotFittedError(\"Keyphrases not fitted.\")\n\n X = super().transform(raw_documents)\n return self._tfidf.transform(X, copy=False)\n"
] |
[
[
"sklearn.feature_extraction.text.TfidfTransformer",
"sklearn.exceptions.NotFittedError"
]
] |
krantikiran/EdgeML
|
[
"e5c7bd7c56884ca61f6d54cedb0074553cfdc896",
"e5c7bd7c56884ca61f6d54cedb0074553cfdc896"
] |
[
"Tools/SeeDot/seedot/compiler/converter/test.py",
"pytorch/examples/FastCells/fastcell_example.py"
] |
[
"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nimport math\nimport numpy as np\n\n\ndef getScale(maxabs: float, bits):\n return int(np.ceil(np.log2(maxabs) - np.log2((1 << (bits - 2)) - 1)))\n\n\ndef printUspsRNN():\n ite = 16\n print(\"let a0 = (XX[0] * W) in\")\n print(\"let c0 = a0 in\")\n print(\"let g0 = sigmoid(c0 + Bg) in\")\n print(\"let h0 = tanh(c0 + Bh) in\")\n print(\"let H0 = (zeta * (1.0 - g0) + nu) <*> h0 in \")\n print(\"\")\n for i in range(1, ite):\n print(\"let a%d = (XX[%d] * W) in\" % (i, i))\n print(\"let b%d = (H%d * U) in\" % (i, i-1))\n print(\"let c%d = a%d + b%d in\" % (i, i, i))\n print(\"let g%d = sigmoid(c%d + Bg) in\" % (i, i))\n print(\"let h%d = tanh(c%d + Bh) in\" % (i, i))\n print(\"let H%d = (g%d <*> H%d) + (zeta * (1.0 - g%d) + nu) <*> h%d in \" %\n (i, i, i-1, i, i))\n print(\"\\n\")\n print(\"let score = (H%d * FC) + FCbias in\" % (ite-1))\n print(\"argmax(score)\")\n\n\ndef printDsaRNN():\n ite = 125\n print(\"let a0 = (XX[0] * W1) * W2 in\")\n print(\"let c0 = a0 in\")\n print(\"let g0 = sigmoid(c0 + Bg) in\")\n print(\"let h0 = tanh(c0 + Bh) in\")\n print(\"let H0 = (zeta * (1.0 - g0) + nu) <*> h0 in \")\n print(\"\")\n for i in range(1, ite):\n print(\"let a%d = (XX[%d] * W1) * W2 in\" % (i, i))\n print(\"let b%d = (H%d * U1) * U2 in\" % (i, i-1))\n print(\"let c%d = a%d + b%d in\" % (i, i, i))\n print(\"let g%d = sigmoid(c%d + Bg) in\" % (i, i))\n print(\"let h%d = tanh(c%d + Bh) in\" % (i, i))\n print(\"let H%d = (g%d <*> H%d) + (zeta * (1.0 - g%d) + nu) <*> h%d in \" %\n (i, i, i-1, i, i))\n print(\"\\n\")\n print(\"let score = (H%d * FC) + FCbias in\" % (ite-1))\n print(\"argmax(score)\")\n\n\ndef printSpectakomRNN():\n ite = 7\n print(\"let a0 = (XX[0] * W1) * W2 in\")\n print(\"let c0 = a0 in\")\n print(\"let g0 = sigmoid(c0 + Bg) in\")\n print(\"let h0 = tanh(c0 + Bh) in\")\n print(\"let H0 = (zeta * (1.0 - g0) + nu) <*> h0 in \")\n print(\"\")\n for i in range(1, ite):\n print(\"let a%d = (XX[%d] * W1) * W2 in\" % (i, i))\n print(\"let b%d = (H%d * U1) * U2 in\" % (i, i-1))\n print(\"let c%d = a%d + b%d in\" % (i, i, i))\n print(\"let g%d = sigmoid(c%d + Bg) in\" % (i, i))\n print(\"let h%d = tanh(c%d + Bh) in\" % (i, i))\n print(\"let H%d = (g%d <*> H%d) + (zeta * (1.0 - g%d) + nu) <*> h%d in \" %\n (i, i, i-1, i, i))\n print(\"\\n\")\n print(\"let score = ((H%d * FC1) * FC2) + FCBias in\" % (ite-1))\n print(\"argmax(score)\")\n\n\ndef treeSum(tmp, length, height_shr, height_noshr):\n\n count = length\n depth = 0\n shr = True\n\n while depth < (height_shr + height_noshr):\n if depth >= height_shr:\n shr = False\n\n for p in range(int(length / 2) + 1):\n if p < (count >> 1):\n sum = tmp[2 * p] + tmp[(2 * p) + 1]\n elif (p == (count >> 1)) and ((count & 1) == 1):\n sum = tmp[2 * p]\n else:\n sum = 0\n\n if shr:\n tmp[p] = sum / 2\n else:\n tmp[p] = sum\n count = (count + 1) >> 1\n\n depth += 1\n\n print(tmp)\n\n return tmp[0]\n\n\ndef treeSumNew(tmp, count, height_shr, height_noshr):\n if count == 1:\n return tmp[0]\n\n shr = True\n\n for depth in range(height_shr + height_noshr):\n if depth >= height_shr:\n shr = False\n\n for p in range(count // 2):\n sum = tmp[2 * p] + tmp[(2 * p) + 1]\n\n if shr:\n tmp[p] = sum / 2\n else:\n tmp[p] = sum\n\n if count % 2 == 1:\n index = count // 2 + 1\n if shr:\n tmp[index - 1] = tmp[count - 1] / 2\n else:\n tmp[index - 1] = tmp[count - 1]\n\n tmp[index - 1 + 1] = 0\n else:\n tmp[count // 2] = 0\n\n count = (count + 1) >> 1\n\n print(tmp)\n\n return tmp[0]\n\n# printUspsRNN()\n\n# printDsaRNN()\n\n# printSpectakomRNN()\n\n\ndef treeSumTest():\n #tmp = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]\n tmp = [0.1]\n tmpNew = list(tmp)\n\n sum = treeSum(tmp, 1, 1, 0)\n print(sum)\n\n print('\\n\\n')\n\n sum = treeSumNew(tmpNew, 1, 0, 1)\n print(sum)\n\n\ndef computeScale(val, bits):\n l = np.log2(val)\n if int(l) == l:\n c = l + 1\n else:\n c = np.ceil(l)\n return -int((bits - 1) - c)\n\n\ndef test(n, bits):\n print(np.log2(n))\n s1 = computeScale(n, bits)\n s2 = getScale(n, bits)\n v1 = int(np.ldexp(n, -s1))\n v2 = int(np.ldexp(n, -s2))\n print(\"%f scale = %d int = %d\" % (n, s1, v1))\n print(\"%f scale = %d int = %d\" % (n, s2, v2))\n\n\ndef getShrForMul(scale_A, scale_B):\n bits = 16\n MAX_SCALE = -9\n\n shr1, shr2 = bits // 2, (bits // 2) - 1\n pRes = (scale_A + shr1) + (scale_B + shr2)\n\n if pRes <= MAX_SCALE:\n if scale_A <= scale_B:\n shrA, shrB = shr1, shr2\n else:\n shrA, shrB = shr2, shr1\n return [shrA, shrB]\n else:\n save = abs(abs(pRes) - abs(MAX_SCALE))\n if save % 2 == 1:\n shr1 -= 1\n save -= 1\n save = save // 2\n if scale_A <= scale_B:\n shrA = max(shr1 - save, 0)\n shrB = max(shr2 - save, 0)\n else:\n shrA = max(shr2 - save, 0)\n shrB = max(shr1 - save, 0)\n\n return [shrA, shrB]\n\n\nx = getShrForMul(-12, -12)\nprint(x)\n",
"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nimport helpermethods\nimport torch\nimport numpy as np\nimport sys\nfrom pytorch_edgeml.graph.rnn import *\nfrom pytorch_edgeml.trainer.fastTrainer import FastTrainer\n\n\ndef main():\n # change cuda:0 to cuda:gpuid for specific allocation\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n # Fixing seeds for reproducibility\n torch.manual_seed(42)\n np.random.seed(42)\n\n # Hyper Param pre-processing\n args = helpermethods.getArgs()\n\n dataDir = args.data_dir\n cell = args.cell\n inputDims = args.input_dim\n hiddenDims = args.hidden_dim\n\n totalEpochs = args.epochs\n learningRate = args.learning_rate\n outFile = args.output_file\n batchSize = args.batch_size\n decayStep = args.decay_step\n decayRate = args.decay_rate\n\n wRank = args.wRank\n uRank = args.uRank\n\n sW = args.sW\n sU = args.sU\n\n update_non_linearity = args.update_nl\n gate_non_linearity = args.gate_nl\n\n (dataDimension, numClasses, Xtrain, Ytrain, Xtest, Ytest,\n mean, std) = helpermethods.preProcessData(dataDir)\n\n assert dataDimension % inputDims == 0, \"Infeasible per step input, \" + \\\n \"Timesteps have to be integer\"\n\n currDir = helpermethods.createTimeStampDir(dataDir, cell)\n\n helpermethods.dumpCommand(sys.argv, currDir)\n helpermethods.saveMeanStd(mean, std, currDir)\n\n if cell == \"FastGRNN\":\n FastCell = FastGRNNCell(inputDims, hiddenDims,\n gate_non_linearity=gate_non_linearity,\n update_non_linearity=update_non_linearity,\n wRank=wRank, uRank=uRank)\n elif cell == \"FastRNN\":\n FastCell = FastRNNCell(inputDims, hiddenDims,\n update_non_linearity=update_non_linearity,\n wRank=wRank, uRank=uRank)\n elif cell == \"UGRNN\":\n FastCell = UGRNNLRCell(inputDims, hiddenDims,\n update_non_linearity=update_non_linearity,\n wRank=wRank, uRank=uRank)\n elif cell == \"GRU\":\n FastCell = GRULRCell(inputDims, hiddenDims,\n update_non_linearity=update_non_linearity,\n wRank=wRank, uRank=uRank)\n elif cell == \"LSTM\":\n FastCell = LSTMLRCell(inputDims, hiddenDims,\n update_non_linearity=update_non_linearity,\n wRank=wRank, uRank=uRank)\n else:\n sys.exit('Exiting: No Such Cell as ' + cell)\n\n FastCellTrainer = FastTrainer(FastCell, numClasses, sW=sW, sU=sU,\n learningRate=learningRate, outFile=outFile,\n device=device)\n\n FastCellTrainer.train(batchSize, totalEpochs,\n torch.from_numpy(Xtrain.astype(np.float32)),\n torch.from_numpy(Xtest.astype(np.float32)),\n torch.from_numpy(Ytrain.astype(np.float32)),\n torch.from_numpy(Ytest.astype(np.float32)),\n decayStep, decayRate, dataDir, currDir)\n\n\nif __name__ == '__main__':\n\n main()\n"
] |
[
[
"numpy.ceil",
"numpy.log2",
"numpy.ldexp"
],
[
"torch.manual_seed",
"torch.cuda.is_available",
"numpy.random.seed"
]
] |
riskaware-ltd/ridt
|
[
"c0288a2f814b2749bdf73de7157f7477ca271aff"
] |
[
"ridt/analysis/exposure.py"
] |
[
"from typing import Union\n\nfrom scipy.integrate import cumtrapz\nfrom numpy import ndarray\n\nfrom ridt.config import RIDTConfig\n\nfrom ridt.data import DataStore\nfrom ridt.data import BatchDataStore\n\n\nclass Exposure:\n \"\"\"The Exposure class\n\n The class which takes a :class:`~.DataStore` or :class:`~.BatchDataStore`\n and returns another instance of the same containing the computed \n exposure.\n\n Attributes\n ----------\n setting : :class:`~.RIDTConfig`\n The settings for the run in question.\n \n data_store : Union[:class:`~.DataStore`, :class:`~.BatchDataStore`]\n The data store or batch data store of computed exposures.\n \n delta_t : :obj:`float`\n The time step for the current data set.\n\n \"\"\"\n\n def __new__(cls, *args, **kwargs):\n instance = super(Exposure, cls).__new__(cls)\n instance.__init__(*args, **kwargs)\n return instance.data_store\n \n def __init__(self, setting: RIDTConfig, data_store: Union[DataStore, BatchDataStore]):\n \"\"\"The Exposure class initialiser\n\n\n Parameters\n ----------\n setting : :class:`~.RIDTConfig`\n The settings for the run in question.\n \n data_store : Union[:class:`~.DataStore`, :class:`~.BatchDataStore`]\n The data store or batch data store to be analysed.\n \n \"\"\"\n self.setting = setting\n self.delta_t = self.setting.total_time / self.setting.time_samples\n self.data_store = self.evaluate(data_store)\n \n @property\n def geometries(self):\n \"\"\":obj:`list` [:obj:`str`] : the list of geometries selected for\n evaluation in :attr:`setting`.\n\n \"\"\"\n locations = self.setting.models.eddy_diffusion.monitor_locations\n return [g for g, e in locations.evaluate.items() if e]\n\n def compute(self, data: ndarray) -> ndarray:\n \"\"\"Cumulative integral over the time axis.\n\n Parameters\n ----------\n data : :class:`~numpy.ndarray`\n The data array to integrate over.\n\n Returns\n -------\n :class:`~numpy.ndarray`\n The integrated array containing exposures.\n\n \"\"\"\n return cumtrapz(data, dx=self.delta_t, axis=0, initial=0)\n\n def evaluate(self, data_store: Union[DataStore, BatchDataStore])\\\n -> Union[DataStore, BatchDataStore]:\n \"\"\"Iterates over all geometries and computes exposures.\n\n Parameters\n ----------\n data_store : Union[:class:`~.DataStore`, :class:`~.BatchDataStore`]\n The data store or batch data store to be analysed.\n\n Returns\n -------\n Union[:class:`~.DataStore`, :class:`~.BatchDataStore`]\n The computed exposures.\n\n Raises\n ------\n :obj:`TypeError`\n If the `data_store` is not a :class:`~.DataStore` or\n :class:`~.BatchDataStore`.\n\n \"\"\"\n if isinstance(data_store, DataStore):\n rv = DataStore()\n for geometry in self.geometries:\n for name, data in getattr(data_store, geometry).items():\n rv.add(geometry, name, self.compute(data))\n return rv\n elif isinstance(data_store, BatchDataStore):\n rv = BatchDataStore()\n for setting, store in data_store.items():\n rv.add_run(setting)\n rv[setting] = self.evaluate(data_store[setting])\n return rv\n else:\n raise TypeError(f\"Expecting {DataStore} or {BatchDataStore}.\")\n "
] |
[
[
"scipy.integrate.cumtrapz"
]
] |
arplaboratory/python_gp_kalman_hyperparam
|
[
"4540de21e98185767998a740ca47b20c7b31e563"
] |
[
"pssgp/toymodels/gp_samples.py"
] |
[
"\"\"\"\nDraw a sample from a GP.\n\n\"\"\"\n\nimport numpy as np\nfrom scipy.linalg import expm\n\n\n# from ..kalman import StateSpaceModel\n\ndef draw_gp_batch(gp: None,\n T: np.ndarray) -> np.ndarray:\n \"\"\"\n Draw a sample from an GP given cov and mean functions.\n \n Args:\n gp: GP object\n T: time instances (t1, t2, ...)\n \n Returns:\n f(t1, t2, ...)\n \"\"\"\n m = 0\n cov = 0\n\n return m + np.linalg.cholesky(cov) @ np.random.randn(T.shape[0])\n\n\ndef draw_gp_ss(gp: None,\n T: np.ndarray,\n t0: float,\n m0: np.ndarray,\n P0: np.ndarray) -> np.ndarray:\n \"\"\"\n Draw a GP sample from a LTI SDE.\n \n dx = F x dt + L dW, E[dWdW] = \\dirac\n \n x(t) = exp(F (t - t0)) x(t0) + \\int^t_{t0} exp(F (t - s)) L dW(s)\n \n Note that it must be LTI, or the matrix exponentional breaks.\n \"\"\"\n # Get F, L, Q etc from StateSpaceModel\n F = 0\n L = 0\n\n # Draw a init point\n x0 = m0 + np.linalg.cholesky(P0) @ np.random.rand(m0.shape[0])\n\n # Draw dW\n T_int = np.interp()\n dW = np.random.randn(T_int.shape[0])\n\n # Solution\n x = np.zeros(T.shape)\n ito_itegrand = np.zeros(T.shape)\n\n # ODE and Riemannian\n for id, t in enumerate(T):\n\n x[id] = expm(F * (t - t0)) @ x0\n\n # Riemannian\n for id2, s in [t0, t]:\n ito_itegrand[idx] = expm(F * (t - s)) * L * dW[0]\n\n x[id] += x[id] + np.sum(ito_itegrand)\n\n return x\n"
] |
[
[
"scipy.linalg.expm",
"numpy.random.randn",
"numpy.random.rand",
"numpy.interp",
"numpy.linalg.cholesky",
"numpy.zeros",
"numpy.sum"
]
] |
yull1860outlook/Data-Analysis
|
[
"34a48f16f6be757ed3f35cb3fc458569023c9bd8",
"34a48f16f6be757ed3f35cb3fc458569023c9bd8"
] |
[
"sentdex_data_analysis/pandas_joiningData.py",
"sentdex_data_analysis/pandas_intro.py"
] |
[
"import pickle\nimport pandas as pd\nimport quandl\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\n\nstyle.use(\"seaborn\")\n\nquandl.ApiConfig.api_key = \"rFsSehe51RLzREtYhLfo\"\n\n\ndef mortgage_30yr():\n df = quandl.get(\"FMAC/MORTG\")\n df = df[df.index > \"1974-12-01\"]\n df = (df[\"Value\"] - df[\"Value\"][0]) / df[\"Value\"][0] * 100\n df = df.resample(\"M\").mean()\n return df\n\n\nax1 = plt.subplot(2, 1, 1)\nax2 = plt.subplot(2, 1, 2, sharex=ax1)\n\n# initial_state_data()\n\npickle_in = open(\"fifty_states_pct.pickle\", \"rb\")\nHPI_data = pickle.load(pickle_in)\n\n# HPI_Benchmark()\n\npickle_in = open(\"us_pct.pickle\", \"rb\")\nbenchmark = pickle.load(pickle_in)\n\n\nm30 = mortgage_30yr()\n\nHPI_Bench = benchmark\n\nstate_HPI_M30 = HPI_data.join(m30)\nstate_HPI_M30.rename({\"Value\": \"M30\"}, inplace=True)\n\nprint(state_HPI_M30.corr().describe()[\"Value\"])\n",
"import pandas as pd\nimport datetime\nfrom pandas_datareader import data\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\n\nstyle.use(\"seaborn-dark\")\n\nstart = datetime.datetime(2010, 1, 1)\nend = datetime.datetime(2016, 12, 31)\n\ndf = data.DataReader(\"GM\", \"yahoo\", start, end)\n\nprint(df.head())\n\ndf[\"Adj Close\"].plot()\n\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.subplot",
"matplotlib.style.use"
],
[
"matplotlib.pyplot.show",
"matplotlib.style.use"
]
] |
evggenshch/EDVR
|
[
"ffcf0ca6b9f6f526c35b1d59dfdc75eb1757e2ec"
] |
[
"codes/test_Vid4_REDS4_with_GT_all.py"
] |
[
"\n'''\nTest Vid4 (SR) and REDS4 (SR-clean, SR-blur, deblur-clean, deblur-compression) datasets\n'''\n\nimport os\nimport os.path as osp\nimport glob\nimport logging\nimport numpy as np\nimport cv2\nimport torch\nimport copy\nimport json\n\nimport utils.util as util\nimport data.util as data_util\nimport models.archs.EDVR_arch as EDVR_arch\n\nimport argparse\n\nclass metrics_file:\n\n def __init__(self, name):\n self.name = name\n self.gt_ssim = []\n self.aposterior_ssim = []\n self.psnr = []\n\n def add_gt_ssim(self, gt_ssim):\n self.gt_ssim.append(gt_ssim)\n\n def add_aposterior_ssim(self, aposterior_ssim):\n self.aposterior_ssim.append(aposterior_ssim)\n\n def add_psnr(self, psnr):\n self.psnr.append(psnr)\n\n\n\ndef main():\n ####################\n # arguments parser #\n ####################\n # [format] dataset(vid4, REDS4) N(number of frames)\n\n\n\n # data_mode = str(args.dataset)\n # N_in = int(args.n_frames)\n # metrics = str(args.metrics)\n # output_format = str(args.output_format)\n\n\n #################\n # configurations\n #################\n device = torch.device('cuda')\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n #data_mode = 'Vid4' # Vid4 | sharp_bicubic | blur_bicubic | blur | blur_comp\n # Vid4: SR\n # REDS4: sharp_bicubic (SR-clean), blur_bicubic (SR-blur);\n # blur (deblur-clean), blur_comp (deblur-compression).\n\n\n # STAGE Vid4\n # Collecting results for Vid4\n\n model_path = '../experiments/pretrained_models/EDVR_Vimeo90K_SR_L.pth'\n stage = 1 # 1 or 2, use two stage strategy for REDS dataset.\n flip_test = False\n\n predeblur, HR_in = False, False\n back_RBs = 40\n\n N_model_default = 7\n data_mode = 'Vid4'\n\n # vid4_dir_map = {\"calendar\": 0, \"city\": 1, \"foliage\": 2, \"walk\": 3}\n vid4_results = {\"calendar\": {}, \"city\": {}, \"foliage\": {}, \"walk\": {}}\n\n #vid4_results = 4 * [[]]\n\n for N_in in range(1, N_model_default + 1):\n raw_model = EDVR_arch.EDVR(128, N_model_default, 8, 5, back_RBs, predeblur=predeblur, HR_in=HR_in)\n model = EDVR_arch.EDVR(128, N_in, 8, 5, back_RBs, predeblur=predeblur, HR_in=HR_in)\n\n test_dataset_folder = '../datasets/Vid4/BIx4'\n GT_dataset_folder = '../datasets/Vid4/GT'\n aposterior_GT_dataset_folder = '../datasets/Vid4/GT_7'\n\n crop_border = 0\n border_frame = N_in // 2 # border frames when evaluate\n padding = 'new_info'\n\n save_imgs = False\n\n raw_model.load_state_dict(torch.load(model_path), strict=True)\n\n model.nf = raw_model.nf\n model.center = N_in // 2 # if center is None else center\n model.is_predeblur = raw_model.is_predeblur\n model.HR_in = raw_model.HR_in\n model.w_TSA = raw_model.w_TSA\n\n if model.is_predeblur:\n model.pre_deblur = raw_model.pre_deblur # Predeblur_ResNet_Pyramid(nf=nf, HR_in=self.HR_in)\n model.conv_1x1 = raw_model.conv_1x1 # nn.Conv2d(nf, nf, 1, 1, bias=True)\n else:\n if model.HR_in:\n model.conv_first_1 = raw_model.conv_first_1 # nn.Conv2d(3, nf, 3, 1, 1, bias=True)\n model.conv_first_2 = raw_model.conv_first_2 # nn.Conv2d(nf, nf, 3, 2, 1, bias=True)\n model.conv_first_3 = raw_model.conv_first_3 # nn.Conv2d(nf, nf, 3, 2, 1, bias=True)\n else:\n model.conv_first = raw_model.conv_first # nn.Conv2d(3, nf, 3, 1, 1, bias=True)\n model.feature_extraction = raw_model.feature_extraction # arch_util.make_layer(ResidualBlock_noBN_f, front_RBs)\n model.fea_L2_conv1 = raw_model.fea_L2_conv1 # nn.Conv2d(nf, nf, 3, 2, 1, bias=True)\n model.fea_L2_conv2 = raw_model.fea_L2_conv2 # nn.Conv2d(nf, nf, 3, 1, 1, bias=True)\n model.fea_L3_conv1 = raw_model.fea_L3_conv1 # nn.Conv2d(nf, nf, 3, 2, 1, bias=True)\n model.fea_L3_conv2 = raw_model.fea_L3_conv2 # nn.Conv2d(nf, nf, 3, 1, 1, bias=True)\n\n model.pcd_align = raw_model.pcd_align # PCD_Align(nf=nf, groups=groups)\n\n model.tsa_fusion.center = model.center\n\n model.tsa_fusion.tAtt_1 = raw_model.tsa_fusion.tAtt_1\n model.tsa_fusion.tAtt_2 = raw_model.tsa_fusion.tAtt_2\n\n model.tsa_fusion.fea_fusion = copy.deepcopy(raw_model.tsa_fusion.fea_fusion)\n model.tsa_fusion.fea_fusion.weight = copy.deepcopy(torch.nn.Parameter(raw_model.tsa_fusion.fea_fusion.weight[:, 0:N_in * 128, :, :]))\n\n model.tsa_fusion.sAtt_1 = copy.deepcopy(raw_model.tsa_fusion.sAtt_1)\n model.tsa_fusion.sAtt_1.weight = copy.deepcopy(torch.nn.Parameter(raw_model.tsa_fusion.sAtt_1.weight[:, 0:N_in * 128, :, :]))\n\n model.tsa_fusion.maxpool = raw_model.tsa_fusion.maxpool\n model.tsa_fusion.avgpool = raw_model.tsa_fusion.avgpool\n model.tsa_fusion.sAtt_2 = raw_model.tsa_fusion.sAtt_2\n model.tsa_fusion.sAtt_3 = raw_model.tsa_fusion.sAtt_3\n model.tsa_fusion.sAtt_4 = raw_model.tsa_fusion.sAtt_4\n model.tsa_fusion.sAtt_5 = raw_model.tsa_fusion.sAtt_5\n model.tsa_fusion.sAtt_L1 = raw_model.tsa_fusion.sAtt_L1\n model.tsa_fusion.sAtt_L2 = raw_model.tsa_fusion.sAtt_L2\n model.tsa_fusion.sAtt_L3 = raw_model.tsa_fusion.sAtt_L3\n model.tsa_fusion.sAtt_add_1 = raw_model.tsa_fusion.sAtt_add_1\n model.tsa_fusion.sAtt_add_2 = raw_model.tsa_fusion.sAtt_add_2\n\n model.tsa_fusion.lrelu = raw_model.tsa_fusion.lrelu\n\n model.recon_trunk = raw_model.recon_trunk\n\n model.upconv1 = raw_model.upconv1\n model.upconv2 = raw_model.upconv2\n model.pixel_shuffle = raw_model.pixel_shuffle\n model.HRconv = raw_model.HRconv\n model.conv_last = raw_model.conv_last\n\n model.lrelu = raw_model.lrelu\n\n #####################################################\n\n model.eval()\n model = model.to(device)\n\n #avg_psnr_l, avg_psnr_center_l, avg_psnr_border_l = [], [], []\n subfolder_name_l = []\n\n subfolder_l = sorted(glob.glob(osp.join(test_dataset_folder, '*')))\n subfolder_GT_l = sorted(glob.glob(osp.join(GT_dataset_folder, '*')))\n\n subfolder_GT_a_l = sorted(glob.glob(osp.join(aposterior_GT_dataset_folder, \"*\")))\n # for each subfolder\n for subfolder, subfolder_GT, subfolder_GT_a in zip(subfolder_l, subfolder_GT_l, subfolder_GT_a_l):\n subfolder_name = osp.basename(subfolder)\n subfolder_name_l.append(subfolder_name)\n\n img_path_l = sorted(glob.glob(osp.join(subfolder, '*')))\n max_idx = len(img_path_l)\n\n print(\"MAX_IDX: \", max_idx)\n\n\n #### read LQ and GT images\n imgs_LQ = data_util.read_img_seq(subfolder)\n img_GT_l = []\n for img_GT_path in sorted(glob.glob(osp.join(subfolder_GT, '*'))):\n img_GT_l.append(data_util.read_img(None, img_GT_path))\n\n img_GT_a = []\n for img_GT_a_path in sorted(glob.glob(osp.join(subfolder_GT_a, '*'))):\n img_GT_a.append(data_util.read_img(None, img_GT_a_path))\n #avg_psnr, avg_psnr_border, avg_psnr_center, N_border, N_center = 0, 0, 0, 0, 0\n\n # process each image\n for img_idx, img_path in enumerate(img_path_l):\n img_name = osp.splitext(osp.basename(img_path))[0]\n select_idx = data_util.index_generation(img_idx, max_idx, N_in, padding=padding)\n\n imgs_in = imgs_LQ.index_select(0, torch.LongTensor(select_idx)).unsqueeze(0).to(device)\n\n if flip_test:\n output = util.flipx4_forward(model, imgs_in)\n else:\n print(\"IMGS_IN SHAPE: \", imgs_in.shape)\n output = util.single_forward(model, imgs_in)\n output = util.tensor2img(output.squeeze(0))\n\n # calculate PSNR\n output = output / 255.\n GT = np.copy(img_GT_l[img_idx])\n # For REDS, evaluate on RGB channels; for Vid4, evaluate on the Y channel\n #if data_mode == 'Vid4': # bgr2y, [0, 1]\n\n GT = data_util.bgr2ycbcr(GT, only_y=True)\n output = data_util.bgr2ycbcr(output, only_y=True)\n GT_a = np.copy(img_GT_a[img_idx])\n GT_a = data_util.bgr2ycbcr(GT_a, only_y=True)\n output_a = copy.deepcopy(output)\n\n output, GT = util.crop_border([output, GT], crop_border)\n crt_psnr = util.calculate_psnr(output * 255, GT * 255)\n crt_ssim = util.calculate_ssim(output * 255, GT * 255)\n\n output_a, GT_a = util.crop_border([output_a, GT_a], crop_border)\n\n crt_aposterior = util.calculate_ssim(output_a * 255, GT_a * 255) # CHANGE\n\n\n t = vid4_results[subfolder_name].get(str(img_name))\n\n if t != None:\n vid4_results[subfolder_name][img_name].add_psnr(crt_psnr)\n vid4_results[subfolder_name][img_name].add_gt_ssim(crt_ssim)\n vid4_results[subfolder_name][img_name].add_aposterior_ssim(crt_aposterior)\n else:\n vid4_results[subfolder_name].update({img_name: metrics_file(img_name)})\n vid4_results[subfolder_name][img_name].add_psnr(crt_psnr)\n vid4_results[subfolder_name][img_name].add_gt_ssim(crt_ssim)\n vid4_results[subfolder_name][img_name].add_aposterior_ssim(crt_aposterior)\n\n\n ############################################################################\n #### model\n\n\n\n#### writing vid4 results\n\n\n util.mkdirs('../results/calendar')\n util.mkdirs('../results/city')\n util.mkdirs('../results/foliage')\n util.mkdirs('../results/walk')\n save_folder = '../results/'\n\n for i, dir_name in enumerate([\"calendar\", \"city\", \"foliage\", \"walk\"]):\n save_subfolder = osp.join(save_folder, dir_name)\n for j, value in vid4_results[dir_name].items():\n # cur_result = json.dumps(_)\n with open(osp.join(save_subfolder, '{}.json'.format(value.name)), 'w') as outfile:\n json.dump(value.__dict__, outfile, ensure_ascii=False, indent=4)\n #json.dump(cur_result, outfile)\n\n #cv2.imwrite(osp.join(save_subfolder, '{}.png'.format(img_name)), output)\n\n\n\n###################################################################################\n\n\n\n\n\n # STAGE REDS\n\n reds4_results = {\"000\": {}, \"011\": {}, \"015\": {}, \"020\": {}}\n data_mode = 'sharp_bicubic'\n\n N_model_default = 5\n\n for N_in in range(1, N_model_default + 1):\n for stage in range(1,3):\n\n flip_test = False\n\n if data_mode == 'sharp_bicubic':\n if stage == 1:\n model_path = '../experiments/pretrained_models/EDVR_REDS_SR_L.pth'\n else:\n model_path = '../experiments/pretrained_models/EDVR_REDS_SR_Stage2.pth'\n elif data_mode == 'blur_bicubic':\n if stage == 1:\n model_path = '../experiments/pretrained_models/EDVR_REDS_SRblur_L.pth'\n else:\n model_path = '../experiments/pretrained_models/EDVR_REDS_SRblur_Stage2.pth'\n elif data_mode == 'blur':\n if stage == 1:\n model_path = '../experiments/pretrained_models/EDVR_REDS_deblur_L.pth'\n else:\n model_path = '../experiments/pretrained_models/EDVR_REDS_deblur_Stage2.pth'\n elif data_mode == 'blur_comp':\n if stage == 1:\n model_path = '../experiments/pretrained_models/EDVR_REDS_deblurcomp_L.pth'\n else:\n model_path = '../experiments/pretrained_models/EDVR_REDS_deblurcomp_Stage2.pth'\n else:\n raise NotImplementedError\n\n predeblur, HR_in = False, False\n back_RBs = 40\n if data_mode == 'blur_bicubic':\n predeblur = True\n if data_mode == 'blur' or data_mode == 'blur_comp':\n predeblur, HR_in = True, True\n if stage == 2:\n HR_in = True\n back_RBs = 20\n\n if stage == 1:\n test_dataset_folder = '../datasets/REDS4/{}'.format(data_mode)\n else:\n test_dataset_folder = '../results/REDS-EDVR_REDS_SR_L_flipx4'\n print('You should modify the test_dataset_folder path for stage 2')\n GT_dataset_folder = '../datasets/REDS4/GT'\n\n raw_model = EDVR_arch.EDVR(128, N_model_default, 8, 5, back_RBs, predeblur=predeblur, HR_in=HR_in)\n model = EDVR_arch.EDVR(128, N_in, 8, 5, back_RBs, predeblur=predeblur, HR_in=HR_in)\n\n crop_border = 0\n border_frame = N_in // 2 # border frames when evaluate\n # temporal padding mode\n if data_mode == 'Vid4' or data_mode == 'sharp_bicubic':\n padding = 'new_info'\n else:\n padding = 'replicate'\n save_imgs = True\n\n data_mode_t = copy.deepcopy(data_mode)\n if stage == 1 and data_mode_t != 'Vid4':\n data_mode = 'REDS-EDVR_REDS_SR_L_flipx4'\n save_folder = '../results/{}'.format(data_mode)\n data_mode = copy.deepcopy(data_mode_t)\n util.mkdirs(save_folder)\n util.setup_logger('base', save_folder, 'test', level=logging.INFO, screen=True, tofile=True)\n\n\n aposterior_GT_dataset_folder = '../datasets/REDS4/GT_5'\n\n crop_border = 0\n border_frame = N_in // 2 # border frames when evaluate\n\n raw_model.load_state_dict(torch.load(model_path), strict=True)\n\n model.nf = raw_model.nf\n model.center = N_in // 2 # if center is None else center\n model.is_predeblur = raw_model.is_predeblur\n model.HR_in = raw_model.HR_in\n model.w_TSA = raw_model.w_TSA\n\n if model.is_predeblur:\n model.pre_deblur = raw_model.pre_deblur # Predeblur_ResNet_Pyramid(nf=nf, HR_in=self.HR_in)\n model.conv_1x1 = raw_model.conv_1x1 # nn.Conv2d(nf, nf, 1, 1, bias=True)\n else:\n if model.HR_in:\n model.conv_first_1 = raw_model.conv_first_1 # nn.Conv2d(3, nf, 3, 1, 1, bias=True)\n model.conv_first_2 = raw_model.conv_first_2 # nn.Conv2d(nf, nf, 3, 2, 1, bias=True)\n model.conv_first_3 = raw_model.conv_first_3 # nn.Conv2d(nf, nf, 3, 2, 1, bias=True)\n else:\n model.conv_first = raw_model.conv_first # nn.Conv2d(3, nf, 3, 1, 1, bias=True)\n model.feature_extraction = raw_model.feature_extraction # arch_util.make_layer(ResidualBlock_noBN_f, front_RBs)\n model.fea_L2_conv1 = raw_model.fea_L2_conv1 # nn.Conv2d(nf, nf, 3, 2, 1, bias=True)\n model.fea_L2_conv2 = raw_model.fea_L2_conv2 # nn.Conv2d(nf, nf, 3, 1, 1, bias=True)\n model.fea_L3_conv1 = raw_model.fea_L3_conv1 # nn.Conv2d(nf, nf, 3, 2, 1, bias=True)\n model.fea_L3_conv2 = raw_model.fea_L3_conv2 # nn.Conv2d(nf, nf, 3, 1, 1, bias=True)\n\n model.pcd_align = raw_model.pcd_align # PCD_Align(nf=nf, groups=groups)\n\n model.tsa_fusion.center = model.center\n\n model.tsa_fusion.tAtt_1 = raw_model.tsa_fusion.tAtt_1\n model.tsa_fusion.tAtt_2 = raw_model.tsa_fusion.tAtt_2\n\n model.tsa_fusion.fea_fusion = copy.deepcopy(raw_model.tsa_fusion.fea_fusion)\n model.tsa_fusion.fea_fusion.weight = copy.deepcopy(torch.nn.Parameter(raw_model.tsa_fusion.fea_fusion.weight[:, 0:N_in * 128, :, :]))\n\n model.tsa_fusion.sAtt_1 = copy.deepcopy(raw_model.tsa_fusion.sAtt_1)\n model.tsa_fusion.sAtt_1.weight = copy.deepcopy(torch.nn.Parameter(raw_model.tsa_fusion.sAtt_1.weight[:, 0:N_in * 128, :, :]))\n\n model.tsa_fusion.maxpool = raw_model.tsa_fusion.maxpool\n model.tsa_fusion.avgpool = raw_model.tsa_fusion.avgpool\n model.tsa_fusion.sAtt_2 = raw_model.tsa_fusion.sAtt_2\n model.tsa_fusion.sAtt_3 = raw_model.tsa_fusion.sAtt_3\n model.tsa_fusion.sAtt_4 = raw_model.tsa_fusion.sAtt_4\n model.tsa_fusion.sAtt_5 = raw_model.tsa_fusion.sAtt_5\n model.tsa_fusion.sAtt_L1 = raw_model.tsa_fusion.sAtt_L1\n model.tsa_fusion.sAtt_L2 = raw_model.tsa_fusion.sAtt_L2\n model.tsa_fusion.sAtt_L3 = raw_model.tsa_fusion.sAtt_L3\n model.tsa_fusion.sAtt_add_1 = raw_model.tsa_fusion.sAtt_add_1\n model.tsa_fusion.sAtt_add_2 = raw_model.tsa_fusion.sAtt_add_2\n\n model.tsa_fusion.lrelu = raw_model.tsa_fusion.lrelu\n\n model.recon_trunk = raw_model.recon_trunk\n\n model.upconv1 = raw_model.upconv1\n model.upconv2 = raw_model.upconv2\n model.pixel_shuffle = raw_model.pixel_shuffle\n model.HRconv = raw_model.HRconv\n model.conv_last = raw_model.conv_last\n\n model.lrelu = raw_model.lrelu\n\n #####################################################\n\n model.eval()\n model = model.to(device)\n\n #avg_psnr_l, avg_psnr_center_l, avg_psnr_border_l = [], [], []\n subfolder_name_l = []\n\n subfolder_l = sorted(glob.glob(osp.join(test_dataset_folder, '*')))\n subfolder_GT_l = sorted(glob.glob(osp.join(GT_dataset_folder, '*')))\n\n subfolder_GT_a_l = sorted(glob.glob(osp.join(aposterior_GT_dataset_folder, \"*\")))\n # for each subfolder\n for subfolder, subfolder_GT, subfolder_GT_a in zip(subfolder_l, subfolder_GT_l, subfolder_GT_a_l):\n\n subfolder_name = osp.basename(subfolder)\n subfolder_name_l.append(subfolder_name)\n save_subfolder = osp.join(save_folder, subfolder_name)\n\n img_path_l = sorted(glob.glob(osp.join(subfolder, '*')))\n max_idx = len(img_path_l)\n\n print(\"MAX_IDX: \", max_idx)\n\n print(\"SAVE FOLDER::::::\", save_folder)\n\n if save_imgs:\n util.mkdirs(save_subfolder)\n\n\n #### read LQ and GT images\n imgs_LQ = data_util.read_img_seq(subfolder)\n img_GT_l = []\n for img_GT_path in sorted(glob.glob(osp.join(subfolder_GT, '*'))):\n img_GT_l.append(data_util.read_img(None, img_GT_path))\n\n img_GT_a = []\n for img_GT_a_path in sorted(glob.glob(osp.join(subfolder_GT_a, '*'))):\n img_GT_a.append(data_util.read_img(None, img_GT_a_path))\n #avg_psnr, avg_psnr_border, avg_psnr_center, N_border, N_center = 0, 0, 0, 0, 0\n\n # process each image\n for img_idx, img_path in enumerate(img_path_l):\n img_name = osp.splitext(osp.basename(img_path))[0]\n select_idx = data_util.index_generation(img_idx, max_idx, N_in, padding=padding)\n\n imgs_in = imgs_LQ.index_select(0, torch.LongTensor(select_idx)).unsqueeze(0).to(device)\n\n if flip_test:\n output = util.flipx4_forward(model, imgs_in)\n else:\n print(\"IMGS_IN SHAPE: \", imgs_in.shape)\n output = util.single_forward(model, imgs_in)\n output = util.tensor2img(output.squeeze(0))\n\n if save_imgs and stage == 1:\n cv2.imwrite(osp.join(save_subfolder, '{}.png'.format(img_name)), output)\n # calculate PSNR\n if stage == 2:\n\n output = output / 255.\n GT = np.copy(img_GT_l[img_idx])\n # For REDS, evaluate on RGB channels; for Vid4, evaluate on the Y channel\n #if data_mode == 'Vid4': # bgr2y, [0, 1]\n\n GT_a = np.copy(img_GT_a[img_idx])\n output_a = copy.deepcopy(output)\n\n output, GT = util.crop_border([output, GT], crop_border)\n crt_psnr = util.calculate_psnr(output * 255, GT * 255)\n crt_ssim = util.calculate_ssim(output * 255, GT * 255)\n\n output_a, GT_a = util.crop_border([output_a, GT_a], crop_border)\n\n crt_aposterior = util.calculate_ssim(output_a * 255, GT_a * 255) # CHANGE\n\n\n t = reds4_results[subfolder_name].get(str(img_name))\n\n if t != None:\n reds4_results[subfolder_name][img_name].add_psnr(crt_psnr)\n reds4_results[subfolder_name][img_name].add_gt_ssim(crt_ssim)\n reds4_results[subfolder_name][img_name].add_aposterior_ssim(crt_aposterior)\n else:\n reds4_results[subfolder_name].update({img_name: metrics_file(img_name)})\n reds4_results[subfolder_name][img_name].add_psnr(crt_psnr)\n reds4_results[subfolder_name][img_name].add_gt_ssim(crt_ssim)\n reds4_results[subfolder_name][img_name].add_aposterior_ssim(crt_aposterior)\n\n\n\n ############################################################################\n #### model\n\n\n\n#### writing reds4 results\n\n util.mkdirs('../results/000')\n util.mkdirs('../results/011')\n util.mkdirs('../results/015')\n util.mkdirs('../results/020')\n save_folder = '../results/'\n\n for i, dir_name in enumerate([\"000\", \"011\", \"015\", \"020\"]): # +\n save_subfolder = osp.join(save_folder, dir_name)\n for j, value in reds4_results[dir_name].items():\n # cur_result = json.dumps(value.__dict__)\n with open(osp.join(save_subfolder, '{}.json'.format(value.name)), 'w') as outfile:\n json.dump(value.__dict__, outfile, ensure_ascii=False, indent=4)\n\n\n\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"torch.LongTensor",
"torch.nn.Parameter",
"torch.load",
"numpy.copy",
"torch.device"
]
] |
maxberezov/PaddleOCR
|
[
"09604c38e42591c240771edbbff43a6dd7ebf592",
"09604c38e42591c240771edbbff43a6dd7ebf592"
] |
[
"ppocr/data/imaug/gen_table_mask.py",
"tools/infer_e2e.py"
] |
[
"\"\"\"\n# Copyright (c) 2020 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\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport sys\nimport six\nimport cv2\nimport numpy as np\n\n\nclass GenTableMask(object):\n \"\"\" gen table mask \"\"\"\n\n def __init__(self, shrink_h_max, shrink_w_max, mask_type=0, **kwargs):\n self.shrink_h_max = 5\n self.shrink_w_max = 5\n self.mask_type = mask_type\n \n def projection(self, erosion, h, w, spilt_threshold=0):\n # 水平投影\n projection_map = np.ones_like(erosion)\n project_val_array = [0 for _ in range(0, h)]\n\n for j in range(0, h):\n for i in range(0, w):\n if erosion[j, i] == 255:\n project_val_array[j] += 1\n # 根据数组,获取切割点\n start_idx = 0 # 记录进入字符区的索引\n end_idx = 0 # 记录进入空白区域的索引\n in_text = False # 是否遍历到了字符区内\n box_list = []\n for i in range(len(project_val_array)):\n if in_text == False and project_val_array[i] > spilt_threshold: # 进入字符区了\n in_text = True\n start_idx = i\n elif project_val_array[i] <= spilt_threshold and in_text == True: # 进入空白区了\n end_idx = i\n in_text = False\n if end_idx - start_idx <= 2:\n continue\n box_list.append((start_idx, end_idx + 1))\n\n if in_text:\n box_list.append((start_idx, h - 1))\n # 绘制投影直方图\n for j in range(0, h):\n for i in range(0, project_val_array[j]):\n projection_map[j, i] = 0\n return box_list, projection_map\n\n def projection_cx(self, box_img):\n box_gray_img = cv2.cvtColor(box_img, cv2.COLOR_BGR2GRAY)\n h, w = box_gray_img.shape\n # 灰度图片进行二值化处理\n ret, thresh1 = cv2.threshold(box_gray_img, 200, 255, cv2.THRESH_BINARY_INV)\n # 纵向腐蚀\n if h < w:\n kernel = np.ones((2, 1), np.uint8)\n erode = cv2.erode(thresh1, kernel, iterations=1)\n else:\n erode = thresh1\n # 水平膨胀\n kernel = np.ones((1, 5), np.uint8)\n erosion = cv2.dilate(erode, kernel, iterations=1)\n # 水平投影\n projection_map = np.ones_like(erosion)\n project_val_array = [0 for _ in range(0, h)]\n\n for j in range(0, h):\n for i in range(0, w):\n if erosion[j, i] == 255:\n project_val_array[j] += 1\n # 根据数组,获取切割点\n start_idx = 0 # 记录进入字符区的索引\n end_idx = 0 # 记录进入空白区域的索引\n in_text = False # 是否遍历到了字符区内\n box_list = []\n spilt_threshold = 0\n for i in range(len(project_val_array)):\n if in_text == False and project_val_array[i] > spilt_threshold: # 进入字符区了\n in_text = True\n start_idx = i\n elif project_val_array[i] <= spilt_threshold and in_text == True: # 进入空白区了\n end_idx = i\n in_text = False\n if end_idx - start_idx <= 2:\n continue\n box_list.append((start_idx, end_idx + 1))\n\n if in_text:\n box_list.append((start_idx, h - 1))\n # 绘制投影直方图\n for j in range(0, h):\n for i in range(0, project_val_array[j]):\n projection_map[j, i] = 0\n split_bbox_list = []\n if len(box_list) > 1:\n for i, (h_start, h_end) in enumerate(box_list):\n if i == 0:\n h_start = 0\n if i == len(box_list):\n h_end = h\n word_img = erosion[h_start:h_end + 1, :]\n word_h, word_w = word_img.shape\n w_split_list, w_projection_map = self.projection(word_img.T, word_w, word_h)\n w_start, w_end = w_split_list[0][0], w_split_list[-1][1]\n if h_start > 0:\n h_start -= 1\n h_end += 1\n word_img = box_img[h_start:h_end + 1:, w_start:w_end + 1, :]\n split_bbox_list.append([w_start, h_start, w_end, h_end])\n else:\n split_bbox_list.append([0, 0, w, h])\n return split_bbox_list\n\n def shrink_bbox(self, bbox):\n left, top, right, bottom = bbox\n sh_h = min(max(int((bottom - top) * 0.1), 1), self.shrink_h_max)\n sh_w = min(max(int((right - left) * 0.1), 1), self.shrink_w_max)\n left_new = left + sh_w\n right_new = right - sh_w\n top_new = top + sh_h\n bottom_new = bottom - sh_h\n if left_new >= right_new:\n left_new = left\n right_new = right\n if top_new >= bottom_new:\n top_new = top\n bottom_new = bottom\n return [left_new, top_new, right_new, bottom_new]\n\n def __call__(self, data):\n img = data['image']\n cells = data['cells']\n height, width = img.shape[0:2]\n if self.mask_type == 1:\n mask_img = np.zeros((height, width), dtype=np.float32)\n else:\n mask_img = np.zeros((height, width, 3), dtype=np.float32)\n cell_num = len(cells)\n for cno in range(cell_num):\n if \"bbox\" in cells[cno]:\n bbox = cells[cno]['bbox']\n left, top, right, bottom = bbox\n box_img = img[top:bottom, left:right, :].copy()\n split_bbox_list = self.projection_cx(box_img)\n for sno in range(len(split_bbox_list)):\n split_bbox_list[sno][0] += left\n split_bbox_list[sno][1] += top\n split_bbox_list[sno][2] += left\n split_bbox_list[sno][3] += top\n\n for sno in range(len(split_bbox_list)):\n left, top, right, bottom = split_bbox_list[sno]\n left, top, right, bottom = self.shrink_bbox([left, top, right, bottom])\n if self.mask_type == 1:\n mask_img[top:bottom, left:right] = 1.0\n data['mask_img'] = mask_img\n else:\n mask_img[top:bottom, left:right, :] = (255, 255, 255) \n data['image'] = mask_img\n return data\n\nclass ResizeTableImage(object):\n def __init__(self, max_len, **kwargs):\n super(ResizeTableImage, self).__init__()\n self.max_len = max_len\n\n def get_img_bbox(self, cells):\n bbox_list = []\n if len(cells) == 0:\n return bbox_list\n cell_num = len(cells)\n for cno in range(cell_num):\n if \"bbox\" in cells[cno]:\n bbox = cells[cno]['bbox']\n bbox_list.append(bbox)\n return bbox_list\n\n def resize_img_table(self, img, bbox_list, max_len):\n height, width = img.shape[0:2]\n ratio = max_len / (max(height, width) * 1.0)\n resize_h = int(height * ratio)\n resize_w = int(width * ratio)\n img_new = cv2.resize(img, (resize_w, resize_h))\n bbox_list_new = []\n for bno in range(len(bbox_list)):\n left, top, right, bottom = bbox_list[bno].copy()\n left = int(left * ratio)\n top = int(top * ratio)\n right = int(right * ratio)\n bottom = int(bottom * ratio)\n bbox_list_new.append([left, top, right, bottom])\n return img_new, bbox_list_new\n \n def __call__(self, data):\n img = data['image']\n if 'cells' not in data:\n cells = []\n else:\n cells = data['cells']\n bbox_list = self.get_img_bbox(cells)\n img_new, bbox_list_new = self.resize_img_table(img, bbox_list, self.max_len)\n data['image'] = img_new\n cell_num = len(cells)\n bno = 0\n for cno in range(cell_num):\n if \"bbox\" in data['cells'][cno]:\n data['cells'][cno]['bbox'] = bbox_list_new[bno]\n bno += 1\n data['max_len'] = self.max_len\n return data\n\nclass PaddingTableImage(object):\n def __init__(self, **kwargs):\n super(PaddingTableImage, self).__init__()\n \n def __call__(self, data):\n img = data['image']\n max_len = data['max_len']\n padding_img = np.zeros((max_len, max_len, 3), dtype=np.float32)\n height, width = img.shape[0:2]\n padding_img[0:height, 0:width, :] = img.copy()\n data['image'] = padding_img\n return data\n ",
"# Copyright (c) 2020 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\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nimport os\nimport sys\n\n__dir__ = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(__dir__)\nsys.path.append(os.path.abspath(os.path.join(__dir__, '..')))\n\nos.environ[\"FLAGS_allocator_strategy\"] = 'auto_growth'\n\nimport cv2\nimport json\nimport paddle\n\nfrom ppocr.data import create_operators, transform\nfrom ppocr.modeling.architectures import build_model\nfrom ppocr.postprocess import build_post_process\nfrom ppocr.utils.save_load import init_model\nfrom ppocr.utils.utility import get_image_file_list\nimport tools.program as program\n\n\ndef draw_e2e_res(dt_boxes, strs, config, img, img_name):\n if len(dt_boxes) > 0:\n src_im = img\n for box, str in zip(dt_boxes, strs):\n box = box.astype(np.int32).reshape((-1, 1, 2))\n cv2.polylines(src_im, [box], True, color=(255, 255, 0), thickness=2)\n cv2.putText(\n src_im,\n str,\n org=(int(box[0, 0, 0]), int(box[0, 0, 1])),\n fontFace=cv2.FONT_HERSHEY_COMPLEX,\n fontScale=0.7,\n color=(0, 255, 0),\n thickness=1)\n save_det_path = os.path.dirname(config['Global'][\n 'save_res_path']) + \"/e2e_results/\"\n if not os.path.exists(save_det_path):\n os.makedirs(save_det_path)\n save_path = os.path.join(save_det_path, os.path.basename(img_name))\n cv2.imwrite(save_path, src_im)\n logger.info(\"The e2e Image saved in {}\".format(save_path))\n\n\ndef main():\n global_config = config['Global']\n\n # build model\n model = build_model(config['Architecture'])\n\n init_model(config, model)\n\n # build post process\n post_process_class = build_post_process(config['PostProcess'],\n global_config)\n\n # create data ops\n transforms = []\n for op in config['Eval']['dataset']['transforms']:\n op_name = list(op)[0]\n if 'Label' in op_name:\n continue\n elif op_name == 'KeepKeys':\n op[op_name]['keep_keys'] = ['image', 'shape']\n transforms.append(op)\n\n ops = create_operators(transforms, global_config)\n\n save_res_path = config['Global']['save_res_path']\n if not os.path.exists(os.path.dirname(save_res_path)):\n os.makedirs(os.path.dirname(save_res_path))\n\n model.eval()\n with open(save_res_path, \"wb\") as fout:\n for file in get_image_file_list(config['Global']['infer_img']):\n logger.info(\"infer_img: {}\".format(file))\n with open(file, 'rb') as f:\n img = f.read()\n data = {'image': img}\n batch = transform(data, ops)\n images = np.expand_dims(batch[0], axis=0)\n shape_list = np.expand_dims(batch[1], axis=0)\n images = paddle.to_tensor(images)\n preds = model(images)\n post_result = post_process_class(preds, shape_list)\n points, strs = post_result['points'], post_result['texts']\n # write resule\n dt_boxes_json = []\n for poly, str in zip(points, strs):\n tmp_json = {\"transcription\": str}\n tmp_json['points'] = poly.tolist()\n dt_boxes_json.append(tmp_json)\n otstr = file + \"\\t\" + json.dumps(dt_boxes_json) + \"\\n\"\n fout.write(otstr.encode())\n src_img = cv2.imread(file)\n draw_e2e_res(points, strs, config, src_img, file)\n logger.info(\"success!\")\n\n\nif __name__ == '__main__':\n config, device, logger, vdl_writer = program.preprocess()\n main()\n"
] |
[
[
"numpy.ones_like",
"numpy.zeros",
"numpy.ones"
],
[
"numpy.expand_dims"
]
] |
JeshuaT/PsyNeuLink
|
[
"912f691028e848659055430f37b6c15273c762f1",
"912f691028e848659055430f37b6c15273c762f1"
] |
[
"psyneulink/library/models/Nieuwenhuis2005Model.py",
"Scripts/Debug/markus_test_umemoto.py"
] |
[
"# Import all dependencies.\nimport argparse\n\nimport numpy as np\nimport psyneulink as pnl\n# from scipy.special import erfinv # need to import this to make us of the UniformToNormalDist function.\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--no-plot', action='store_false', help='Disable plotting', dest='enable_plot')\nargs = parser.parse_args()\n\n# --------------------------------- Global Variables ----------------------------------------\n# Now, we set the global variables, weights and initial values as in the paper.\n# WATCH OUT !!! In the paper the weight \"Mutual inhibition among response units\" is not defined, but needs to be set to\n# 0 in order to reproduce the paper.\nSD = 0.15 # noise determined by standard deviation (SD)\na = 0.50 # Parameter describing shape of the FitzHugh–Nagumo cubic nullcline for the fast excitation variable v\nd = 0.5 # Uncorrelated Activity\nk = 1.5 # Scaling factor for transforming NE release (u ) to gain (g ) on potentiated units\nG = 0.5 # Base level of gain applied to decision and response units\ndt = 0.02 # time step size\nC = 0.90 # LC coherence (see Gilzenrat et al. (2002) on more details on LC coherence\n\ninitial_hv = 0.07 # Initial value for h(v)\ninitial_w = 0.14 # initial value u\ninitial_v = (initial_hv - (1 - C) * d) / C # get initial v from initial h(v)\n\n# Weights:\ninpwt = 1.5 # inpwt (Input to decision layer)\ncrswt = 1 / 3 # crswt (Crosstalk input to decision layer)\ninhwt = 1.0 # inhwt (Mutual inhibition among decision units)\nrespinhwt = 0 # respinhwt (Mutual inhibition among response units) !!! WATCH OUT: this parameter is not mentioned\n# in the original paper, most likely since it was set 0\ndecwt = 3.5 # decwt (Target decision unit to response unit)\nselfdwt = 2.5 # selfdwt (Self recurrent conn. for each decision unit)\nselfrwt = 2.0 # selfrwt (Self recurrent conn. for response unit)\nlcwt = 0.3 # lcwt (Target decision unit to LC)\ndecbias = 1.75 # decbias (Bias input to decision units)\nrespbias = 1.75 # respbias (Bias input to response units)\ntau_v = 0.05 # Time constant for fast LC excitation variable v\ntau_u = 5.00 # Time constant for slow LC recovery variable (‘NE release’) u\ntrials = 1100 # number of trials to reproduce Figure 3 from Nieuwenhuis et al. (2005)\n\n# Setting seed (if noise is applied)\n# np.random.seed(22) # Set noise with seed generator to 22 to use the UniformToNormalDist function to have a python\n# seed compatible with MATLAB random seed generator (rsg=22)\n# Please see https://github.com/jonasrauber/randn-matlab-python for further documentation\n\n# Create mechanisms ---------------------------------------------------------------------------------------------------\n\n# Input Layer --- [ Target 1, Target 2, Distractor ]\n\n# First, we create the 3 layers of the behavioral network, i.e. INPUT LAYER, DECISION LAYER, and RESPONSE LAYER.\ninput_layer = pnl.TransferMechanism(\n size=3, # Number of units in input layer\n initial_value=[[0.0, 0.0, 0.0]], # Initial input values\n name='INPUT LAYER' # Define the name of the layer; this is optional,\n) # but will help you to overview your model later on\n\n# Create Decision Layer --- [ Target 1, Target 2, Distractor ]\ndecision_layer = pnl.LCAMechanism(\n size=3, # Number of units in input layer\n initial_value=[[0.0, 0.0, 0.0]], # Initial input values\n time_step_size=dt, # Integration step size\n leak=1.0, # Sets off diagonals to negative values\n self_excitation=selfdwt, # Set diagonals to self excitate\n competition=inhwt, # Set off diagonals to inhibit\n function=pnl.Logistic(x_0=decbias), # Set the Logistic function with bias = decbias\n # noise=pnl.UniformToNormalDist(standard_deviation = SD).function, # The UniformToNormalDist function will\n integrator_mode=True, # set the noise with a seed generator that is compatible with\n name='DECISION LAYER' # MATLAB random seed generator 22 (rsg=22)\n)\n\n# decision_layer.set_log_conditions('RESULT') # Log RESULT of the decision layer\ndecision_layer.set_log_conditions('value') # Log value of the decision layer\n\nfor output_port in decision_layer.output_ports:\n output_port.parameters.value.set(output_port.value * 0.0, override=True) # Set initial output values for decision layer to 0\n\n# Create Response Layer --- [ Target1, Target2 ]\nresponse_layer = pnl.LCAMechanism(\n size=2, # Number of units in input layer\n initial_value=[[0.0, 0.0]], # Initial input values\n time_step_size=dt, # Integration step size\n leak=1.0, # Sets off diagonals to negative values\n self_excitation=selfrwt, # Set diagonals to self excitate\n competition=respinhwt, # Set off diagonals to inhibit\n function=pnl.Logistic(x_0=respbias), # Set the Logistic function with bias = decbias\n # noise=pnl.UniformToNormalDist(standard_deviation = SD).function,\n integrator_mode=True,\n name='RESPONSE LAYER'\n)\n\nresponse_layer.set_log_conditions('RESULT') # Log RESULT of the response layer\nfor output_port in response_layer.output_ports:\n output_port.parameters.value.set(output_port.value * 0.0, override=True) # Set initial output values for response layer to 0\n\n# Connect mechanisms --------------------------------------------------------------------------------------------------\n# Weight matrix from Input Layer --> Decision Layer\ninput_weights = np.array([\n [inpwt, crswt, crswt], # Input weights are diagonals, cross weights are off diagonals\n [crswt, inpwt, crswt],\n [crswt, crswt, inpwt]\n])\n\n# Weight matrix from Decision Layer --> Response Layer\noutput_weights = np.array([\n [decwt, 0.0], # Weight from T1 and T2 but not distractor unit (row 3 set to all zeros) to response layer\n [0.0, decwt], # Need a 3 by 2 matrix, to project from decision layer with 3 units to response layer with 2 units\n [0.0, 0.0]\n])\n\ndecision_pathway = pnl.Pathway(\n pathway=[\n input_layer,\n input_weights,\n decision_layer,\n output_weights,\n response_layer\n ],\n name='DECISION PATHWAY'\n)\n\n# Abstracted LC to modulate gain --------------------------------------------------------------------\n\n# This LCControlMechanism modulates gain.\nLC = pnl.LCControlMechanism(\n integration_method=\"EULER\", # We set the integration method to Euler like in the paper\n threshold_FitzHughNagumo=a, # Here we use the Euler method for integration and we want to set the parameters,\n uncorrelated_activity_FitzHughNagumo=d, # for the FitzHugh–Nagumo system.\n time_step_size_FitzHughNagumo=dt,\n mode_FitzHughNagumo=C,\n time_constant_v_FitzHughNagumo=tau_v,\n time_constant_w_FitzHughNagumo=tau_u,\n a_v_FitzHughNagumo=-1.0,\n b_v_FitzHughNagumo=1.0,\n c_v_FitzHughNagumo=1.0,\n d_v_FitzHughNagumo=0.0,\n e_v_FitzHughNagumo=-1.0,\n f_v_FitzHughNagumo=1.0,\n a_w_FitzHughNagumo=1.0,\n b_w_FitzHughNagumo=-1.0,\n c_w_FitzHughNagumo=0.0,\n t_0_FitzHughNagumo=0.0,\n base_level_gain=G, # Additionally, we set the parameters k and G to compute the gain equation\n scaling_factor_gain=k,\n initial_v_FitzHughNagumo=initial_v, # Initialize v\n initial_w_FitzHughNagumo=initial_w, # Initialize w\n objective_mechanism=pnl.ObjectiveMechanism(\n function=pnl.Linear,\n monitor=[(\n decision_layer, # Project output of T1 and T2 but not distractor from decision layer to LC\n np.array([[lcwt], [lcwt], [0.0]])\n )],\n name='Combine values'\n ),\n modulated_mechanisms=[decision_layer, response_layer], # Modulate gain of decision & response layers\n name='LC'\n)\n\n# Log value of LC\nLC.set_log_conditions('value')\n\n# Set initial gain to G + k*initial_w, when the System runs the very first time,\n# since the decison layer executes before the LC and hence needs one initial gain value to start with.\nfor output_port in LC.output_ports:\n output_port.parameters.value.set(output_port.value * (G + k * initial_w), override=True)\n\ntask = pnl.Composition()\ntask.add_linear_processing_pathway(decision_pathway)\ntask.add_node(LC)\n\n# Create Stimulus -----------------------------------------------------------------------------------------------------\n\n# In the paper, each period has 100 time steps, so we will create 11 time periods.\n# As described in the paper in figure 3, during the first 3 time periods input to distractor units is fixed to 1.\n# Then T1 gets turned on during time period 4 with an input of 1.\n# T2 gets turns on with some lag from T1 onset on, in this example we turn T2 on with Lag 2 and an input of 1\n# Between T1 and T2 and after T2 the distractor unit is on.\n# We create one array with 3 numbers, one for each input unit and repeat this array 100 times for one time period\n# We do this 11 times. T1 is on for time4, T2 is on for time7 to model Lag3\nnum_time_steps = 100 # Each stimulus is presented for two units of time which is equivalent to 100 time steps\nstimulus_T1 = np.repeat(np.array([[0, 0, 1]]), num_time_steps, axis=0)\nstimulus_T2 = np.repeat(np.array([[0, 0, 1]]), num_time_steps, axis=0)\nstimulus_T3 = np.repeat(np.array([[0, 0, 1]]), num_time_steps, axis=0)\nstimulus_T4 = np.repeat(np.array([[1, 0, 0]]), num_time_steps, axis=0) # Turn T1 on\nstimulus_T5 = np.repeat(np.array([[0, 0, 1]]), num_time_steps, axis=0)\nstimulus_T6 = np.repeat(np.array([[0, 1, 0]]), num_time_steps, axis=0) # Turn T2 on --> example for Lag 2\nstimulus_T7 = np.repeat(np.array([[0, 0, 1]]), num_time_steps, axis=0)\nstimulus_T8 = np.repeat(np.array([[0, 0, 1]]), num_time_steps, axis=0)\nstimulus_T9 = np.repeat(np.array([[0, 0, 1]]), num_time_steps, axis=0)\nstimulus_T10 = np.repeat(np.array([[0, 0, 1]]), num_time_steps, axis=0)\nstimulus_T11 = np.repeat(np.array([[0, 0, 1]]), num_time_steps, axis=0)\n\n# Concatenate the 11 arrays to one array with 1100 rows and 3 columns.\ntime = np.concatenate((stimulus_T1, stimulus_T2, stimulus_T3, stimulus_T4, stimulus_T5, stimulus_T6,\n stimulus_T7, stimulus_T8, stimulus_T9, stimulus_T10, stimulus_T11), axis=0)\n\n# assign inputs to input_layer (Origin Mechanism) for each trial\nstim_list_dict = {input_layer: time}\n\n# show the system\n# task.show_graph()\n\n# run the system\ntask.run(stim_list_dict, num_trials=trials)\n\n\n# This displays a diagram of the System\n# task.show_graph()\n\nLC_results = LC.log.nparray()[1][1] # get logged results\nLC_results_w = np.zeros([trials]) # get LC_results_w\nfor i in range(trials):\n LC_results_w[i] = LC_results[5][i + 1][2][0][0]\nLC_results_v = np.zeros([trials]) # get LC_results_v\nfor i in range(trials):\n LC_results_v[i] = LC_results[5][i + 1][1][0][0]\n\n\ndef h_v(v, C, d): # Compute h(v)\n return C * v + (1 - C) * d\n\n\nLC_results_hv = np.zeros([trials]) # get LC_results_hv\nfor i in range(trials):\n LC_results_hv[i] = h_v(LC_results_v[i], C, d)\n\n\nif args.enable_plot:\n import matplotlib.pyplot as plt\n\n # Plot the Figure 3 from the paper\n t = np.linspace(0, trials, trials) # Create array for x axis with same length then LC_results_v\n fig = plt.figure() # Instantiate figure\n ax = plt.gca() # Get current axis for plotting\n ax2 = ax.twinx() # Create twin axis with a different y-axis on the right side of the figure\n ax.plot(t, LC_results_hv, label=\"h(v)\") # Plot h(v)\n ax2.plot(t, LC_results_w, label=\"w\", color='red') # Plot w\n h1, l1 = ax.get_legend_handles_labels()\n h2, l2 = ax2.get_legend_handles_labels()\n ax.legend(h1 + h2, l1 + l2, loc=2) # Create legend on one side\n ax.set_xlabel('Time (ms)') # Set x axis lable\n ax.set_ylabel('LC Activity') # Set left y axis label\n ax2.set_ylabel('NE Output') # Set right y axis label\n plt.title('Nieuwenhuis 2005 PsyNeuLink Lag 2 without noise', fontweight='bold') # Set title\n ax.set_ylim((-0.2, 1.0)) # Set left y axis limits\n ax2.set_ylim((0.0, 0.4)) # Set right y axis limits\n plt.show(block=not pnl._called_from_pytest)\n",
"import numpy as np\nimport psyneulink as pnl\n\n\n# here we implement a test demo as in the EVC paper example:\n#in v2 we add control signals and a EVC mechanism to the model\n\n# EVC params for Umemoto et al\nimport psyneulink.core.components.functions.nonstateful.transferfunctions\n\nw_t = 0.065\nw_d = 0.065\nf_t = 1\nf_d = 1\n\n\n# EVC params for Umemoto et al\nt0 = 0.2\nc = 0.19\nthresh = 0.21\nx_0 = 0 # starting point\n\n#wTarget = 0.065 # I think this has to do with learning and is constant over trials in Umemoto\ncostParam1 = 0.35\nreconfCostParam1 = 5\nrewardTaskA = 50\nrewardTaskBToA = 0.7\n\n\n# Control Parameters\nsignalSearchRange = np.arange(0.0, 4.1, 0.2) #like in MATLAB Umemoto[0.0:0.2:4.0]# needs to be adjusted\n\nprint(signalSearchRange)\n\n# Stimulus Mechanisms\nTarget_Stim = pnl.TransferMechanism(name='Target Stimulus', function=psyneulink.core.components.functions.nonstateful.transferfunctions.Linear)\nTarget_Stim.set_log_conditions('value') # Log Target_Rep\n\nDistractor_Stim = pnl.TransferMechanism(name='Distractor Stimulus', function=psyneulink.core.components.functions.nonstateful.transferfunctions.Linear)\nDistractor_Stim.set_log_conditions('value') # Log Target_Rep\n\n# Processing Mechanisms (Control)\nTarget_Rep = pnl.TransferMechanism(name='Target Representation',\n function=psyneulink.core.components.functions.nonstateful.transferfunctions.Linear(\n slope=(1.0)))#, pnl.ControlProjection(\n # control_signal_params={\n # pnl.ALLOCATION_SAMPLES: signalSearchRange}))))\nTarget_Rep.set_log_conditions('value') # Log Target_Rep\nTarget_Rep.loggable_items\n\nDistractor_Rep = pnl.TransferMechanism(name='Distractor Representation',\n function=psyneulink.core.components.functions.nonstateful.transferfunctions.Linear(\n slope=(1.0)))#, pnl.ControlProjection(\n # control_signal_params={\n # pnl.ALLOCATION_SAMPLES: signalSearchRange}))))\n\nDistractor_Rep.set_log_conditions('value') # Log Flanker_Rep\nDistractor_Rep.loggable_items\n# Processing Mechanism (Automatic)\nAutomatic_Component_Target = pnl.TransferMechanism(name='Automatic Component Target', function=psyneulink.core.components.functions.nonstateful.transferfunctions.Linear)\nAutomatic_Component_Target.loggable_items\nAutomatic_Component_Target.set_log_conditions('value')\n\n# Markus october 25 2018: I think we need 2 automatic components\n\nAutomatic_Component_Flanker = pnl.TransferMechanism(name='Automatic Component Flanker', function=psyneulink.core.components.functions.nonstateful.transferfunctions.Linear)\nAutomatic_Component_Flanker.loggable_items\nAutomatic_Component_Flanker.set_log_conditions('value')\n#\n\n\n# Decision Mechanisms\nDecision = pnl.DDM(function=psyneulink.core.components.functions.nonstateful.distributionfunctions.DriftDiffusionAnalytical(\n # drift_rate=(0.3),\n threshold=(thresh),\n noise=(c),\n starting_point=(x_0),\n t0=t0\n ),name='Decision',\n output_ports=[\n pnl.DECISION_VARIABLE,\n pnl.RESPONSE_TIME,\n pnl.PROBABILITY_UPPER_THRESHOLD,\n {\n pnl.NAME: 'OFFSET RT',\n pnl.VARIABLE: (pnl.OWNER_VALUE, 2),\n pnl.FUNCTION: psyneulink.core.components.functions.nonstateful.transferfunctions.Linear(0, slope=1.0, intercept=1)\n }\n ],) #drift_rate=(1.0),threshold=(0.2645),noise=(0.5),starting_point=(0), t0=0.15\n\nprint(Decision.execute([1]))\n\n# Decision.set_log_conditions('DECISION_VARIABLE')\n# Decision.set_log_conditions('value')\n# Decision.set_log_conditions('PROBABILITY_UPPER_THRESHOLD')\nDecision.set_log_conditions('InputPort-0')\n# Decision.set_log_conditions('RESPONSE_TIME')\n\n# Decision.loggable_items\n\n# Outcome Mechanisms:\nReward = pnl.TransferMechanism(size = 1,\n name='Reward')\n\n# Processes:\nTargetControlProcess = pnl.Process(\n default_variable=[0],\n pathway=[Target_Stim, Target_Rep, Decision],\n name='Target Control Process'\n)\n\nFlankerControlProcess = pnl.Process(\n default_variable=[0],\n pathway=[Distractor_Stim, Distractor_Rep, Decision],\n name='Flanker Control Process'\n)\n\nTargetAutomaticProcess = pnl.Process(\n default_variable=[0],\n pathway=[Target_Stim, Automatic_Component_Target, Decision],\n name='Target Automatic Process'\n)\n\nFlankerAutomaticProcess = pnl.Process(\n default_variable=[0],\n pathway=[Distractor_Stim, Automatic_Component_Flanker, Decision], #\n name='Flanker1 Automatic Process'\n)\n\nRewardProcess = pnl.Process(\n pathway=[Reward],\n name='RewardProcess'\n)\n\n# System:\nmySystem = pnl.System(processes=[TargetControlProcess,\n FlankerControlProcess,\n TargetAutomaticProcess,\n FlankerAutomaticProcess,\n RewardProcess],\n controller=pnl.EVCControlMechanism(\n control_signals=pnl.ControlSignal(modulates=[(pnl.SLOPE, Target_Rep),\n (pnl.SLOPE, Distractor_Rep)\n ],\n function=psyneulink.core.components.functions.nonstateful.transferfunctions.Logistic,\n cost_options=[pnl.CostFunctions.INTENSITY,\n pnl.CostFunctions.ADJUSTMENT],\n allocation_samples=signalSearchRange\n )),\n enable_controller=True,\n monitor_for_control=[\n # (None, None, np.ones((2,1))), # what the **** is this for? Markus October 25 2018\n Reward,\n Decision.PROBABILITY_UPPER_THRESHOLD,\n ('OFFSET RT', 1, -1),\n ],\n name='EVC Markus System')\n\n# log controller\n\nmySystem.loggable_items\n\n\n# Show characteristics of system:\nmySystem.show()\n# mySystem.controller.show()\n\n# Show graph of system\nmySystem.show_graph(show_control=True, show_dimensions=True)\n\n#Markus: incongruent trial weights:\n\n# f = np.array([1,1])\n# W_inc = np.array([[1.0, 0.0],[0.0, 1.5]])\n# W_con = np.array([[1.0, 0.0],[1.5, 0.0]])\n\n\n# generate stimulus environment\nnTrials = 3\ntargetFeatures = [w_t]\nflankerFeatures_inc = [w_d]\nreward = [100]\n\n\ntargetInputList = targetFeatures\nflankerInputList = flankerFeatures_inc\nrewardList = reward\n\nstim_list_dict = {\n Target_Stim: targetInputList,\n Distractor_Stim: flankerInputList,\n Reward: rewardList\n}\n\ndef x():\n #print(mySystem.conroller.)\n # print(mySystem.controller.control_signals.values)\n print(\"============== \")\n print(\"decision input vale:\", Decision.input_values)\n print(\"============== \")\n\n # print(Decision.output_ports[pnl.PROBABILITY_UPPER_THRESHOLD].value)\n # print(Decision.output_ports[pnl.DECISION_VARIABLE].value)\n # print(Decision.output_ports[pnl.RESPONSE_TIME].value)\n # print(Target_Rep.input_values)\n # print(\"target rep variable:\", Target_Rep.input_ports[0].variable)\n # print(\"target rep input ports:\", Target_Rep.input_ports)\n # print(\"output target stim\", Target_Stim.output_values)\n #\n # print(Target_Rep.path_afferents)\n # print(\"control proj sender value:\", Target_Rep.mod_afferents[0].sender.value)\n #\n # # print(Target_Rep.path_afferents)\n #\n #\n # print(\"distractor rep input: \", Distractor_Rep.input_values)\n # print(\"my system controller: \", mySystem.controller.control_signals.values)\n # print(\"my system controller SLOPE: \", mySystem.controller.control_signals.values)\n #\n # print(\"InputPort bla bla:\", Target_Rep.input_ports[0].function.exponents)\n # print(\"============== \")\n # print(\"my system stuff: \", mySystem.controller.control_signals.values)\n #\n\n\n\n\n\n # print(Target_Rep.output_values)\n # print(Automatic_Component_Target.output_values)\n #\n # print(Distractor_Rep.output_values)\n # print(Automatic_Component_Flanker.output_values)\n\n\n\nmySystem.run(num_trials=nTrials,\n inputs=stim_list_dict,\n call_after_trial=x)\n\n# Flanker_Rep.log.print_entries()\n# Target_Rep.log.print_entries()\nfrom pprint import pprint\na = Decision.log.nparray_dictionary()\npprint(a)\n# Target_Stim.log.print_entries()\n# Distractor_Stim.log.print_entries()\n# Target_Rep.log.print_entries()\n# Distractor_Rep.log.print_entries()\n#\nDecision.log.print_entries()\n# mySystem.controller.control_signals.values\n\n"
] |
[
[
"matplotlib.pyplot.gca",
"numpy.linspace",
"matplotlib.pyplot.title",
"numpy.concatenate",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
],
[
"numpy.arange"
]
] |
A-LinCui/Discriminator-Guiding-Knowledge-Distillation-MAR
|
[
"e8caad8de2a559b9c9532448bdcdedd566cb2cfa"
] |
[
"aw_nas/final/ofa_model.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nA cell-based model whose architecture is described by a genotype.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport re\n\nimport torch\nfrom torch import nn\n\nfrom aw_nas.common import genotype_from_str\nfrom aw_nas.final.base import FinalModel\nfrom aw_nas.weights_manager.ofa_backbone import BaseBackboneArch\n\n\nclass OFAGenotypeModel(FinalModel):\n NAME = \"ofa_final_model\"\n\n def __init__(self, search_space, device,\n genotypes=None,\n backbone_type=\"mbv2_backbone\",\n backbone_cfg=None,\n supernet_state_dict=None,\n filter_regex=None,\n schedule_cfg=None):\n super(OFAGenotypeModel, self).__init__(schedule_cfg)\n\n self.search_space = search_space\n self.device = device\n self.backbone_cfg = backbone_cfg or {}\n\n self.backbone = BaseBackboneArch.get_class_(backbone_type)(\n device=self.device, **backbone_cfg)\n self.load_supernet_state_dict(supernet_state_dict, filter_regex)\n self.genotypes = genotypes\n if genotypes:\n rollout = search_space.rollout_from_genotype(genotypes)\n self.finalize(rollout)\n\n self.to(self.device)\n\n # for flops calculation\n self.total_flops = 0\n self._flops_calculated = False\n self.set_hook()\n\n def forward(self, inputs):\n res = self.backbone(inputs)\n if not self._flops_calculated:\n self.logger.info(\"FLOPS: flops num = %d M\", self.total_flops/1.e6)\n self._flops_calculated = True\n return res\n\n def extract_features(self, inputs, p_levels=(4, 5), drop_connect_rate=0.0):\n return self.backbone.extract_features(inputs, p_levels, drop_connect_rate=drop_connect_rate)\n\n def get_feature_channel_num(self, p_level):\n return self.backbone.get_feature_channel_num(p_level)\n\n def load_state_dict(self, model, strict=True):\n keys = model.keys()\n for key in keys:\n if key.startswith('backbone'):\n return super().load_state_dict(model, strict)\n else:\n return self.backbone.load_state_dict(model, strict)\n\n def load_supernet_state_dict(self, supernet_state_dict, filter_regex=None):\n \"\"\"\n supernet_state_dict includes all params and weights of FlexibileArch\n \"\"\"\n if supernet_state_dict is not None:\n if isinstance(supernet_state_dict, dict):\n state_dict = supernet_state_dict\n else:\n state_dict = torch.load(supernet_state_dict, map_location=\"cpu\")\n state_dict = state_dict.get(\"weights_manager\", state_dict)\n if filter_regex is not None:\n regex = re.compile(filter_regex)\n state_dict = {k: v for k, v in state_dict.items() if not regex.match(k)}\n mismatch = self.load_state_dict(state_dict, strict=filter_regex is None)\n self.logger.info(\"loading supernet: \" + str(mismatch))\n return self\n\n def finalize(self, rollout):\n self.backbone = self.backbone.finalize(rollout.depth, rollout.width, rollout.kernel)\n return self\n\n def set_hook(self):\n for _, module in self.named_modules():\n module.register_forward_hook(self._hook_intermediate_feature)\n\n def _hook_intermediate_feature(self, module, inputs, outputs):\n if not self._flops_calculated:\n if isinstance(module, nn.Conv2d):\n self.total_flops += 2* inputs[0].size(1) * outputs.size(1) * \\\n module.kernel_size[0] * module.kernel_size[1] * \\\n outputs.size(2) * outputs.size(3) / module.groups\n elif isinstance(module, nn.Linear):\n self.total_flops += 2 * inputs[0].size(1) * outputs.size(1)\n else:\n pass\n\n @classmethod\n def supported_data_types(cls):\n return [\"image\"]\n\n def layer_idx_to_named_modules(self, idx):\n stage_idx, block_idx = idx\n prefix = \"backbone.cells.{}.{}\".format(stage_idx, block_idx)\n m = self\n for name in prefix.split('.'):\n m = getattr(m, name)\n for n, _ in m.named_modules():\n if not n:\n yield prefix\n yield '.'.join([prefix, n])\n"
] |
[
[
"torch.load"
]
] |
StdCarrot/PyAthena
|
[
"1c4688714ff45f1e9e0127900ee38746e3375975"
] |
[
"tests/test_pandas_cursor.py"
] |
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport contextlib\nimport random\nimport string\nimport time\nimport unittest\nfrom concurrent.futures import ThreadPoolExecutor\nfrom datetime import datetime\nfrom decimal import Decimal\n\nimport numpy as np\nimport pandas as pd\nfrom past.builtins.misc import xrange\n\nfrom pyathena.error import DatabaseError, ProgrammingError\nfrom pyathena.model import AthenaQueryExecution\nfrom pyathena.pandas_cursor import PandasCursor\nfrom pyathena.result_set import AthenaPandasResultSet\nfrom tests import WithConnect, SCHEMA, ENV, S3_PREFIX\nfrom tests.util import with_pandas_cursor\n\n\nclass TestPandasCursor(unittest.TestCase, WithConnect):\n\n @with_pandas_cursor()\n def test_fetchone(self, cursor):\n cursor.execute('SELECT * FROM one_row')\n self.assertEqual(cursor.rownumber, 0)\n self.assertEqual(cursor.fetchone(), (1,))\n self.assertEqual(cursor.rownumber, 1)\n self.assertIsNone(cursor.fetchone())\n\n @with_pandas_cursor()\n def test_fetchmany(self, cursor):\n cursor.execute('SELECT * FROM many_rows LIMIT 15')\n self.assertEqual(len(cursor.fetchmany(10)), 10)\n self.assertEqual(len(cursor.fetchmany(10)), 5)\n\n @with_pandas_cursor()\n def test_fetchall(self, cursor):\n cursor.execute('SELECT * FROM one_row')\n self.assertEqual(cursor.fetchall(), [(1,)])\n cursor.execute('SELECT a FROM many_rows ORDER BY a')\n self.assertEqual(cursor.fetchall(), [(i,) for i in xrange(10000)])\n\n @with_pandas_cursor()\n def test_iterator(self, cursor):\n cursor.execute('SELECT * FROM one_row')\n self.assertEqual(list(cursor), [(1,)])\n self.assertRaises(StopIteration, cursor.__next__)\n\n @with_pandas_cursor()\n def test_arraysize(self, cursor):\n cursor.arraysize = 5\n cursor.execute('SELECT * FROM many_rows LIMIT 20')\n self.assertEqual(len(cursor.fetchmany()), 5)\n\n @with_pandas_cursor()\n def test_arraysize_default(self, cursor):\n self.assertEqual(cursor.arraysize, AthenaPandasResultSet.DEFAULT_FETCH_SIZE)\n\n @with_pandas_cursor()\n def test_invalid_arraysize(self, cursor):\n with self.assertRaises(ProgrammingError):\n cursor.arraysize = 10000\n with self.assertRaises(ProgrammingError):\n cursor.arraysize = -1\n\n @with_pandas_cursor()\n def test_complex(self, cursor):\n cursor.execute(\"\"\"\n SELECT\n col_boolean\n ,col_tinyint\n ,col_smallint\n ,col_int\n ,col_bigint\n ,col_float\n ,col_double\n ,col_string\n ,col_timestamp\n ,CAST(col_timestamp AS time) AS col_time\n ,col_date\n ,col_binary\n ,col_array\n ,CAST(col_array AS json) AS col_array_json\n ,col_map\n ,CAST(col_map AS json) AS col_map_json\n ,col_struct\n ,col_decimal\n FROM one_row_complex\n \"\"\")\n self.assertEqual(cursor.description, [\n ('col_boolean', 'boolean', None, None, 0, 0, 'UNKNOWN'),\n ('col_tinyint', 'tinyint', None, None, 3, 0, 'UNKNOWN'),\n ('col_smallint', 'smallint', None, None, 5, 0, 'UNKNOWN'),\n ('col_int', 'integer', None, None, 10, 0, 'UNKNOWN'),\n ('col_bigint', 'bigint', None, None, 19, 0, 'UNKNOWN'),\n ('col_float', 'float', None, None, 17, 0, 'UNKNOWN'),\n ('col_double', 'double', None, None, 17, 0, 'UNKNOWN'),\n ('col_string', 'varchar', None, None, 2147483647, 0, 'UNKNOWN'),\n ('col_timestamp', 'timestamp', None, None, 3, 0, 'UNKNOWN'),\n ('col_time', 'time', None, None, 3, 0, 'UNKNOWN'),\n ('col_date', 'date', None, None, 0, 0, 'UNKNOWN'),\n ('col_binary', 'varbinary', None, None, 1073741824, 0, 'UNKNOWN'),\n ('col_array', 'array', None, None, 0, 0, 'UNKNOWN'),\n ('col_array_json', 'json', None, None, 0, 0, 'UNKNOWN'),\n ('col_map', 'map', None, None, 0, 0, 'UNKNOWN'),\n ('col_map_json', 'json', None, None, 0, 0, 'UNKNOWN'),\n ('col_struct', 'row', None, None, 0, 0, 'UNKNOWN'),\n ('col_decimal', 'decimal', None, None, 10, 1, 'UNKNOWN'),\n ])\n rows = cursor.fetchall()\n expected = [(\n True,\n 127,\n 32767,\n 2147483647,\n 9223372036854775807,\n 0.5,\n 0.25,\n 'a string',\n pd.Timestamp(2017, 1, 1, 0, 0, 0),\n datetime(2017, 1, 1, 0, 0, 0).time(),\n pd.Timestamp(2017, 1, 2),\n b'123',\n '[1, 2]',\n [1, 2],\n '{1=2, 3=4}',\n {'1': 2, '3': 4},\n '{a=1, b=2}',\n Decimal('0.1'),\n )]\n self.assertEqual(rows, expected)\n\n @with_pandas_cursor()\n def test_fetch_no_data(self, cursor):\n self.assertRaises(ProgrammingError, cursor.fetchone)\n self.assertRaises(ProgrammingError, cursor.fetchmany)\n self.assertRaises(ProgrammingError, cursor.fetchall)\n self.assertRaises(ProgrammingError, cursor.as_pandas)\n\n @with_pandas_cursor()\n def test_as_pandas(self, cursor):\n df = cursor.execute('SELECT * FROM one_row').as_pandas()\n self.assertEqual(df.shape[0], 1)\n self.assertEqual(df.shape[1], 1)\n self.assertEqual([(row['number_of_rows'],) for _, row in df.iterrows()], [(1,)])\n self.assertIsNotNone(cursor.query_id)\n self.assertIsNotNone(cursor.query)\n self.assertEqual(cursor.state, AthenaQueryExecution.STATE_SUCCEEDED)\n self.assertIsNone(cursor.state_change_reason)\n self.assertIsNotNone(cursor.completion_date_time)\n self.assertIsInstance(cursor.completion_date_time, datetime)\n self.assertIsNotNone(cursor.submission_date_time)\n self.assertIsInstance(cursor.submission_date_time, datetime)\n self.assertIsNotNone(cursor.data_scanned_in_bytes)\n self.assertIsNotNone(cursor.execution_time_in_millis)\n self.assertIsNotNone(cursor.output_location)\n\n @with_pandas_cursor()\n def test_many_as_pandas(self, cursor):\n df = cursor.execute('SELECT * FROM many_rows').as_pandas()\n self.assertEqual(df.shape[0], 10000)\n self.assertEqual(df.shape[1], 1)\n self.assertEqual([(row['a'],) for _, row in df.iterrows()],\n [(i,) for i in xrange(10000)])\n\n @with_pandas_cursor()\n def test_complex_as_pandas(self, cursor):\n df = cursor.execute(\"\"\"\n SELECT\n col_boolean\n ,col_tinyint\n ,col_smallint\n ,col_int\n ,col_bigint\n ,col_float\n ,col_double\n ,col_string\n ,col_timestamp\n ,CAST(col_timestamp AS time) AS col_time\n ,col_date\n ,col_binary\n ,col_array\n ,CAST(col_array AS json) AS col_array_json\n ,col_map\n ,CAST(col_map AS json) AS col_map_json\n ,col_struct\n ,col_decimal\n FROM one_row_complex\n \"\"\").as_pandas()\n self.assertEqual(df.shape[0], 1)\n self.assertEqual(df.shape[1], 18)\n dtypes = tuple([\n df['col_boolean'].dtype.type,\n df['col_tinyint'].dtype.type,\n df['col_smallint'].dtype.type,\n df['col_int'].dtype.type,\n df['col_bigint'].dtype.type,\n df['col_float'].dtype.type,\n df['col_double'].dtype.type,\n df['col_string'].dtype.type,\n df['col_timestamp'].dtype.type,\n df['col_time'].dtype.type,\n df['col_date'].dtype.type,\n df['col_binary'].dtype.type,\n df['col_array'].dtype.type,\n df['col_array_json'].dtype.type,\n df['col_map'].dtype.type,\n df['col_map_json'].dtype.type,\n df['col_struct'].dtype.type,\n df['col_decimal'].dtype.type,\n ])\n self.assertEqual(dtypes, tuple([\n np.bool_,\n np.int64,\n np.int64,\n np.int64,\n np.int64,\n np.float64,\n np.float64,\n np.object_,\n np.datetime64,\n np.object_,\n np.datetime64,\n np.object_,\n np.object_,\n np.object_,\n np.object_,\n np.object_,\n np.object_,\n np.object_,\n ]))\n rows = [tuple([\n row['col_boolean'],\n row['col_tinyint'],\n row['col_smallint'],\n row['col_int'],\n row['col_bigint'],\n row['col_float'],\n row['col_double'],\n row['col_string'],\n row['col_timestamp'],\n row['col_time'],\n row['col_date'],\n row['col_binary'],\n row['col_array'],\n row['col_array_json'],\n row['col_map'],\n row['col_map_json'],\n row['col_struct'],\n row['col_decimal'],\n ]) for _, row in df.iterrows()]\n self.assertEqual(rows, [(\n True,\n 127,\n 32767,\n 2147483647,\n 9223372036854775807,\n 0.5,\n 0.25,\n 'a string',\n pd.Timestamp(2017, 1, 1, 0, 0, 0),\n datetime(2017, 1, 1, 0, 0, 0).time(),\n pd.Timestamp(2017, 1, 2),\n b'123',\n '[1, 2]',\n [1, 2],\n '{1=2, 3=4}',\n {'1': 2, '3': 4},\n '{a=1, b=2}',\n Decimal('0.1'),\n )])\n\n @with_pandas_cursor()\n def test_cancel(self, cursor):\n def cancel(c):\n time.sleep(random.randint(1, 5))\n c.cancel()\n\n with ThreadPoolExecutor(max_workers=1) as executor:\n executor.submit(cancel, cursor)\n\n self.assertRaises(DatabaseError, lambda: cursor.execute(\"\"\"\n SELECT a.a * rand(), b.a * rand()\n FROM many_rows a\n CROSS JOIN many_rows b\n \"\"\"))\n\n @with_pandas_cursor()\n def test_cancel_initial(self, cursor):\n self.assertRaises(ProgrammingError, cursor.cancel)\n\n def test_open_close(self):\n with contextlib.closing(self.connect()) as conn:\n with conn.cursor(PandasCursor):\n pass\n\n def test_no_ops(self):\n conn = self.connect()\n cursor = conn.cursor(PandasCursor)\n cursor.close()\n conn.close()\n\n @with_pandas_cursor()\n def test_empty_result(self, cursor):\n table = 'test_pandas_cursor_empty_result_' + ''.join([random.choice(\n string.ascii_lowercase + string.digits) for _ in xrange(10)])\n location = '{0}{1}/{2}/'.format(ENV.s3_staging_dir, S3_PREFIX, table)\n df = cursor.execute(\"\"\"\n CREATE EXTERNAL TABLE IF NOT EXISTS\n {schema}.{table} (number_of_rows INT)\n ROW FORMAT DELIMITED FIELDS TERMINATED BY '\\t'\n LINES TERMINATED BY '\\n' STORED AS TEXTFILE\n LOCATION '{location}'\n \"\"\".format(schema=SCHEMA, table=table, location=location)).as_pandas()\n self.assertEqual(df.shape[0], 0)\n self.assertEqual(df.shape[1], 0)\n\n @with_pandas_cursor()\n def test_integer_na_values(self, cursor):\n df = cursor.execute(\"\"\"\n SELECT * FROM integer_na_values\n \"\"\").as_pandas()\n rows = [tuple([\n row['a'],\n row['b'],\n ]) for _, row in df.iterrows()]\n self.assertEqual(rows, [\n (1, 2),\n (1, np.nan),\n (np.nan, np.nan),\n ])\n\n @with_pandas_cursor()\n def test_boolean_na_values(self, cursor):\n df = cursor.execute(\"\"\"\n SELECT * FROM boolean_na_values\n \"\"\").as_pandas()\n rows = [tuple([\n row['a'],\n row['b'],\n ]) for _, row in df.iterrows()]\n self.assertEqual(rows, [\n (True, False),\n (False, None),\n (None, None),\n ])\n\n @with_pandas_cursor()\n def test_executemany(self, cursor):\n cursor.executemany(\n 'INSERT INTO execute_many_pandas (a) VALUES (%(a)s)',\n [{'a': i} for i in xrange(1, 3)]\n )\n cursor.execute('SELECT * FROM execute_many_pandas')\n self.assertEqual(sorted(cursor.fetchall()), [(i,) for i in xrange(1, 3)])\n\n @with_pandas_cursor()\n def test_executemany_fetch(self, cursor):\n cursor.executemany(\n 'SELECT %(x)d FROM one_row',\n [{'x': i} for i in range(1, 2)]\n )\n # Operations that have result sets are not allowed with executemany.\n self.assertRaises(ProgrammingError, cursor.fetchall)\n self.assertRaises(ProgrammingError, cursor.fetchmany)\n self.assertRaises(ProgrammingError, cursor.fetchone)\n self.assertRaises(ProgrammingError, cursor.as_pandas)\n"
] |
[
[
"pandas.Timestamp"
]
] |
Frankzd/distiller
|
[
"931138e2d23989ef9305712e5aa147ae3dff53de"
] |
[
"apputils/checkpoint.py"
] |
[
"#\n# Copyright (c) 2018 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\" Helper code for checkpointing models, with support for saving the pruning schedule.\n\nAdding the schedule information in the model checkpoint is helpful in resuming\na pruning session, or for querying the pruning schedule of a sparse model.\n\"\"\"\n\nimport os\nimport shutil\nfrom errno import ENOENT\nimport logging\nimport torch\nimport distiller\nmsglogger = logging.getLogger()\n\n\ndef save_checkpoint(epoch, arch, model, optimizer=None, scheduler=None,\n best_top1=None, is_best=False, name=None, dir='.'):\n \"\"\"Save a pytorch training checkpoint\n\n Args:\n epoch: current epoch\n arch: name of the network arechitecture/topology\n model: a pytorch model\n optimizer: the optimizer used in the training session\n scheduler: the CompressionScheduler instance used for training, if any\n best_top1: the best top1 score seen so far\n is_best: True if this is the best (top1 accuracy) model so far\n name: the name of the checkpoint file\n dir: directory in which to save the checkpoint\n \"\"\"\n if not os.path.isdir(dir):\n raise IOError(ENOENT, 'Checkpoint directory does not exist at', os.path.abspath(dir))\n\n filename = 'checkpoint.pth.tar' if name is None else name + '_checkpoint.pth.tar'\n fullpath = os.path.join(dir, filename)\n msglogger.info(\"Saving checkpoint to: %s\" % fullpath)\n filename_best = 'best.pth.tar' if name is None else name + '_best.pth.tar'\n fullpath_best = os.path.join(dir, filename_best)\n checkpoint = {}\n checkpoint['epoch'] = epoch\n checkpoint['arch'] = arch\n checkpoint['state_dict'] = model.state_dict()\n if best_top1 is not None:\n checkpoint['best_top1'] = best_top1\n if optimizer is not None:\n checkpoint['optimizer'] = optimizer.state_dict()\n if scheduler is not None:\n checkpoint['compression_sched'] = scheduler.state_dict()\n if hasattr(model, 'thinning_recipes'):\n checkpoint['thinning_recipes'] = model.thinning_recipes\n if hasattr(model, 'quantizer_metadata'):\n checkpoint['quantizer_metadata'] = model.quantizer_metadata\n\n torch.save(checkpoint, fullpath)\n if is_best:\n shutil.copyfile(fullpath, fullpath_best)\n\n\ndef load_checkpoint(model, chkpt_file, optimizer=None):\n \"\"\"Load a pytorch training checkpoint\n\n Args:\n model: the pytorch model to which we will load the parameters\n chkpt_file: the checkpoint file\n optimizer: the optimizer to which we will load the serialized state\n \"\"\"\n compression_scheduler = None\n start_epoch = 0\n\n if os.path.isfile(chkpt_file):\n msglogger.info(\"=> loading checkpoint %s\", chkpt_file)\n checkpoint = torch.load(chkpt_file)\n msglogger.info(\"Checkpoint keys:\\n{}\".format(\"\\n\\t\".join(k for k in checkpoint.keys())))\n start_epoch = checkpoint['epoch'] + 1\n best_top1 = checkpoint.get('best_top1', None)\n if best_top1 is not None:\n msglogger.info(\" best top@1: %.3f\", best_top1)\n\n if 'compression_sched' in checkpoint:\n compression_scheduler = distiller.CompressionScheduler(model)\n compression_scheduler.load_state_dict(checkpoint['compression_sched'])\n msglogger.info(\"Loaded compression schedule from checkpoint (epoch %d)\",\n checkpoint['epoch'])\n else:\n msglogger.info(\"Warning: compression schedule data does not exist in the checkpoint\")\n\n if 'thinning_recipes' in checkpoint:\n if 'compression_sched' not in checkpoint:\n raise KeyError(\"Found thinning_recipes key, but missing mandatory key compression_sched\")\n msglogger.info(\"Loaded a thinning recipe from the checkpoint\")\n # Cache the recipes in case we need them later\n model.thinning_recipes = checkpoint['thinning_recipes']\n distiller.execute_thinning_recipes_list(model,\n compression_scheduler.zeros_mask_dict,\n model.thinning_recipes)\n\n if 'quantizer_metadata' in checkpoint:\n msglogger.info('Loaded quantizer metadata from the checkpoint')\n qmd = checkpoint['quantizer_metadata']\n quantizer = qmd['type'](model,optimizer, **qmd['params'])\n quantizer.prepare_model()\n\n msglogger.info(\"=> loaded checkpoint '%s' (epoch %d)\", chkpt_file, checkpoint['epoch'])\n\n model.load_state_dict(checkpoint['state_dict'])\n return model, compression_scheduler, start_epoch\n else:\n raise IOError(ENOENT, 'Could not find a checkpoint file at', chkpt_file)\n"
] |
[
[
"torch.load",
"torch.save"
]
] |
JamesPMColeman/Computer-Vision-Practice
|
[
"bc0c832d275b811a59f135d0a06eea6478945d05"
] |
[
"Homework2/homework2_part2.py"
] |
[
"#=============================================================================#\n# #\n# James Coleman #\n# CS 3150 #\n# Homework 2 part one #\n# September 26th #\n# #\n#=============================================================================#\n\n # >>>>>>>>>> Goals <<<<<<<<<<\n # \n # 1. Smooth out the iris image to suppress small \n # edges.\n # 2. Produce edges of the image using Sobal filters\n # and gradient\n # 3. Detect the center of the of the eye\n # 4. Detect the boundary of the eye (radius is \n # roughly 35 to 45 pixels)\n # \n #\n\n# Imports\nimport cv2\nimport math\nimport numpy\nfrom scipy.signal import convolve2d\nfrom matplotlib import pyplot\n# Helper methods\ndef show(image, name):\n pyplot.figure()\n pyplot.title(name)\n pyplot.imshow(image, cmap=\"gray\", vmin=0, vmax=255)\n pyplot.show()\n# Acquire the image and display\noriginal = cv2.imread('./iris.bmp')\neye = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)\nh, w = eye.shape\nshow(eye, \"Original\") \n\n# Blur the image\navg_filter = numpy.zeros((7, 7)) ## Create a 15 by 15\navg_filter += 1/(7 * 7) ## average filter.\navg_eye = cv2.filter2D(eye, -1, avg_filter) ## Apply filter. \n\nshow(avg_eye, \"Smoothed Eye\")\t ## Displayed averaged image\n\n# Detect edges\nvt_filter = numpy.array([ ## create vertical and \n [1, 0, -1], ## horizontal sobal filters\n [2, 0, -2],\n [1, 0, -1] \n])\nht_filter = numpy.array([\n [1, 2, 1],\n [0, 0, 0],\n [-1, -2, -1]\n])\nvt_eye = convolve2d(avg_eye, vt_filter) ## apply filters\nht_eye = convolve2d(avg_eye, ht_filter)\n\nshow(vt_eye, \"Vertical Sobal\")\nshow(ht_eye, \"Horizontal Sobal\")\n\ngradient = numpy.sqrt( ## Create new image to be \n numpy.square(vt_eye) + ## the square root of the \n numpy.square(ht_eye) ## vertical and horizontal \n) ## image squared and summed\n\nshow(gradient, \"Sobal Gradient\") ## Display gradient image\n\n# Detect the focus of the eye\nr1 = 45 ## Create a ring filter \nr2 = 35 ## with outer radius 45 and\nring = numpy.zeros((120, 120)) ## inner radius 35\n\nfor i in range(120):\n for j in range(120):\n if math.sqrt((i - 60)**2 + (j - 60)**2) < r1 and \\\n math.sqrt((i - 60)**2 + (j - 60)**2) > r2:\n ring[i][j] = 1\n### show(ring) ### ## apply filter\n\npupil_focus = convolve2d(gradient, ring, mode=\"same\", boundary=\"symm\") \npupil_focus = numpy.absolute(pupil_focus)\npupil_focus *= 255 / numpy.max(pupil_focus)\n\nshow(pupil_focus, \"Ring Filtered\")\n\na_focus = 0\nb_focus = 0\nintense = 0\n\nfor i in range(45, h-45): ## acquire the coordinates \n for j in range(45, w-45): ## of the maximum\n if pupil_focus[i][j] > intense: \n a_focus = i\n b_focus = j\n intense = pupil_focus[i][j]\n\n### show(focus) ### \n\nfor i in range(h): ## super impose the focus \n for j in range(w): ## image (just the center\n if math.sqrt((i - a_focus)**2 + ## dot) on to the gradient\n (j - b_focus)**2) < 3: ## image\n gradient[i][j] = 255 \n\nshow(gradient, \"Focus\")\n\n# Detect the boundary of the circle.\nfor i in range(h):\n for j in range(w): \n if math.sqrt((i - a_focus + 2)**2 + \n (j - b_focus + 2)**2) < 38 and \\\n math.sqrt((i - a_focus + 2)**2 + \n (j - b_focus + 2)**2) > 37: \n eye[i][j] = 255 \n \n# Display results\nshow(eye, \"Pupil boundary\") \n"
] |
[
[
"numpy.square",
"matplotlib.pyplot.imshow",
"numpy.absolute",
"matplotlib.pyplot.title",
"scipy.signal.convolve2d",
"numpy.max",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
usarawgi911/PD-mlhc
|
[
"5fc631e74466b3328201eebb212f47bf3e3f5264"
] |
[
"dtw_distance.py"
] |
[
"import numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom tqdm import tqdm\nfrom fastdtw import fastdtw\nimport pickle\n\n# find the distance between a set of samples\n# it take too long to run this on every sample (and it's not very insightful)\n\nsampling_rate = 0.1\n\nbase = '/Users/daphne/Dropbox (MIT)/'\n\nsubjects = [1004, 1006, 1007, 1019, 1020, 1023, 1032, 1034, 1038, 1043, 1048, 1049]\n\n# load in labels\n\npath = base + \"/pd-mlhc/CIS/data_labels/CIS-PD_Training_Data_IDs_Labels.csv\"\n \nlabels = pd.read_csv(path)\n\n# load the waveforms, put everything into lists\nprint('\\nloading waveforms...\\n')\n\n\nwfs = []\ntremor = []\nfor s in tqdm(subjects) :\n labels_per = list(labels[labels['subject_id'] == s]['measurement_id'])\n tremor.append(list(labels[labels['subject_id'] == s]['tremor']))\n wfs_per = []\n for loc in labels_per :\n path = base + \"pd-mlhc/CIS/training_data/\" + loc + '.csv'\n wf = pd.read_csv(path)\n wfs_per.append(np.asarray(wf.loc[:,['X','Y','Z']]))\n wfs.append(wfs_per)\n \n\ntremor_all = []\npid = []\nwfs_all = []\n\ni = 0\nfor w in range(len(wfs)) :\n for wf in range(len(wfs[w])):\n r = np.random.rand()\n if r < sampling_rate :\n wfs_all.append(wfs[w][wf])\n pid.append(i)\n tremor_all.append(tremor[w][wf])\n else :\n continue\n i += 1\n\nprint('\\ncomputing distances\\n')\n\ndist_array = np.zeros((len(wfs_all),len(wfs_all)))\n\nfor i in tqdm(range(len(wfs_all))) :\n for j in tqdm(range(len(wfs_all))) :\n dist_array[i,j] = fastdtw(wfs_all[i],wfs_all[j])[0]\n\nprint('\\nsaving variables\\n')\n\n\npickle.dump( [dist_array,pid,tremor_all,wfs_all], open( \"dist_set.p\", \"wb\" ) )"
] |
[
[
"numpy.asarray",
"pandas.read_csv",
"numpy.random.rand"
]
] |
yisyang/stock-prediction
|
[
"c671a4b32a06c4732d126dc2d8d1ba2bfc021828"
] |
[
"data_loader.py"
] |
[
"import csv\nimport numpy as np\nimport torch\n\n\nclass DataLoader:\n def __init__(self, x_seq_length, x_features, y_seq_length, mode='train', return_format='keras',\n torch_device=None):\n self.x_seq_length = x_seq_length\n self.x_features = x_features\n self.y_seq_length = y_seq_length\n self.return_format = return_format\n self.torch_device = torch_device\n self.train_x_set = []\n self.train_y_set = []\n self.val_x_set = []\n self.val_y_set = []\n self.pred_x_set = []\n self.prepare_data(mode)\n\n @staticmethod\n def load_csv_data(filename_x, filename_y=None):\n with open(filename_x, 'r') as file1:\n reader1 = csv.reader(file1, quoting=csv.QUOTE_NONNUMERIC)\n if filename_y is None:\n return [row for row in reader1]\n with open(filename_y, 'r') as file2:\n reader2 = csv.reader(file2, quoting=csv.QUOTE_NONNUMERIC)\n return [row for row in reader1], [row for row in reader2]\n\n def format_data(self, s_x, s_y):\n if self.return_format == 'torch':\n s_x = torch.from_numpy(s_x)\n s_y = torch.from_numpy(s_y)\n if self.torch_device is not None:\n return s_x.to(device=self.torch_device), s_y.to(device=self.torch_device)\n return s_x, s_y\n\n def get_batch(self, n=20, source='train'):\n x_set, y_set, size = self.get_set_data(source)\n rng = np.random.default_rng()\n indices = rng.integers(0, size, n)\n s_x = np.take(a=x_set, indices=indices, axis=0).astype('f4').reshape((n, self.x_seq_length, self.x_features))\n s_y = np.take(a=y_set, indices=indices, axis=0).astype('f4')\n return self.format_data(s_x, s_y)\n\n def get_all_data(self, source='train'):\n x_set, y_set, size = self.get_set_data(source)\n s_x = np.array(x_set, dtype='f4').reshape((size, self.x_seq_length, self.x_features))\n s_y = np.array(y_set, dtype='f4')\n return self.format_data(s_x, s_y)\n\n def get_set_data(self, source='train'):\n assert source in ['train', 'validate', 'predict']\n if source == 'train':\n x_set = self.train_x_set\n y_set = self.train_y_set\n elif source == 'validate':\n x_set = self.val_x_set\n y_set = self.val_y_set\n else:\n x_set = self.pred_x_set\n y_set = []\n size = len(x_set)\n return x_set, y_set, size\n\n def prepare_data(self, mode='train'):\n # Use hardcoded filenames.\n filename_train_x = f'data/train_x_{self.x_seq_length}_{self.x_features}.csv'\n filename_train_y = f'data/train_y_{self.y_seq_length}.csv'\n filename_val_x = f'data/val_x_{self.x_seq_length}_{self.x_features}.csv'\n filename_val_y = f'data/val_y_{self.y_seq_length}.csv'\n filename_pred_x = f'data/pred_x_{self.x_seq_length}_{self.x_features}.csv'\n\n if mode == 'train' and len(self.train_y_set) == 0:\n print('Loading training data.')\n self.train_x_set, self.train_y_set = self.load_csv_data(filename_train_x, filename_train_y)\n n_samples = len(self.train_y_set)\n print(f'Training samples: {n_samples}')\n print(f'Sample x: {self.train_x_set[0]}')\n print(f'Sample y: {self.train_y_set[0]}')\n\n if mode in ['train', 'validate'] and len(self.val_y_set) == 0:\n print('Loading validation data.')\n self.val_x_set, self.val_y_set = self.load_csv_data(filename_val_x, filename_val_y)\n n_samples = len(self.val_y_set)\n print(f'Validation samples: {n_samples}')\n\n if mode == 'predict' and len(self.pred_x_set) == 0:\n print('Loading prediction data.')\n self.pred_x_set = self.load_csv_data(filename_pred_x)\n n_samples = len(self.pred_x_set)\n print(f'Prediction samples: {n_samples}')\n"
] |
[
[
"numpy.take",
"numpy.array",
"torch.from_numpy",
"numpy.random.default_rng"
]
] |
facebookresearch/MTRF
|
[
"2fee8f3f1c2150fcecc2db2fa9e122a664a72d72"
] |
[
"MTRF/r3l/r3l/utils/camera/kinect_image_service.py"
] |
[
"# Copyright (c) Facebook, Inc. and its affiliates\n# Copyright (c) MTRF authors\n\nfrom sensor_msgs.msg import Image as Image_msg\nimport rospy\nimport numpy as np\nimport skimage\nimport matplotlib.pyplot as plt\n\nimport warnings\nfrom sklearn.exceptions import DataConversionWarning\nwarnings.filterwarnings(action='ignore', category=DataConversionWarning)\n\nclass KinectImageService(object):\n def __init__(self, image_shape=(32, 32, 3), topic=\"/kinect2/qhd/image_color\"):\n self.image_shape = image_shape\n self.image = None\n rospy.init_node('images_service', anonymous=True)\n print(\"subscribing to: \", topic)\n rospy.Subscriber(\n topic,\n Image_msg,\n self.store_image,\n queue_size=1,\n buff_size=2**24,\n tcp_nodelay=True)\n\n connection_attempts = 5\n for i in range(connection_attempts):\n if self.image is not None:\n break\n print(\"No image found yet.\")\n rospy.sleep(1)\n\n if i == (connection_attempts - 1):\n raise ValueError\n\n def process_image(self, image):\n image = np.flip(image.reshape((540, 960, 3)), axis=2)\n image = image[:, 225:225+540] # Free screw\n # image = image[:, 110:110+540] # Fixed screw\n # image = image[84:422, :422]\n\n resize_to = next(\n 2 ** i for i in reversed(range(10))\n if 2 ** i < image.shape[0])\n image = skimage.transform.resize(\n image, (resize_to, resize_to), anti_aliasing=True, mode='constant')\n width = image.shape[0] // self.image_shape[0]\n height = image.shape[1] // self.image_shape[1]\n image = skimage.transform.downscale_local_mean(\n image, (width, height, 1))\n image = skimage.util.img_as_ubyte(image)\n\n return image\n\n def store_image(self, data):\n # start = rospy.Time.now()\n\n image = np.frombuffer(data.data, dtype=np.uint8)\n image = self.process_image(image.copy())\n self.image = image\n\n # end = rospy.Time.now()\n\n # transport_delay = (start - data.header.stamp).to_sec()\n # process_delay = (end - start).to_sec()\n # total_delay = transport_delay + process_delay\n\n # print(f\"Processing frame\"\n # f\" | Transport delay:{transport_delay:6.3f}\"\n # f\" | Process delay: {process_delay:6.3f}\"\n # f\" | Total delay: {total_delay:6.3f}\")\n\n def get_image(self, *args, width=32, height=32, **kwargs):\n if self.image.shape[:2] != (width, height):\n old_width, old_height = self.image.shape[:2]\n assert old_width >= width and old_height >= height, (\n f'{(old_width, old_height)} needs to be >= {(width, height)}')\n old_image = self.image.copy()\n # skimage requires the image be converted to float first\n float_img = skimage.util.img_as_float(old_image)\n assert old_width % width == 0 and old_height % height == 0\n width_factor = old_width // width\n height_factor = old_height // height\n downsampled = skimage.transform.downscale_local_mean(\n float_img, (width_factor, height_factor, 1))\n # Convert back to uint8\n downsampled = skimage.util.img_as_ubyte(downsampled)\n return downsampled\n\n # old_image = self.image.copy()\n\n # same_frame = np.all(old_image == self._image)\n # if same_frame:\n # self._same_frame_count += 1\n # else:\n # self._same_frame_count = 0\n\n # if self._same_frame_count > 100:\n assert self.image.shape[:2] == (width, height)\n return self.image\n\n\ndef test_image_service():\n image_service = KinectImageService()\n for i in range(10):\n image = image_service.get_image()\n if image is None:\n print(\"No pixels received yet\")\n else:\n print(image.dtype, image.shape)\n\n show_images = False\n if show_images:\n plt.imshow(image.copy())\n plt.show()\n\n rospy.sleep(1)\n\n\nif __name__ == '__main__':\n try:\n test_image_service()\n except rospy.ROSInterruptException:\n pass\n"
] |
[
[
"numpy.frombuffer",
"matplotlib.pyplot.show"
]
] |
sxj731533730/shufflenetv2_demo
|
[
"291edf1ccdf4982b4d1ac230efcc177af5b0b5f1"
] |
[
"my_dataset.py"
] |
[
"from PIL import Image\nimport torch\nfrom torch.utils.data import Dataset\n\n\nclass MyDataSet(Dataset):\n \"\"\"自定义数据集\"\"\"\n\n def __init__(self, images_path: list, images_class: list, transform=None):\n self.images_path = images_path\n self.images_class = images_class\n self.transform = transform\n\n def __len__(self):\n return len(self.images_path)\n\n def __getitem__(self, item):\n img = Image.open(self.images_path[item])\n img=img.convert('RGB')\n # RGB为彩色图片,L为灰度图片\n if img.mode != 'RGB':\n raise ValueError(\"image: {} isn't RGB mode.\".format(self.images_path[item]))\n label = self.images_class[item]\n\n if self.transform is not None:\n img = self.transform(img)\n\n return img, label\n\n @staticmethod\n def collate_fn(batch):\n # 官方实现的default_collate可以参考\n # https://github.com/pytorch/pytorch/blob/67b7e751e6b5931a9f45274653f4f653a4e6cdf6/torch/utils/data/_utils/collate.py\n images, labels = tuple(zip(*batch))\n\n images = torch.stack(images, dim=0)\n labels = torch.as_tensor(labels)\n return images, labels\n"
] |
[
[
"torch.stack",
"torch.as_tensor"
]
] |
Atinary-technologies/experiment_planning_plugins
|
[
"1c5110abceb456ee19a2924cf58ec3d72cfefbb6"
] |
[
"tests/test_chimera.py"
] |
[
"#!/usr/bin/env python\n\nimport numpy as np\n\nfrom chimera import Chimera\n\n# ==============================================================================\n\n\ndef test_chimera_absolutes():\n chim = Chimera(absolutes=np.zeros(2))\n assert len(chim.absolutes) == 2\n assert np.sum(chim.absolutes) == 0\n assert len(chim.relatives) == 2\n assert np.isnan(chim.relatives[0])\n\n\ndef test_chimera_relatives():\n chim = Chimera(relatives=np.zeros(2))\n assert len(chim.absolutes) == 2\n assert np.isnan(chim.absolutes[0])\n assert len(chim.relatives) == 2\n assert np.sum(chim.relatives) == 0\n\n\ndef test_chimera_scalarize():\n chim = Chimera(relatives=np.zeros(2) + 0.1)\n np.random.seed(100691)\n merits = chim.scalarize(np.random.uniform(low=0, high=1, size=(3, 2)))\n assert len(merits) == 3\n assert np.abs(merits[0] - 1.00000) < 1e-4\n assert np.abs(merits[1] - 0.76011) < 1e-4\n assert np.abs(merits[2] - 0.00000) < 1e-4\n\n\n# ==============================================================================\n\nif __name__ == \"__main__\":\n test_chimera_scalarize()\n"
] |
[
[
"numpy.abs",
"numpy.random.seed",
"numpy.isnan",
"numpy.random.uniform",
"numpy.zeros",
"numpy.sum"
]
] |
barretobrock/server-tools
|
[
"2f2b899994df90817686b2232d3d65e53defd8c2"
] |
[
"scripts/weather/daily_weather_and_sig_temp_warn.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom datetime import (\n datetime,\n timedelta\n)\nimport pandas as pd\nfrom kavalkilu import LogWithInflux\nfrom servertools import (\n YrNoWeather,\n YRNOLocation,\n SlackWeatherNotification\n)\nfrom servertools.plants import Plants\n\n\n# Initiate Log, including a suffix to the log name to denote which instance of log is running\nlog = LogWithInflux('significant_change', log_dir='weather')\n\nswno = SlackWeatherNotification(parent_log=log)\nplants = Plants()\n\nnow = datetime.now()\ntomorrow = (now + timedelta(hours=36))\n\n# Get weather details\nwx = YrNoWeather(location=YRNOLocation.ATX)\nforecast_df = wx.hourly_summary()\nforecast_df['date'] = pd.to_datetime(forecast_df['from'])\nforecast_df = forecast_df[['date', 'temp-avg']]\n# Filter on next 48 hours\nforecast_df = forecast_df.loc[forecast_df['date'] <= tomorrow]\n# Get lowest temp\nlowest = forecast_df['temp-avg'].min()\n# Extract plants that might be affected\naffected_plants = plants.get_plants_below(lowest)\n\nif len(affected_plants) > 0:\n # Get the highest low temp of the affected plants\n highest_lowtemp = max([x.temp_min for x in affected_plants])\n # Get the times in which the temps fall below highest_lowtemp\n lowtemps_df = forecast_df.loc[forecast_df['temp-avg'] <= highest_lowtemp]\n # TODO: Group consistent hours for display (e.g., 3pm - 8am)\n # TODO: Build message blocks for these that include plant names\n\n\n# focus on just the following day's measurements\nnextday = hours_df[hours_df['date'].dt.day == tomorrow.day].copy()\nnextday['day'] = nextday['date'].dt.day\nnextday['hour'] = nextday['date'].dt.hour\ntemp_dict = {}\nmetrics_to_collect = dict(zip(\n ['temp-avg', 'feels-temp-avg', 'precip-intensity', 'precip-prob'],\n ['temp', 'apptemp', 'precip_int', 'precip_prob'],\n))\n# Determine which hours are important to examine (e.g., for commuting / outside work)\nimportant_hours = [0, 6, 12, 15, 18]\nfor hour in important_hours:\n hour_info = nextday[nextday['hour'] == hour]\n temp_dict[hour] = {\n f'{shortname}': hour_info[metric].values[0] for metric, shortname in metrics_to_collect.items()\n }\n\ntemp_diff = temp_dict[0]['temp'] - temp_dict[12]['temp']\napptemp_diff = temp_dict[0]['apptemp'] - temp_dict[12]['apptemp']\nif apptemp_diff >= 5:\n # Temp drops by greater than 5 degrees C. Issue warning.\n swno.sig_temp_change_alert(temp_diff, apptemp_diff, temp_dict)\n\n# Send out daily report as well\n\nreport = ['hour\\tt\\tft\\tr-prob\\tr-int']\nfor h in important_hours:\n precip_multiplier = int(round(temp_dict[h]['precip_prob'] * 10 / 2) - 1)\n line = f'{h:02d}:00\\t{temp_dict[h][\"temp\"]:.0f}\\t({temp_dict[h][\"apptemp\"]:.1f})\\t' \\\n f'{temp_dict[h][\"precip_prob\"]:.1%}\\t{temp_dict[h][\"precip_int\"]:.2f}'\n if precip_multiplier > 0:\n line += f\"\\t{''.join([':droplet:'] * precip_multiplier)}\"\n report.append(line)\nswno.daily_weather_briefing(tomorrow, report)\n\nlog.close()\n"
] |
[
[
"pandas.to_datetime"
]
] |
m4ta1l/botorch
|
[
"26a6a511db78dbecae0665755a08afdf3b0fe9b5"
] |
[
"test/utils/test_sampling.py"
] |
[
"#!/usr/bin/env python3\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 itertools\nimport warnings\n\nimport torch\nfrom botorch import settings\nfrom botorch.exceptions.warnings import SamplingWarning\nfrom botorch.posteriors.gpytorch import GPyTorchPosterior\nfrom botorch.utils.sampling import (\n batched_multinomial,\n construct_base_samples,\n construct_base_samples_from_posterior,\n draw_sobol_samples,\n manual_seed,\n sample_hypersphere,\n sample_simplex,\n)\nfrom botorch.utils.testing import BotorchTestCase\nfrom gpytorch.distributions import MultitaskMultivariateNormal, MultivariateNormal\nfrom torch.quasirandom import SobolEngine\n\n\nclass TestManualSeed(BotorchTestCase):\n def test_manual_seed(self):\n initial_state = torch.random.get_rng_state()\n with manual_seed():\n self.assertTrue(torch.all(torch.random.get_rng_state() == initial_state))\n with manual_seed(1234):\n self.assertFalse(torch.all(torch.random.get_rng_state() == initial_state))\n self.assertTrue(torch.all(torch.random.get_rng_state() == initial_state))\n\n\nclass TestConstructBaseSamples(BotorchTestCase):\n def test_construct_base_samples(self):\n test_shapes = [\n {\"batch\": [2], \"output\": [4, 3], \"sample\": [5]},\n {\"batch\": [1], \"output\": [5, 3], \"sample\": [5, 6]},\n {\"batch\": [2, 3], \"output\": [2, 3], \"sample\": [5]},\n ]\n for tshape, qmc, seed, dtype in itertools.product(\n test_shapes, (False, True), (None, 1234), (torch.float, torch.double)\n ):\n batch_shape = torch.Size(tshape[\"batch\"])\n output_shape = torch.Size(tshape[\"output\"])\n sample_shape = torch.Size(tshape[\"sample\"])\n expected_shape = sample_shape + batch_shape + output_shape\n samples = construct_base_samples(\n batch_shape=batch_shape,\n output_shape=output_shape,\n sample_shape=sample_shape,\n qmc=qmc,\n seed=seed,\n device=self.device,\n dtype=dtype,\n )\n self.assertEqual(samples.shape, expected_shape)\n self.assertEqual(samples.device.type, self.device.type)\n self.assertEqual(samples.dtype, dtype)\n # check that warning is issued if dimensionality is too large\n with warnings.catch_warnings(record=True) as w, settings.debug(True):\n construct_base_samples(\n batch_shape=torch.Size(),\n output_shape=torch.Size([200, 6]),\n sample_shape=torch.Size([1]),\n qmc=True,\n )\n self.assertEqual(len(w), 1)\n self.assertTrue(issubclass(w[-1].category, SamplingWarning))\n exp_str = f\"maximum supported by qmc ({SobolEngine.MAXDIM})\"\n self.assertTrue(exp_str in str(w[-1].message))\n\n def test_construct_base_samples_from_posterior(self): # noqa: C901\n for dtype in (torch.float, torch.double):\n # single-output\n mean = torch.zeros(2, device=self.device, dtype=dtype)\n cov = torch.eye(2, device=self.device, dtype=dtype)\n mvn = MultivariateNormal(mean=mean, covariance_matrix=cov)\n posterior = GPyTorchPosterior(mvn=mvn)\n for sample_shape, qmc, seed in itertools.product(\n (torch.Size([5]), torch.Size([5, 3])), (False, True), (None, 1234)\n ):\n expected_shape = sample_shape + torch.Size([2, 1])\n samples = construct_base_samples_from_posterior(\n posterior=posterior, sample_shape=sample_shape, qmc=qmc, seed=seed\n )\n self.assertEqual(samples.shape, expected_shape)\n self.assertEqual(samples.device.type, self.device.type)\n self.assertEqual(samples.dtype, dtype)\n # single-output, batch mode\n mean = torch.zeros(2, 2, device=self.device, dtype=dtype)\n cov = torch.eye(2, device=self.device, dtype=dtype).expand(2, 2, 2)\n mvn = MultivariateNormal(mean=mean, covariance_matrix=cov)\n posterior = GPyTorchPosterior(mvn=mvn)\n for sample_shape, qmc, seed, collapse_batch_dims in itertools.product(\n (torch.Size([5]), torch.Size([5, 3])),\n (False, True),\n (None, 1234),\n (False, True),\n ):\n if collapse_batch_dims:\n expected_shape = sample_shape + torch.Size([1, 2, 1])\n else:\n expected_shape = sample_shape + torch.Size([2, 2, 1])\n samples = construct_base_samples_from_posterior(\n posterior=posterior,\n sample_shape=sample_shape,\n qmc=qmc,\n collapse_batch_dims=collapse_batch_dims,\n seed=seed,\n )\n self.assertEqual(samples.shape, expected_shape)\n self.assertEqual(samples.device.type, self.device.type)\n self.assertEqual(samples.dtype, dtype)\n # multi-output\n mean = torch.zeros(2, 2, device=self.device, dtype=dtype)\n cov = torch.eye(4, device=self.device, dtype=dtype)\n mtmvn = MultitaskMultivariateNormal(mean=mean, covariance_matrix=cov)\n posterior = GPyTorchPosterior(mvn=mtmvn)\n for sample_shape, qmc, seed in itertools.product(\n (torch.Size([5]), torch.Size([5, 3])), (False, True), (None, 1234)\n ):\n expected_shape = sample_shape + torch.Size([2, 2])\n samples = construct_base_samples_from_posterior(\n posterior=posterior, sample_shape=sample_shape, qmc=qmc, seed=seed\n )\n self.assertEqual(samples.shape, expected_shape)\n self.assertEqual(samples.device.type, self.device.type)\n self.assertEqual(samples.dtype, dtype)\n # multi-output, batch mode\n mean = torch.zeros(2, 2, 2, device=self.device, dtype=dtype)\n cov = torch.eye(4, device=self.device, dtype=dtype).expand(2, 4, 4)\n mtmvn = MultitaskMultivariateNormal(mean=mean, covariance_matrix=cov)\n posterior = GPyTorchPosterior(mvn=mtmvn)\n for sample_shape, qmc, seed, collapse_batch_dims in itertools.product(\n (torch.Size([5]), torch.Size([5, 3])),\n (False, True),\n (None, 1234),\n (False, True),\n ):\n if collapse_batch_dims:\n expected_shape = sample_shape + torch.Size([1, 2, 2])\n else:\n expected_shape = sample_shape + torch.Size([2, 2, 2])\n samples = construct_base_samples_from_posterior(\n posterior=posterior,\n sample_shape=sample_shape,\n qmc=qmc,\n collapse_batch_dims=collapse_batch_dims,\n seed=seed,\n )\n self.assertEqual(samples.shape, expected_shape)\n self.assertEqual(samples.device.type, self.device.type)\n self.assertEqual(samples.dtype, dtype)\n\n\nclass TestSampleUtils(BotorchTestCase):\n def test_draw_sobol_samples(self):\n batch_shapes = [None, [3, 5], torch.Size([2]), (5, 3, 2, 3), []]\n for d, q, n, batch_shape, seed, dtype in itertools.product(\n (1, 3),\n (1, 2),\n (2, 5),\n batch_shapes,\n (None, 1234),\n (torch.float, torch.double),\n ):\n tkwargs = {\"device\": self.device, \"dtype\": dtype}\n bounds = torch.stack([torch.rand(d), 1 + torch.rand(d)]).to(**tkwargs)\n samples = draw_sobol_samples(\n bounds=bounds, n=n, q=q, batch_shape=batch_shape, seed=seed\n )\n batch_shape = batch_shape or torch.Size()\n self.assertEqual(samples.shape, torch.Size([n, *batch_shape, q, d]))\n self.assertTrue(torch.all(samples >= bounds[0]))\n self.assertTrue(torch.all(samples <= bounds[1]))\n self.assertEqual(samples.device.type, self.device.type)\n self.assertEqual(samples.dtype, dtype)\n\n def test_sample_simplex(self):\n for d, n, qmc, seed, dtype in itertools.product(\n (1, 2, 3), (2, 5), (False, True), (None, 1234), (torch.float, torch.double)\n ):\n samples = sample_simplex(\n d=d, n=n, qmc=qmc, seed=seed, device=self.device, dtype=dtype\n )\n self.assertEqual(samples.shape, torch.Size([n, d]))\n self.assertTrue(torch.all(samples >= 0))\n self.assertTrue(torch.all(samples <= 1))\n self.assertTrue(torch.max((samples.sum(dim=-1) - 1).abs()) < 1e-5)\n self.assertEqual(samples.device.type, self.device.type)\n self.assertEqual(samples.dtype, dtype)\n\n def test_sample_hypersphere(self):\n for d, n, qmc, seed, dtype in itertools.product(\n (1, 2, 3), (2, 5), (False, True), (None, 1234), (torch.float, torch.double)\n ):\n samples = sample_hypersphere(\n d=d, n=n, qmc=qmc, seed=seed, device=self.device, dtype=dtype\n )\n self.assertEqual(samples.shape, torch.Size([n, d]))\n self.assertTrue(torch.max((samples.pow(2).sum(dim=-1) - 1).abs()) < 1e-5)\n self.assertEqual(samples.device.type, self.device.type)\n self.assertEqual(samples.dtype, dtype)\n\n def test_batched_multinomial(self):\n num_categories = 5\n num_samples = 4\n Trulse = (True, False)\n for batch_shape, dtype, replacement, use_gen, use_out in itertools.product(\n ([], [3], [2, 3]), (torch.float, torch.double), Trulse, Trulse, Trulse\n ):\n weights = torch.rand(*batch_shape, num_categories, dtype=dtype)\n out = None\n if use_out:\n out = torch.empty(*batch_shape, num_samples, dtype=torch.long)\n samples = batched_multinomial(\n weights,\n num_samples,\n replacement=replacement,\n generator=torch.Generator() if use_gen else None,\n out=out,\n )\n self.assertEqual(samples.shape, torch.Size([*batch_shape, num_samples]))\n if use_out:\n self.assertTrue(torch.equal(samples, out))\n if not replacement:\n for s in samples.view(-1, num_samples):\n self.assertTrue(torch.unique(s).size(0), num_samples)\n"
] |
[
[
"torch.all",
"torch.Generator",
"torch.Size",
"torch.empty",
"torch.zeros",
"torch.random.get_rng_state",
"torch.eye",
"torch.equal",
"torch.unique",
"torch.rand"
]
] |
luzgool/ReachMaster
|
[
"e7ef5087fb4e5c55e0b680fc00391f2f8cdc5367"
] |
[
"software/reach_master/build/lib.linux-x86_64-2.7/reachmaster/settings/camera_settings.py"
] |
[
"\"\"\"The camera settings window is opened as a child of the \nReachMaster root application. It provides functionality for \nspecifying the number of cameras, setting their intrinsic \nparameters (e.g., exposure, gain, triggers, etc.), and data \noutput parameters (e.g., cropping, pixel resolution, etc.). It \nprovides functions to capture images and record videos which can\nbe useful for post-hoc camera calibration. It also provides \nfunctions for adding, removing and saving pixels-of-interest \nwhich are used by the experiment protocols for reach detection.\n\nTodo:\n * GPU-accelerated video encoding\n * Currently can't trigger images with lights on\n * Remove fps setting? \n * Automate unit tests\n * Python 3 compatibility\n * PEP 8\n\n\"\"\"\n\nfrom .. import config\nfrom ..interfaces import experiment_interface as expint\nfrom ..interfaces import camera_interface as camint\nimport Tkinter as tk \nimport tkMessageBox\nimport cv2\nimport PIL.Image, PIL.ImageTk\nfrom ximea import xiapi\nimport time\nimport datetime\nimport numpy as np\nimport serial\nimport os \nfrom collections import deque\nfrom vidgear.gears import WriteGear\n\nclass CameraSettings(tk.Toplevel):\n \"\"\"The primary class for the camera settings window.\n\n Configures and provides window callback methods. Also provides \n methods to stream/record video and capture images that can be \n used for post hoc analyses (e.g., camera calibration). The \n `on_quit()` method is called prior to application destruction. \n\n Attributes\n ----------\n config : dict\n The current configuration settings for the application\n output_params : dict\n Video output parameters for WriteGear\n exp_controller : instance\n Serial interface to the experiment microcontroller\n exp_connected : bool \n True if the experiment interface is active\n num_cams : instance\n Tkinter StringVar that captures the user-selected number \n of cameras\n fps : instance \n Tkinter StringVar that captures the user-selected frames \n per second\n exposure : instance \n Tkinter StringVar that captures the user-selected camera \n exposure\n gain : instance \n Tkinter StringVar that captures the user-selected camera \n gain.\n gpi_mode : instance \n Tkinter StringVar that captures the camera input mode. \n Currently, this is selected by the configuration file and \n not the user as it is assumed all camera interfaces will \n trigger images with the same method.\n trigger_source : instance \n Tkinter StringVar that captures the user-selected camera \n trigger source. Defers to the configuration file. Do not \n change unless you know what you are doing.\n gpo_mode : instance \n Tkinter StringVar that captures the user-selected camera \n sync output mode.\n buffer_dur : instance \n Tkinter StringVar that captures the user-selected duration \n that should be used by protocols for buffering images in \n RAM when real-time encoding is not used. \n img_width : instance \n Tkinter StringVar that captures the user-selected image \n width in pixels. Must be less than your camera's maximum \n allowable image width and divisible by it's width increment \n value. See your camera's manual for details.\n img_height : instance \n Tkinter StringVar that captures the user-selected image \n height in pixels. Must be less than your camera's maximum \n allowable image width and divisible by it's width increment \n value. See your camera's manual for details. \n offset_x : instance \n Tkinter StringVar that captures the user-selected image \n horizontal offset in pixels. Must be less than your camera's\n maximum allowable image width minus the selected img_width. \n See your camera's manual for details.\n offset_y : instance \n Tkinter StringVar that captures the user-selected image \n vertical offset in pixels. Must be less than your camera's \n maximum allowable image width minus the selected img_height. \n See your camera's manual for details.\n downsampling : instance\n Tkinter StringVar that captures the user-selected image \n downsampling. Can be 'XI_1x1' (full resolution) or 'XI_2x2' \n (1/4 resolution). The latter can only be used when no cropping \n or offsets are applied. \n poi_threshold : instance \n Tkinter StringVar that captures the user-selected \n pixel-of-interest (poi) threshold (standard deviations) used \n for reach detection.\n streaming : bool\n True if camera interface is acquiring and displaying images.\n cams_connected : bool\n True if camera interface is active.\n draw_saved : bool \n True if saved poi's should be displayed while streaming.\n add_pois : bool \n True if clicking on images should add new poi's during \n streaming.\n remove_pois : bool\n True if clicking on images should remove added or saved poi's \n during streaming.\n added_pois : list \n A nested list of added poi coordinates for each camera. \n saved_pois : list\n A nested list of saved poi coordinates for each camera. \n capture : bool\n True if image should be saved to png while streaming.\n record : bool\n True while recording video.\n img_num : int \n Counts captured images \n\n \"\"\"\n\n def __init__(self, parent):\n #create window and suppress parent\n tk.Toplevel.__init__(self, parent)\n self.transient(parent) \n self.grab_set()\n self.title(\"Camera Settings\")\n self.configure(bg=\"white\")\n self.protocol(\"WM_DELETE_WINDOW\", self.on_quit) \n #initialize tk variables from config\n self.config = config.load_config(open('./temp/tmp_config.txt'))\n self.output_params = self.config['CameraSettings']['output_params'] \n self.exp_controller = expint.start_interface(self.config)\n self.exp_connected = True \n self.num_cams = tk.StringVar()\n self.num_cams.set(str(self.config['CameraSettings']['num_cams']))\n self.fps = tk.StringVar()\n self.fps.set(str(self.config['CameraSettings']['fps']))\n self.exposure = tk.StringVar()\n self.exposure.set(str(self.config['CameraSettings']['exposure']))\n self.gain = tk.StringVar()\n self.gain.set(str(self.config['CameraSettings']['gain'])) \n self.gpi_mode = tk.StringVar()\n self.gpi_mode.set(self.config['CameraSettings']['gpi_mode'])\n self.trigger_source = tk.StringVar()\n self.trigger_source.set(self.config['CameraSettings']['trigger_source'])\n self.gpo_mode = tk.StringVar()\n self.gpo_mode.set(self.config['CameraSettings']['gpo_mode'])\n self.buffer_dur = tk.StringVar()\n self.buffer_dur.set(str(self.config['ExperimentSettings']['buffer_dur']))\n self.img_width = tk.StringVar()\n self.img_width.set(str(self.config['CameraSettings']['img_width']))\n self.img_height = tk.StringVar()\n self.img_height.set(str(self.config['CameraSettings']['img_height']))\n self.offset_x = tk.StringVar()\n self.offset_x.set(str(self.config['CameraSettings']['offset_x']))\n self.offset_y = tk.StringVar()\n self.offset_y.set(str(self.config['CameraSettings']['offset_y']))\n self.downsampling = tk.StringVar()\n self.downsampling.set(str(self.config['CameraSettings']['downsampling']))\n self.poi_threshold = tk.StringVar()\n self.poi_threshold.set(str(self.config['CameraSettings']['poi_threshold'])) \n #initialize housekeeping variables \n self.streaming = False\n self.cams_connected = False\n self.draw_saved = False\n self.add_pois = False\n self.remove_pois = False\n self.added_pois = [[] for _ in range(self.config['CameraSettings']['num_cams'])]\n self.saved_pois = [[] for _ in range(self.config['CameraSettings']['num_cams'])] \n self.capture = False\n self.record = False\n self.img_num = [1]\n #configure window \n self._configure_window()\n\n def on_quit(self):\n \"\"\"Called prior to destruction of the camera settings window.\n\n Prior to destruction, the configuration file must be updated\n to reflect the change in settings, and any active interfaces \n must be closed. \n\n \"\"\"\n self.config['CameraSettings']['num_cams'] = int(self.num_cams.get())\n self.config['CameraSettings']['fps'] = int(self.fps.get())\n self.config['CameraSettings']['exposure'] = int(self.exposure.get())\n self.config['CameraSettings']['gain'] = float(self.gain.get()) \n self.config['CameraSettings']['img_width'] = int(self.img_width.get())\n self.config['CameraSettings']['img_height'] = int(self.img_height.get())\n self.config['CameraSettings']['offset_x'] = int(self.offset_x.get())\n self.config['CameraSettings']['offset_y'] = int(self.offset_y.get())\n self.config['CameraSettings']['downsampling'] = self.downsampling.get()\n self.config['CameraSettings']['trigger_source'] = self.trigger_source.get()\n self.config['CameraSettings']['gpo_mode'] = self.gpo_mode.get()\n self.config['CameraSettings']['poi_threshold'] = float(self.poi_threshold.get())\n self.config['CameraSettings']['self.output_params'] = (self.config['CameraSettings']['num_cams']*\n self.config['CameraSettings']['img_width'],self.config['CameraSettings']['img_height'])\n config.save_tmp(self.config)\n if self.streaming:\n self._on_stream_quit()\n expint.stop_interface(self.exp_controller)\n self.destroy()\n\n def _configure_window(self): \n tk.Label(\n self,\n text = \"# Cameras:\", \n font = 'Arial 10 bold', \n bg = \"white\",\n width = 23,\n anchor = \"e\"\n ).grid(row = 0, sticky = 'W') \n self.num_cams_menu = tk.OptionMenu(self, self.num_cams,\"1\",\"2\",\"3\")\n self.num_cams_menu.configure(width = 12, anchor = \"w\")\n self.num_cams_menu.grid(row = 0, column = 1)\n tk.Label(\n self,\n text = \"FPS:\", \n font = 'Arial 10 bold', \n bg = \"white\", \n width = 23,\n anchor = \"e\"\n ).grid(row = 1, sticky = 'W') \n tk.Entry(self, textvariable = self.fps, width = 17).grid(row = 1, column = 1)\n tk.Label(\n self,\n text = \"Exposure (usec):\", \n font = 'Arial 10 bold', \n bg = \"white\",\n width = 23,\n anchor = \"e\"\n ).grid(row = 2, sticky = 'W') \n tk.Entry(self, textvariable = self.exposure, width = 17).grid(row = 2, column = 1)\n tk.Label(\n self,\n text = \"Gain:\", \n font = 'Arial 10 bold', \n bg = \"white\",\n width = 23,\n anchor = \"e\"\n ).grid(row = 3, sticky = 'W') \n tk.Entry(self, textvariable = self.gain, width = 17).grid(row = 3, column = 1)\n tk.Label(\n self,\n text = \"Trigger Source:\", \n font = 'Arial 10 bold', \n bg = \"white\",\n width = 23,\n anchor = \"e\"\n ).grid(row = 4, sticky = 'W') \n self.gpi_trig_menu = tk.OptionMenu(\n self,\n self.trigger_source,\n \"XI_TRG_OFF\",\n \"XI_TRG_EDGE_RISING\",\n \"XI_TRG_EDGE_FALLING\",\n \"XI_TRG_SOFTWARE\",\n \"XI_TRG_LEVEL_HIGH\",\n \"XI_TRG_LEVEL_LOW\")\n self.gpi_trig_menu.configure(width = 12, anchor = \"w\")\n self.gpi_trig_menu.grid(row = 4, column = 1)\n tk.Label(\n self,\n text = \"Sync Mode:\", \n font = 'Arial 10 bold', \n bg = \"white\",\n width = 23,\n anchor = \"e\"\n ).grid(row = 5, sticky = 'W') \n self.gpo_mode_menu = tk.OptionMenu(\n self,\n self.gpo_mode,\n \"XI_GPO_OFF\",\n \"XI_GPO_ON\",\n \"XI_GPO_FRAME_ACTIVE\",\n \"XI_GPO_FRAME_ACTIVE_NEG\",\n \"XI_GPO_EXPOSURE_ACTIVE\",\n \"XI_GPO_EXPOSURE_ACTIVE_NEG\",\n \"XI_GPO_FRAME_TRIGGER_WAIT\",\n \"XI_GPO_FRAME_TRIGGER_WAIT_NEG\",\n \"XI_GPO_EXPOSURE_PULSE\",\n \"XI_GPO_EXPOSURE_PULSE_NEG\",\n \"XI_GPO_BUSY\",\n \"XI_GPO_BUSY_NEG\",\n \"XI_GPO_HIGH_IMPEDANCE\",\n \"XI_GPO_FRAME_BUFFER_OVERFLOW\")\n self.gpo_mode_menu.configure(width = 12, anchor = \"w\")\n self.gpo_mode_menu.grid(row = 5, column = 1)\n tk.Label(\n self,\n text = \"Image Buffer (sec):\", \n font = 'Arial 10 bold', \n bg = \"white\",\n width = 23,\n anchor = \"e\"\n ).grid(row = 6, sticky = 'W') \n tk.Entry(self, textvariable = self.buffer_dur, width = 17).grid(row = 6, column = 1)\n tk.Label(\n self,\n text = \"Image Width (pix):\", \n font = 'Arial 10 bold', \n bg = \"white\",\n width = 23,\n anchor = \"e\"\n ).grid(row = 7, sticky = 'W') \n tk.Entry(self, textvariable = self.img_width, width = 17).grid(row = 7, column = 1)\n tk.Label(\n self,\n text = \"Image Height (pix):\", \n font = 'Arial 10 bold', \n bg = \"white\",\n width = 23,\n anchor = \"e\"\n ).grid(row = 8, sticky = 'W') \n tk.Entry(self, textvariable = self.img_height, width = 17).grid(row = 8, column = 1)\n tk.Label(\n self,\n text = \"Image X Offest (pix):\", \n font = 'Arial 10 bold', \n bg = \"white\",\n width = 23,\n anchor = \"e\"\n ).grid(row = 9, sticky = 'W') \n tk.Entry(self, textvariable = self.offset_x, width = 17).grid(row = 9, column = 1)\n tk.Label(\n self,\n text = \"Image Y Offset (pix):\", \n font = 'Arial 10 bold', \n bg = \"white\",\n width = 23,\n anchor = \"e\"\n ).grid(row = 10, sticky = 'W') \n tk.Entry(self, textvariable = self.offset_y, width = 17).grid(row = 10, column = 1)\n tk.Label(\n self,\n text = \"Downsampling:\", \n font = 'Arial 10 bold', \n bg = \"white\",\n width = 23,\n anchor = \"e\").grid(row = 11, sticky = 'W') \n self.downsampling_menu = tk.OptionMenu(\n self,\n self.downsampling,\n \"XI_DWN_1x1\",\n \"XI_DWN_2x2\")\n self.downsampling_menu.configure(width = 12, anchor = \"w\")\n self.downsampling_menu.grid(row = 11, column = 1)\n tk.Button(\n self,\n text = \"Start Streaming\",\n font = 'Arial 10 bold',\n width = 14,\n command = self.start_stream_callback\n ).grid(row = 12, column = 0, sticky = \"e\")\n tk.Button(\n self,\n text = \"Stop Streaming\",\n font = 'Arial 10 bold',\n width = 14,\n command = self.stop_stream_callback\n ).grid(row = 13, column = 0, sticky = \"e\")\n tk.Button(\n self,\n text = \"Load POIs\",\n font = 'Arial 10 bold',\n width = 14,\n command = self.load_pois_callback\n ).grid(row = 12, column = 1)\n tk.Button(\n self,\n text = \"Save POIs\",\n font = 'Arial 10 bold',\n width = 14,\n command = self.save_pois_callback\n ).grid(row = 13, column = 1)\n tk.Button(\n self,\n text = \"Add POIs\",\n font = 'Arial 10 bold',\n width = 14,\n command = self.add_pois_callback\n ).grid(row = 12, column = 2)\n tk.Button(\n self,\n text = \"Remove POIs\",\n font = 'Arial 10 bold',\n width = 14,\n command = self.remove_pois_callback\n ).grid(row = 13, column = 2)\n tk.Button(\n self,\n text = \"Capture Image\",\n font = 'Arial 10 bold',\n width = 14,\n command = self.capture_image_callback\n ).grid(row = 14, column = 0,sticky = \"e\")\n tk.Button(\n self,\n text = \"Start Record\",\n font = 'Arial 10 bold',\n width = 14,\n command = self.start_rec_callback\n ).grid(row = 14, column = 1)\n tk.Button(\n self,\n text = \"Stop Record\",\n font = 'Arial 10 bold',\n width = 14,\n command = self.stop_rec_callback\n ).grid(row = 14, column = 2) \n tk.Label(\n self,\n text = \"POI Threshold (stdev):\", \n font = 'Arial 10 bold', \n bg = \"white\",\n width = 23,\n anchor = \"e\"\n ).grid(row = 15, sticky = 'W') \n tk.Entry(self, textvariable = self.poi_threshold, width = 17).grid(row = 15, column = 1)\n tk.Button(\n self,\n text = \"Toggle Lights\", \n font = 'Arial 10 bold',\n width = 14, \n command = self.toggle_lights_callback\n ).grid(row = 16, column = 1)\n\n # Callbacks -----------------------------------------------------------------------------------\n\n def start_stream_callback(self):\n \"\"\"Begins triggering and displaying camera images to the screen.\"\"\"\n if not self.cams_connected:\n self.config['CameraSettings']['num_cams'] = int(self.num_cams.get())\n self.config['CameraSettings']['fps'] = int(self.fps.get())\n self.config['CameraSettings']['exposure'] = int(self.exposure.get())\n self.config['CameraSettings']['gain'] = float(self.gain.get()) \n self.config['CameraSettings']['trigger_source'] = self.trigger_source.get()\n self.config['CameraSettings']['gpo_mode'] = self.gpo_mode.get()\n self.config['CameraSettings']['img_width'] = int(self.img_width.get())\n self.config['CameraSettings']['img_height'] = int(self.img_height.get())\n self.config['CameraSettings']['offset_x'] = int(self.offset_x.get())\n self.config['CameraSettings']['offset_y'] = int(self.offset_y.get()) \n self.config['CameraSettings']['downsampling'] = self.downsampling.get()\n self.cams = camint.start_interface(self.config)\n self.cams_connected = True \n self.img = camint.init_image() \n if not self.streaming:\n self._start_stream()\n else: \n tkMessageBox.showinfo(\"Warning\", \"Already streaming.\") \n\n def stop_stream_callback(self):\n \"\"\"Stops triggering and displaying new images.\"\"\"\n self.streaming = False \n\n\n def load_pois_callback(self):\n \"\"\"Loads previously saved pixels-of-interest and displays them\n over the streaming images in green.\"\"\"\n if self.streaming:\n if len(self.config['CameraSettings']['saved_pois'])>0:\n self.saved_pois = self.config['CameraSettings']['saved_pois']\n self.draw_saved = True\n else:\n tkMessageBox.showinfo(\"Warning\", \"No saved POIs.\")\n else: \n tkMessageBox.showinfo(\"Warning\", \"Must be streaming to load POIs.\")\n\n def add_pois_callback(self):\n \"\"\"Allows the user to add new pixels-of-interest by clicking \n the desired pixel using the cursor. Unsaved added pixels are\n displayed in red.\"\"\"\n if self.streaming:\n self.add_pois = True\n self.remove_pois = False\n else: \n tkMessageBox.showinfo(\"Warning\", \"Must be streaming to add POIs.\") \n\n def remove_pois_callback(self):\n \"\"\"Allows the user to removed either saved or unsaved \n pixels-of-interest. However, the user must save all added \n pixels in order for the changes to be reflected in the\n configuration file.\"\"\" \n if self.streaming:\n if (len(self.added_pois)+len(self.saved_pois))>0:\n self.add_pois = False\n self.remove_pois = True\n else:\n tkMessageBox.showinfo(\"Warning\", \"No POIs to remove.\")\n else: \n tkMessageBox.showinfo(\"Warning\", \"Must be streaming to remove POIs.\")\n\n def save_pois_callback(self):\n \"\"\"Saves all added and/or removed pixel-of-interest to the \n configuration file.\"\"\"\n for i in range(self.config['CameraSettings']['num_cams']):\n self.saved_pois[i] += self.added_pois[i] \n self.config['CameraSettings']['saved_pois'] = self.saved_pois \n self.added_pois = [[] for _ in range(self.config['CameraSettings']['num_cams'])]\n\n def capture_image_callback(self):\n \"\"\"Allows the user to capture an image while streaming. The image\n is saved to the `calibration images` folder in the data output \n directory.\"\"\"\n if self.streaming:\n self.capture = True\n else: \n tkMessageBox.showinfo(\"Warning\", \"Must be streaming to capture images.\")\n\n def start_rec_callback(self):\n \"\"\"Allows the user to record a video which is saved to the `calibration\n videos` folder of the data output directory.\"\"\"\n if not self.streaming:\n self.config['CameraSettings']['num_cams'] = int(self.num_cams.get())\n self.config['CameraSettings']['fps'] = int(self.fps.get())\n self.config['CameraSettings']['exposure'] = int(self.exposure.get())\n self.config['CameraSettings']['gain'] = float(self.gain.get()) \n self.config['CameraSettings']['trigger_source'] = self.trigger_source.get()\n self.config['CameraSettings']['gpo_mode'] = self.gpo_mode.get()\n self.config['CameraSettings']['img_width'] = int(self.img_width.get())\n self.config['CameraSettings']['img_height'] = int(self.img_height.get())\n self.config['CameraSettings']['offset_x'] = int(self.offset_x.get())\n self.config['CameraSettings']['offset_y'] = int(self.offset_y.get())\n self.output_params = (self.config['CameraSettings']['num_cams']*\n self.config['CameraSettings']['img_width'],self.config['CameraSettings']['img_height']) \n self.config['CameraSettings']['output_params'] = self.output_params \n self.cams = camint.start_interface(self.config)\n self.cams_connected = True\n self.img = camint.init_image()\n self.calibration_path = self.config['ReachMaster']['data_dir'] + \"/calibration_videos/\"\n if not os.path.isdir(self.calibration_path):\n os.makedirs(self.calibration_path)\n self.vid_fn = self.calibration_path + str(datetime.datetime.now()) + '.mp4' \n self.video = WriteGear(\n output_filename = self.vid_fn,\n compression_mode = True,\n logging=False,\n **self.output_params)\n self.delay = int(np.round(1.0/float(self.config['CameraSettings']['fps'])*1000.0))\n self.record = True\n self._rec()\n else: \n tkMessageBox.showinfo(\"Warning\", \"Shouldn't record while streaming. Bad framerates!\")\n\n def stop_rec_callback(self):\n \"\"\"Stops a video recording.\"\"\"\n self.record = False\n self.video.close()\n camint.stop_interface(self.cams)\n self.cams_connected = False\n\n def toggle_lights_callback(self):\n \"\"\"Allows the user to toggle the neopixel lights while streaming or\n recording a video.\"\"\"\n if self.exp_connected:\n expint.toggle_lights(self.exp_controller)\n else:\n tkMessageBox.showinfo(\"Warning\", \"Experiment controller not connected.\")\n\n # private methods -------------------------------------------------------------------------------\n\n def _on_stream_quit(self):\n self.streaming = False \n self.poi_active = False \n self.draw_saved = False \n for i in range(self.config['CameraSettings']['num_cams']):\n self.cam_windows[i].destroy()\n camint.stop_interface(self.cams)\n self.cams_connected = False\n\n def _start_stream(self):\n self.cam_windows = [0 for _ in range(self.config['CameraSettings']['num_cams'])]\n for i in range(self.config['CameraSettings']['num_cams']):\n self.cam_windows[i] = tk.Toplevel(self)\n self.cam_windows[i].title(\"Camera\"+str(i))\n self.cam_windows[i].protocol(\"WM_DELETE_WINDOW\", self._on_stream_quit)\n self.cam_windows[i].canvas = tk.Canvas(self.cam_windows[i], \n width = self.config['CameraSettings']['img_width'], \n height = self.config['CameraSettings']['img_height'])\n self.cam_windows[i].canvas.grid(row=0,column= 0) \n self.delay = int(np.round(1.0/float(self.config['CameraSettings']['fps'])*1000.0))\n self.photo_img = [0 for _ in range(self.config['CameraSettings']['num_cams'])]\n self.streaming = True\n self._refresh()\n\n def _refresh(self):\n if self.streaming:\n expint.trigger_image(self.exp_controller)\n now = str(int(round(time.time()*1000))) \n for i in range(self.config['CameraSettings']['num_cams']):\n #display image\n npimg = camint.get_npimage(self.cams[i],self.img)\n npimg = cv2.cvtColor(npimg,cv2.COLOR_BAYER_BG2RGB)\n self.photo_img[i] = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(npimg))\n self.cam_windows[i].canvas.create_image(\n 0, 0, image = self.photo_img[i], anchor = tk.NW\n ) \n #draw saved pixels (green)\n if self.draw_saved:\n for poi in self.saved_pois[i]: \n self.cam_windows[i].canvas.create_line(\n poi[0], poi[1], poi[0] + 1, poi[1], width = 1, fill = 'green'\n )\n #draw currently addded pixels (red)\n for poi in self.added_pois[i]: \n self.cam_windows[i].canvas.create_line(\n poi[0], poi[1], poi[0] + 1, poi[1], width = 1, fill = 'red'\n )\n #draw cursor for adding/removing pois\n if self.add_pois or self.remove_pois:\n self._draw_cursor(i)\n self.cam_windows[i].bind(\n '<Button-1>', lambda event, camid = i:self._draw_poi(event,camid)\n )\n #prepare frame for possible capture\n if i == 0:\n frame = npimg\n else:\n frame = np.hstack((frame,npimg))\n if self.capture:\n self.calibration_path = self.config['ReachMaster']['data_dir'] + \"/calibration_images/\"\n if not os.path.isdir(self.calibration_path):\n os.makedirs(self.calibration_path)\n fn = \"image\" + str(self.img_num[0])\n cv2.imwrite('%s/%s.png' % (self.calibration_path, fn), frame)\n self.capture = False\n self.img_num[0] += 1\n self.after(self.delay,self._refresh)\n\n def _draw_cursor(self,i):\n self.cam_windows[i].bind('<Motion>', self.cam_windows[i].config(cursor = \"cross\")) \n\n def _draw_poi(self, event, camid):\n if self.add_pois:\n self.added_pois[camid].append([event.x,event.y]) \n elif self.remove_pois:\n if len(self.saved_pois[camid])>0:\n tmp = []\n for poi in self.saved_pois[camid]:\n if np.sqrt((event.x-poi[0])**2+(event.y-poi[1])**2)>5:\n tmp.append(poi)\n self.saved_pois[camid] = tmp\n if len(self.added_pois[camid])>0:\n tmp = []\n for poi in self.added_pois[camid]:\n if np.sqrt((event.x-poi[0])**2+(event.y-poi[1])**2)>5:\n tmp.append(poi)\n self.added_pois[camid] = tmp\n\n def _rec(self):\n if self.record:\n expint.trigger_image(self.exp_controller)\n now = str(int(round(time.time()*1000))) \n for i in range(self.config['CameraSettings']['num_cams']):\n npimg = camint.get_npimage(self.cams[i],self.img)\n # npimg = cv2.cvtColor(npimg,cv2.COLOR_BAYER_BG2RGB)\n if i == 0:\n frame = npimg\n else:\n frame = np.hstack((frame,npimg)) \n self.video.write(frame)\n self.after(self.delay,self.rec)"
] |
[
[
"numpy.hstack",
"numpy.sqrt"
]
] |
vanvalenlab/tf-serving-redis-interface
|
[
"f696c05ee622ac6cc38dc1afcef2379d2ea9d9f0"
] |
[
"redis_consumer/consumers/caliban_consumer_test.py"
] |
[
"# Copyright 2016-2022 The Van Valen Lab at the California Institute of\n# Technology (Caltech), with support from the Paul Allen Family Foundation,\n# Google, & National Institutes of Health (NIH) under Grant U24CA224309-01.\n# All rights reserved.\n#\n# Licensed under a modified 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.github.com/vanvalenlab/kiosk-redis-consumer/LICENSE\n#\n# The Work provided may be used for non-commercial academic purposes only.\n# For any other use of the Work, including commercial use, please contact:\n# vanvalenlab@gmail.com\n#\n# Neither the name of Caltech nor the names of its contributors may be used\n# to endorse or promote products derived from this software without specific\n# prior written permission.\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Tests for post-processing functions\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport random\nimport string\n\nimport pytest\n\nimport numpy as np\nimport tifffile\n\nfrom redis_consumer import consumers\nfrom redis_consumer import settings\nfrom redis_consumer.testing_utils import Bunch\nfrom redis_consumer.testing_utils import DummyStorage\nfrom redis_consumer.testing_utils import redis_client\nfrom redis_consumer.testing_utils import _get_image\n\n\nclass TestCalibanConsumer(object):\n # pylint: disable=R0201,W0621\n def test_is_valid_hash(self, mocker, redis_client):\n queue = 'track'\n storage = DummyStorage()\n consumer = consumers.CalibanConsumer(redis_client, storage, queue)\n\n mocker.patch.object(redis_client, 'hget', lambda x, y: x.split(':')[-1])\n\n assert consumer.is_valid_hash(None) is False\n assert consumer.is_valid_hash('predict:123456789:file.png') is False\n assert consumer.is_valid_hash('predict:1234567890:file.tiff') is True\n assert consumer.is_valid_hash('predict:1234567890:file.png') is False\n assert consumer.is_valid_hash('track:1234567890:file.ZIp') is False\n assert consumer.is_valid_hash('track:123456789:file.zip') is False\n assert consumer.is_valid_hash('track:1234567890:file.png') is False\n assert consumer.is_valid_hash('track:1234567890:file.tiff') is True\n assert consumer.is_valid_hash('track:1234567890:file.trk') is True\n assert consumer.is_valid_hash('track:1234567890:file.trks') is True\n\n def test__load_data(self, tmpdir, mocker, redis_client):\n queue = 'track'\n storage = DummyStorage()\n consumer = consumers.CalibanConsumer(redis_client, storage, queue)\n tmpdir = str(tmpdir)\n exp = random.randint(0, 99)\n\n # test load trk files\n key = 'trk file test'\n mocker.patch('redis_consumer.utils.load_track_file', lambda x: exp)\n result = consumer._load_data(key, tmpdir, 'data.trk')\n assert result == exp\n result = consumer._load_data(key, tmpdir, 'data.trks')\n assert result == exp\n\n # test bad filetype\n key = 'invalid filetype test'\n with pytest.raises(ValueError):\n consumer._load_data(key, tmpdir, 'data.npz')\n\n # test bad ndim for tiffstack\n fname = 'test.tiff'\n filepath = os.path.join(tmpdir, fname)\n tifffile.imsave(filepath, _get_image())\n with pytest.raises(ValueError):\n consumer._load_data(key, tmpdir, fname)\n\n # test successful workflow\n def hget_successful_status(*_):\n return consumer.final_status\n\n def hget_failed_status(*_):\n return consumer.failed_status\n\n def write_child_tiff(*_, **__):\n letters = string.ascii_lowercase\n name = ''.join(random.choice(letters) for i in range(12))\n path = os.path.join(tmpdir, '{}.tiff'.format(name))\n tifffile.imsave(path, _get_image(21, 21))\n return [path]\n\n mocker.patch.object(settings, 'INTERVAL', 0)\n mocker.patch.object(redis_client, 'hget', hget_successful_status)\n mocker.patch('redis_consumer.utils.iter_image_archive',\n write_child_tiff)\n\n for label_detect in (True, False):\n mocker.patch.object(settings, 'SCALE_DETECT_ENABLED', label_detect)\n mocker.patch.object(settings, 'LABEL_DETECT_ENABLED', label_detect)\n\n tifffile.imsave(filepath, np.random.random((3, 21, 21)))\n results = consumer._load_data(key, tmpdir, fname)\n X, y = results.get('X'), results.get('y')\n assert isinstance(X, np.ndarray)\n assert isinstance(y, np.ndarray)\n assert X.shape == y.shape\n\n # test failed child\n with pytest.raises(RuntimeError):\n mocker.patch.object(redis_client, 'hget', hget_failed_status)\n consumer._load_data(key, tmpdir, fname)\n\n # test wrong number of images in the test file\n with pytest.raises(RuntimeError):\n mocker.patch.object(redis_client, 'hget', hget_successful_status)\n mocker.patch('redis_consumer.utils.iter_image_archive',\n lambda *x: range(1, 3))\n consumer._load_data(key, tmpdir, fname)\n\n def test__consume(self, mocker, redis_client):\n queue = 'track'\n storage = DummyStorage()\n test_hash = 0\n\n dummy_results = {\n 'y_tracked': np.zeros((32, 32, 1)),\n 'tracks': []\n }\n\n mock_model = Bunch(\n get_batch_size=lambda *x: 1,\n input_shape=(1, 32, 32, 1)\n )\n mock_app = Bunch(\n predict=lambda *x, **y: dummy_results,\n track=lambda *x, **y: dummy_results,\n model_mpp=1,\n model=mock_model,\n )\n\n consumer = consumers.CalibanConsumer(redis_client, storage, queue)\n\n mocker.patch.object(consumer, 'get_grpc_app',\n lambda *x, **y: mock_app)\n # mock get_model_wrapper for neighborhood encoder\n mocker.patch.object(consumer, 'get_model_wrapper',\n lambda *x, **y: mock_model)\n\n frames = 3\n dummy_data = {\n 'X': np.array([_get_image(21, 21) for _ in range(frames)]),\n 'y': np.random.randint(0, 9, size=(frames, 21, 21)),\n }\n\n mocker.patch.object(consumer, '_load_data', lambda *x: dummy_data)\n\n # test finished statuses are returned\n for status in (consumer.failed_status, consumer.final_status):\n test_hash += 1\n data = {'input_file_name': 'file.tiff', 'status': status}\n redis_client.hmset(test_hash, data)\n result = consumer._consume(test_hash)\n assert result == status\n\n # test new key is processed\n test_hash += 1\n data = {'input_file_name': 'file.tiff', 'status': 'new'}\n redis_client.hmset(test_hash, data)\n result = consumer._consume(test_hash)\n assert result == consumer.final_status\n assert redis_client.hget(test_hash, 'status') == consumer.final_status\n"
] |
[
[
"numpy.random.random",
"numpy.zeros",
"numpy.random.randint"
]
] |
mrelmi/InsightFace-PyTorch
|
[
"a235c4f6e3f3ea58aac53a0420921431b97995a8"
] |
[
"utils.py"
] |
[
"import argparse\nimport os\nfrom shutil import copyfile\n\nimport cv2 as cv\nimport numpy as np\nimport torch\n\nfrom align_faces import get_reference_facial_points, warp_and_crop_face\nfrom config import im_size\nfrom retinaface.detector import detector\n\n\ndef clip_gradient(optimizer, grad_clip):\n \"\"\"\n Clips gradients computed during backpropagation to avoid explosion of gradients.\n :param optimizer: optimizer with the gradients to be clipped\n :param grad_clip: clip value\n \"\"\"\n for group in optimizer.param_groups:\n for param in group['params']:\n if param.grad is not None:\n param.grad.data.clamp_(-grad_clip, grad_clip)\n\n\ndef save_checkpoint(epoch, epochs_since_improvement, model, metric_fc, optimizer, acc, is_best, scheduler):\n state = {'epoch': epoch,\n 'epochs_since_improvement': epochs_since_improvement,\n 'acc': acc,\n 'model': model,\n 'metric_fc': metric_fc,\n 'optimizer': optimizer,\n 'scheduler': scheduler}\n # filename = 'checkpoint_' + str(epoch) + '_' + str(loss) + '.tar'\n filename = 'checkpoint.tar'\n torch.save(state, filename)\n # If this checkpoint is the best so far, store a copy so it doesn't get overwritten by a worse checkpoint\n if is_best:\n torch.save(state, 'BEST_checkpoint.tar')\n\n\nclass AverageMeter(object):\n \"\"\"\n Keeps track of most recent, average, sum, and count of a metric.\n \"\"\"\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\ndef adjust_learning_rate(optimizer, shrink_factor):\n \"\"\"\n Shrinks learning rate by a specified factor.\n :param optimizer: optimizer whose learning rate must be shrunk.\n :param shrink_factor: factor in interval (0, 1) to multiply learning rate with.\n \"\"\"\n\n print(\"\\nDECAYING learning rate.\")\n for param_group in optimizer.param_groups:\n param_group['lr'] = param_group['lr'] * shrink_factor\n print(\"The new learning rate is %f\\n\" % (optimizer.param_groups[0]['lr'],))\n\n\ndef get_learning_rate(optimizer):\n for param_group in optimizer.param_groups:\n return param_group['lr']\n\n\ndef accuracy(scores, targets, k=1):\n batch_size = targets.size(0)\n _, ind = scores.topk(k, 1, True, True)\n correct = ind.eq(targets.view(-1, 1).expand_as(ind))\n correct_total = correct.view(-1).float().sum() # 0D tensor\n return correct_total.item() * (100.0 / batch_size)\n\n\ndef align_face(raw, facial5points):\n # raw = cv.imread(img_fn, True) # BGR\n facial5points = np.reshape(facial5points, (2, 5))\n\n crop_size = (im_size, im_size)\n\n default_square = True\n inner_padding_factor = 0.25\n outer_padding = (0, 0)\n output_size = (im_size, im_size)\n\n # get the reference 5 landmarks position in the crop settings\n reference_5pts = get_reference_facial_points(\n output_size, inner_padding_factor, outer_padding, default_square)\n\n # dst_img = warp_and_crop_face(raw, facial5points)\n dst_img = warp_and_crop_face(raw, facial5points, reference_pts=reference_5pts, crop_size=crop_size)\n return dst_img\n\n\ndef get_face_attributes(full_path):\n try:\n img = cv.imread(full_path)\n bounding_boxes, landmarks = detector.detect_faces(img)\n\n if len(landmarks) > 0:\n landmarks = [int(round(x)) for x in landmarks[0]]\n return True, landmarks\n\n except KeyboardInterrupt:\n raise\n except:\n pass\n return False, None\n\n\ndef select_significant_face(bboxes):\n best_index = -1\n best_rank = float('-inf')\n for i, b in enumerate(bboxes):\n bbox_w, bbox_h = b[2] - b[0], b[3] - b[1]\n area = bbox_w * bbox_h\n score = b[4]\n rank = score * area\n if rank > best_rank:\n best_rank = rank\n best_index = i\n\n return best_index\n\n\ndef get_central_face_attributes(full_path):\n try:\n img = cv.imread(full_path)\n bboxes, landmarks = detector.detect_faces(img)\n\n if len(landmarks) > 0:\n i = select_significant_face(bboxes)\n return True, [bboxes[i]], [landmarks[i]]\n\n except KeyboardInterrupt:\n raise\n except ValueError:\n pass\n except IOError:\n pass\n return False, None, None\n\n\ndef get_all_face_attributes(full_path):\n img = cv.imread(full_path)\n bounding_boxes, landmarks = detector.detect_faces(img)\n return bounding_boxes, landmarks\n\n\ndef draw_bboxes(img, bounding_boxes, facial_landmarks=[]):\n for b in bounding_boxes:\n cv.rectangle(img, (int(b[0]), int(b[1])), (int(b[2]), int(b[3])), (255, 255, 255), 1)\n\n for p in facial_landmarks:\n for i in range(5):\n cv.circle(img, (int(p[i]), int(p[i + 5])), 1, (0, 255, 0), -1)\n\n break # only first\n\n return img\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Train face network')\n # general\n parser.add_argument('--pretrained', type=bool, default=False, help='pretrained model')\n parser.add_argument('--network', default='r101', help='specify network')\n parser.add_argument('--end-epoch', type=int, default=1000, help='training epoch size.')\n parser.add_argument('--lr', type=float, default=0.1, help='start learning rate')\n parser.add_argument('--lr-step', type=int, default=10, help='period of learning rate decay')\n parser.add_argument('--optimizer', default='adam', help='optimizer')\n parser.add_argument('--weight-decay', type=float, default=5e-4, help='weight decay')\n parser.add_argument('--mom', type=float, default=0.9, help='momentum')\n parser.add_argument('--emb-size', type=int, default=512, help='embedding length')\n parser.add_argument('--batch-size', type=int, default=128, help='batch size in each context')\n parser.add_argument('--margin-m', type=float, default=0.5, help='angular margin m')\n parser.add_argument('--margin-s', type=float, default=64.0, help='feature scale s')\n parser.add_argument('--easy-margin', type=bool, default=False, help='easy margin')\n parser.add_argument('--focal-loss', type=bool, default=False, help='focal loss')\n parser.add_argument('--gamma', type=float, default=2.0, help='focusing parameter gamma')\n parser.add_argument('--use-se', type=bool, default=True, help='use SEBlock')\n parser.add_argument('--full-log', type=bool, default=False, help='full logging')\n parser.add_argument('--checkpoint', type=str, default=None, help='checkpoint')\n args = parser.parse_args()\n return args\n\n\ndef ensure_folder(folder):\n import os\n if not os.path.isdir(folder):\n os.mkdir(folder)\n\n\ndef full_log(epoch):\n full_log_dir = 'data/full_log'\n if not os.path.isdir(full_log_dir):\n os.mkdir(full_log_dir)\n filename = 'angles_{}.txt'.format(epoch)\n dst_file = os.path.join(full_log_dir, filename)\n src_file = 'data/angles.txt'\n copyfile(src_file, dst_file)\n"
] |
[
[
"numpy.reshape",
"torch.save"
]
] |
TinasheMTapera/bids-pres
|
[
"7ad27ec13966b498cee4e55c6c3a47c0ef90e1bd"
] |
[
"flywheel_bids_tools/group_query.py"
] |
[
"import pandas as pd\nimport argparse\nfrom .query_bids import unlist_item\n\n\ndef read_flywheel_csv(fpath, required_cols=['acquisition.label']):\n '''\n Read in a CSV and also ensure it's one of ours\n\n Input:\n fpath: path to the file\n required_cols: list of columns to ensure csv is a flywheel query\n Output:\n df: a pandas dataframe\n '''\n\n df = pd.read_csv(fpath)\n\n if not all(elem in df.columns.tolist() for elem in required_cols):\n raise Exception((\"It doesn't look like this csv is correctly formatted\",\n \" for this flywheel editing process!\"))\n\n return(df)\n\n\ndef main():\n\n parser = argparse.ArgumentParser(description=(\"Use this tool to group a Flywheel query file by a column with common values.\"))\n parser.add_argument(\n \"-input\", \"--input-file\",\n dest='infile',\n help=\"Flywheel query file\",\n required=True\n )\n parser.add_argument(\n \"-output\", \"--grouped-output\",\n help=\"The path and name of a grouped version of the output CSV of the query\",\n dest=\"group_output\",\n required=True\n )\n parser.add_argument(\n \"-groups\", \"--groupings\",\n nargs='+',\n dest='group',\n help=\"Columns to group unique rows by\",\n required=True\n )\n args = parser.parse_args()\n\n # read in the file\n query_result = read_flywheel_csv(args.infile)\n\n # add a group index, group\n query_result['group_id'] = (query_result\n # groupby and keep the columns as columns\n .groupby(args.group, as_index=False)\n # index the groups\n .ngroup()\n .add(1))\n query_result = (query_result\n # groupby and sample 1 exemplar\n .groupby(args.group, as_index=False)\n .nth(1)\n .reset_index(drop=True))\n # add index for group indeces\n query_result['groups'] = unlist_item(args.group)\n query_result.to_csv(args.group_output, index=False)\n print(\"Done\")\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"pandas.read_csv"
]
] |
houshengyuan/MAN
|
[
"03912e80b21e0fc40c36515b6893d4244b82e6b6"
] |
[
"translation/fairseq/data/data_utils.py"
] |
[
"# 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 contextlib\nimport os\n\nimport numpy as np\n\n\ndef infer_language_pair(path):\n \"\"\"Infer language pair from filename: <split>.<lang1>-<lang2>.(...).idx\"\"\"\n src, dst = None, None\n for filename in os.listdir(path):\n parts = filename.split('.')\n if len(parts) >= 3 and len(parts[1].split('-')) == 2:\n return parts[1].split('-')\n return src, dst\n\n\ndef collate_tokens(values, pad_idx, eos_idx, left_pad, move_eos_to_beginning=False):\n \"\"\"Convert a list of 1d tensors into a padded 2d tensor.\"\"\"\n size = max(v.size(0) for v in values)\n res = values[0].new(len(values), size).fill_(pad_idx)\n\n def copy_tensor(src, dst):\n assert dst.numel() == src.numel()\n if move_eos_to_beginning:\n assert src[-1] == eos_idx\n dst[0] = eos_idx\n dst[1:] = src[:-1]\n else:\n dst.copy_(src)\n\n for i, v in enumerate(values):\n copy_tensor(v, res[i][size - len(v):] if left_pad else res[i][:len(v)])\n return res\n\n\n@contextlib.contextmanager\ndef numpy_seed(seed):\n \"\"\"Context manager which seeds the NumPy PRNG with the specified seed and\n restores the state afterward\"\"\"\n if seed is None:\n yield\n return\n state = np.random.get_state()\n np.random.seed(seed)\n try:\n yield\n finally:\n np.random.set_state(state)\n\n\ndef collect_filtered(function, iterable, filtered):\n \"\"\"\n Similar to :func:`filter` but collects filtered elements in ``filtered``.\n\n Args:\n function (callable): function that returns ``False`` for elements that\n should be filtered\n iterable (iterable): iterable to filter\n filtered (list): list to store filtered elements\n \"\"\"\n for el in iterable:\n if function(el):\n yield el\n else:\n filtered.append(el)\n\n\ndef filter_by_size(indices, size_fn, max_positions, raise_exception=False):\n \"\"\"\n Filter indices based on their size.\n\n Args:\n indices (List[int]): ordered list of dataset indices\n size_fn (callable): function that returns the size of a given index\n max_positions (tuple): filter elements larger than this size.\n Comparisons are done component-wise.\n raise_exception (bool, optional): if ``True``, raise an exception\n if any elements are filtered. Default: ``False``\n \"\"\"\n def check_size(idx):\n if isinstance(max_positions, float) or isinstance(max_positions, int):\n return size_fn(idx) <= max_positions\n else:\n return all(a is None or b is None or a <= b\n for a, b in zip(size_fn(idx), max_positions))\n\n ignored = []\n itr = collect_filtered(check_size, indices, ignored)\n for idx in itr:\n if len(ignored) > 0 and raise_exception:\n raise Exception((\n 'Size of sample #{} is invalid (={}) since max_positions={}, '\n 'skip this example with --skip-invalid-size-inputs-valid-test'\n ).format(idx, size_fn(idx), max_positions))\n yield idx\n\n if len(ignored) > 0:\n print((\n '| WARNING: {} samples have invalid sizes and will be skipped, '\n 'max_positions={}, first few sample ids={}'\n ).format(len(ignored), max_positions, ignored[:10]))\n\n\ndef batch_by_size(\n indices, num_tokens_fn, max_tokens=None, max_sentences=None,\n required_batch_size_multiple=1,\n):\n \"\"\"\n Yield mini-batches of indices bucketed by size. Batches may contain\n sequences of different lengths.\n\n Args:\n indices (List[int]): ordered list of dataset indices\n num_tokens_fn (callable): function that returns the number of tokens at\n a given index\n max_tokens (int, optional): max number of tokens in each batch.\n Default: ``None``\n max_sentences (int, optional): max number of sentences in each\n batch. Default: ``None``\n required_batch_size_multiple (int, optional): require batch size to\n be a multiple of N. Default: ``1``\n \"\"\"\n max_tokens = max_tokens if max_tokens is not None else float('Inf')\n max_sentences = max_sentences if max_sentences is not None else float('Inf')\n bsz_mult = required_batch_size_multiple\n\n batch = []\n\n def is_batch_full(num_tokens):\n if len(batch) == 0:\n return False\n if len(batch) == max_sentences:\n return True\n if num_tokens > max_tokens:\n return True\n return False\n\n sample_len = 0\n sample_lens = []\n ignored = []\n for idx in indices:\n sample_lens.append(num_tokens_fn(idx))\n sample_len = max(sample_len, sample_lens[-1])\n num_tokens = (len(batch) + 1) * sample_len\n if is_batch_full(num_tokens):\n mod_len = max(\n bsz_mult * (len(batch) // bsz_mult),\n len(batch) % bsz_mult,\n )\n yield batch[:mod_len]\n batch = batch[mod_len:]\n sample_lens = sample_lens[mod_len:]\n sample_len = max(sample_lens) if len(sample_lens) > 0 else 0\n\n batch.append(idx)\n\n if len(batch) > 0:\n yield batch\n"
] |
[
[
"numpy.random.get_state",
"numpy.random.set_state",
"numpy.random.seed"
]
] |
edgarriba/lightning-flash
|
[
"62472d7615d95990df92a8a2f92f80af1ab737ac"
] |
[
"flash_examples/finetuning/summarization.py"
] |
[
"# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport torch\n\nimport flash\nfrom flash import download_data, Trainer\nfrom flash.text import SummarizationData, SummarizationTask\n\n# 1. Download the data\ndownload_data(\"https://pl-flash-data.s3.amazonaws.com/xsum.zip\", \"data/\")\n\n# 2. Load the data\ndatamodule = SummarizationData.from_files(\n train_file=\"data/xsum/train.csv\",\n val_file=\"data/xsum/valid.csv\",\n test_file=\"data/xsum/test.csv\",\n input=\"input\",\n target=\"target\"\n)\n\n# 3. Build the model\nmodel = SummarizationTask()\n\n# 4. Create the trainer. Run once on data\ntrainer = flash.Trainer(gpus=int(torch.cuda.is_available()), fast_dev_run=True)\n\n# 5. Fine-tune the model\ntrainer.finetune(model, datamodule=datamodule)\n\n# 6. Save it!\ntrainer.save_checkpoint(\"summarization_model_xsum.pt\")\n"
] |
[
[
"torch.cuda.is_available"
]
] |
peterdonnelly1/u24_lymphocyte
|
[
"dff7ceed404c38582feb81aa9b8a55d80ada0f77"
] |
[
"archive/lym_pipeline/prediction/pred.py"
] |
[
"import pickle\nimport sys\nimport os\nimport urllib\nimport gzip\nimport cPickle\nimport time\nimport lasagne\nimport theano\nimport numpy as np\nimport theano.tensor as T\n\nfrom lasagne import layers\nfrom lasagne.updates import nesterov_momentum\nfrom nolearn.lasagne import NeuralNet\nfrom nolearn.lasagne import BatchIterator\nfrom theano.sandbox.neighbours import neibs2images\nfrom lasagne.nonlinearities import sigmoid, rectify, leaky_rectify, identity\nfrom lasagne.nonlinearities import softmax\nfrom lasagne import regularization\nfrom scipy import misc\nfrom PIL import Image\nfrom lasagne import init\nfrom math import floor\n\nfrom shape import ReshapeLayer\nfrom batch_norms import batch_norm, SoftThresPerc\nfrom data_aug import data_aug\nfrom ch_inner_prod import ChInnerProd, ChInnerProdMerge\n\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import mean_squared_error, accuracy_score, hamming_loss, roc_curve, auc\n\nAPS = 100;\nPS = 100;\nTileFolder = sys.argv[1] + '/';\nLearningRate = theano.shared(np.array(5e-3, dtype=np.float32));\nBatchSize = 80;\n\nfilename_mu = 'models/mu.pkl';\nfilename_sigma = 'models/sigma.pkl';\nheat_map_out = 'patch-level-lym.txt';\nCNNModel = 'models/cnn_model.pkl';\n\nmu = pickle.load(open(filename_mu, 'rb'));\nsigma = pickle.load(open(filename_sigma, 'rb'));\naug_fea_n = 1;\n\n\ndef whiteness(png):\n wh = (np.std(png[:,:,0].flatten()) + np.std(png[:,:,1].flatten()) + np.std(png[:,:,2].flatten())) / 3.0;\n return wh;\n\n\ndef load_data(todo_list, rind):\n X = np.zeros(shape=(BatchSize*20, 3, APS, APS), dtype=np.float32);\n inds = np.zeros(shape=(BatchSize*20,), dtype=np.int32);\n coor = np.zeros(shape=(1000000, 2), dtype=np.int32);\n\n xind = 0;\n lind = 0;\n cind = 0;\n for fn in todo_list:\n lind += 1;\n full_fn = TileFolder + '/' + fn;\n if not os.path.isfile(full_fn):\n continue;\n if len(fn.split('_')) < 4:\n continue;\n\n x_off = float(fn.split('_')[0]);\n y_off = float(fn.split('_')[1]);\n svs_pw = float(fn.split('_')[2]);\n png_pw = float(fn.split('_')[3].split('.png')[0]);\n\n png = np.array(Image.open(full_fn).convert('RGB'));\n for x in range(0, png.shape[1], APS):\n if x + APS > png.shape[1]:\n continue;\n for y in range(0, png.shape[0], APS):\n if y + APS > png.shape[0]:\n continue;\n\n if (whiteness(png[y:y+APS, x:x+APS, :]) >= 12):\n X[xind, :, :, :] = png[y:y+APS, x:x+APS, :].transpose();\n inds[xind] = rind;\n xind += 1;\n\n coor[cind, 0] = np.int32(x_off + (x + APS/2) * svs_pw / png_pw);\n coor[cind, 1] = np.int32(y_off + (y + APS/2) * svs_pw / png_pw);\n cind += 1;\n rind += 1;\n\n if xind >= BatchSize:\n break;\n\n X = X[0:xind];\n inds = inds[0:xind];\n coor = coor[0:cind];\n\n return todo_list[lind:], X, inds, coor, rind;\n\n\ndef from_output_to_pred(output):\n pred = np.copy(output);\n pred = (pred >= 0.5).astype(np.int32);\n return pred;\n\n\ndef multi_win_during_val(val_fn, inputs, augs, targets):\n for idraw in [-1,]:\n for jdraw in [-1,]:\n inpt_multiwin = data_aug(inputs, mu, sigma, deterministic=True, idraw=idraw, jdraw=jdraw);\n err_pat, output_pat = val_fn(inpt_multiwin, augs, targets);\n if 'weight' in locals():\n weight += 1.0;\n err += err_pat;\n output += output_pat;\n else:\n weight = 1.0;\n err = err_pat;\n output = output_pat;\n return err/weight, output/weight;\n\n\ndef val_fn_epoch_on_disk(classn, val_fn):\n all_or = np.zeros(shape=(1000000, classn), dtype=np.float32);\n all_inds = np.zeros(shape=(1000000,), dtype=np.int32);\n all_coor = np.zeros(shape=(1000000, 2), dtype=np.int32);\n rind = 0;\n n1 = 0;\n n2 = 0;\n n3 = 0;\n todo_list = os.listdir(TileFolder);\n while len(todo_list) > 0:\n todo_list, inputs, inds, coor, rind = load_data(todo_list, rind);\n augs = get_aug_feas(inputs);\n targets = np.zeros((inputs.shape[0], classn), dtype=np.int32);\n\n err, output = multi_win_during_val(val_fn, inputs, augs, targets);\n all_or[n1:n1+len(output)] = output;\n all_inds[n2:n2+len(inds)] = inds;\n all_coor[n3:n3+len(coor)] = coor;\n n1 += len(output);\n n2 += len(inds);\n n3 += len(coor);\n\n all_or = all_or[:n1];\n all_inds = all_inds[:n2];\n all_coor = all_coor[:n3];\n return all_or, all_inds, all_coor;\n\n\ndef confusion_matrix(Or, Tr, thres):\n tpos = np.sum((Or>=thres) * (Tr==1));\n tneg = np.sum((Or< thres) * (Tr==0));\n fpos = np.sum((Or>=thres) * (Tr==0));\n fneg = np.sum((Or< thres) * (Tr==1));\n return tpos, tneg, fpos, fneg;\n\n\ndef auc_roc(Pr, Tr):\n fpr, tpr, _ = roc_curve(Tr, Pr, pos_label=1.0);\n return auc(fpr, tpr);\n\n\ndef build_network_from_ae(classn):\n input_var = T.tensor4('input_var');\n\n layer = layers.InputLayer(shape=(None, 3, PS, PS), input_var=input_var);\n layer = batch_norm(layers.Conv2DLayer(layer, 100, filter_size=(5,5), stride=1, pad='same', nonlinearity=leaky_rectify));\n layer = batch_norm(layers.Conv2DLayer(layer, 120, filter_size=(5,5), stride=1, pad='same', nonlinearity=leaky_rectify));\n layer = layers.Pool2DLayer(layer, pool_size=(2,2), stride=2, mode='average_inc_pad');\n layer = batch_norm(layers.Conv2DLayer(layer, 240, filter_size=(3,3), stride=1, pad='same', nonlinearity=leaky_rectify));\n layer = batch_norm(layers.Conv2DLayer(layer, 320, filter_size=(3,3), stride=1, pad='same', nonlinearity=leaky_rectify));\n layer = layers.Pool2DLayer(layer, pool_size=(2,2), stride=2, mode='average_inc_pad');\n layer = batch_norm(layers.Conv2DLayer(layer, 640, filter_size=(3,3), stride=1, pad='same', nonlinearity=leaky_rectify));\n prely = batch_norm(layers.Conv2DLayer(layer, 1024, filter_size=(3,3), stride=1, pad='same', nonlinearity=leaky_rectify));\n\n featm = batch_norm(layers.Conv2DLayer(prely, 640, filter_size=(1,1), nonlinearity=leaky_rectify));\n feat_map = batch_norm(layers.Conv2DLayer(featm, 100, filter_size=(1,1), nonlinearity=rectify, name=\"feat_map\"));\n maskm = batch_norm(layers.Conv2DLayer(prely, 100, filter_size=(1,1), nonlinearity=leaky_rectify));\n mask_rep = batch_norm(layers.Conv2DLayer(maskm, 1, filter_size=(1,1), nonlinearity=None), beta=None, gamma=None);\n mask_map = SoftThresPerc(mask_rep, perc=97.0, alpha=0.1, beta=init.Constant(0.5), tight=100.0, name=\"mask_map\");\n enlyr = ChInnerProdMerge(feat_map, mask_map, name=\"encoder\");\n\n layer = batch_norm(layers.Deconv2DLayer(enlyr, 1024, filter_size=(3,3), stride=1, crop='same', nonlinearity=leaky_rectify));\n layer = batch_norm(layers.Deconv2DLayer(layer, 640, filter_size=(3,3), stride=1, crop='same', nonlinearity=leaky_rectify));\n layer = batch_norm(layers.Deconv2DLayer(layer, 640, filter_size=(4,4), stride=2, crop=(1,1), nonlinearity=leaky_rectify));\n layer = batch_norm(layers.Deconv2DLayer(layer, 320, filter_size=(3,3), stride=1, crop='same', nonlinearity=leaky_rectify));\n layer = batch_norm(layers.Deconv2DLayer(layer, 320, filter_size=(3,3), stride=1, crop='same', nonlinearity=leaky_rectify));\n layer = batch_norm(layers.Deconv2DLayer(layer, 240, filter_size=(4,4), stride=2, crop=(1,1), nonlinearity=leaky_rectify));\n layer = batch_norm(layers.Deconv2DLayer(layer, 120, filter_size=(5,5), stride=1, crop='same', nonlinearity=leaky_rectify));\n layer = batch_norm(layers.Deconv2DLayer(layer, 100, filter_size=(5,5), stride=1, crop='same', nonlinearity=leaky_rectify));\n layer = layers.Deconv2DLayer(layer, 3, filter_size=(1,1), stride=1, crop='same', nonlinearity=identity);\n\n glblf = batch_norm(layers.Conv2DLayer(prely, 128, filter_size=(1,1), nonlinearity=leaky_rectify));\n glblf = layers.Pool2DLayer(glblf, pool_size=(5,5), stride=5, mode='average_inc_pad');\n glblf = batch_norm(layers.Conv2DLayer(glblf, 64, filter_size=(3,3), stride=1, pad='same', nonlinearity=leaky_rectify));\n gllyr = batch_norm(layers.Conv2DLayer(glblf, 5, filter_size=(1,1), nonlinearity=rectify), name=\"global_feature\");\n\n glblf = batch_norm(layers.Deconv2DLayer(gllyr, 256, filter_size=(3,3), stride=1, crop='same', nonlinearity=leaky_rectify));\n glblf = batch_norm(layers.Deconv2DLayer(glblf, 128, filter_size=(3,3), stride=1, crop='same', nonlinearity=leaky_rectify));\n glblf = batch_norm(layers.Deconv2DLayer(glblf, 128, filter_size=(9,9), stride=5, crop=(2,2), nonlinearity=leaky_rectify));\n glblf = batch_norm(layers.Deconv2DLayer(glblf, 128, filter_size=(3,3), stride=1, crop='same', nonlinearity=leaky_rectify));\n glblf = batch_norm(layers.Deconv2DLayer(glblf, 128, filter_size=(3,3), stride=1, crop='same', nonlinearity=leaky_rectify));\n glblf = batch_norm(layers.Deconv2DLayer(glblf, 64, filter_size=(4,4), stride=2, crop=(1,1), nonlinearity=leaky_rectify));\n glblf = batch_norm(layers.Deconv2DLayer(glblf, 64, filter_size=(3,3), stride=1, crop='same', nonlinearity=leaky_rectify));\n glblf = batch_norm(layers.Deconv2DLayer(glblf, 64, filter_size=(3,3), stride=1, crop='same', nonlinearity=leaky_rectify));\n glblf = batch_norm(layers.Deconv2DLayer(glblf, 32, filter_size=(4,4), stride=2, crop=(1,1), nonlinearity=leaky_rectify));\n glblf = batch_norm(layers.Deconv2DLayer(glblf, 32, filter_size=(3,3), stride=1, crop='same', nonlinearity=leaky_rectify));\n glblf = batch_norm(layers.Deconv2DLayer(glblf, 32, filter_size=(3,3), stride=1, crop='same', nonlinearity=leaky_rectify));\n glblf = layers.Deconv2DLayer(glblf, 3, filter_size=(1,1), stride=1, crop='same', nonlinearity=identity);\n\n layer = layers.ElemwiseSumLayer([layer, glblf]);\n\n network = ReshapeLayer(layer, ([0], -1));\n\n mask_map.beta.set_value(np.float32(0.9*mask_map.beta.get_value()));\n old_params = layers.get_all_params(network, trainable=True);\n\n # Adding more layers\n aug_var = T.matrix('aug_var');\n target_var = T.imatrix('targets');\n add_a = batch_norm(layers.Conv2DLayer(enlyr, 320, filter_size=(1,1), nonlinearity=leaky_rectify));\n add_b = batch_norm(layers.Conv2DLayer(add_a, 320, filter_size=(1,1), nonlinearity=leaky_rectify));\n add_c = batch_norm(layers.Conv2DLayer(add_b, 320, filter_size=(1,1), nonlinearity=leaky_rectify));\n add_d = batch_norm(layers.Conv2DLayer(add_c, 320, filter_size=(1,1), nonlinearity=leaky_rectify));\n add_0 = layers.Pool2DLayer(add_d, pool_size=(25,25), stride=25, mode='average_inc_pad');\n add_1 = batch_norm(layers.DenseLayer(add_0, 100, nonlinearity=leaky_rectify));\n\n add_2 = batch_norm(layers.DenseLayer(gllyr, 320, nonlinearity=leaky_rectify));\n add_3 = batch_norm(layers.DenseLayer(add_2, 320, nonlinearity=leaky_rectify));\n add_4 = batch_norm(layers.DenseLayer(add_3, 100, nonlinearity=leaky_rectify));\n\n aug_layer = layers.InputLayer(shape=(None, aug_fea_n), input_var=aug_var);\n\n cat_layer = lasagne.layers.ConcatLayer([add_1, add_4, aug_layer], axis=1);\n\n hidden_layer = layers.DenseLayer(cat_layer, 80, nonlinearity=leaky_rectify);\n network = layers.DenseLayer(hidden_layer, classn, nonlinearity=sigmoid);\n\n all_params = layers.get_all_params(network, trainable=True);\n new_params = [x for x in all_params if x not in old_params];\n\n return network, new_params, input_var, aug_var, target_var;\n\ndef make_training_functions(network, new_params, input_var, aug_var, target_var):\n output = lasagne.layers.get_output(network, deterministic=True, batch_norm_use_averages=True, batch_norm_update_averages=False);\n loss = lasagne.objectives.binary_crossentropy(output, target_var).mean();\n\n deter_output = lasagne.layers.get_output(network, deterministic=True);\n deter_loss = lasagne.objectives.binary_crossentropy(deter_output, target_var).mean();\n\n params = layers.get_all_params(network, trainable=True);\n updates = lasagne.updates.nesterov_momentum(loss, params, learning_rate=LearningRate, momentum=0.985);\n new_params_updates = lasagne.updates.nesterov_momentum(loss, new_params, learning_rate=LearningRate, momentum=0.985);\n\n val_fn = theano.function([input_var, aug_var, target_var], [deter_loss, deter_output]);\n train_fn = theano.function([input_var, aug_var, target_var], loss, updates=updates);\n new_params_train_fn = theano.function([input_var, aug_var, target_var], loss, updates=new_params_updates);\n\n return train_fn, new_params_train_fn, val_fn;\n\n\ndef get_aug_feas(X):\n aug_feas = np.zeros((X.shape[0], aug_fea_n), dtype=np.float32);\n return aug_feas;\n\n\ndef split_validation(classn):\n network, new_params, input_var, aug_var, target_var = build_network_from_ae(classn);\n train_fn, new_params_train_fn, val_fn = make_training_functions(network, new_params, input_var, aug_var, target_var);\n layers.set_all_param_values(network, pickle.load(open(CNNModel, 'rb')));\n\n # Testing\n Or, inds, coor = val_fn_epoch_on_disk(classn, val_fn);\n Or_all = np.zeros(shape=(coor.shape[0],), dtype=np.float32);\n Or_all[inds] = Or[:, 0];\n\n fid = open(TileFolder + '/' + heat_map_out, 'w');\n for idx in range(0, Or_all.shape[0]):\n fid.write('{} {} {}\\n'.format(coor[idx][0], coor[idx][1], Or_all[idx]));\n fid.close();\n\n return;\n\n\ndef main():\n if not os.path.exists(TileFolder):\n exit(0);\n\n classes = ['Lymphocytes'];\n classn = len(classes);\n sys.setrecursionlimit(10000);\n\n split_validation(classn);\n print('DONE!');\n\n\nif __name__ == \"__main__\":\n main();\n\n\n"
] |
[
[
"numpy.int32",
"sklearn.metrics.roc_curve",
"numpy.copy",
"sklearn.metrics.auc",
"numpy.array",
"numpy.zeros",
"numpy.sum"
]
] |
ShiroNekoHouse/MyFate
|
[
"961c0e6e0dff0b3af0fe7186f1429b41ab8c3093"
] |
[
"functional_enc_msg_party_test.py"
] |
[
"#\n# Copyright 2019 The FATE 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\nimport time\n\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.metrics import precision_recall_fscore_support\n\nfrom arch.api.eggroll import init\nfrom federatedml.ftl.autoencoder import Autoencoder\nfrom federatedml.ftl.data_util.common_data_util import series_plot, split_data_combined\nfrom federatedml.ftl.data_util.uci_credit_card_util import load_UCI_Credit_Card_data\nfrom federatedml.ftl.encrypted_ftl import EncryptedFTLHostModel, EncryptedFTLGuestModel, \\\n LocalEncryptedFederatedTransferLearning\nfrom federatedml.ftl.test.mock_models import MockFTLModelParam\nfrom federatedml.secureprotol.encrypt import PaillierEncrypt\n\n\nif __name__ == '__main__':\n\n init()\n infile = \"../data/UCI_Credit_Card.csv\"\n X, y = load_UCI_Credit_Card_data(infile=infile, balanced=True)\n\n X = X[:500]\n y = y[:500]\n\n X_A, y_A, X_B, y_B, overlap_indexes = split_data_combined(X, y,\n overlap_ratio=0.1,\n ab_split_ratio=0.1,\n n_feature_b=23)\n\n valid_ratio = 0.3\n non_overlap_indexes = np.setdiff1d(range(X_B.shape[0]), overlap_indexes)\n validate_indexes = non_overlap_indexes[:int(valid_ratio * len(non_overlap_indexes))]\n test_indexes = non_overlap_indexes[int(valid_ratio*len(non_overlap_indexes)):]\n x_B_valid = X_B[validate_indexes]\n y_B_valid = y_B[validate_indexes]\n x_B_test = X_B[test_indexes]\n y_B_test = y_B[test_indexes]\n\n print(\"X_A shape\", X_A.shape)\n print(\"y_A shape\", y_A.shape)\n print(\"X_B shape\", X_B.shape)\n print(\"y_B shape\", y_B.shape)\n\n print(\"overlap_indexes len\", len(overlap_indexes))\n print(\"non_overlap_indexes len\", len(non_overlap_indexes))\n print(\"validate_indexes len\", len(validate_indexes))\n print(\"test_indexes len\", len(test_indexes))\n\n print(\"################################ Build Federated Models ############################\")\n\n tf.reset_default_graph()\n\n autoencoder_A = Autoencoder(1)\n autoencoder_B = Autoencoder(2)\n\n autoencoder_A.build(X_A.shape[-1], 32, learning_rate=0.01)\n autoencoder_B.build(X_B.shape[-1], 32, learning_rate=0.01)\n\n paillierEncrypt = PaillierEncrypt()\n paillierEncrypt.generate_key()\n publickey = paillierEncrypt.get_public_key()\n privatekey = paillierEncrypt.get_privacy_key()\n\n fake_model_param = MockFTLModelParam(alpha=100)\n partyA = EncryptedFTLGuestModel(autoencoder_A, fake_model_param, public_key=publickey)\n partyB = EncryptedFTLHostModel(autoencoder_B, fake_model_param, public_key=publickey)\n\n federatedLearning = LocalEncryptedFederatedTransferLearning(partyA, partyB, privatekey)\n\n print(\"################################ Train Federated Models ############################\")\n start_time = time.time()\n epochs = 10\n init = tf.global_variables_initializer()\n with tf.Session() as sess:\n autoencoder_A.set_session(sess)\n autoencoder_B.set_session(sess)\n\n sess.run(init)\n losses = []\n fscores = []\n aucs = []\n for ep in range(epochs):\n loss = federatedLearning.fit(X_A, X_B, y_A, overlap_indexes, non_overlap_indexes)\n losses.append(loss)\n\n if ep % 1 == 0:\n print(\"ep\", ep, \"loss\", loss)\n y_pred = federatedLearning.predict(x_B_test)\n y_pred_label = []\n pos_count = 0\n neg_count = 0\n for _y in y_pred:\n if _y <= 0.5:\n neg_count += 1\n y_pred_label.append(-1)\n else:\n pos_count += 1\n y_pred_label.append(1)\n y_pred_label = np.array(y_pred_label)\n print(\"neg:\", neg_count, \"pos:\", pos_count)\n precision, recall, fscore, _ = precision_recall_fscore_support(y_B_test, y_pred_label, average=\"weighted\")\n fscores.append(fscore)\n print(\"fscore:\", fscore)\n # auc = roc_auc_score(y_B_test, y_pred, average=\"weighted\")\n # aucs.append(auc)\n\n end_time = time.time()\n series_plot(losses, fscores, aucs)\n print(\"running time\", end_time - start_time)\n\n"
] |
[
[
"tensorflow.global_variables_initializer",
"sklearn.metrics.precision_recall_fscore_support",
"tensorflow.reset_default_graph",
"tensorflow.Session",
"numpy.array"
]
] |
apmoore1/allennlp
|
[
"bdb29a831ed68cb948b18b42fa61646b9ec11bf8"
] |
[
"allennlp/tests/modules/masked_layer_norm_test.py"
] |
[
"import numpy as np\nimport torch\n\nfrom allennlp.common.testing import AllenNlpTestCase\nfrom allennlp.modules.masked_layer_norm import MaskedLayerNorm\n\n\nclass TestMaskedLayerNorm(AllenNlpTestCase):\n def test_masked_layer_norm(self):\n x_n = np.random.rand(2, 3, 7)\n mask_n = np.array([[1, 1, 0], [1, 1, 1]])\n\n x = torch.from_numpy(x_n).float()\n mask = torch.from_numpy(mask_n).bool()\n\n layer_norm = MaskedLayerNorm(7, gamma0=0.2)\n normed_x = layer_norm(x, mask)\n\n N = 7 * 5\n mean = (x_n * np.expand_dims(mask_n, axis=-1)).sum() / N\n std = np.sqrt((((x_n - mean) * np.expand_dims(mask_n, axis=-1)) ** 2).sum() / N + 1e-6)\n expected = 0.2 * (x_n - mean) / (std + 1e-6)\n\n assert np.allclose(normed_x.data.numpy(), expected)\n"
] |
[
[
"torch.from_numpy",
"numpy.array",
"numpy.expand_dims",
"numpy.random.rand"
]
] |
ConnorChristie/MonoGRNet
|
[
"693a7534c0fd4d69e5705bdf23386932b96a87a4"
] |
[
"inputs/kitti_input.py"
] |
[
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport matplotlib\nmatplotlib.use('Agg')\nimport itertools\nimport json\nimport logging\nimport os\nimport sys\nimport random\nfrom random import shuffle\nimport pdb\nfrom PIL import Image, ImageEnhance\nimport numpy as np\n\nimport scipy as scp\nimport scipy.misc\nimport matplotlib.pyplot as plt\nfrom scipy.misc import imread, imresize\nfrom skimage.util import random_noise\nfrom skimage.filters import gaussian\nfrom skimage.exposure import rescale_intensity\n\n\nimport tensorflow as tf\n\nfrom utils.data_utils import (annotation_jitter, annotation_to_h5)\nfrom utils.annolist import AnnotationLib as AnnoLib\nfrom utils.rect import Rect\n\nimport threading\n\nfrom collections import namedtuple\nfake_anno = namedtuple('fake_anno_object', ['rects'])\n\ndef _noise(image):\n if np.random.uniform() < 0.5:\n return image\n scale = np.random.uniform(0, 32)\n noise = np.random.normal(-scale, scale, size=image.shape)\n image_new = np.clip(image.astype(np.float32) + \n noise, 0, 255).astype(np.uint8)\n return image_new\n\ndef _enhance(image):\n if np.random.uniform() < 0.5:\n return image\n image_obj = Image.fromarray(image)\n image_obj = ImageEnhance.Color(image_obj).enhance(np.random.uniform(0.5, 1.5))\n image_obj = ImageEnhance.Brightness(image_obj).enhance(np.random.uniform(0.7, 1.3))\n image_obj = ImageEnhance.Contrast(image_obj).enhance(np.random.uniform(0.7, 1.3))\n return np.array(image_obj)\n\ndef _projection(point, calib):\n point_r = np.reshape(point, (3, ))\n point_exp = np.reshape([point_r[0], point_r[1], point_r[2], 1], (4, 1))\n point_proj = np.dot(calib, point_exp)\n point_proj = point_proj[:2] / point_proj[2]\n return np.reshape(point_proj, (2, ))\n\ndef _vis(im_obj, anno, index):\n plt.figure(figsize=(12, 4))\n plt.imshow(np.clip(im_obj, 0, 255).astype(np.int32))\n\n for r in anno.rects:\n if r.classID == -1:\n continue\n plt.plot([r.x1, r.x2, r.x2, r.x1, r.x1], \n [r.y1, r.y1, r.y2, r.y2, r.y1])\n bottom_proj = _projection([r.x_3d, r.y_3d, r.z_3d], r.calib)\n plt.scatter(bottom_proj[0], bottom_proj[1])\n plt.savefig('/home/mcg/{}'.format(index))\n plt.close()\n return\n\ndef _jitter(im_obj, anno, jitter_pixel=24):\n im = np.array(im_obj)\n trans = np.random.normal(scale=jitter_pixel, size=(2, ))\n height_jitter, width_jitter = np.clip(trans,\n a_min = -jitter_pixel * 2,\n a_max = +jitter_pixel * 2).astype(np.int32)\n image_jitter = np.zeros(shape=np.shape(im), dtype=np.uint8)\n image_means = im.mean(axis=(0, 1), keepdims=True).astype(np.uint8)\n image_jitter += image_means\n height, width, channels = np.shape(im)\n left_new = max(0, width_jitter)\n left_ori = max(0, -width_jitter)\n right_new = min(width + width_jitter, width)\n right_ori = min(width - width_jitter, width)\n top_new = max(0, height_jitter)\n top_ori = max(0, -height_jitter)\n bottom_new = min(height + height_jitter, height)\n bottom_ori = min(height - height_jitter, height)\n image_jitter[top_new:bottom_new, left_new:right_new] = im[top_ori:bottom_ori, left_ori:right_ori]\n new_rects = []\n\n for r in anno.rects:\n focal_length = r.calib.reshape(3, 4)[0, 0]\n r.x_3d += r.z_3d * width_jitter / focal_length\n r.y_3d += r.z_3d * height_jitter / focal_length\n r.x1 = max(r.x1 + width_jitter, 0)\n r.x2 = min(r.x2 + width_jitter, width)\n r.y1 = max(r.y1 + height_jitter, 0)\n r.y2 = min(r.y2 + height_jitter, height)\n if r.x1 < r.x2 and r.y1 < r.y2:\n new_rects.append(r)\n anno.rects = new_rects\n return image_jitter, anno\n\ndef _flip(im_obj, anno):\n if np.random.uniform() < 0.5:\n return im_obj, anno\n im_obj = np.fliplr(im_obj)\n height, width, channels = np.shape(im_obj)\n for r in anno.rects:\n calib = r.calib.reshape((3, 4))\n focal_length = calib[0, 0]\n ppoint_x = calib[0, 2]\n trans_x = calib[0, 3]\n delta_x = (r.z_3d*(width-1-2*ppoint_x) - 2*trans_x)/focal_length - 2*r.x_3d\n r.x_3d += delta_x\n r.x1, r.x2 = (width-1-r.x2, width-1-r.x1)\n r.alpha = np.pi - r.alpha if r.alpha > 0 else -np.pi - r.alpha \n return im_obj, anno\n\ndef read_kitti_anno(label_file, calib_file, detect_truck):\n \"\"\" Reads a kitti annotation file.\n\n Args:\n label_file: Path to file\n\n Returns:\n Lists of rectangels: Cars and don't care area.\n \"\"\"\n labels = [line.rstrip().split(' ') for line in open(label_file)]\n\n label_file_split = label_file.rstrip().split('/')\n index = label_file_split[-1].split('.')[0]\n #import pdb \n #pdb.set_trace()\n calibs = [line.rstrip().split(' ') for line in open(calib_file)]\n assert calibs[2][0] == 'P2:'\n calib = np.reshape(calibs[2][1:], (3, 4)).astype(np.float32)\n calib_pinv = np.linalg.pinv(calib)\n rect_list = []\n for label in labels:\n if not (label[0] == 'Car' or label[0] == 'Van' or\n label[0] == 'Truck' or label[0] == 'DontCare'):\n continue\n notruck = not detect_truck\n if notruck and label[0] == 'Truck':\n continue\n if label[0] == 'DontCare':\n class_id = -1\n else:\n class_id = 1\n object_rect = AnnoLib.AnnoRect(\n x1=float(label[4]), y1=float(label[5]),\n x2=float(label[6]), y2=float(label[7]),\n height=float(label[8]), width=float(label[9]),\n length=float(label[10]), x=float(label[11]), \n y=float(label[12]), z=float(label[13]), \n alpha=float(label[14]), calib=calib, \n calib_pinv=calib_pinv)\n assert object_rect.x1 < object_rect.x2\n assert object_rect.y1 < object_rect.y2\n object_rect.classID = class_id\n\n view_angle = np.arctan2(object_rect.z_3d, object_rect.x_3d)\n object_rect.alpha += view_angle - np.pi * 0.5\n\n rect_list.append(object_rect)\n return rect_list\n\n\ndef _rescale_boxes(current_shape, anno, target_height, target_width):\n x_scale = target_width / float(current_shape[1])\n y_scale = target_height / float(current_shape[0])\n z_3d_scale = ((x_scale**2 + y_scale**2)*0.5)**0.5\n for r in anno.rects:\n assert r.x1 < r.x2\n r.x1 *= x_scale\n r.x2 *= x_scale\n assert r.x1 < r.x2\n r.y1 *= y_scale\n r.y2 *= y_scale\n r.xy_scale = np.array([x_scale, y_scale], dtype=np.float32)\n return anno\n\n\ndef _generate_mask(hypes, ignore_rects):\n\n width = hypes[\"image_width\"]\n height = hypes[\"image_height\"]\n grid_width = hypes[\"grid_width\"]\n grid_height = hypes[\"grid_height\"]\n\n mask = np.ones([grid_height, grid_width])\n\n if not hypes['use_mask']:\n return mask\n\n for rect in ignore_rects:\n left = int((rect.x1+2)/width*grid_width)\n right = int((rect.x2-2)/width*grid_width)\n top = int((rect.y1+2)/height*grid_height)\n bottom = int((rect.y2-2)/height*grid_height)\n for x in range(left, right+1):\n for y in range(top, bottom+1):\n mask[y, x] = 0\n\n return mask\n\n\ndef _load_kitti_txt(kitti_txt, hypes, jitter=False, random_shuffel=True):\n \"\"\"Take the txt file and net configuration and create a generator\n that outputs a jittered version of a random image from the annolist\n that is mean corrected.\"\"\"\n\n base_path = os.path.realpath(os.path.dirname(kitti_txt))\n files = [line.rstrip() for line in open(kitti_txt)]\n if hypes['data']['truncate_data']:\n files = files[:10]\n random.seed(0)\n for epoch in itertools.count():\n if random_shuffel:\n random.shuffle(files)\n for file in files:\n image_file, gt_image_file = file.split(\" \")\n image_file_split = image_file.split('/')\n index = image_file_split[-1].split('.')[0]\n calib_file = os.path.join(base_path, image_file_split[0], 'calib', index + '.txt')\n assert os.path.exists(calib_file), \\\n \"File does not exist: %s\" % calib_file\n \n image_file = os.path.join(base_path, image_file)\n assert os.path.exists(image_file), \\\n \"File does not exist: %s\" % image_file\n gt_image_file = os.path.join(base_path, gt_image_file)\n assert os.path.exists(gt_image_file), \\\n \"File does not exist: %s\" % gt_image_file\n\n rect_list = read_kitti_anno(gt_image_file, calib_file, \n detect_truck=hypes['detect_truck'])\n\n anno = AnnoLib.Annotation()\n anno.rects = rect_list\n\n im = scp.misc.imread(image_file)\n if im.shape[2] == 4:\n im = im[:, :, :3]\n \n if jitter: \n im, anno = _flip(im, anno)\n im, anno = _jitter(im, anno)\n im = _noise(_enhance(im))\n # _vis(im, anno, index)\n \n anno = _rescale_boxes(im.shape, anno,\n hypes[\"image_height\"],\n hypes[\"image_width\"])\n im = imresize(\n im, (hypes[\"image_height\"], hypes[\"image_width\"]),\n interp='cubic')\n\n \n pos_list = [rect for rect in anno.rects if rect.classID == 1]\n pos_anno = fake_anno(pos_list)\n # boxes: [1, grid_height*grid_width, 11, max_len, 1]\n # for each cell, this array contains the ground truth boxes around it (within focus area, defined by center distance)\n # confs: [1, grid_height*grid_width, 1, max_len, 1]\n # record the valid boxes, since max_len is greater than the number of ground truth boxes\n boxes, confs, calib, calib_pinv, xy_scale = annotation_to_h5(hypes,\n pos_anno,\n hypes[\"grid_width\"],\n hypes[\"grid_height\"],\n hypes[\"rnn_len\"])\n # masks are zero in \"Don't care\" area \n mask_list = [rect for rect in anno.rects if rect.classID == -1]\n mask = _generate_mask(hypes, mask_list)\n\n boxes = boxes.reshape([hypes[\"grid_height\"],\n hypes[\"grid_width\"], 11])\n confs = confs.reshape(hypes[\"grid_height\"], hypes[\"grid_width\"])\n calib = calib.reshape(hypes[\"grid_height\"], \n hypes[\"grid_width\"], 3, 4)\n xy_scale = xy_scale.reshape(hypes[\"grid_height\"], \n hypes[\"grid_width\"], 2)\n calib_pinv = calib_pinv.reshape(hypes['grid_height'], \n hypes['grid_width'], 4, 3)\n yield {\"image\": im, \"boxes\": boxes, \"confs\": confs, \"calib\": calib, \"calib_pinv\": calib_pinv, \n \"xy_scale\": xy_scale, \"rects\": pos_list, \"mask\": mask}\n\n\ndef _make_sparse(n, d):\n v = np.zeros((d,), dtype=np.float32)\n v[n] = 1.\n return v\n\n\ndef create_queues(hypes, phase):\n \"\"\"Create Queues.\"\"\"\n hypes[\"rnn_len\"] = 1\n dtypes = [tf.float32, tf.float32, tf.float32, tf.float32, tf.float32, tf.float32, tf.float32]\n grid_size = hypes['grid_width'] * hypes['grid_height']\n shapes = ([hypes['image_height'], hypes['image_width'], 3],\n [hypes['grid_height'], hypes['grid_width']],\n [hypes['grid_height'], hypes['grid_width'], 11],\n [hypes['grid_height'], hypes['grid_width']], \n [hypes['grid_height'], hypes['grid_width'], 3, 4], \n [hypes['grid_height'], hypes['grid_width'], 4, 3], \n [hypes['grid_height'], hypes['grid_width'], 2])\n capacity = 30\n q = tf.FIFOQueue(capacity=capacity, dtypes=dtypes, shapes=shapes)\n return q\n\n\ndef _processe_image(hypes, image):\n # Because these operations are not commutative, consider randomizing\n # randomize the order their operation.\n augment_level = hypes['augment_level']\n if augment_level > 0:\n image = tf.image.random_brightness(image, max_delta=30)\n image = tf.image.random_contrast(image, lower=0.75, upper=1.25)\n if augment_level > 1:\n image = tf.image.random_saturation(image, lower=0.5, upper=1.6)\n image = tf.image.random_hue(image, max_delta=0.15)\n\n image = tf.minimum(image, 255.0)\n image = tf.maximum(image, 0)\n\n return image\n\n\ndef start_enqueuing_threads(hypes, q, phase, sess):\n \"\"\"Start enqueuing threads.\"\"\"\n\n # Creating Placeholder for the Queue\n x_in = tf.placeholder(tf.float32)\n confs_in = tf.placeholder(tf.float32)\n boxes_in = tf.placeholder(tf.float32)\n mask_in = tf.placeholder(tf.float32)\n\n calib_in = tf.placeholder(tf.float32)\n calib_pinv_in = tf.placeholder(tf.float32)\n xy_scale_in = tf.placeholder(tf.float32)\n\n # Creating Enqueue OP\n enqueue_op = q.enqueue((x_in, confs_in, boxes_in, mask_in, calib_in, calib_pinv_in, xy_scale_in))\n\n def make_feed(data):\n return {x_in: data['image'],\n confs_in: data['confs'],\n boxes_in: data['boxes'],\n mask_in: data['mask'], \n calib_in: data['calib'], \n calib_pinv_in: data['calib_pinv'], \n xy_scale_in: data['xy_scale']}\n\n def thread_loop(sess, enqueue_op, gen):\n for d in gen:\n sess.run(enqueue_op, feed_dict=make_feed(d))\n\n data_file = hypes[\"data\"]['%s_file' % phase]\n data_dir = hypes['dirs']['data_dir']\n data_file = os.path.join(data_dir, data_file)\n\n gen = _load_kitti_txt(data_file, hypes,\n jitter={'train': hypes['solver']['use_jitter'],\n 'val': False}[phase])\n\n data = next(gen)\n sess.run(enqueue_op, feed_dict=make_feed(data))\n t = threading.Thread(target=thread_loop,\n args=(sess, enqueue_op, gen))\n t.daemon = True\n t.start()\n\n\ndef inputs(hypes, q, phase):\n\n if phase == 'val':\n image, confidences, boxes, mask, calib, calib_pinv, xy_scale = q.dequeue()\n image = tf.expand_dims(image, 0)\n confidences = tf.expand_dims(confidences, 0)\n boxes = tf.expand_dims(boxes, 0)\n mask = tf.expand_dims(mask, 0)\n calib = tf.expand_dims(calib, 0)\n calib_pinv = tf.expand_dims(calib_pinv, 0)\n xy_scale = tf.expand_dims(xy_scale, 0)\n return image, (confidences, boxes, mask, calib, calib_pinv, xy_scale)\n elif phase == 'train':\n image, confidences, boxes, mask, calib, calib_pinv, xy_scale = q.dequeue_many(hypes['batch_size'])\n image = _processe_image(hypes, image)\n return image, (confidences, boxes, mask, calib, calib_pinv, xy_scale)\n else:\n assert(\"Bad phase: {}\".format(phase))\n"
] |
[
[
"numpy.dot",
"tensorflow.image.random_contrast",
"tensorflow.minimum",
"tensorflow.image.random_saturation",
"matplotlib.pyplot.plot",
"numpy.arctan2",
"tensorflow.image.random_hue",
"numpy.clip",
"numpy.reshape",
"numpy.fliplr",
"matplotlib.pyplot.close",
"numpy.zeros",
"matplotlib.pyplot.figure",
"tensorflow.image.random_brightness",
"tensorflow.FIFOQueue",
"tensorflow.placeholder",
"numpy.array",
"scipy.misc.imresize",
"matplotlib.pyplot.scatter",
"matplotlib.use",
"tensorflow.maximum",
"tensorflow.expand_dims",
"numpy.ones",
"numpy.linalg.pinv",
"numpy.random.normal",
"numpy.shape",
"scipy.misc.imread",
"numpy.random.uniform"
]
] |
guillaumekln/OpenNMT-tf
|
[
"ca96cb35efd083d0380c05041bc254f81ee383e0"
] |
[
"opennmt/models/model.py"
] |
[
"\"\"\"Base class for models.\"\"\"\n\nfrom __future__ import print_function\n\nimport time\nimport abc\nimport six\n\nimport tensorflow as tf\n\nfrom opennmt.utils import decay\nfrom opennmt.utils.misc import add_dict_to_collection, item_or_tuple\n\n\ndef learning_rate_decay_fn(decay_type,\n decay_rate,\n decay_steps,\n staircase=True,\n start_decay_steps=0,\n minimum_learning_rate=0):\n \"\"\"Returns the learning rate decay functions.\n\n Args:\n decay_type: The type of decay. A function from ``tf.train`` or\n :mod:`opennmt.utils.decay` as a string.\n decay_rate: The decay rate to apply.\n decay_steps: The decay steps as described in the decay type function.\n staircase: If ``True``, learning rate is decayed in a staircase fashion.\n start_decay_steps: Start decay after this many steps.\n minimum_learning_rate: Do not decay past this learning rate value.\n\n Returns:\n A function with signature\n ``(learning_rate, global_step) -> decayed_learning_rate``.\n\n Raises:\n ValueError: if :obj:`decay_type` can not be resolved.\n \"\"\"\n def _decay_fn(learning_rate, global_step):\n decay_op_name = None\n\n if decay_op_name is None:\n decay_op_name = getattr(tf.train, decay_type, None)\n if decay_op_name is None:\n decay_op_name = getattr(decay, decay_type, None)\n if decay_op_name is None:\n raise ValueError(\"Unknown decay function: {}\".format(decay_type))\n\n decayed_learning_rate = decay_op_name(\n learning_rate,\n tf.maximum(global_step - start_decay_steps, 0),\n decay_steps,\n decay_rate,\n staircase=staircase)\n decayed_learning_rate = tf.maximum(decayed_learning_rate, minimum_learning_rate)\n\n return decayed_learning_rate\n\n return _decay_fn\n\ndef get_optimizer_class(classname):\n \"\"\"Returns the optimizer class.\n\n Args:\n classname: The name of the optimizer class in ``tf.train`` or\n ``tf.contrib.opt`` as a string.\n\n Returns:\n A class inheriting from ``tf.train.Optimizer``.\n\n Raises:\n ValueError: if :obj:`classname` can not be resolved.\n \"\"\"\n optimizer_class = None\n\n if optimizer_class is None:\n optimizer_class = getattr(tf.train, classname, None)\n if optimizer_class is None:\n optimizer_class = getattr(tf.contrib.opt, classname, None)\n if optimizer_class is None:\n raise ValueError(\"Unknown optimizer class: {}\".format(classname))\n\n return optimizer_class\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass Model(object):\n \"\"\"Base class for models.\"\"\"\n\n def __init__(self, name):\n self.name = name\n\n def __call__(self, features, labels, params, mode, config):\n \"\"\"Creates the model.\n\n See Also:\n ``tf.estimator.Estimator`` 's ``model_fn`` argument for more details about\n arguments and the returned value.\n \"\"\"\n if mode == tf.estimator.ModeKeys.TRAIN:\n self._register_word_counters(features, labels)\n\n with tf.variable_scope(self.name):\n outputs, predictions = self._build(features, labels, params, mode, config)\n\n if predictions is not None:\n # Register predictions in a collection so that hooks can easily fetch them.\n add_dict_to_collection(\"predictions\", predictions)\n\n if mode != tf.estimator.ModeKeys.PREDICT:\n loss = self._compute_loss(features, labels, outputs, mode)\n train_op = self._build_train_op(loss, params)\n\n if mode == tf.estimator.ModeKeys.EVAL:\n eval_metric_ops = self._compute_metrics(features, labels, predictions)\n else:\n eval_metric_ops = None\n\n return tf.estimator.EstimatorSpec(\n mode,\n loss=loss,\n train_op=train_op,\n eval_metric_ops=eval_metric_ops)\n else:\n export_outputs = {}\n export_outputs[tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = \\\n tf.estimator.export.PredictOutput(predictions)\n\n return tf.estimator.EstimatorSpec(\n mode,\n predictions=predictions,\n export_outputs=export_outputs)\n\n @abc.abstractmethod\n def _build(self, features, labels, params, mode, config):\n \"\"\"Creates the graph.\n\n Returns:\n outputs: The model outputs (usually unscaled probabilities).\n Optional if :obj:`mode` is ``tf.estimator.ModeKeys.PREDICT``.\n predictions: The model predictions.\n Optional if :obj:`mode` is ``tf.estimator.ModeKeys.TRAIN``.\n \"\"\"\n raise NotImplementedError()\n\n @abc.abstractmethod\n def _compute_loss(self, features, labels, outputs, mode):\n \"\"\"Computes the loss.\n\n Args:\n features: The dict of features ``tf.Tensor``.\n labels: The dict of labels ``tf.Tensor``.\n output: The model outputs (usually unscaled probabilities).\n mode: A ``tf.estimator.ModeKeys`` mode.\n\n Returns:\n The loss.\n \"\"\"\n raise NotImplementedError()\n\n def _compute_metrics(self, features, labels, predictions): # pylint: disable=unused-argument\n \"\"\"Computes additional metrics on the predictions.\n\n Args:\n features: The dict of features ``tf.Tensor``.\n labels: The dict of labels ``tf.Tensor``.\n predictions: The model predictions.\n\n Returns:\n A dict of metric results (tuple ``(metric_tensor, update_op)``) keyed by\n name.\n \"\"\"\n return None\n\n def _build_train_op(self, loss, params):\n \"\"\"Builds the training op given parameters.\"\"\"\n global_step = tf.train.get_or_create_global_step()\n decay_type = params.get(\"decay_type\")\n\n if decay_type is not None:\n decay_fn = learning_rate_decay_fn(\n decay_type,\n params[\"decay_rate\"],\n params[\"decay_steps\"],\n staircase=params.get(\"staircase\", True),\n start_decay_steps=params.get(\"start_decay_steps\", 0),\n minimum_learning_rate=params.get(\"minimum_learning_rate\", 0))\n else:\n decay_fn = None\n\n train_op = tf.contrib.layers.optimize_loss(\n loss,\n global_step,\n params[\"learning_rate\"],\n get_optimizer_class(params[\"optimizer\"]),\n clip_gradients=params.get(\"clip_gradients\"),\n learning_rate_decay_fn=decay_fn,\n summaries=[\n \"learning_rate\",\n \"loss\",\n \"global_gradient_norm\",\n ])\n\n return train_op\n\n def _register_word_counters(self, features, labels):\n \"\"\"Stores word counter operators for sequences (if any) of :obj:`features`\n and :obj:`labels`.\n\n See Also:\n :meth:`opennmt.utils.misc.WordCounterHook` that fetches these counters\n to log their value in TensorBoard.\n \"\"\"\n def _add_counter(word_count, name):\n word_count = tf.cast(word_count, tf.int64)\n total_word_count_init = tf.Variable(\n initial_value=0,\n name=name + \"_init\",\n trainable=False,\n dtype=tf.int64)\n total_word_count = tf.assign_add(\n total_word_count_init,\n word_count,\n name=name)\n tf.add_to_collection(\"counters\", total_word_count)\n\n features_length = self._get_features_length(features)\n labels_length = self._get_labels_length(labels)\n\n with tf.variable_scope(\"words_per_sec\"):\n if features_length is not None:\n _add_counter(tf.reduce_sum(features_length), \"features\")\n if labels_length is not None:\n _add_counter(tf.reduce_sum(labels_length), \"labels\")\n\n def _filter_example(self,\n features,\n labels,\n maximum_features_length=None,\n maximum_labels_length=None):\n \"\"\"Defines an example filtering condition.\n\n Args:\n features: The features ``tf.Tensor``.\n labels: The labels ``tf.Tensor``.\n maximum_features_length: The maximum length or list of maximum lengths of\n the features sequence(s). ``None`` to not constrain the length.\n maximum_labels_length: The maximum length of the labels sequence.\n ``None`` to not constrain the length.\n\n Returns:\n A ``tf.Tensor`` of type ``tf.bool`` with a logical value of ``False``\n if the example does not meet the requirements.\n \"\"\"\n cond = []\n\n def _constrain_length(length, maximum_length):\n # Work with lists of lengths which correspond to the general multi source case.\n if not isinstance(length, list):\n length = [length]\n if not isinstance(maximum_length, list):\n maximum_length = [maximum_length]\n\n # Unset maximum lengths are set to None (i.e. no constraint).\n maximum_length += [None] * (len(length) - len(maximum_length))\n\n for l, maxlen in zip(length, maximum_length):\n cond.append(tf.greater(l, 0))\n if maxlen is not None:\n cond.append(tf.less_equal(l, maxlen))\n\n features_length = self._get_features_length(features)\n labels_length = self._get_labels_length(labels)\n\n if features_length is not None:\n _constrain_length(features_length, maximum_features_length)\n if labels_length is not None:\n _constrain_length(labels_length, maximum_labels_length)\n\n return tf.reduce_all(cond)\n\n def _initialize(self, metadata):\n \"\"\"Runs model specific initialization (e.g. vocabularies loading).\n\n Args:\n metadata: A dictionary containing additional metadata set\n by the user.\n \"\"\"\n pass\n\n @abc.abstractmethod\n def _get_serving_input_receiver(self):\n \"\"\"Returns an input receiver for serving this model.\n\n Returns:\n A ``tf.estimator.export.ServingInputReceiver``.\n \"\"\"\n raise NotImplementedError()\n\n def _get_features_length(self, features): # pylint: disable=unused-argument\n \"\"\"Returns the features length.\n\n Args:\n features: A dict of ``tf.Tensor``.\n\n Returns:\n The length as a ``tf.Tensor`` or list of ``tf.Tensor``, or ``None`` if\n length is undefined.\n \"\"\"\n return None\n\n def _get_labels_length(self, labels): # pylint: disable=unused-argument\n \"\"\"Returns the labels length.\n\n Args:\n labels: A dict of ``tf.Tensor``.\n\n Returns:\n The length as a ``tf.Tensor`` or ``None`` if length is undefined.\n \"\"\"\n return None\n\n @abc.abstractmethod\n def _get_features_builder(self, features_file):\n \"\"\"Returns the recipe to build features.\n\n Args:\n features_file: The file of features.\n\n Returns:\n A tuple ``(tf.data.Dataset, process_fn, padded_shapes_fn)``.\n \"\"\"\n raise NotImplementedError()\n\n @abc.abstractmethod\n def _get_labels_builder(self, labels_file):\n \"\"\"Returns the recipe to build labels.\n\n Args:\n labels_file: The file of labels.\n\n Returns:\n A tuple ``(tf.data.Dataset, process_fn, padded_shapes_fn)``.\n \"\"\"\n raise NotImplementedError()\n\n def _input_fn_impl(self,\n mode,\n batch_size,\n buffer_size,\n num_parallel_process_calls,\n metadata,\n features_file,\n labels_file=None,\n num_buckets=None,\n maximum_features_length=None,\n maximum_labels_length=None):\n \"\"\"See ``input_fn``.\"\"\"\n self._initialize(metadata)\n\n feat_dataset, feat_process_fn, feat_padded_shapes_fn = self._get_features_builder(features_file)\n\n if labels_file is None:\n dataset = feat_dataset\n # Parallel inputs must be catched in a single tuple and not considered as multiple arguments.\n process_fn = lambda *arg: feat_process_fn(item_or_tuple(arg))\n padded_shapes_fn = feat_padded_shapes_fn\n else:\n labels_dataset, labels_process_fn, labels_padded_shapes_fn = (\n self._get_labels_builder(labels_file))\n\n dataset = tf.data.Dataset.zip((feat_dataset, labels_dataset))\n process_fn = lambda features, labels: (\n feat_process_fn(features), labels_process_fn(labels))\n padded_shapes_fn = lambda: (\n feat_padded_shapes_fn(), labels_padded_shapes_fn())\n\n dataset = dataset.map(\n process_fn,\n num_parallel_calls=num_parallel_process_calls).prefetch(buffer_size)\n padded_shapes = padded_shapes_fn()\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n dataset = dataset.filter(lambda features, labels: self._filter_example(\n features,\n labels,\n maximum_features_length=maximum_features_length,\n maximum_labels_length=maximum_labels_length))\n dataset = dataset.shuffle(buffer_size, seed=int(time.time()))\n dataset = dataset.repeat()\n\n if mode == tf.estimator.ModeKeys.PREDICT or num_buckets is None or num_buckets <= 1:\n dataset = dataset.padded_batch(\n batch_size,\n padded_shapes=padded_shapes)\n else:\n # For training and evaluation, use bucketing.\n def _key_func(features, labels):\n length = None\n\n if length is None:\n length = self._get_features_length(features)\n maximum_length = maximum_features_length\n # For multi inputs, apply bucketing on the target side or none at all.\n if isinstance(length, list):\n length = None\n maximum_length = None\n if length is None:\n length = self._get_labels_length(labels)\n maximum_length = maximum_labels_length\n if length is None:\n return tf.constant(0, dtype=tf.int64)\n\n if maximum_length is not None:\n bucket_width = (maximum_length + num_buckets - 1) // num_buckets\n else:\n bucket_width = 10\n\n bucket_id = length // bucket_width\n bucket_id = tf.minimum(bucket_id, num_buckets)\n return tf.to_int64(bucket_id)\n\n def _reduce_func(unused_key, dataset):\n return dataset.padded_batch(\n batch_size,\n padded_shapes=padded_shapes)\n\n dataset = dataset.apply(tf.contrib.data.group_by_window(\n _key_func,\n _reduce_func,\n window_size=batch_size))\n\n iterator = dataset.make_initializable_iterator()\n\n # Add the initializer to a standard collection for it to be initialized.\n tf.add_to_collection(tf.GraphKeys.TABLE_INITIALIZERS, iterator.initializer)\n\n return iterator.get_next()\n\n def input_fn(self,\n mode,\n batch_size,\n buffer_size,\n num_parallel_process_calls,\n metadata,\n features_file,\n labels_file=None,\n num_buckets=None,\n maximum_features_length=None,\n maximum_labels_length=None):\n \"\"\"Returns an input function.\n\n Args:\n mode: A ``tf.estimator.ModeKeys`` mode.\n batch_size: The batch size to use.\n buffer_size: The prefetch buffer size (used e.g. for shuffling).\n num_parallel_process_calls: The number of elements processed in parallel.\n metadata: A dictionary containing additional metadata set\n by the user.\n features_file: The file containing input features.\n labels_file: The file containing output labels.\n num_buckets: The number of buckets to store examples of similar sizes.\n maximum_features_length: The maximum length or list of maximum lengths of\n the features sequence(s). ``None`` to not constrain the length.\n maximum_labels_length: The maximum length of the labels sequence.\n ``None`` to not constrain the length.\n\n Returns:\n A callable that returns the next element.\n\n Raises:\n ValueError: if :obj:`labels_file` is not set when in training or\n evaluation mode.\n\n See Also:\n ``tf.estimator.Estimator``.\n \"\"\"\n if mode != tf.estimator.ModeKeys.PREDICT and labels_file is None:\n raise ValueError(\"Labels file is required for training and evaluation\")\n\n return lambda: self._input_fn_impl(\n mode,\n batch_size,\n buffer_size,\n num_parallel_process_calls,\n metadata,\n features_file,\n labels_file=labels_file,\n num_buckets=num_buckets,\n maximum_features_length=maximum_features_length,\n maximum_labels_length=maximum_labels_length)\n\n def _serving_input_fn_impl(self, metadata):\n \"\"\"See ``serving_input_fn``.\"\"\"\n self._initialize(metadata)\n return self._get_serving_input_receiver()\n\n def serving_input_fn(self, metadata):\n \"\"\"Returns the serving input function.\n\n Args:\n metadata: A dictionary containing additional metadata set\n by the user.\n\n Returns:\n A callable that returns a ``tf.estimator.export.ServingInputReceiver``.\n \"\"\"\n return lambda: self._serving_input_fn_impl(metadata)\n\n def print_prediction(self, prediction, params=None, stream=None):\n \"\"\"Prints the model prediction.\n\n Args:\n prediction: The evaluated prediction.\n params: (optional) Dictionary of formatting parameters.\n stream: (optional) The stream to print to.\n \"\"\"\n _ = params\n print(prediction, file=stream)\n"
] |
[
[
"tensorflow.to_int64",
"tensorflow.constant",
"tensorflow.assign_add",
"tensorflow.Variable",
"tensorflow.greater",
"tensorflow.estimator.export.PredictOutput",
"tensorflow.maximum",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.reduce_all",
"tensorflow.minimum",
"tensorflow.train.get_or_create_global_step",
"tensorflow.less_equal",
"tensorflow.data.Dataset.zip",
"tensorflow.estimator.EstimatorSpec",
"tensorflow.variable_scope",
"tensorflow.add_to_collection",
"tensorflow.contrib.data.group_by_window"
]
] |
koeller21/ma_code
|
[
"3b31fb7af74cc62e495a6a0ad77d52aa9d7d5b1d"
] |
[
"gym_torcs.py"
] |
[
"\n\nimport gym\nfrom gym import spaces\nimport numpy as np\n\nimport snakeoil3_gym as snakeoil3\nimport numpy as np\nimport copy\nimport collections as col\nimport os\nimport time\n\n\nclass TorcsEnv:\n terminal_judge_start = 560 # If after 100 timestep still no progress, terminated\n termination_limit_progress = 5 # [km/h], episode terminates if car is running slower than this limit\n default_speed = 50\n\n initial_reset = True\n\n def __init__(self, vision=False, throttle=False, gear_change=False):\n self.vision = vision\n self.throttle = throttle\n self.gear_change = gear_change\n\n self.initial_run = True\n\n ##print(\"launch torcs\")\n os.system('pkill torcs')\n time.sleep(0.5)\n if self.vision is True:\n os.system('torcs -nofuel -nodamage -nolaptime -vision &')\n else:\n os.system('torcs -nofuel -nolaptime &')\n time.sleep(0.5)\n os.system('sh autostart.sh')\n time.sleep(0.5)\n\n \"\"\"\n # Modify here if you use multiple tracks in the environment\n self.client = snakeoil3.Client(p=3101, vision=self.vision) # Open new UDP in vtorcs\n self.client.MAX_STEPS = np.inf\n\n client = self.client\n client.get_servers_input() # Get the initial input from torcs\n\n obs = client.S.d # Get the current full-observation from torcs\n \"\"\"\n if throttle is False:\n self.action_space = spaces.Box(low=-1.0, high=1.0, shape=(1,))\n else:\n self.action_space = spaces.Box(low=-1.0, high=1.0, shape=(3,))\n\n if vision is False:\n high = np.array([1., np.inf, np.inf, np.inf, 1., np.inf, 1., np.inf])\n low = np.array([0., -np.inf, -np.inf, -np.inf, 0., -np.inf, 0., -np.inf])\n self.observation_space = spaces.Box(low=low, high=high)\n else:\n high = np.array([1., np.inf, np.inf, np.inf, 1., np.inf, 1., np.inf, 255])\n low = np.array([0., -np.inf, -np.inf, -np.inf, 0., -np.inf, 0., -np.inf, 0])\n self.observation_space = spaces.Box(low=low, high=high)\n\n def step(self, u):\n #print(\"Step\")\n # convert thisAction to the actual torcs actionstr\n client = self.client\n\n this_action = self.agent_to_torcs(u)\n\n # Apply Action\n action_torcs = client.R.d\n\n # Steering\n action_torcs['steer'] = this_action['steer'] # in [-1, 1]\n\n # Simple Autnmatic Throttle Control by Snakeoil\n if self.throttle is False:\n target_speed = self.default_speed\n if client.S.d['speedX'] < target_speed - (client.R.d['steer']*50):\n client.R.d['accel'] += .01\n else:\n client.R.d['accel'] -= .01\n\n if client.R.d['accel'] > 0.2:\n client.R.d['accel'] = 0.2\n\n if client.S.d['speedX'] < 10:\n client.R.d['accel'] += 1/(client.S.d['speedX']+.1)\n\n # Traction Control System\n if ((client.S.d['wheelSpinVel'][2]+client.S.d['wheelSpinVel'][3]) -\n (client.S.d['wheelSpinVel'][0]+client.S.d['wheelSpinVel'][1]) > 5):\n action_torcs['accel'] -= .2\n else:\n action_torcs['accel'] = this_action['accel']\n action_torcs['brake'] = this_action['brake']\n\n # Automatic Gear Change by Snakeoil\n if self.gear_change is True:\n action_torcs['gear'] = this_action['gear']\n else:\n # Automatic Gear Change by Snakeoil is possible\n action_torcs['gear'] = 1\n if self.throttle:\n if client.S.d['speedX'] > 50:\n action_torcs['gear'] = 2\n if client.S.d['speedX'] > 80:\n action_torcs['gear'] = 3\n if client.S.d['speedX'] > 110:\n action_torcs['gear'] = 4\n if client.S.d['speedX'] > 140:\n action_torcs['gear'] = 5\n if client.S.d['speedX'] > 170:\n action_torcs['gear'] = 6\n # Save the privious full-obs from torcs for the reward calculation\n obs_pre = copy.deepcopy(client.S.d)\n\n # One-Step Dynamics Update #################################\n # Apply the Agent's action into torcs\n client.respond_to_server()\n # Get the response of TORCS\n client.get_servers_input()\n\n # Get the current full-observation from torcs\n obs = client.S.d\n\n # Make an obsevation from a raw observation vector from TORCS\n self.observation = self.make_observaton(obs)\n\n\n # Reward setting Here #######################################\n # direction-dependent positive reward\n track = np.array(obs['track'])\n trackPos = np.array(obs['trackPos'])\n sp = np.array(obs['speedX'])\n damage = np.array(obs['damage'])\n rpm = np.array(obs['rpm'])\n oppmin = np.min(np.array(obs['opponents']))\n if oppmin <= 7: \n reward_car_distance = -10\n else:\n reward_car_distance = 0\n\n ########### ATTENTION #########################\n ########### Change reward function here #######\n \n #### Reward function 1 ###############\n #progress = sp*np.cos(obs['angle']) - np.abs(sp*np.sin(obs['angle'])) - sp * np.abs(obs['trackPos']) \n ###############################################\n\n\n #### Reward function 2 ###############\n #progress = sp*( np.cos(obs['angle']) - np.abs(obs['trackPos']) ) \n ###############################################\n\n\n #### Reward function 3 ###############\n progress = sp* np.cos(obs['angle']) - np.abs(sp*np.sin(obs['angle'])) - sp * np.abs(obs['trackPos']) + reward_car_distance\n ###############################################\n\n\n ######## Not doing anything penalty\n reward = progress - 1 # -1 is the not-doing-anything-penalty\n\n \n ###############################################\n ### only for race modus\n if obs[\"racePos\"] < obs_pre[\"racePos\"]:\n reward += 150\n if obs[\"racePos\"] > obs_pre[\"racePos\"]:\n reward -= 150\n ###############################################\n\n # collision detection\n if obs['damage'] - obs_pre['damage'] > 0:\n reward = -50\n\n # Termination judgement #########################\n episode_terminate = False\n if (abs(track.any()) > 1 or abs(trackPos) > 1): # Episode is terminated if the car is out of track\n reward = -50\n episode_terminate = True\n client.R.d['meta'] = True\n\n if self.terminal_judge_start < self.time_step: # Episode terminates if the progress of agent is small\n if progress < self.termination_limit_progress:\n print(\"No progress\")\n reward = -10\n episode_terminate = True\n client.R.d['meta'] = True\n\n if np.cos(obs['angle']) < 0: # Episode is terminated if the agent runs backward\n reward = -50\n episode_terminate = True\n client.R.d['meta'] = True\n\n\n if client.R.d['meta'] is True: # Send a reset signal\n self.initial_run = False\n client.respond_to_server()\n\n self.time_step += 1\n\n return self.get_obs(), reward, client.R.d['meta'], {}\n\n def reset(self, relaunch=False):\n #print(\"Reset\")\n\n self.time_step = 0\n\n if self.initial_reset is not True:\n self.client.R.d['meta'] = True\n self.client.respond_to_server()\n\n ## TENTATIVE. Restarting TORCS every episode suffers the memory leak bug!\n if relaunch is True:\n self.reset_torcs()\n print(\"### TORCS is RELAUNCHED ###\")\n\n # Modify here if you use multiple tracks in the environment\n self.client = snakeoil3.Client(p=3101, vision=self.vision) # Open new UDP in vtorcs\n self.client.MAX_STEPS = np.inf\n\n client = self.client\n client.get_servers_input() # Get the initial input from torcs\n\n obs = client.S.d # Get the current full-observation from torcs\n self.observation = self.make_observaton(obs)\n\n self.last_u = None\n\n self.initial_reset = False\n return self.get_obs()\n\n def end(self):\n os.system('pkill torcs')\n\n def get_obs(self):\n return self.observation\n\n def reset_torcs(self):\n #print(\"relaunch torcs\")\n os.system('pkill torcs')\n time.sleep(0.5)\n if self.vision is True:\n os.system('torcs -nofuel -nodamage -nolaptime -vision &')\n else:\n os.system('torcs -nofuel -nolaptime &')\n time.sleep(0.5)\n os.system('sh autostart.sh')\n time.sleep(0.5)\n\n def agent_to_torcs(self, u):\n torcs_action = {'steer': u[0]}\n\n if self.throttle is True: # throttle action is enabled\n torcs_action.update({'accel': u[1]})\n torcs_action.update({'brake': u[2]})\n\n if self.gear_change is True: # gear change action is enabled\n torcs_action.update({'gear': int(u[3])})\n\n return torcs_action\n\n\n def obs_vision_to_image_rgb(self, obs_image_vec):\n image_vec = obs_image_vec\n r = image_vec[0:len(image_vec):3]\n g = image_vec[1:len(image_vec):3]\n b = image_vec[2:len(image_vec):3]\n\n sz = (64, 64)\n r = np.array(r).reshape(sz)\n g = np.array(g).reshape(sz)\n b = np.array(b).reshape(sz)\n return np.array([r, g, b], dtype=np.uint8)\n\n def make_observaton(self, raw_obs):\n if self.vision is False:\n names = ['focus', \"distRaced\", \"racePos\",\n 'speedX', 'speedY', 'speedZ', 'angle', 'damage',\n 'opponents',\n 'rpm',\n 'track', \n 'trackPos',\n 'wheelSpinVel']\n Observation = col.namedtuple('Observaion', names)\n return Observation(focus=np.array(raw_obs['focus'], dtype=np.float32)/200.,\n speedX=np.array(raw_obs['speedX'], dtype=np.float32)/300.0,\n speedY=np.array(raw_obs['speedY'], dtype=np.float32)/300.0,\n speedZ=np.array(raw_obs['speedZ'], dtype=np.float32)/300.0,\n angle=np.array(raw_obs['angle'], dtype=np.float32)/3.1416,\n distRaced=np.array(raw_obs['distRaced'], dtype=np.float32),\n racePos=np.array(raw_obs['racePos'], dtype=np.float32),\n damage=np.array(raw_obs['damage'], dtype=np.float32),\n opponents=np.array(raw_obs['opponents'], dtype=np.float32)/200.,\n rpm=np.array(raw_obs['rpm'], dtype=np.float32)/10000,\n track=np.array(raw_obs['track'], dtype=np.float32)/200.,\n trackPos=np.array(raw_obs['trackPos'], dtype=np.float32)/1.,\n wheelSpinVel=np.array(raw_obs['wheelSpinVel'], dtype=np.float32))\n else:\n names = ['focus',\n 'speedX', 'speedY', 'speedZ', 'angle',\n 'opponents',\n 'rpm',\n 'track',\n 'trackPos',\n 'wheelSpinVel',\n 'img']\n Observation = col.namedtuple('Observaion', names)\n\n # Get RGB from observation\n image_rgb = self.obs_vision_to_image_rgb(raw_obs[names[8]])\n\n return Observation(focus=np.array(raw_obs['focus'], dtype=np.float32)/200.,\n speedX=np.array(raw_obs['speedX'], dtype=np.float32)/self.default_speed,\n speedY=np.array(raw_obs['speedY'], dtype=np.float32)/self.default_speed,\n speedZ=np.array(raw_obs['speedZ'], dtype=np.float32)/self.default_speed,\n opponents=np.array(raw_obs['opponents'], dtype=np.float32)/200.,\n rpm=np.array(raw_obs['rpm'], dtype=np.float32),\n track=np.array(raw_obs['track'], dtype=np.float32)/200.,\n trackPos=np.array(raw_obs['trackPos'], dtype=np.float32)/1.,\n wheelSpinVel=np.array(raw_obs['wheelSpinVel'], dtype=np.float32),\n img=image_rgb)\n"
] |
[
[
"numpy.abs",
"numpy.array",
"numpy.cos",
"numpy.sin"
]
] |
jphacks/NG_1703
|
[
"0c0bec03d71f467f90d8fbe01b31ed4341f3e1a5"
] |
[
"komagen/seb_inclient_fordemo.py"
] |
[
"#!/usr/bin/env python\n# vim:fileencoding=utf-8\nimport time\nimport numpy as np\nimport pyaudio as pa\nimport requests\nimport sys\nimport json\nimport string, random\nimport cv2\n\n# set Device ID to variable \"id\".\n# Device ID: You can get the id from portal\n# https://www6.arche.blue/portal/\n#id = \"device id string\"\nid = \"c59ea1212a11cf\"\n\n# global \n# edge_id get by register_client_sdk\napiurl = \"https://www6.arche.blue/api/v1/\"\nedge_id = \"\"\nedge_port = 80\nedge_ip_addr = \"\"\nsession_id = \"\"\n\n# cv2.cv.CV_FOURCC\n#def cv_fourcc(c1, c2, c3, c4):\n# return (ord(c1) & 255) + ((ord(c2) & 255) << 8) + \\\n# ((ord(c3) & 255) << 16) + ((ord(c4) & 255) << 24)\n\n #字幕生成\n#def make_subtitle(c_frame,text,place_x,place_y,size,R,G,B):\n# font = cv2.FONT_HERSHEY_PLAIN\n# g_frame = cv2.putText(c_frame,text,(place_x,place_y),font, size,(R,G,B),3)\n\n# return (g_frame)\n\n# Generate random string. It is used in session create to cloud edge.\ndef random_string(length, seq=string.digits + string.ascii_lowercase):\n sr = random.SystemRandom()\n return ''.join([sr.choice(seq) for i in range(length)])\nrnd = \"?\"+random_string(4)\n\n\n# This program does not run without setting id variable.\n# If not set, program stop.\nif(id is None):\n print(\"Error. Set Device ID to variable \\\"id\\\" in this source code by text editors.\")\n sys.exit()\n\n\n# This callback is called from pyaudio periodically.\n# chunk is a piece of sound.\ndef callback(in_data, frame_count, time_info, status):\n global chunk\n global w_flag\n\n in_data = np.frombuffer(in_data, dtype=np.int16) \n chunk = in_data.tobytes()\n w_flag = True\n\n return (in_data, pa.paContinue)\n\n\n\n# Call Management Server API \"Create Edge\"\n# POST https://www6.arche.blue/api/v1/<device_id>/edge\n# It returns an existing cloud edge id or (if not exist) create a new cloud edge.\n# This API returns device ID(it is same device_id) and edge ID with json form.\ndef create_edge():\n global edge_id\n \n request_url = apiurl + id + \"/edge\"\n try:\n r = requests.post(request_url) \n# r = requests.post(request_url, proxies=proxies) \n except:\n print (\"Error! Fail to connect edge server.\")\n sys.exit()\n if (r.status_code > 299):\n print (\"Error! Fail to request management server. Check client id. status=\"+str(r.status_code))\n sys.exit()\n \n# print(\"Booting Edge Server.\")\n \n edge_id = r.json()[\"edge_id\"]\n print(\"edge id:\" +edge_id)\n return r.json() \n\n\n\n# Call Management Server API \"Get Edge Info\"\n# GET https://www6.arche.blue/api/v1/<device_id>/edge/<edge_id>\n#\n# This API return Edge Status and Information with json form,\n# {\n# \"ready\":true/false, // true -> connectable\n# \"error\":true/false, // true -> error. Reboot client and generate another VM.\n# \"description\":\"...\", // readable status\n# \"ip_address\":\"xx.xx.xx.xx\" // it is returned when ready = true\n# }\n# The API should be called periodically until 'ready' becomes true\ndef get_edge_info():\n global edge_ip_addr\n \n if(edge_id == \"\"):\n print (\"Error! Edge ID Lost.\")\n sys.exit()\n \n request_url = apiurl + id + \"/edge/\" + edge_id\n try:\n r = requests.get(request_url)\n# r = requests.get(request_url, proxies=proxies)\n except:\n print (\"Error! Fail to connect edge server.\")\n sys.exit()\n if (r.status_code > 299):\n print (\"Error! Fail to connect management server.\"+str(r.status_code))\n sys.exit()\n\n data = r.json()\n if(data[\"error\"]):\n print (\"Error! Fail to start edge server.\")\n sys.exit()\n \n if(data[\"ready\"]):\n edge_ip_addr = data[\"ip_address\"]\n # print (\"Edge Server Ready.\")\n \n return(data)\n\n\n# Call Edge API \"Connect to edge server\"\n# Get http://edge_ipaddress/sounddetect/v1/<device_id>/edge/<edge_id>\n# It returns \"session id\" with json form.\ndef connect_edge_server():\n global session_id\n if( edge_ip_addr == \"\"):\n print(\"Error, IP address of Edge Server unknown.\")\n sys.exit()\n \n if(edge_id == \"\"):\n print(\"Error, Edge Server ID unknown.\")\n sys.exit()\n\n bufsize = 4096\n\n# print(\"Connect to Edge Server.\")\n\n request_url = \"http://\" + edge_ip_addr +\"/sounddetect/v1/\" + id + \"/edge/\" + edge_id + rnd\n try:\n r = requests.get(request_url)\n# r = requests.get(request_url, proxies=proxies)\n except:\n print (\"Error! Fail to connect edge server.\")\n sys.exit()\n if(r.status_code > 299):\n print (\"Error! Edge server replied error code:\"+str(r.status_code))\n sys.exit()\n\n data = r.json()\n session_id = data[\"session\"]\n print(\"Connected Successfully. Session ID:\"+session_id)\n\n return session_id\n\n\n# Call Edge API \"Send Sound chunk data to edge server\"\n# POST http://edge_ipaddress/sounddetect/v1/<device_id>/edge/<edge_id>/session/<session_id>\ndef send_chunk_edge_server(chunk):\n retry = 3\n\n request_url = \"http://\" + edge_ip_addr +\"/sounddetect/v1/\" + id + \"/edge/\" + edge_id + \"/session/\" + session_id\n\n session = requests.Session()\n session.mount(\"http://\", requests.adapters.HTTPAdapter(max_retries=retry))\n session.mount(\"https://\", requests.adapters.HTTPAdapter(max_retries=retry))\n\n try:\n r = requests.post(request_url, data=chunk, timeout=(10.0, 30.0))\n# r = requests.post(request_url, data=chunk, timeout=(10.0, 30.0), proxies=proxies)\n except:\n print (\"Error! Fail to connect edge server.\")\n sys.exit()\n if(r.status_code > 299):\n print (\"Error! Edge server replied error code:\"+str(r.status_code))\n sys.exit()\n print(\"Send data successfully\")\n return True\n\n\n# Call Edge API \"Last Event\"\n# GET http://edge_ipaddress/v1/<device_id>/event\n# @return array(\"event\":{eventtype},\"unixtime\":{eventtime})\ndef get_last_event():\n\n request_url = apiurl + id + \"/event\"\n\n session = requests.Session()\n\n try:\n r = requests.get(request_url)\n# r = requests.get(request_url, proxies=proxies)\n except:\n print (\"Error! Fail to connect management server.\")\n #sys.exit()\n return None;\n if(r.status_code > 299):\n print (\"Error! Management server replied error code:\"+str(r.status_code))\n #sys.exit()\n return None;\n\n if(len(r.content) == 0):\n return None\n data = r.json()\n if(len(data) >0):\n return r.json()[0]\n else:\n return None\n\n\n# start setting up sound recording and sending sounds to the edge server.\ndef start_sound_detect():\n connect_edge_server()\n\n # pyaudio\n p_in = pa.PyAudio()\n bytes = 2\n py_format = p_in.get_format_from_width(bytes)\n fs = 0\n channels = 1\n use_device_index = -1\n \n # find input device\n for i in range(p_in.get_device_count()):\n maxInputChannels = p_in.get_device_info_by_index(i)['maxInputChannels']\n if maxInputChannels > 0:\n if use_device_index == -1:\n use_device_index = i\n fs = int(p_in.get_device_info_by_index(i)['defaultSampleRate'])\n chank_size = fs * 1\n\n print('use_device_index = ', use_device_index)\n print('SampleRate = ', fs)\n\n # generate an input stream\n in_stream = p_in.open(format=py_format,\n channels=channels,\n rate=fs,\n input=True,\n frames_per_buffer=chank_size,\n input_device_index=use_device_index,\n stream_callback=callback)\n\n in_stream.start_stream()\n return in_stream\n\nif __name__ == \"__main__\":\n global w_flag\n global chunk\n\n ESC_KEY = 27 # Escキー\n INTERVAL= 33 # 待ち時間\n FRAME_RATE = 30 # fps\n\n# ORG_WINDOW_NAME = \"org\"\n GAUSSIAN_WINDOW_NAME = \"gaussian\"\n\n# GAUSSIAN_FILE_NAME = \"gaussian.avi\"\n\n DEVICE_ID = 0\n\n # カメラ映像取得\n cap = cv2.VideoCapture(DEVICE_ID)\n\n # 保存ビデオファイルの準備\n end_flag, c_frame = cap.read()\n# height, width, channels = c_frame.shape\n# rec = cv2.VideoWriter(GAUSSIAN_FILE_NAME, \\\n# cv_fourcc('X', 'V', 'I', 'D'), \\\n# FRAME_RATE, \\\n# (width, height), \\\n# True)\n # ウィンドウの準備\n# cv2.namedWindow(ORG_WINDOW_NAME)\n cv2.namedWindow(GAUSSIAN_WINDOW_NAME)\n\n\n komagen_flag = True \n\n create_edge()\n\n print(\"Now creating your Cloud Edge. Please wait for approx 60 sec ..\")\n \n edgeinfo = get_edge_info()\n sys.stderr.write(\"Progress %3s%%\" % (edgeinfo[\"progress\"]))\n pre_progress = int(edgeinfo[\"progress\"])\n progress = int(edgeinfo[\"progress\"])\n while ((edgeinfo[\"ready\"] == False) and (edgeinfo[\"error\"] == False)):\n# start = time.time()\n time.sleep(3)\n edgeinfo = get_edge_info()\n new_progress = int(edgeinfo[\"progress\"])\n if(pre_progress == new_progress):\n progress += 1\n else:\n progress = int(new_progress)\n pre_progress = progress\n \n sys.stderr.write(\"\\rProgress %3s%%\" % (progress))\n sys.stderr.write(\"\\n\")\n\n if(edgeinfo[\"error\"]):\n print(\"Fail to create your Cloud Edge.\")\n sys.exit()\n\n print(\"Edge Server IP address:\", edge_ip_addr)\n\n w_flag = False\n\n old_event = get_last_event()\n\n in_stream = start_sound_detect()\n \n count = 0\n while (in_stream.is_active() or (end_flag == True)):\n if (count % 50 == 0): \n text = \"\"\n#as client\n if w_flag:\n w_flag = False\n if komagen_flag == True:\n print(\"check start\")\n komagen_flag = False\n send_chunk_edge_server(chunk)\n \n e_flag = False\n new_event = get_last_event()\n if(new_event != None):\n if(old_event == None):\n old_event= new_event \n e_flag = True\n elif(old_event['unixtime'] != new_event['unixtime']):\n old_event= new_event \n e_flag = True\n if(e_flag):\n# print(\"\"+new_event['event'])\n text = new_event['event']\n print(text)\n if text == \"TimerAlarm\":\n text = \"Ring!Ring!Ring!\"\n\n# print(\"time = {}\".format(time.time()-start)) \n if(count % 50 == 0):\n R = int(random.uniform(0,200))\n G = int(random.uniform(0,200))\n B = int(random.uniform(0,200))\n #字幕生成\n place_x = int(random.uniform(0,400))\n place_y = int(random.uniform(0,400))\n font = cv2.FONT_HERSHEY_PLAIN\n size = random.uniform(3,8)\n count += 1\n g_frame = cv2.putText(c_frame,text,(place_x,place_y),font, size,(R,G,B),15)\n# g_frame = make_subtitle(c_frame,text,200,200,3)\n # フレーム書き込み\n# rec.write(g_frame)\n # フレーム表示\n cv2.imshow(GAUSSIAN_WINDOW_NAME, g_frame)\n\n # Escキーで終了\n# key = cv2.waitKey(INTERVAL)\n# if key == ESC_KEY:\n# break\n\n # 次のフレーム読み込み\n end_flag, c_frame = cap.read()\n else:\n in_stream.stop_stream()\n in_stream.close()\n # 終了処理\n cv2.destroyAllWindows()\n"
] |
[
[
"numpy.frombuffer"
]
] |
Akorsvang/WIRT-implementation
|
[
"086a03007687dbb10f48a9228be47c8a2828bc9d"
] |
[
"polar/polar_common.py"
] |
[
"\"\"\"\nShared functions used for polar encoding and decoding\n\"\"\"\n\nfrom functools import lru_cache\n\nimport numpy as np\n\ndef idx(phi, beta, lamb):\n return phi + (beta << lamb)\n\ndef polar_calculate_weights(N):\n \"\"\"\n Calculate polar weights\n Right now only supports N <= 2**8, for more look at\n np.unpackbits(np.array([3]).byteswap().view(np.uint8))\n \"\"\"\n if np.log2(N) > 8:\n raise ValueError(\"Ordering calculation does not support above 2**8\")\n\n beta = 2**(1 / 4)\n\n I = np.arange(N, dtype=np.uint8)\n beta_power = (beta**np.arange(7, -1, -1))\n\n W = np.empty(I.shape)\n for i in I:\n W[i] = (np.unpackbits(i) * beta_power).sum()\n\n W_index = np.argsort(W)\n return W_index\n\n@lru_cache()\ndef polar_hpw(N):\n \"\"\"\n Calculate polar weights using the higher order method\n \"\"\"\n\n beta = 2**(1 / 4)\n\n I = np.arange(N, dtype='>u4') # Creating this as a big-endian array, so we don't have to byteswap\n beta_power = (beta**np.arange(31, -1, -1))\n beta_power_quad = (beta**((1 / 4) * np.arange(31, -1, -1)))\n\n elem_bits = np.unpackbits(I.view(np.uint8)).reshape(-1, 32)\n W = (elem_bits * (beta_power + (1/4) * beta_power_quad)).sum(axis=1)\n\n W_index = np.argsort(W)\n return W_index\n\n@lru_cache()\ndef polar_find_ordering(N):\n o = np.arange(N, dtype='>u4')\n n_bits = np.log2(N).astype(int)\n\n # We use some view tricks here to find the bits that correspond to the entries in o\n elem_bits = np.unpackbits(o.view(np.uint8)).reshape(-1, 32)\n\n # Flip the bit order, roll the bits down to the correct order and revert the view from before\n return np.packbits(np.roll(np.fliplr(elem_bits), 32 - n_bits)).view('>u4')\n\n@lru_cache()\ndef polar_find_G(N, reorder=True):\n n = np.log2(N).astype(int)\n\n F = np.array([[1, 0], [1, 1]], dtype=np.uint8)\n G = F.copy()\n for _ in range(1, n):\n G = np.kron(G, F)\n\n if reorder:\n G_shuffled = G[polar_find_ordering(N)]\n else:\n G_shuffled = G\n\n return G_shuffled\n\n\ndef polar_transform_pipelined(u, reorder=True):\n N = len(u)\n N_half = N//2\n n = np.log2(N).astype(int)\n\n working_bits = u.copy()\n for n_i in range(n):\n u2 = working_bits[1::2].copy()\n\n working_bits[:N_half] = working_bits[::2] ^ u2\n working_bits[N_half:] = u2\n\n if reorder:\n order = polar_find_ordering(N)\n working_bits = working_bits[order]\n\n return working_bits\n\n\ndef polar_transform(u):\n \"\"\"\n This should be a way to use encode using the bit reversal structure -> more efficient in HW.\n\n Based on http://pfister.ee.duke.edu/courses/ecen655/polar.pdf\n \"\"\"\n if len(u) == 1:\n x = u\n else:\n u1u2 = np.mod(u[::2] + u[1::2], 2)\n u2 = u[1::2]\n\n x = np.concatenate((polar_transform(u1u2), polar_transform(u2)))\n return x"
] |
[
[
"numpy.log2",
"numpy.fliplr",
"numpy.arange",
"numpy.kron",
"numpy.mod",
"numpy.argsort",
"numpy.array",
"numpy.empty",
"numpy.unpackbits"
]
] |
littlepure2333/st-gcn
|
[
"1b002c6d42902d135da605d649654aa00cad0d06"
] |
[
"feeder/feeder_nmv.py"
] |
[
"# sys\nimport os\nimport sys\nimport numpy as np\nimport random\nimport pickle\nimport json\n# torch\nimport torch\nimport torch.nn as nn\nfrom torchvision import datasets, transforms\n\n# operation\nfrom . import tools\n\n\nclass Feeder_nmv(torch.utils.data.Dataset):\n \"\"\" Feeder for skeleton-based action recognition in NMV dataset\n Arguments:\n data_path: the path to '.npy' data, the shape of data should be (N, C, T, V, M)\n label_path: the path to label\n random_choose: If true, randomly choose a portion of the input sequence\n random_shift: If true, randomly pad zeros at the begining or end of sequence\n random_move: If true, perform randomly but continuously changed transformation to input sequence\n window_size: The length of the output sequence\n pose_matching: If ture, match the pose between two frames\n num_person_in: The number of people the feeder can observe in the input sequence\n num_person_out: The number of people the feeder in the output sequence\n big_class: If true, the class label will be set to big class (rather than small class)\n debug: If true, only use the first 100 samples\n \"\"\"\n\n def __init__(self,\n data_path,\n ignore_empty_sample=True,\n random_choose=False,\n random_shift=False,\n random_move=False,\n window_size=-1,\n pose_matching=False,\n num_person_in=5,\n num_person_out=1,\n big_class=True,\n debug=False):\n self.debug = debug\n self.data_path = data_path\n self.random_choose = random_choose\n self.random_shift = random_shift\n self.random_move = random_move\n self.window_size = window_size\n self.num_person_in = num_person_in\n self.num_person_out = num_person_out\n self.pose_matching = pose_matching\n self.ignore_empty_sample = ignore_empty_sample\n self.big_class = big_class\n\n self.load_data()\n\n def load_data(self):\n # load file list\n self.sample_name = os.listdir(self.data_path)\n\n if self.debug:\n self.sample_name = self.sample_name[0:3]\n\n # output data shape (N, C, T, V, M)\n self.N = len(self.sample_name) #sample\n self.C = 3 #channel\n self.T = 300 #frame\n self.V = 18 #joint\n self.M = self.num_person_out #person\n\n def __len__(self):\n return len(self.sample_name)\n\n def __iter__(self):\n return self\n\n def __getitem__(self, index):\n\n # output shape (C, T, V, M)\n # get data\n sample_name = self.sample_name[index]\n sample_path = os.path.join(self.data_path, sample_name)\n with open(sample_path, 'r') as f:\n video_info = json.load(f)\n\n # fill data_numpy\n data_numpy = np.zeros((self.C, self.T, self.V, self.num_person_in))\n for frame_info in video_info['annotations']:\n frame_index = frame_info['frame_index']\n for m, skeleton_info in enumerate(frame_info[\"person\"]):\n if m >= self.num_person_in:\n break\n keypoint_17 = skeleton_info['keypoint']\n # convert 17 keypoints to 18 keypoints\n if len(keypoint_17) > 0:\n neck = [keypoint_17[5][0] + keypoint_17[6][0],\n keypoint_17[5][1] + keypoint_17[6][1],\n keypoint_17[5][2] + keypoint_17[6][2]] # neck is the mean of shoulders\n keypoint_17.append(neck)\n for index, v in enumerate([0, 17, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3]):\n data_numpy[:, frame_index, index, m] = keypoint_17[v]\n\n # centralization\n W, H = video_info[\"info\"][\"resolution\"]\n data_numpy[0, :, :, :] = data_numpy[0, :, :, :] / W - 0.5\n data_numpy[1, :, :, :] = data_numpy[1, :, :, :] / H - 0.5\n data_numpy[0][data_numpy[2] == 0] = 0\n data_numpy[1][data_numpy[2] == 0] = 0\n\n # get label index\n label = int(video_info['category_id'])\n if self.big_class:\n if 0 <= label & label <= 12:\n label = 0 # 持械\n elif 13 <= label & label <= 22:\n label = 1 # 踢\n elif 23 <= label & label <= 33:\n label = 2 # 打\n elif 34 <= label & label <= 38:\n label = 3 # 扼掐\n elif 39 <= label & label <= 40:\n label = 4 # 无暴力\n else:\n print(\"Not exist this label\")\n \n\n # data augmentation\n if self.random_shift:\n data_numpy = tools.random_shift(data_numpy)\n if self.random_choose:\n data_numpy = tools.random_choose(data_numpy, self.window_size)\n elif self.window_size > 0:\n data_numpy = tools.auto_pading(data_numpy, self.window_size)\n if self.random_move:\n data_numpy = tools.random_move(data_numpy)\n\n # sort by score\n sort_index = (-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1)\n for t, s in enumerate(sort_index):\n data_numpy[:, t, :, :] = data_numpy[:, t, :, s].transpose((1, 2,\n 0))\n data_numpy = data_numpy[:, :, :, 0:self.num_person_out]\n\n # match poses between 2 frames\n if self.pose_matching:\n data_numpy = tools.openpose_match(data_numpy)\n\n return data_numpy, label\n\n def top_k(self, score, top_k):\n assert (all(self.label >= 0))\n\n rank = score.argsort()\n hit_top_k = [l in rank[i, -top_k:] for i, l in enumerate(self.label)]\n return sum(hit_top_k) * 1.0 / len(hit_top_k)\n\n def top_k_by_category(self, score, top_k):\n assert (all(self.label >= 0))\n return tools.top_k_by_category(self.label, score, top_k)\n\n def calculate_recall_precision(self, score):\n assert (all(self.label >= 0))\n return tools.calculate_recall_precision(self.label, score)\n"
] |
[
[
"numpy.zeros"
]
] |
rcrehuet/getcontacts
|
[
"a82354367483f79bdbeaa8d43d47d34dc196f70e"
] |
[
"Applications/get_fingerprint_clusters.py"
] |
[
"#!/usr/bin/env python3\n\"\"\"\n\n\"\"\"\n\nfrom scipy.cluster.hierarchy import linkage, fcluster\nimport numpy as np\n\n\ndef parse_table(lines):\n col_names = [l.strip() for l in lines[0].split(\"\\t\")[2:]]\n row_names = []\n frequencies = []\n\n for line in lines[1:]:\n tokens = line.split(\"\\t\")\n row_names.append((tokens[0], tokens[1]))\n frequencies.append([float(t) for t in tokens[2:]])\n\n return row_names, col_names, frequencies\n\n\nif __name__ == \"__main__\":\n import sys\n from os import path\n sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))\n from contact_calc.transformations import parse_contacts\n\n # Parse command line arguments\n import argparse as ap\n parser = ap.ArgumentParser(description=__doc__, formatter_class=ap.RawTextHelpFormatter)\n optional = parser._action_groups.pop()\n required = parser.add_argument_group('required arguments')\n parser._action_groups.append(optional) # added this line\n\n required.add_argument('--table_input',\n required=True,\n type=ap.FileType('r'),\n metavar='FILE',\n help='A fingerprint table generated by get_contact_fingerprints.py')\n required.add_argument('--num_row_clusters',\n required=False,\n default=5,\n type=int,\n metavar='INT',\n help='Max number of interaction clusters')\n required.add_argument('--num_col_clusters',\n required=False,\n default=5,\n type=int,\n metavar='INT',\n help='Max number of structure clusters')\n required.add_argument('--pymol_output',\n required=True,\n metavar='FILE',\n type=str,\n help='The name of the output ')\n\n args = parser.parse_args()\n print(\"Parsing table from \" + args.table_input.name)\n rows, cols, freqs = parse_table(args.table_input.readlines())\n\n freq_matrix = np.matrix(freqs)\n m, n = freq_matrix.shape\n print(\"Building linkage for clustering .. \")\n row_linkage = linkage(freq_matrix, method='ward')\n col_linkage = linkage(freq_matrix.T, method='ward')\n\n print(\"Splitting into clusters based on linkage .. \")\n row_cluster_assignments = fcluster(row_linkage, args.num_row_clusters, criterion='maxclust') - 1\n col_cluster_assignments = fcluster(col_linkage, args.num_col_clusters, criterion='maxclust') - 1\n row_clusters = list(set(row_cluster_assignments))\n col_clusters = list(set(col_cluster_assignments))\n\n # Compute cluster-matrix frequency\n print(\"Computing cluster-matrix frequencies .. \")\n cluster_freq_matrix = np.zeros((len(row_clusters), len(col_clusters)))\n for row_cluster in row_clusters:\n row_indices = [i for i in range(m) if row_cluster_assignments[i] == row_cluster]\n for col_cluster in col_clusters:\n col_indices = [i for i in range(n) if col_cluster_assignments[i] == col_cluster]\n\n ixgrid = np.ix_(row_indices, col_indices)\n cluster_freq_matrix[row_cluster, col_cluster] = \\\n np.sum(freq_matrix[ixgrid]) / (len(row_indices) * len(col_indices))\n\n print(cluster_freq_matrix)\n\n print(\"Writing to \" + args.pymol_output)\n if args.pymol_output:\n for cluster in col_clusters:\n cols_in_cluster = [cols[i] for i in range(n) if col_cluster_assignments[i] == cluster]\n fname = \"%s_%04d.pml\" % (args.pymol_output, cluster)\n\n with open(fname, 'w') as outfile:\n\n for col in cols_in_cluster:\n outfile.write(\"#load(%s)\\n\" % col)\n\n outfile.write(\"\\n\")\n\n for row_cluster in row_clusters:\n rows_in_cluster = [rows[i] for i in range(m) if row_cluster_assignments[i] == row_cluster]\n object_name = \"cluster_%d_freq_%.3f\" % (row_cluster, cluster_freq_matrix[row_cluster, cluster])\n for row in rows_in_cluster:\n resi1 = \"chain %s & resi %s & name CA+C1'\" % (row[0].split(\":\")[0], row[0].split(\":\")[2])\n resi2 = \"chain %s & resi %s & name CA+C1'\" % (row[1].split(\":\")[0], row[1].split(\":\")[2])\n outfile.write(\"distance %s, %s, %s\\n\" % (object_name, resi1, resi2))\n outfile.write(\"\\n\")\n\n\n__license__ = \"Apache License 2.0\"\n__maintainer__ = \"Rasmus Fonseca\"\n__email__ = \"fonseca.rasmus@gmail.com\"\n"
] |
[
[
"numpy.matrix",
"numpy.ix_",
"scipy.cluster.hierarchy.linkage",
"numpy.sum",
"scipy.cluster.hierarchy.fcluster"
]
] |
leonyip/GamestonkTerminal
|
[
"030bec00e5580d90c57e116c8800e773237c5baf",
"030bec00e5580d90c57e116c8800e773237c5baf"
] |
[
"gamestonk_terminal/helper_funcs.py",
"gamestonk_terminal/main_helper.py"
] |
[
"import argparse\nfrom datetime import datetime, timedelta, time as Time\nimport os\nimport random\nimport re\nimport sys\nfrom pytz import timezone\nimport iso8601\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom holidays import US as holidaysUS\nfrom colorama import Fore, Style\nimport pandas.io.formats.format\nfrom pandas._config.config import get_option\nfrom pandas.plotting import register_matplotlib_converters\nfrom screeninfo import get_monitors\nfrom gamestonk_terminal import feature_flags as gtff\nfrom gamestonk_terminal import config_plot as cfgPlot\n\nregister_matplotlib_converters()\nif cfgPlot.BACKEND is not None:\n matplotlib.use(cfgPlot.BACKEND)\n\n\ndef check_non_negative(value) -> int:\n ivalue = int(value)\n if ivalue < 0:\n raise argparse.ArgumentTypeError(f\"{value} is negative\")\n return ivalue\n\n\ndef check_positive(value) -> int:\n ivalue = int(value)\n if ivalue <= 0:\n raise argparse.ArgumentTypeError(f\"{value} is an invalid positive int value\")\n return ivalue\n\n\ndef valid_date(s: str) -> datetime:\n try:\n return datetime.strptime(s, \"%Y-%m-%d\")\n except ValueError as value_error:\n raise argparse.ArgumentTypeError(f\"Not a valid date: {s}\") from value_error\n\n\ndef plot_view_stock(df, symbol):\n df.sort_index(ascending=True, inplace=True)\n\n try:\n _, axVolume = plt.subplots(figsize=plot_autoscale(), dpi=cfgPlot.PLOT_DPI)\n except Exception as e:\n print(e)\n print(\n \"Encountered an error trying to open a chart window. Check your X server configuration.\"\n )\n return\n\n plt.bar(df.index, df.iloc[:, -1], color=\"k\", alpha=0.8, width=0.3)\n plt.ylabel(\"Volume\")\n _ = axVolume.twinx()\n plt.plot(df.index, df.iloc[:, :-1])\n plt.title(symbol.upper() + \" (Time Series)\")\n plt.xlim(df.index[0], df.index[-1])\n plt.xlabel(\"Time\")\n plt.ylabel(\"Share Price ($)\")\n plt.legend(df.columns)\n plt.grid(b=True, which=\"major\", color=\"#666666\", linestyle=\"-\")\n plt.minorticks_on()\n plt.grid(b=True, which=\"minor\", color=\"#999999\", linestyle=\"-\", alpha=0.2)\n\n if gtff.USE_ION:\n plt.ion()\n\n plt.show()\n print(\"\")\n\n\ndef us_market_holidays(years) -> list:\n if isinstance(years, int):\n years = [\n years,\n ]\n # https://www.nyse.com/markets/hours-calendars\n marketHolidays = [\n \"Martin Luther King Jr. Day\",\n \"Washington's Birthday\",\n \"Memorial Day\",\n \"Independence Day\",\n \"Labor Day\",\n \"Thanksgiving\",\n \"Christmas Day\",\n ]\n # http://www.maa.clell.de/StarDate/publ_holidays.html\n goodFridays = {\n 2010: \"2010-04-02\",\n 2011: \"2011-04-22\",\n 2012: \"2012-04-06\",\n 2013: \"2013-03-29\",\n 2014: \"2014-04-18\",\n 2015: \"2015-04-03\",\n 2016: \"2016-03-25\",\n 2017: \"2017-04-14\",\n 2018: \"2018-03-30\",\n 2019: \"2019-04-19\",\n 2020: \"2020-04-10\",\n 2021: \"2021-04-02\",\n 2022: \"2022-04-15\",\n 2023: \"2023-04-07\",\n 2024: \"2024-03-29\",\n 2025: \"2025-04-18\",\n 2026: \"2026-04-03\",\n 2027: \"2027-03-26\",\n 2028: \"2028-04-14\",\n 2029: \"2029-03-30\",\n 2030: \"2030-04-19\",\n }\n marketHolidays_and_obsrvd = marketHolidays + [\n holiday + \" (Observed)\" for holiday in marketHolidays\n ]\n allHolidays = holidaysUS(years=years)\n validHolidays = []\n for date in list(allHolidays):\n if allHolidays[date] in marketHolidays_and_obsrvd:\n validHolidays.append(date)\n for year in years:\n new_Year = datetime.strptime(f\"{year}-01-01\", \"%Y-%m-%d\")\n if new_Year.weekday() != 5: # ignore saturday\n validHolidays.append(new_Year.date())\n if new_Year.weekday() == 6: # add monday for Sunday\n validHolidays.append(new_Year.date() + timedelta(1))\n for year in years:\n validHolidays.append(datetime.strptime(goodFridays[year], \"%Y-%m-%d\").date())\n return validHolidays\n\n\ndef b_is_stock_market_open() -> bool:\n \"\"\"checks if the stock market is open\"\"\"\n # Get current US time\n now = datetime.now(timezone(\"US/Eastern\"))\n # Check if it is a weekend\n if now.date().weekday() > 4:\n return False\n # Check if it is a holiday\n if now.strftime(\"%Y-%m-%d\") in us_market_holidays(now.year):\n return False\n # Check if it hasn't open already\n if now.time() < Time(hour=9, minute=30, second=0):\n return False\n # Check if it has already closed\n if now.time() > Time(hour=16, minute=0, second=0):\n return False\n # Otherwise, Stock Market is open!\n return True\n\n\ndef long_number_format(num) -> str:\n if isinstance(num, float):\n magnitude = 0\n while abs(num) >= 1000:\n magnitude += 1\n num /= 1000.0\n num_str = int(num) if num.is_integer() else f\"{num:.3f}\"\n return f\"{num_str} {' KMBTP'[magnitude]}\".strip()\n if isinstance(num, int):\n num = str(num)\n if num.lstrip(\"-\").isdigit():\n num = int(num)\n num /= 1.0\n magnitude = 0\n while abs(num) >= 1000:\n magnitude += 1\n num /= 1000.0\n num_str = int(num) if num.is_integer() else f\"{num:.3f}\"\n return f\"{num_str} {' KMBTP'[magnitude]}\".strip()\n return num\n\n\ndef clean_data_values_to_float(val: str) -> float:\n # Remove any leading or trailing parentheses and spaces\n val = val.strip(\"( )\")\n if val == \"-\":\n val = \"0\"\n\n # Convert percentage to decimal\n if val.endswith(\"%\"):\n val_as_float = float(val[:-1]) / 100.0\n # Convert from billions\n elif val.endswith(\"B\"):\n val_as_float = float(val[:-1]) * 1_000_000_000\n # Convert from millions\n elif val.endswith(\"M\"):\n val_as_float = float(val[:-1]) * 1_000_000\n # Convert from thousands\n elif val.endswith(\"K\"):\n val_as_float = float(val[:-1]) * 1000\n else:\n val_as_float = float(val)\n return val_as_float\n\n\ndef int_or_round_float(x) -> str:\n if (x - int(x) < -sys.float_info.epsilon) or (x - int(x) > sys.float_info.epsilon):\n return \" \" + str(round(x, 2))\n\n return \" \" + str(int(x))\n\n\ndef divide_chunks(data, n):\n # looping till length of data\n for i in range(0, len(data), n):\n yield data[i : i + n]\n\n\ndef get_next_stock_market_days(last_stock_day, n_next_days) -> list:\n n_days = 0\n l_pred_days = list()\n years: list = []\n holidays: list = []\n while n_days < n_next_days:\n last_stock_day += timedelta(hours=24)\n year = last_stock_day.date().year\n if year not in years:\n years.append(year)\n holidays = holidays + us_market_holidays(year)\n # Check if it is a weekend\n if last_stock_day.date().weekday() > 4:\n continue\n # Check if it is a holiday\n if last_stock_day.strftime(\"%Y-%m-%d\") in holidays:\n continue\n # Otherwise stock market is open\n n_days += 1\n l_pred_days.append(last_stock_day)\n\n return l_pred_days\n\n\ndef get_data(tweet):\n if \"+\" in tweet[\"created_at\"]:\n s_datetime = tweet[\"created_at\"].split(\" +\")[0]\n else:\n s_datetime = iso8601.parse_date(tweet[\"created_at\"]).strftime(\n \"%Y-%m-%d %H:%M:%S\"\n )\n\n if \"full_text\" in tweet.keys():\n s_text = tweet[\"full_text\"]\n else:\n s_text = tweet[\"text\"]\n\n data = {\"created_at\": s_datetime, \"text\": s_text}\n return data\n\n\ndef clean_tweet(tweet: str, s_ticker: str) -> str:\n whitespace = re.compile(r\"\\s+\")\n web_address = re.compile(r\"(?i)http(s):\\/\\/[a-z0-9.~_\\-\\/]+\")\n ticker = re.compile(fr\"(?i)@{s_ticker}(?=\\b)\")\n user = re.compile(r\"(?i)@[a-z0-9_]+\")\n\n tweet = whitespace.sub(\" \", tweet)\n tweet = web_address.sub(\"\", tweet)\n tweet = ticker.sub(s_ticker, tweet)\n tweet = user.sub(\"\", tweet)\n\n return tweet\n\n\ndef get_user_agent() -> str:\n user_agent_strings = [\n \"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.10; rv:86.1) Gecko/20100101 Firefox/86.1\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:86.1) Gecko/20100101 Firefox/86.1\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:82.1) Gecko/20100101 Firefox/82.1\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:86.0) Gecko/20100101 Firefox/86.0\",\n \"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:86.0) Gecko/20100101 Firefox/86.0\",\n \"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.10; rv:83.0) Gecko/20100101 Firefox/83.0\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:84.0) Gecko/20100101 Firefox/84.0\",\n ]\n\n return random.choice(user_agent_strings)\n\n\n# monkey patch Pandas\ndef text_adjustment_init(self):\n self.ansi_regx = re.compile(r\"\\x1B[@-_][0-?]*[ -/]*[@-~]\")\n self.encoding = get_option(\"display.encoding\")\n\n\ndef text_adjustment_len(self, text):\n # return compat.strlen(self.ansi_regx.sub(\"\", text), encoding=self.encoding)\n return len(self.ansi_regx.sub(\"\", text))\n\n\ndef text_adjustment_justify(self, texts, max_len, mode=\"right\"):\n jfunc = (\n str.ljust\n if (mode == \"left\")\n else str.rjust\n if (mode == \"right\")\n else str.center\n )\n out = []\n for s in texts:\n escapes = self.ansi_regx.findall(s)\n if len(escapes) == 2:\n out.append(\n escapes[0].strip()\n + jfunc(self.ansi_regx.sub(\"\", s), max_len)\n + escapes[1].strip()\n )\n else:\n out.append(jfunc(s, max_len))\n return out\n\n\n# pylint: disable=unused-argument\ndef text_adjustment_join_unicode(self, lines, sep=\"\"):\n try:\n return sep.join(lines)\n except UnicodeDecodeError:\n # sep = compat.text_type(sep)\n return sep.join([x.decode(\"utf-8\") if isinstance(x, str) else x for x in lines])\n\n\n# pylint: disable=unused-argument\ndef text_adjustment_adjoin(self, space, *lists, **kwargs):\n # Add space for all but the last column:\n pads = ([space] * (len(lists) - 1)) + [0]\n max_col_len = max(len(col) for col in lists)\n new_cols = []\n for col, pad in zip(lists, pads):\n width = max(self.len(s) for s in col) + pad\n c = self.justify(col, width, mode=\"left\")\n # Add blank cells to end of col if needed for different col lens:\n if len(col) < max_col_len:\n c.extend([\" \" * width] * (max_col_len - len(col)))\n new_cols.append(c)\n\n rows = [self.join_unicode(row_tup) for row_tup in zip(*new_cols)]\n return self.join_unicode(rows, sep=\"\\n\")\n\n\n# https://github.com/pandas-dev/pandas/issues/18066#issuecomment-522192922\ndef patch_pandas_text_adjustment():\n pandas.io.formats.format.TextAdjustment.__init__ = text_adjustment_init\n pandas.io.formats.format.TextAdjustment.len = text_adjustment_len\n pandas.io.formats.format.TextAdjustment.justify = text_adjustment_justify\n pandas.io.formats.format.TextAdjustment.join_unicode = text_adjustment_join_unicode\n pandas.io.formats.format.TextAdjustment.adjoin = text_adjustment_adjoin\n\n\ndef parse_known_args_and_warn(parser, l_args):\n parser.add_argument(\n \"-h\", \"--help\", action=\"store_true\", help=\"show this help message\"\n )\n\n if gtff.USE_CLEAR_AFTER_CMD:\n os.system(\"cls||clear\")\n\n (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)\n\n if ns_parser.help:\n parser.print_help()\n print(\"\")\n return None\n\n if l_unknown_args:\n print(f\"The following args couldn't be interpreted: {l_unknown_args}\")\n\n return ns_parser\n\n\ndef financials_colored_values(val: str) -> str:\n if val == \"N/A\" or str(val) == \"nan\":\n val = f\"{Fore.YELLOW}N/A{Style.RESET_ALL}\"\n elif sum(c.isalpha() for c in val) < 2:\n if \"%\" in val:\n if \"-\" in val:\n val = f\"{Fore.RED}{val}{Style.RESET_ALL}\"\n else:\n val = f\"{Fore.GREEN}{val}{Style.RESET_ALL}\"\n elif \"(\" in val:\n val = f\"{Fore.RED}{val}{Style.RESET_ALL}\"\n\n return val\n\n\ndef check_ohlc(type_ohlc: str) -> str:\n if bool(re.match(\"^[ohlca]+$\", type_ohlc)):\n return type_ohlc\n raise argparse.ArgumentTypeError(\"The type specified is not recognized\")\n\n\ndef lett_to_num(word: str) -> str:\n replacements = [(\"o\", \"1\"), (\"h\", \"2\"), (\"l\", \"3\"), (\"c\", \"4\"), (\"a\", \"5\")]\n for (a, b) in replacements:\n word = word.replace(a, b)\n return word\n\n\ndef check_sources(source: str) -> str:\n available_historical_price_sources = [\"yf\", \"av\"]\n if source in available_historical_price_sources:\n return source\n raise argparse.ArgumentTypeError(\n \"This source for historical data is not available.\"\n )\n\n\ndef get_flair() -> str:\n flair = {\n \"rocket\": \"(🚀🚀)\",\n \"diamond\": \"(💎💎)\",\n \"stars\": \"(✨)\",\n \"baseball\": \"(⚾)\",\n \"boat\": \"(⛵)\",\n \"phone\": \"(☎)\",\n \"mercury\": \"(☿)\",\n \"sun\": \"(☼)\",\n \"moon\": \"(☾)\",\n \"nuke\": \"(☢)\",\n \"hazard\": \"(☣)\",\n \"tunder\": \"(☈)\",\n \"king\": \"(♔)\",\n \"queen\": \"(♕)\",\n \"knight\": \"(♘)\",\n \"recycle\": \"(♻)\",\n \"scales\": \"(⚖)\",\n \"ball\": \"(⚽)\",\n \"golf\": \"(⛳)\",\n \"piece\": \"(☮)\",\n \"yy\": \"(☯)\",\n }\n\n if flair.get(gtff.USE_FLAIR):\n return flair[gtff.USE_FLAIR]\n\n return \"\"\n\n\ndef str_to_bool(value):\n if isinstance(value, bool):\n return value\n if value.lower() in {\"false\", \"f\", \"0\", \"no\", \"n\"}:\n return False\n if value.lower() in {\"true\", \"t\", \"1\", \"yes\", \"y\"}:\n return True\n raise ValueError(f\"{value} is not a valid boolean value\")\n\n\ndef get_screeninfo():\n screens = get_monitors() # Get all available monitors\n if len(screens) - 1 < cfgPlot.MONITOR: # Check to see if chosen monitor is detected\n monitor = 0\n print(f\"Could not locate monitor {cfgPlot.MONITOR}, using primary monitor.\")\n else:\n monitor = cfgPlot.MONITOR\n main_screen = screens[monitor] # Choose what monitor to get\n\n return (main_screen.width, main_screen.height)\n\n\ndef plot_autoscale():\n\n if gtff.USE_PLOT_AUTOSCALING:\n x, y = get_screeninfo() # Get screen size\n x = ((x) * cfgPlot.PLOT_WIDTH_PERCENTAGE * 10 ** -2) / (\n cfgPlot.PLOT_DPI\n ) # Calculate width\n if cfgPlot.PLOT_HEIGHT_PERCENTAGE == 100: # If full height\n y = y - 60 # Remove the height of window toolbar\n y = ((y) * cfgPlot.PLOT_HEIGHT_PERCENTAGE * 10 ** -2) / (cfgPlot.PLOT_DPI)\n else: # If not autoscale, use size defined in config_plot.py\n x = cfgPlot.PLOT_WIDTH / (cfgPlot.PLOT_DPI)\n y = cfgPlot.PLOT_HEIGHT / (cfgPlot.PLOT_DPI)\n return x, y\n",
"import argparse\nfrom typing import List\nfrom sys import stdout\nimport random\nfrom datetime import datetime, timedelta\nimport subprocess\nimport hashlib\nimport matplotlib.pyplot as plt\nfrom numpy.core.fromnumeric import transpose\nimport pandas as pd\nfrom alpha_vantage.timeseries import TimeSeries\nimport mplfinance as mpf\nimport yfinance as yf\nimport pytz\nfrom tabulate import tabulate\n\nfrom gamestonk_terminal.helper_funcs import (\n valid_date,\n plot_view_stock,\n parse_known_args_and_warn,\n check_ohlc,\n lett_to_num,\n check_sources,\n plot_autoscale,\n)\n\nfrom gamestonk_terminal import config_terminal as cfg\nfrom gamestonk_terminal import feature_flags as gtff\nfrom gamestonk_terminal.technical_analysis import trendline_api as trend\n\n\ndef print_help(s_ticker, s_start, s_interval, b_is_market_open):\n \"\"\"Print help\"\"\"\n print(\"What do you want to do?\")\n print(\" help help to see this menu again\")\n print(\" update update terminal from remote\")\n print(\" reset reset terminal and reload configs\")\n print(\" quit to abandon the program\")\n print(\"\")\n print(\" clear clear a specific stock ticker from analysis\")\n print(\" load load a specific stock ticker for analysis\")\n print(\" quote view the current price for a specific stock ticker\")\n print(\" candle view a candle chart for a specific stock ticker\")\n print(\" view view and load a specific stock ticker for technical analysis\")\n if s_ticker:\n print(\n \" export export the currently loaded dataframe to a file or stdout\"\n )\n\n s_intraday = (f\"Intraday {s_interval}\", \"Daily\")[s_interval == \"1440min\"]\n if s_ticker and s_start:\n print(f\"\\n{s_intraday} Stock: {s_ticker} (from {s_start.strftime('%Y-%m-%d')})\")\n elif s_ticker:\n print(f\"\\n{s_intraday} Stock: {s_ticker}\")\n else:\n print(\"\\nStock: ?\")\n print(f\"Market {('CLOSED', 'OPEN')[b_is_market_open]}.\\n\")\n\n print(\n \" > disc discover trending stocks, \\t e.g. map, sectors, high short interest\"\n )\n print(\n \" > scr screener stocks, \\t\\t e.g. overview/performance, using preset filters\"\n )\n print(\" > mill papermill menu, \\t\\t menu to generate notebook reports\")\n print(\" > econ economic data, \\t\\t e.g.: FRED, events\")\n print(\n \" > pa portfolio analysis, \\t\\t supports: robinhood, alpaca, ally \"\n )\n print(\n \" > crypto cryptocurrencies, \\t\\t from: coingecko, coinmarketcap, binance\"\n )\n print(\n \" > po portfolio optimization, \\t optimal portfolio weights from pyportfolioopt\"\n )\n print(\" > gov government menu, \\t\\t congress, senate, house trading\")\n print(\" > etf etf menu, \\t\\t\\t from: StockAnalysis.com\")\n print(\" > fx forex menu, \\t\\t\\t forex support through Oanda\")\n print(\" > rc resource collection, \\t\\t e.g. hf letters\")\n\n if s_ticker:\n print(\n \" > ba behavioural analysis, \\t from: reddit, stocktwits, twitter, google\"\n )\n print(\n \" > res research web page, \\t e.g.: macroaxis, yahoo finance, fool\"\n )\n print(\n \" > ca comparison analysis, \\t e.g.: historical, correlation, financials\"\n )\n print(\n \" > fa fundamental analysis, \\t e.g.: income, balance, cash, earnings\"\n )\n print(\n \" > ta technical analysis, \\t e.g.: ema, macd, rsi, adx, bbands, obv\"\n )\n print(\n \" > bt strategy backtester, \\t e.g.: simple ema, ema cross, rsi strategies\"\n )\n print(\n \" > dd in-depth due-diligence, \\t e.g.: news, analyst, shorts, insider, sec\"\n )\n print(\n \" > eda exploratory data analysis,\\t e.g.: decompose, cusum, residuals analysis\"\n )\n print(\n \" > pred prediction techniques, \\t e.g.: regression, arima, rnn, lstm, prophet\"\n )\n print(\n \" > ra residuals analysis, \\t e.g.: model fit, qqplot, hypothesis test\"\n )\n print(\n \" > op options info, \\t e.g.: volume and open interest\"\n )\n print(\"\")\n\n\ndef clear(l_args, s_ticker, s_start, s_interval, df_stock):\n parser = argparse.ArgumentParser(\n add_help=False,\n prog=\"clear\",\n description=\"\"\"Clear previously loaded stock ticker.\"\"\",\n )\n\n try:\n ns_parser = parse_known_args_and_warn(parser, l_args)\n if not ns_parser:\n return \"\", \"\", \"\", pd.DataFrame()\n\n print(\"Clearing stock ticker to be used for analysis\\n\")\n return \"\", \"\", \"\", pd.DataFrame()\n\n except SystemExit:\n print(\"\")\n return s_ticker, s_start, s_interval, df_stock\n\n\ndef load(l_args, s_ticker, s_start, s_interval, df_stock):\n parser = argparse.ArgumentParser(\n add_help=False,\n prog=\"load\",\n description=\"Load stock ticker to perform analysis on. When the data source is 'yf', an Indian ticker can be\"\n \" loaded by using '.NS' at the end, e.g. 'SBIN.NS'. See available market in\"\n \" https://help.yahoo.com/kb/exchanges-data-providers-yahoo-finance-sln2310.html.\",\n )\n parser.add_argument(\n \"-t\",\n \"--ticker\",\n action=\"store\",\n dest=\"s_ticker\",\n required=True,\n help=\"Stock ticker\",\n )\n parser.add_argument(\n \"-s\",\n \"--start\",\n type=valid_date,\n default=\"2019-01-01\",\n dest=\"s_start_date\",\n help=\"The starting date (format YYYY-MM-DD) of the stock\",\n )\n parser.add_argument(\n \"-i\",\n \"--interval\",\n action=\"store\",\n dest=\"n_interval\",\n type=int,\n default=1440,\n choices=[1, 5, 15, 30, 60],\n help=\"Intraday stock minutes\",\n )\n parser.add_argument(\n \"--source\",\n action=\"store\",\n dest=\"source\",\n type=check_sources,\n default=\"yf\",\n help=\"Source of historical data. 'yf' and 'av' available.\",\n )\n parser.add_argument(\n \"-p\",\n \"--prepost\",\n action=\"store_true\",\n default=False,\n dest=\"b_prepost\",\n help=\"Pre/After market hours. Only works for 'yf' source, and intraday data\",\n )\n\n try:\n # For the case where a user uses: 'load BB'\n if l_args:\n if \"-\" not in l_args[0]:\n l_args.insert(0, \"-t\")\n\n ns_parser = parse_known_args_and_warn(parser, l_args)\n if not ns_parser:\n return [s_ticker, s_start, s_interval, df_stock]\n\n # Daily\n if ns_parser.n_interval == 1440:\n\n # Alpha Vantage Source\n if ns_parser.source == \"av\":\n ts = TimeSeries(key=cfg.API_KEY_ALPHAVANTAGE, output_format=\"pandas\")\n # pylint: disable=unbalanced-tuple-unpacking\n df_stock_candidate, _ = ts.get_daily_adjusted(\n symbol=ns_parser.s_ticker, outputsize=\"full\"\n )\n\n # Check that loading a stock was not successful\n if df_stock_candidate.empty:\n print(\"\")\n return [s_ticker, s_start, s_interval, df_stock]\n\n # pylint: disable=no-member\n df_stock_candidate.sort_index(ascending=True, inplace=True)\n\n # Slice dataframe from the starting date YYYY-MM-DD selected\n df_stock_candidate = df_stock_candidate[ns_parser.s_start_date :]\n\n # Yahoo Finance Source\n elif ns_parser.source == \"yf\":\n df_stock_candidate = yf.download(\n ns_parser.s_ticker, start=ns_parser.s_start_date, progress=False\n )\n\n # Check that loading a stock was not successful\n if df_stock_candidate.empty:\n print(\"\")\n return [s_ticker, s_start, s_interval, df_stock]\n\n df_stock_candidate = df_stock_candidate.rename(\n columns={\n \"Open\": \"1. open\",\n \"High\": \"2. high\",\n \"Low\": \"3. low\",\n \"Close\": \"4. close\",\n \"Adj Close\": \"5. adjusted close\",\n \"Volume\": \"6. volume\",\n }\n )\n df_stock_candidate.index.name = \"date\"\n\n # Check if start time from dataframe is more recent than specified\n if df_stock_candidate.index[0] > pd.to_datetime(ns_parser.s_start_date):\n s_start = df_stock_candidate.index[0]\n else:\n s_start = ns_parser.s_start_date\n\n # Intraday\n else:\n\n # Alpha Vantage Source\n if ns_parser.source == \"av\":\n ts = TimeSeries(key=cfg.API_KEY_ALPHAVANTAGE, output_format=\"pandas\")\n # pylint: disable=unbalanced-tuple-unpacking\n df_stock_candidate, _ = ts.get_intraday(\n symbol=ns_parser.s_ticker,\n outputsize=\"full\",\n interval=str(ns_parser.n_interval) + \"min\",\n )\n\n # Check that loading a stock was not successful\n if df_stock_candidate.empty:\n print(\"\")\n return [s_ticker, s_start, s_interval, df_stock]\n\n # pylint: disable=no-member\n df_stock_candidate.sort_index(ascending=True, inplace=True)\n\n # Slice dataframe from the starting date YYYY-MM-DD selected\n df_stock_candidate = df_stock_candidate[ns_parser.s_start_date :]\n\n # Check if start time from dataframe is more recent than specified\n if df_stock_candidate.index[0] > pd.to_datetime(ns_parser.s_start_date):\n s_start = df_stock_candidate.index[0]\n else:\n s_start = ns_parser.s_start_date\n\n # Yahoo Finance Source\n elif ns_parser.source == \"yf\":\n s_int = str(ns_parser.n_interval) + \"m\"\n\n d_granularity = {\"1m\": 6, \"5m\": 59, \"15m\": 59, \"30m\": 59, \"60m\": 729}\n\n s_start_dt = datetime.utcnow() - timedelta(days=d_granularity[s_int])\n s_date_start = s_start_dt.strftime(\"%Y-%m-%d\")\n\n if s_start_dt > ns_parser.s_start_date:\n # Using Yahoo Finance with granularity {s_int} the starting date is set to: {s_date_start}\n\n df_stock_candidate = yf.download(\n ns_parser.s_ticker,\n start=s_date_start,\n progress=False,\n interval=s_int,\n prepost=ns_parser.b_prepost,\n )\n\n else:\n df_stock_candidate = yf.download(\n ns_parser.s_ticker,\n start=ns_parser.s_start_date.strftime(\"%Y-%m-%d\"),\n progress=False,\n interval=s_int,\n prepost=ns_parser.b_prepost,\n )\n\n # Check that loading a stock was not successful\n if df_stock_candidate.empty:\n print(\"\")\n return [s_ticker, s_start, s_interval, df_stock]\n\n if s_start_dt > ns_parser.s_start_date:\n s_start = pytz.utc.localize(s_start_dt)\n else:\n s_start = ns_parser.s_start_date\n\n df_stock_candidate = df_stock_candidate.rename(\n columns={\n \"Open\": \"1. open\",\n \"High\": \"2. high\",\n \"Low\": \"3. low\",\n \"Close\": \"4. close\",\n \"Adj Close\": \"5. adjusted close\",\n \"Volume\": \"6. volume\",\n }\n )\n df_stock_candidate.index.name = \"date\"\n\n s_intraday = (f\"Intraday {s_interval}\", \"Daily\")[ns_parser.n_interval == 1440]\n\n print(\n f\"Loading {s_intraday} {ns_parser.s_ticker.upper()} stock \"\n f\"with starting period {s_start.strftime('%Y-%m-%d')} for analysis.\\n\"\n )\n\n return [\n ns_parser.s_ticker.upper(),\n s_start,\n str(ns_parser.n_interval) + \"min\",\n df_stock_candidate,\n ]\n\n except Exception as e:\n print(e, \"\\nEither the ticker or the API_KEY are invalids. Try again!\\n\")\n return [s_ticker, s_start, s_interval, df_stock]\n\n except SystemExit:\n print(\"\")\n return [s_ticker, s_start, s_interval, df_stock]\n\n\ndef candle(s_ticker: str, s_start: str):\n df_stock = trend.load_ticker(s_ticker, s_start)\n df_stock = trend.find_trendline(df_stock, \"OC_High\", \"high\")\n df_stock = trend.find_trendline(df_stock, \"OC_Low\", \"low\")\n\n mc = mpf.make_marketcolors(\n up=\"green\", down=\"red\", edge=\"black\", wick=\"black\", volume=\"in\", ohlc=\"i\"\n )\n\n s = mpf.make_mpf_style(marketcolors=mc, gridstyle=\":\", y_on_right=True)\n\n ap0 = []\n\n if \"OC_High_trend\" in df_stock.columns:\n ap0.append(\n mpf.make_addplot(df_stock[\"OC_High_trend\"], color=\"g\"),\n )\n\n if \"OC_Low_trend\" in df_stock.columns:\n ap0.append(\n mpf.make_addplot(df_stock[\"OC_Low_trend\"], color=\"b\"),\n )\n\n if gtff.USE_ION:\n plt.ion()\n\n mpf.plot(\n df_stock,\n type=\"candle\",\n mav=(20, 50),\n volume=True,\n title=f\"\\n{s_ticker} - Last 6 months\",\n addplot=ap0,\n xrotation=10,\n style=s,\n figratio=(10, 7),\n figscale=1.10,\n figsize=(plot_autoscale()),\n update_width_config=dict(\n candle_linewidth=1.0, candle_width=0.8, volume_linewidth=1.0\n ),\n )\n print(\"\")\n\n\ndef quote(l_args: List[str], s_ticker: str):\n parser = argparse.ArgumentParser(\n add_help=False,\n prog=\"quote\",\n description=\"Current quote for stock ticker\",\n )\n\n if s_ticker:\n parser.add_argument(\n \"-t\",\n \"--ticker\",\n action=\"store\",\n dest=\"s_ticker\",\n default=s_ticker,\n help=\"Stock ticker\",\n )\n else:\n parser.add_argument(\n \"-t\",\n \"--ticker\",\n action=\"store\",\n dest=\"s_ticker\",\n required=True,\n help=\"Stock ticker\",\n )\n\n try:\n # For the case where a user uses: 'quote BB'\n if l_args:\n if \"-\" not in l_args[0]:\n l_args.insert(0, \"-t\")\n ns_parser = parse_known_args_and_warn(parser, l_args)\n if not ns_parser:\n return\n\n except SystemExit:\n print(\"\")\n return\n\n ticker = yf.Ticker(ns_parser.s_ticker)\n\n try:\n quote_df = pd.DataFrame(\n [\n {\n \"Symbol\": ticker.info[\"symbol\"],\n \"Name\": ticker.info[\"shortName\"],\n \"Price\": ticker.info[\"regularMarketPrice\"],\n \"Open\": ticker.info[\"regularMarketOpen\"],\n \"High\": ticker.info[\"dayHigh\"],\n \"Low\": ticker.info[\"dayLow\"],\n \"Previous Close\": ticker.info[\"previousClose\"],\n \"Volume\": ticker.info[\"volume\"],\n \"52 Week High\": ticker.info[\"fiftyTwoWeekHigh\"],\n \"52 Week Low\": ticker.info[\"fiftyTwoWeekLow\"],\n }\n ]\n )\n\n quote_df[\"Change\"] = quote_df[\"Price\"] - quote_df[\"Previous Close\"]\n quote_df[\"Change %\"] = quote_df.apply(\n lambda x: \"{:.2f}%\".format((x[\"Change\"] / x[\"Previous Close\"]) * 100),\n axis=\"columns\",\n )\n for c in [\n \"Price\",\n \"Open\",\n \"High\",\n \"Low\",\n \"Previous Close\",\n \"52 Week High\",\n \"52 Week Low\",\n \"Change\",\n ]:\n quote_df[c] = quote_df[c].apply(lambda x: f\"{x:.2f}\")\n quote_df[\"Volume\"] = quote_df[\"Volume\"].apply(lambda x: f\"{x:,}\")\n\n quote_df = quote_df.set_index(\"Symbol\")\n\n quote_data = transpose(quote_df)\n\n print(\n tabulate(\n quote_data,\n headers=quote_data.columns,\n tablefmt=\"fancy_grid\",\n stralign=\"right\",\n )\n )\n except KeyError:\n print(f\"Invalid stock ticker: {ns_parser.s_ticker}\")\n\n print(\"\")\n return\n\n\ndef view(l_args, s_ticker, s_start, s_interval, df_stock):\n parser = argparse.ArgumentParser(\n add_help=False,\n prog=\"view\",\n description=\"Visualize historical data of a stock. An alpha_vantage key is necessary.\",\n )\n if s_ticker:\n parser.add_argument(\n \"-t\",\n \"--ticker\",\n action=\"store\",\n dest=\"s_ticker\",\n default=s_ticker,\n help=\"Stock ticker\",\n )\n else:\n parser.add_argument(\n \"-t\",\n \"--ticker\",\n action=\"store\",\n dest=\"s_ticker\",\n required=True,\n help=\"Stock ticker\",\n )\n parser.add_argument(\n \"-s\",\n \"--start\",\n type=valid_date,\n dest=\"s_start_date\",\n default=s_start,\n help=\"The starting date (format YYYY-MM-DD) of the stock\",\n )\n parser.add_argument(\n \"-i\",\n \"--interval\",\n action=\"store\",\n dest=\"n_interval\",\n type=int,\n default=0,\n choices=[1, 5, 15, 30, 60],\n help=\"Intraday stock minutes\",\n )\n parser.add_argument(\n \"--type\",\n action=\"store\",\n dest=\"type\",\n type=check_ohlc,\n default=\"a\", # in case it's adjusted close\n help=(\n \"ohlc corresponds to types: open; high; low; close; \"\n \"while oc corresponds to types: open; close\"\n ),\n )\n\n try:\n ns_parser = parse_known_args_and_warn(parser, l_args)\n if not ns_parser:\n return\n\n except SystemExit:\n print(\"\")\n return\n\n # Update values:\n if ns_parser.s_ticker != s_ticker:\n if ns_parser.n_interval > 0:\n s_ticker, s_start, s_interval, df_stock = load(\n [\n \"-t\",\n ns_parser.s_ticker,\n \"-s\",\n ns_parser.s_start_date.strftime(\"%Y-%m-%d\"),\n \"-i\",\n ns_parser.n_interval,\n ],\n s_ticker,\n s_start,\n s_interval,\n df_stock,\n )\n else:\n s_ticker, s_start, s_interval, df_stock = load(\n [\n \"-t\",\n ns_parser.s_ticker,\n \"-s\",\n ns_parser.s_start_date.strftime(\"%Y-%m-%d\"),\n ],\n s_ticker,\n s_start,\n s_interval,\n df_stock,\n )\n\n # A new interval intraday period was given\n if ns_parser.n_interval != 0:\n s_interval = str(ns_parser.n_interval) + \"min\"\n\n type_candles = lett_to_num(ns_parser.type)\n\n df_stock.sort_index(ascending=True, inplace=True)\n\n # Slice dataframe from the starting date YYYY-MM-DD selected\n df_stock = df_stock[ns_parser.s_start_date :]\n\n # Daily\n if s_interval == \"1440min\":\n # The default doesn't exist for intradaily data\n ln_col_idx = [int(x) - 1 for x in list(type_candles)]\n # Check that the types given are not bigger than 4, as there are only 5 types (0-4)\n # pylint: disable=len-as-condition\n if len([i for i in ln_col_idx if i > 4]) > 0:\n print(\"An index bigger than 4 was given, which is wrong. Try again\")\n return\n # Append last column of df to be filtered which corresponds to: 6. Volume\n ln_col_idx.append(5)\n # Intraday\n else:\n # The default doesn't exist for intradaily data\n if ns_parser.type == \"a\":\n ln_col_idx = [3]\n else:\n ln_col_idx = [int(x) - 1 for x in list(type_candles)]\n # Check that the types given are not bigger than 3, as there are only 4 types (0-3)\n # pylint: disable=len-as-condition\n if len([i for i in ln_col_idx if i > 3]) > 0:\n print(\"An index bigger than 3 was given, which is wrong. Try again\")\n return\n # Append last column of df to be filtered which corresponds to: 5. Volume\n ln_col_idx.append(4)\n\n # Plot view of the stock\n plot_view_stock(df_stock.iloc[:, ln_col_idx], ns_parser.s_ticker)\n\n\ndef export(l_args, df_stock):\n parser = argparse.ArgumentParser(\n add_help=False,\n prog=\"export\",\n description=\"Exports the historical data from this ticker to a file or stdout.\",\n )\n parser.add_argument(\n \"-f\",\n \"--filename\",\n type=str,\n dest=\"s_filename\",\n default=stdout,\n help=\"Name of file to save the historical data exported (stdout if unspecified)\",\n )\n parser.add_argument(\n \"-F\",\n \"--format\",\n dest=\"s_format\",\n type=str,\n default=\"csv\",\n help=\"Export historical data into following formats: csv, json, excel, clipboard\",\n )\n try:\n ns_parser = parse_known_args_and_warn(parser, l_args)\n if not ns_parser:\n return\n\n except SystemExit:\n print(\"\")\n return\n\n if df_stock.empty:\n print(\"No data loaded yet to export.\")\n return\n\n if ns_parser.s_format == \"csv\":\n df_stock.to_csv(ns_parser.s_filename)\n\n elif ns_parser.s_format == \"json\":\n df_stock.to_json(ns_parser.s_filename)\n\n elif ns_parser.s_format == \"excel\":\n df_stock.to_excel(ns_parser.s_filename)\n\n elif ns_parser.s_format == \"clipboard\":\n df_stock.to_clipboard()\n\n print(\"\")\n\n\ndef print_goodbye():\n goodbye_msg = [\n \"An informed ape, is a strong ape. \",\n \"Remember that stonks only go up. \",\n \"Diamond hands. \",\n \"Apes together strong. \",\n \"This is our way. \",\n \"Keep the spacesuit ape, we haven't reached the moon yet. \",\n \"I am not a cat. I'm an ape. \",\n \"We like the terminal. \",\n ]\n\n goodbye_hr = datetime.now().hour\n if goodbye_hr < 5:\n goodbye_msg_time = \"Go get some rest soldier!\"\n elif goodbye_hr < 11:\n goodbye_msg_time = \"Rise and shine baby!\"\n elif goodbye_hr < 17:\n goodbye_msg_time = \"Enjoy your day!\"\n elif goodbye_hr < 23:\n goodbye_msg_time = \"Tomorrow's another day!\"\n else:\n goodbye_msg_time = \"Go get some rest soldier!\"\n\n print(\n goodbye_msg[random.randint(0, len(goodbye_msg) - 1)] + goodbye_msg_time + \"\\n\"\n )\n\n\ndef sha256sum(filename):\n h = hashlib.sha256()\n b = bytearray(128 * 1024)\n mv = memoryview(b)\n with open(filename, \"rb\", buffering=0) as f:\n for n in iter(lambda: f.readinto(mv), 0):\n h.update(mv[:n])\n return h.hexdigest()\n\n\ndef update_terminal():\n poetry_hash = sha256sum(\"poetry.lock\")\n\n completed_process = subprocess.run(\"git pull\", shell=True, check=False)\n if completed_process.returncode != 0:\n return completed_process.returncode\n\n new_poetry_hash = sha256sum(\"poetry.lock\")\n\n if poetry_hash == new_poetry_hash:\n print(\"Great, seems like poetry hasn't been updated!\")\n return completed_process.returncode\n print(\n \"Seems like more modules have been added, grab a coke, this may take a while.\"\n )\n\n completed_process = subprocess.run(\"poetry install\", shell=True, check=False)\n if completed_process.returncode != 0:\n return completed_process.returncode\n\n return 0\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.use",
"matplotlib.pyplot.minorticks_on",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlim",
"pandas.plotting.register_matplotlib_converters",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"pandas._config.config.get_option",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ion",
"matplotlib.pyplot.ylabel"
],
[
"numpy.core.fromnumeric.transpose",
"matplotlib.pyplot.ion",
"pandas.to_datetime",
"pandas.DataFrame"
]
] |
ninoch/UDAGCN
|
[
"f1e1111f188b3f4738b7cdefea20d5ca4370e22a"
] |
[
"dual_gnn/cached_gcn_conv.py"
] |
[
"import torch\nfrom torch.nn import Parameter\nfrom torch_scatter import scatter_add\nfrom torch_geometric.nn.conv import MessagePassing\nfrom torch_geometric.utils import add_remaining_self_loops\n\nfrom torch_geometric.nn.inits import glorot, zeros\n\n\nclass CachedGCNConv(MessagePassing):\n r\"\"\"The graph convolutional operator from the `\"Semi-supervised\n Classification with Graph Convolutional Networks\"\n <https://arxiv.org/abs/1609.02907>`_ paper\n\n .. math::\n \\mathbf{X}^{\\prime} = \\mathbf{\\hat{D}}^{-1/2} \\mathbf{\\hat{A}}\n \\mathbf{\\hat{D}}^{-1/2} \\mathbf{X} \\mathbf{\\Theta},\n\n where :math:`\\mathbf{\\hat{A}} = \\mathbf{A} + \\mathbf{I}` denotes the\n adjacency matrix with inserted self-loops and\n :math:`\\hat{D}_{ii} = \\sum_{j=0} \\hat{A}_{ij}` its diagonal degree matrix.\n\n Args:\n in_channels (int): Size of each input sample.\n out_channels (int): Size of each output sample.\n improved (bool, optional): If set to :obj:`True`, the layer computes\n :math:`\\mathbf{\\hat{A}}` as :math:`\\mathbf{A} + 2\\mathbf{I}`.\n (default: :obj:`False`)\n cached (bool, optional): If set to :obj:`True`, the layer will cache\n the computation of :math:`\\mathbf{\\hat{D}}^{-1/2} \\mathbf{\\hat{A}}\n \\mathbf{\\hat{D}}^{-1/2}` on first execution, and will use the\n cached version for further executions.\n This parameter should only be set to :obj:`True` in transductive\n learning scenarios. (default: :obj:`False`)\n bias (bool, optional): If set to :obj:`False`, the layer will not learn\n an additive bias. (default: :obj:`True`)\n **kwargs (optional): Additional arguments of\n :class:`torch_geometric.nn.conv.MessagePassing`.\n \"\"\"\n\n def __init__(self, in_channels, out_channels,\n weight=None,\n bias=None,\n improved=False,\n use_bias=True, **kwargs):\n super().__init__(aggr='add', **kwargs)\n\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.improved = improved\n self.cache_dict = {}\n\n # self.weight = Parameter(torch.Tensor(in_channels, out_channels))\n #\n # if bias:\n # self.bias = Parameter(torch.Tensor(out_channels))\n # else:\n # self.register_parameter('bias', None)\n\n\n if weight is None:\n self.weight = Parameter(torch.Tensor(in_channels, out_channels).to(torch.float32))\n glorot(self.weight)\n else:\n self.weight = weight\n print(\"use shared weight\")\n\n if bias is None:\n if use_bias:\n self.bias = Parameter(torch.Tensor(out_channels).to(torch.float32))\n else:\n self.register_parameter('bias', None)\n zeros(self.bias)\n else:\n self.bias = bias\n print(\"use shared bias\")\n\n # self.reset_parameters()\n\n # def reset_parameters(self):\n # glorot(self.weight)\n # zeros(self.bias)\n # self.cached_result = None\n # self.cached_num_edges = None\n\n @staticmethod\n def norm(edge_index, num_nodes, edge_weight=None, improved=False,\n dtype=None):\n if edge_weight is None:\n edge_weight = torch.ones((edge_index.size(1), ), dtype=dtype,\n device=edge_index.device)\n\n fill_value = 1 if not improved else 2\n edge_index, edge_weight = add_remaining_self_loops(\n edge_index, edge_weight, fill_value, num_nodes)\n\n row, col = edge_index\n deg = scatter_add(edge_weight, row, dim=0, dim_size=num_nodes)\n deg_inv_sqrt = deg.pow(-0.5)\n deg_inv_sqrt[deg_inv_sqrt == float('inf')] = 0\n\n return edge_index, deg_inv_sqrt[row] * edge_weight * deg_inv_sqrt[col]\n\n def forward(self, x, edge_index, cache_name=\"default_cache\", edge_weight=None):\n \"\"\"\"\"\"\n\n x = torch.matmul(x, self.weight)\n\n if not cache_name in self.cache_dict:\n edge_index, norm = self.norm(edge_index, x.size(0), edge_weight,\n self.improved, x.dtype)\n self.cache_dict[cache_name] = edge_index, norm\n else:\n edge_index, norm = self.cache_dict[cache_name]\n\n\n return self.propagate(edge_index, x=x, norm=norm)\n\n def message(self, x_j, norm):\n return norm.view(-1, 1) * x_j\n\n def update(self, aggr_out):\n if self.bias is not None:\n aggr_out = aggr_out + self.bias\n return aggr_out\n\n def __repr__(self):\n return '{}({}, {})'.format(self.__class__.__name__, self.in_channels,\n self.out_channels)\n"
] |
[
[
"torch.matmul",
"torch.Tensor"
]
] |
juliob29/BitcoinTalk-Insights
|
[
"73033791698c67bb1f6268dc0b762832f0e097dd"
] |
[
"skill/utils.py"
] |
[
"\"\"\"\nUtility functions for testing different search \nalgorithms implemented in this skill.\n\"\"\"\nimport signal\nimport numpy as np\n\nfrom functools import wraps\n\n\nclass LossFunctions:\n \"\"\"\n Loss functions to evaluate the performance\n of search algorithms. All methods available in \n this class take numpy arrays as input.\n\n Methods\n -------\n mape:\n Mean averaged percentage error.\n rmse:\n Root mean squared error.\n mse:\n Mean squared error.\n \"\"\"\n @staticmethod\n def mape(A, B):\n \"\"\"\n Calculates the mean absolute persentage error\n from two series. Original solution from:\n \n https://stats.stackexchange.com/questions/58391/\\\n mean-absolute-percentage-error-mape-in-scikit-learn\n \n Parameters\n ----------\n A, B: numpy.array\n Numpy arrays with the same length with the\n two objects representing the results (A)\n and test data (B).\n\n Returns\n -------\n float\n Floating number in the domain [0, 1].\n \"\"\"\n #\n # Let's add 1 to all values\n # to avoid division by zero.\n #\n A += 0.000000000001\n B += 0.000000000001\n return np.round(np.mean(np.abs(A - B) / A) * 100, 2)\n\n @staticmethod\n def rmse(A, B):\n \"\"\"\n Calculates the root mean square error from\n two series. Original solution from:\n\n https://stackoverflow.com/questions/16774849\\\n /mean-squared-error-in-numpy\n\n Parameters\n ----------\n A, B: numpy.array\n Numpy arrays with the same length with the\n two objects representing the results (A)\n and test data (B).\n\n Returns\n -------\n float\n Floating number in the same domain\n of the original data.\n \"\"\"\n return np.round(np.sqrt(np.square(np.subtract(A, B)).mean()), 2)\n \n @staticmethod\n def mse(A, B):\n \"\"\"\n Calculates the mean square error from\n two series. Original solution from:\n\n https://stackoverflow.com/questions/16774849\\\n /mean-squared-error-in-numpy\n\n Parameters\n ----------\n A, B: numpy.array\n Numpy arrays with the same length with the\n two objects representing the results (A)\n and test data (B).\n\n Returns\n -------\n float\n Floating number in the squared domain\n of the original data.\n \"\"\"\n return np.round(np.square(np.subtract(A, B)).mean(), 2)\n"
] |
[
[
"numpy.subtract",
"numpy.abs"
]
] |
dcroote/madic
|
[
"fb00f312f5abc9f5a0bfc4a00a5a2e6e1c4ee563"
] |
[
"madic/interference.py"
] |
[
"from __future__ import division\nimport numpy as np\nfrom madic import qc\nimport logging\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef _req_tr_for_interference(vals):\n \"\"\" Scaling function for minimum transition ratio deemed interference\n\n Linear scaling between 0.7 and 0.95 for reference transition ratios\n between 0.4 and 0.7 with a floor of 0.7 and a ceiling of 0.95 otherwise\n\n This is useful because some peptides will naturally have skewed\n transition ratios due to a single strong transition. Therefore, for\n these transitions to qualify as interference, the threshold minimum\n transition ratio must be higher.\n\n Args:\n vals (int or np.array)\n\n Returns:\n Minimum transition ratio value(s) (int or np.array)\n \"\"\"\n\n tr_ceil = 0.95\n tr_floor = 0.7\n # x_ceil = 0.7\n # x_floor = 0.4\n\n # precomputed y = mx + b\n # m = (tr_ceil - tr_floor) / (x_ceil - x_floor)\n # b = tr_floor - m*x_floor\n m = 0.833333\n b = 0.366667\n\n reg = vals*m + b\n\n return np.max([np.min([reg, tr_ceil]), tr_floor])\n\n\ndef identify_interference(df, sn_ratio_min=10.0, area_min=2000.0):\n \"\"\" Identify interference in MRM data\n\n Note:\n Operates under the following assumptions:\n * Interference will dominate transition ratio\n * Interference has greater intensity than general noise\n\n Args:\n df (pd.DataFrame): loaded using :func:`io.read_transition_report`\n sn_ratio_min (float): minimum signal (interference) to noise ratio\n to classify as interference\n area_min (float): minimum area (within RT bounds) to classify as\n interference\n\n Returns:\n Original pd.DataFrame with addition bool column indicating interference\n \"\"\"\n\n df = df.copy()\n sub = df.copy()\n\n # limit to peptides failing transition ratio QC\n sub = sub[(~sub.pass_transition_ratio)]\n\n # avoid false positives of peptides with naturally unequal trans ratios\n # by scaling required trans ratio for interference according to the ref\n # trans ratio\n sub['min_tr_for_interference'] = sub.ref_tr.transform(\n _req_tr_for_interference)\n sub = sub[sub.transition_ratio > sub.min_tr_for_interference]\n\n # require distinguished peak (high signal to noise) for interference\n _tsn = []\n for _, row in sub.iterrows():\n _tsn.append(qc._calc_sn(row.times_arr,\n row.intensities_arr,\n row.rt_start,\n row.rt_end))\n\n sub['transition_sn'] = _tsn\n sub = sub[sub.transition_sn >= sn_ratio_min]\n\n # low threshold avoids false positive low intensity spikes\n # in an otherwise low intensity chromatogram\n sub = sub[sub.area >= area_min]\n logger.info(\"Found {} instances of transition \"\n \"interference.\".format(sub.shape[0]))\n\n # merge back into original dataframe\n df['interference'] = False\n df.loc[sub.index, 'interference'] = True\n\n return df\n"
] |
[
[
"numpy.min"
]
] |
ksu-is/sports-betting
|
[
"71d6f128bc516fc8f26decad60c2f7fd6f828945"
] |
[
"sportsbet/datasets/_utils.py"
] |
[
"\"\"\"\nIncludes utilities to download and transform data.\n\"\"\"\n\nfrom abc import abstractmethod, ABCMeta\nfrom difflib import SequenceMatcher\nfrom datetime import datetime, timedelta\nfrom itertools import product\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import ParameterGrid\nfrom sklearn.utils import Bunch, check_scalar\n\n\ndef _combine_odds(odds):\n \"\"\"Combine odds of different targets.\"\"\"\n combined_odds = 1 / (1 / odds).sum(axis=1)\n return combined_odds\n\n\ndef _create_names_mapping_table(left_data, right_data):\n \"\"\"Create names mapping table.\"\"\"\n\n # Rename columns\n key_columns = ['key0', 'key1']\n left_data.columns = key_columns + ['left_team1', 'left_team2']\n right_data.columns = key_columns + ['right_team1', 'right_team2']\n\n # Generate teams names combinations\n names_combinations = pd.merge(left_data, right_data, how='outer').dropna().drop(columns=key_columns).reset_index(drop=True)\n\n # Calculate similarity index\n similarity = names_combinations.apply(lambda row: SequenceMatcher(None, row.left_team1, row.right_team1).ratio() * SequenceMatcher(None, row.left_team2, row.right_team2).ratio(), axis=1)\n\n # Append similarity index\n names_combinations_similarity = pd.concat([names_combinations, similarity], axis=1)\n\n # Filter correct matches\n indices = names_combinations_similarity.groupby(['left_team1', 'left_team2'])[0].idxmax().values\n names_matching = names_combinations.take(indices)\n\n # Teams matching\n matching1 = names_matching.loc[:, ['left_team1', 'right_team1']].rename(columns={'left_team1': 'left_team', 'right_team1': 'right_team'})\n matching2 = names_matching.loc[:, ['left_team2', 'right_team2']].rename(columns={'left_team2': 'left_team', 'right_team2': 'right_team'})\n \n # Combine matching\n matching = matching1.append(matching2)\n matching = matching.groupby(matching.columns.tolist()).size().reset_index()\n indices = matching.groupby('left_team')[0].idxmax().values\n \n # Generate mapping\n names_mapping = matching.take(indices).drop(columns=0).reset_index(drop=True)\n\n return names_mapping\n\n\nclass _DataLoader(metaclass=ABCMeta):\n \"\"\"Base class to load data for model training and testing.\n\n parameters\n ----------\n config : list of tuples\n The configuration of the data preprocessing stage. It contains tuples\n with each tuple having four elements. The first one is the initial\n column name (None for a created column), the second one is the final column\n name (None for a removed column), the third one is the column data type\n and the last one is the id of an output columns (None if it is not an\n output column).\n \n targets : list of tuples\n It defines the calculation of the target columns. It contains tuples\n with each tuple having three elements. The first one is the name of the\n created target column, the second is a function that accepts as input\n the output columns and generates a binary target and the third one is\n the id of the output columns.\n\n param_grid : dict of str to sequence, or sequence of such parameter, default=None\n The parameter grid to explore, as a dictionary mapping data parameters\n to sequences of allowed values. An empty dict signifies default\n parameters. A sequence of dicts signifies a sequence of grids to search,\n and is useful to avoid exploring parameter combinations that do not\n exist. The default value corresponds to all parameters.\n \n drop_na_cols : float, default=None\n The threshold of input columns with missing values to drop. It is a\n float in the [0.0, 1.0] range. The default value ``None``\n corresponds to ``0.0`` i.e. all columns are kept while the value\n ``1.0`` keeps only columns with non missing values.\n \n drop_na_rows : float, default=None\n The threshold of rows with missing values to drop. It is a\n float in the [0.0, 1.0] range. The default value ``None``\n corresponds to ``0.0`` i.e. all rows are kept while the value\n ``1.0`` keeps only rows with non missing values.\n \n odds_type : str, default=None\n The prefix of the odds column to be used for generating the odds\n data. The default value does not return any odds data.\n \n testing_duration : int, default=None\n The number of future weeks to include in the testing data. The\n default value corresponds to one week.\n \"\"\"\n\n def __init__(self, config, targets, param_grid=None, drop_na_cols=None, drop_na_rows=None, odds_type=None, testing_duration=None):\n self.config = config\n self.targets = targets\n self.param_grid = param_grid\n self.drop_na_cols = drop_na_cols\n self.drop_na_rows = drop_na_rows\n self.odds_type = odds_type\n self.testing_duration = testing_duration\n\n def _fetch(self, return_only_params, **load_params):\n \"\"\"Fetch the full parameter grid and the data.\"\"\"\n self._fetch_full_param_grid(**load_params)\n if not return_only_params:\n self._check_parameters()._check_param_grid()._fetch_data(**load_params)._check_data()._check_cols()._transform_data()\n return self\n \n def _fetch_full_param_grid(self, **load_params):\n \"\"\"Fetch the full parameter grid.\"\"\"\n self.full_param_grid_ = None\n return self\n \n def _check_parameters(self):\n \"\"\"Check input parameters.\"\"\"\n\n # Check parameter to drop columns\n self.drop_na_cols_ = self.drop_na_cols if self.drop_na_cols is not None else 0.0\n check_scalar(self.drop_na_cols_, 'drop_na_cols', float, min_val=0.0, max_val=1.0)\n \n # Check parameter to drop rows\n self.drop_na_rows_ = self.drop_na_rows if self.drop_na_rows is not None else 0.0\n check_scalar(self.drop_na_rows_, 'drop_na_cols', float, min_val=0.0, max_val=1.0)\n\n # Check testing duration\n self.testing_duration_ = self.testing_duration if self.testing_duration is not None else 1\n check_scalar(self.testing_duration_, 'testing_duration', int, min_val=1)\n\n # Check odds type\n if self.odds_type is not None:\n if not isinstance(self.odds_type, str):\n raise TypeError(f'Parameter `odds_type` should be a string or None. Got {type(self.odds_type)} instead.')\n cols_odds = [col for _, col, _ in self.config if col is not None and col.split('__')[0] == self.odds_type and col.split('__')[-1] == 'odds']\n if not cols_odds:\n raise ValueError(f'Parameter `odds_type` should be a prefix of available odds columns. Got {self.odds_type} instead.')\n self.odds_type_ = self.odds_type\n else:\n self.odds_type_ = ''\n \n return self\n\n def _check_param_grid(self):\n \"\"\"Check parameter grid.\"\"\"\n if self.param_grid is not None and self.full_param_grid_ is not None:\n param_grid = ParameterGrid(self.param_grid)\n param_grid_df = pd.DataFrame(param_grid)\n full_param_grid_df = pd.DataFrame(self.full_param_grid_)\n if np.any(pd.merge(param_grid_df, full_param_grid_df, how='left').isna()):\n raise ValueError(f'Parameter grid includes values not allowed by available data.')\n else:\n param_grid_df = pd.merge(param_grid_df, full_param_grid_df)\n self.param_grid_ = ParameterGrid([{k: [v] for k, v in row.to_dict().items()} for ind, row in param_grid_df.iterrows()])\n else:\n self.param_grid_ = self.full_param_grid_\n return self\n \n @abstractmethod\n def _fetch_data(self, **load_params):\n \"\"\"Fetch the data.\"\"\"\n self.data_ = pd.DataFrame()\n return self\n \n def _check_data(self):\n \"\"\"Check data format, rename and drop columns.\"\"\"\n if not isinstance(self.data_, pd.DataFrame):\n raise TypeError(f'Attribute `data_` should be a pandas dataframe. Got {type(self.data_).__name__} instead.')\n if self.data_.size == 0:\n raise ValueError(f'Attribute `data_` should be a pandas dataframe with positive size.')\n if 'test' not in self.data_.columns:\n raise KeyError('Attribute `data_` should include a boolean column `test` to distinguish between train and test data.')\n cols_removed = pd.Index([old_col for old_col, new_col, _ in self.config if new_col is None and old_col in self.data_], dtype=object)\n cols_rename_mapping = {old_col: new_col for old_col, new_col, _ in self.config if old_col is not None and new_col is not None}\n self.data_ = self.data_.drop(columns=cols_removed).rename(columns=cols_rename_mapping)\n set(self.data_.columns).difference([col for _, col, _ in self.config if col is not None])\n if not set(self.data_.columns).issubset():\n raise ValueError(f'Columns {self.data_.columns} of attribute `data_` should be included in the schema.')\n return self\n \n def _check_cols(self):\n \"\"\"Check columns.\"\"\"\n \n # Inputs\n self.cols_inputs_ = pd.Index([col for col in self.data_.columns if len(col.split('__')) != 2 and col != 'test'], dtype=object)\n \n # Targets\n targets = pd.DataFrame([target.split('__') for target, _ in self.targets], columns=['target', 'key'])\n\n # Odds\n odds = []\n for col in self.data_:\n splitted_col = col.split('__')\n if splitted_col[0] == self.odds_type_ and splitted_col[-1] == 'odds':\n odds.append((col, '__'.join(splitted_col[1:-1])))\n odds = pd.merge(pd.DataFrame(odds, columns=['odd', 'target']), targets)\n \n # Outputs\n outputs = [(col, col.split('__')[-1]) for col in self.data_.columns if col.split('__')[-1] != 'odds']\n outputs = pd.DataFrame(outputs, columns=['output', 'key']).dropna()\n outputs = pd.merge(outputs, targets)\n \n if odds.size:\n odds = outputs = pd.merge(odds, outputs)\n self.cols_odds_ = pd.Index(odds['odd'].unique(), dtype=object)\n self.cols_outputs_ = pd.Index(outputs['output'].unique(), dtype=object)\n\n return self\n\n def _transform_data(self):\n \"\"\"Rename, drop and change data type of columns.\"\"\"\n \n # Drop rows with only missing values\n mask = self.data_['test']\n data_train, data_test = self.data_[~mask].drop(columns=['test']), self.data_[mask].drop(columns=['test'])\n data_train_init = data_train.copy()\n \n # Drop columns and rows with missing values\n data_train = data_train.dropna(how='all', axis=0)\n if self.drop_na_cols_ > 0.0:\n data_train_dropped_na_cols = data_train[self.cols_inputs_].dropna(axis=1, thresh=int(data_train.shape[0] * self.drop_na_cols_))\n data_train_dropped_na_cols.drop(columns=self.cols_odds_.intersection(data_train_dropped_na_cols.columns), inplace=True)\n data_train = pd.concat([\n data_train_dropped_na_cols,\n data_train[self.cols_outputs_.append(self.cols_odds_)]\n ], axis=1)\n if self.drop_na_rows_ > 0.0:\n data_train = data_train.dropna(how='any', axis=0, subset=self.cols_outputs_.append(self.cols_odds_))\n data_train = data_train.dropna(axis=0, subset=self.cols_inputs_.intersection(data_train.columns), thresh=int(data_train.shape[1] * self.drop_na_rows_))\n self.dropped_na_cols_ = data_train_init.columns.difference(data_train.columns, sort=False)\n self.cols_inputs_ = self.cols_inputs_.difference(self.dropped_na_cols_, sort=False)\n self.dropped_na_rows_ = data_train_init.index.difference(data_train.index)\n \n # Combine data\n cols_init = [col for col in data_train_init if col in data_train]\n data_train = data_train[cols_init]\n data_test = data_test[cols_init]\n data = pd.concat([data_train, data_test], ignore_index=True)\n\n # Convert data types\n data_types = set([data_type for _, _, data_type in self.config if data_type is not None])\n for data_type in data_types:\n converted_cols = list({new_col for _, new_col, dt in self.config if new_col is not None and dt is data_type and new_col in data.columns})\n data_converted_cols = data[converted_cols].fillna(-1 if data_type is int else np.nan)\n data.loc[:, converted_cols] = data_converted_cols.values.astype(data_type) if data_type is not np.datetime64 else pd.to_datetime(data_converted_cols.iloc[:, 0])\n \n # Filter data\n self.data_train_ = data[:data_train.shape[0]]\n self.data_test_ = data[data_train.shape[0]:].drop(columns=self.cols_outputs_).reset_index(drop=True)\n if self.param_grid_ is not None:\n self.data_train_ = pd.merge(self.data_train_, pd.DataFrame(self.param_grid_))\n\n return self\n \n def _extract_test(self):\n \"\"\"Extract test data.\"\"\"\n current_date = datetime.now()\n end_date = current_date + timedelta(weeks=self.testing_duration_)\n mask = (self.data_test_.date.dt.date >= current_date.date()) & (self.data_test_.date.dt.date <= end_date.date())\n X = self.data_test_.loc[mask, self.cols_inputs_].reset_index(drop=True)\n O = X[self.cols_odds_] if self.cols_odds_.size else None\n return Bunch(X=X, Y=None, O=O)\n \n def _extract_train(self):\n \"\"\"Extract train data.\"\"\"\n X = self.data_train_\n Y = []\n for target, func in self.targets:\n outputs = X[self.cols_outputs_]\n Y.append(pd.Series(func(outputs), name=target).reindex_like(outputs))\n Y = pd.concat(Y, axis=1)\n O = X[self.cols_odds_] if self.cols_odds_.size else None\n X = X[self.cols_inputs_]\n return Bunch(X=X, Y=Y, O=O)\n \n def load(self, return_only_params=False, **load_params):\n \"\"\"Extract and load model data.\"\"\"\n self._fetch(return_only_params, **load_params)\n bunch = Bunch(\n training=None,\n testing=None,\n dropped=Bunch(cols=None, rows=None),\n params = Bunch(selected=None, available=pd.DataFrame(self.full_param_grid_))\n )\n if not return_only_params:\n bunch.training = self._extract_train()\n bunch.testing = self._extract_test()\n bunch.dropped.cols=self.dropped_na_cols_\n bunch.dropped.rows=self.dropped_na_rows_\n bunch.params.selected = pd.DataFrame(self.param_grid_)\n return bunch\n"
] |
[
[
"pandas.concat",
"pandas.merge",
"sklearn.utils.Bunch",
"pandas.to_datetime",
"pandas.Index",
"pandas.DataFrame",
"sklearn.model_selection.ParameterGrid",
"sklearn.utils.check_scalar"
]
] |
jonzia/Chess
|
[
"d75dca748f2dba93cbf7d78dd0cef1593ed775c1"
] |
[
"test_bench.py"
] |
[
"# ----------------------------------------------------\n# Test Bench for Chess AI v1.0.2\n# Created By: Jonathan Zia\n# Last Edited: Thursday, May 10 2018\n# Georgia Institute of Technology\n# ----------------------------------------------------\nimport tensorflow as tf\nimport numpy as np\nimport pieces as p\nimport random as r\nimport state as s\nimport time as t\nimport copy as c\nimport math\nimport os\n\n# This program compares the performance of the specified trained model versus\n# a second model for validation purposes. The program calculates wins/losses\n# of the trained model versus a model that follows a random policy.\n\n# ----------------------------------------------------\n# User-Defined Constants\n# ----------------------------------------------------\n# Value Function Approximator Training\nNUM_TESTING\t= 100\t\t# Number of testing steps\nHIDDEN_UNITS = 100\t\t# Number of hidden units\nBATCH_SIZE = 5\t\t\t# Batch size\n\n# Simulation Parameters\nMAX_MOVES = 100\t\t\t# Maximum number of moves\nEPSILON = 0.0\t\t\t# Defining epsilon for e-greedy policy (0 for testing -> greedy policy)\n\n# Load File\nLOAD_FILE = True \t\t# Load trained model from saved checkpoint (True for testing)\nVISUALIZE = True\t\t# Select True to visualize games and False to suppress game output\nPRINT = True\t\t\t# Select True to print moves as text and False to suppress printing\nALGEBRAIC = True\t\t# Specify long algebraic notation (True) or descriptive text (False)\n\n\n# ----------------------------------------------------\n# Data Paths\n# ----------------------------------------------------\n# Specify filenames\n# Root directory:\ndir_name = \"D:\\\\\"\nwith tf.name_scope(\"Model_Data\"):\t\t# Model save/load paths\n\tload_path = os.path.join(dir_name, \"checkpoints/model\")\t\t\t# Model load path\nwith tf.name_scope(\"Filewriter_Data\"):\t# Filewriter save path\n\tfilewriter_path = os.path.join(dir_name, \"output\")\nwith tf.name_scope(\"Output_Data\"):\t\t# Output data filenames (.txt)\n\t# These .txt files will contain loss data for Matlab analysis\n\toutcome_file = os.path.join(dir_name, \"outcomes.txt\")\n\n\n# ----------------------------------------------------\n# User-Defined Methods\n# ----------------------------------------------------\ndef initialize_board(random=False, keep_prob=1.0):\n\t\"\"\"\n\tInitialize Game Board\n\tReturns: Game board state parameters\n\t\"\"\"\n\t# Initialize board pieces\n\tpieces = s.initialize_pieces(random=random,keep_prob=keep_prob)\n\t# Initialize state space \n\tboard_state = s.board_state(pieces)\n\t# Initialize current player:\n\tif random:\n\t\tif r.randint(0,1) == 1:\n\t\t\tplayer = 'white'\n\t\telse:\n\t\t\tplayer = 'black'\n\telse:\n\t\tplayer = 'white'\n\t# Initialize move counter:\n\tmove = 0\n\n\t# Return values\n\treturn pieces, board_state, player, move\n\ndef visualize_board(pieces, player, move):\n\t\"\"\"\n\tVisualize Game Board\n\tReturns: Void\n\t\"\"\"\n\tprint(\"\\nCurrent Board at Move \" + str(move) + \" for Player \" + player)\n\tprint(s.visualize_state(pieces))\n\ndef move_piece(piece,move_index,player,pieces,switch_player=False,print_move=False,algebraic=True):\n\t\"\"\"\n\tPerform specified move\n\tReturns: Void\n\t\"\"\"\n\tif player == 'white':\n\t\tpieces[piece].move(move_index,pieces,print_move=print_move,algebraic=algebraic)\n\telse:\n\t\tpieces[piece+16].move(move_index,pieces,print_move=print_move,algebraic=algebraic)\n\n\tif switch_player:\n\t\tif player == 'white':\n\t\t\tplayer = 'black'\n\t\telse:\n\t\t\tplayer = 'white'\n\t\treturn player\n\ndef generate_outcome(batch_size,max_moves,epsilon,visualize,print_move,algebraic):\n\t\"\"\"\n\tGenerating feature and target batches\n\tReturns: (1) feature batch, (2) label batch, (3) visualize board?, (4) print move?, (5) print algebraic notation?\n\t\"\"\"\n\n\t# Generates training data based on batches of full-depth Monte-Carlo simulations\n\t# performing epsilon-greedy policy evalutaion.\n\n\t# Initialize placeholder for outcome batch\n\toutcome_batch = []\n\n\t# Loop through batch steps\n\tfor batch_step in range(0,batch_size):\n\n\t\t# Print beginning of game notification for visualization\n\t\tif visualize or print_move:\n\t\t\tprint(\"\\n----------BEGIN GAME----------\")\n\n\t\t# ----------------------------------------------------\n\t\t# Initialize Board State\n\t\t# ----------------------------------------------------\n\t\t# Create placeholders for board states and return for each state\n\t\tall_states = []\n\t\tall_returns = []\n\n\t\t# Generating board parameters\n\t\tpieces, initial_state, player, move = initialize_board(random=False, keep_prob=1.0)\n\t\tpoint_diff_0 = s.points(pieces)\n\n\n\t\t# ----------------------------------------------------\n\t\t# Monte Carlo Simulations\n\t\t# ----------------------------------------------------\n\t\t# Run Monte Carlo Simulation until terminal event(s):\n\t\t# Terminal events: Kings.is_active == False or move_counter > MAX_MOVES\n\t\twhile pieces[4].is_active and pieces[28].is_active and move < max_moves:\n\n\t\t\t# Obtain board state\n\t\t\tif move == 0:\n\t\t\t\tboard_state = initial_state\n\t\t\telse:\n\t\t\t\tboard_state = s.board_state(pieces)\n\n\t\t\t# Visualize board state\n\t\t\tif visualize:\n\t\t\t\tvisualize_board(pieces,player,move)\n\n\t\t\t# Obtain current point differential\n\t\t\tnet_diff = s.points(pieces) - point_diff_0\n\t\t\tpoint_diff_0 = s.points(pieces)\n\t\t\t\n\t\t\t# Append initial board state to all_states\n\t\t\tall_states.append(board_state)\n\t\t\t# Add net_diff to all existing returns\n\t\t\tfor i in range(0,len(all_returns)):\n\t\t\t\tall_returns[i] += net_diff\n\t\t\t# Append 0 to end of all_returns representing return for current state\n\t\t\tall_returns.append(0)\n\n\t\t\t# Obtain action space\n\t\t\taction_space = s.action_space(pieces,player)\n\n\n\t\t\t# ----------------------------------------------------\n\t\t\t# Value Function Approximation\n\t\t\t# ----------------------------------------------------\n\t\t\t# For each action in the action space, obtain subsequent board space\n\t\t\t# and calculate estimated return with the partially-trained approximator\n\n\t\t\t# Create placeholder for expected return values\n\t\t\treturn_array = np.zeros((16,56))\n\n\t\t\t# For each possible move...\n\t\t\tfor i in range(0,16):\n\t\t\t\tfor j in range(0,56):\n\t\t\t\t\t# If the move is legal...\n\t\t\t\t\tif action_space[i,j] == 1:\n\n\t\t\t\t\t\t# Perform move and obtain temporary board state\n\t\t\t\t\t\ttemp_pieces = c.deepcopy(pieces)\t\t\t\t# Reset temporary pieces variable\n\t\t\t\t\t\tmove_piece(i,j,player,temp_pieces)\t\t\t\t# Perform temporary move\n\t\t\t\t\t\ttemp_board_state = s.board_state(temp_pieces)\t# Obtain temporary state\n\n\t\t\t\t\t\t# With temporary state, calculate expected return\n\t\t\t\t\t\texpected_return = sess.run(predictions, feed_dict={inputs: np.reshape(temp_board_state,(1,768))})\n\t\t\t\t\t\t# Write estimated return to return_array\n\t\t\t\t\t\treturn_array[i,j] = expected_return\n\n\n\t\t\t# ----------------------------------------------------\n\t\t\t# Policy\n\t\t\t# ----------------------------------------------------\n\t\t\t# Player white chooses greedy policy, player black chooses random policy\n\t\t\t# For player black, choose a random action\n\t\t\tif player == 'black':\n\t\t\t\twhile True:\n\t\t\t\t\t# If the action is valid...\n\t\t\t\t\tpiece_index = r.randint(0,15)\n\t\t\t\t\tmove_index = r.randint(0,55)\n\t\t\t\t\tif return_array[piece_index,move_index] != 0:\n\t\t\t\t\t\t# Perform move and update player\n\t\t\t\t\t\tplayer = move_piece(piece_index,move_index,player,pieces,switch_player=True,print_move=print_move,algebraic=algebraic)\n\t\t\t\t\t\tbreak\n\t\t\t# Else, act greedy w.r.t. expected return\n\t\t\telse:\n\t\t\t\t# Identify indices of maximum return (white) or minimum return (black)\n\t\t\t\tmove_choice = np.nonzero(return_array.max() == return_array)\n\t\t\t\tpiece_index = move_choice[0][0]\n\t\t\t\tmove_index = move_choice[1][0]\n\t\t\t\t# Perform move and update player\n\t\t\t\tplayer = move_piece(piece_index,move_index,player,pieces,switch_player=True,print_move=print_move,algebraic=algebraic)\n\n\t\t\t# Increment move counter\n\t\t\tmove += 1\n\n\t\t# Print end of game notification for visualization\n\t\tif visualize or print_move:\n\t\t\tprint(\"----------END OF GAME----------\")\n\n\t\t# Append outcome\n\t\t# If player white won the game...\n\t\tif all_returns[0] > 0:\n\t\t\toutcome_batch.append(1)\t\t# Return 1\n\t\t# Else, for a draw...\n\t\telif all_returns[0] == 0:\n\t\t\toutcome_batch.append(0)\t\t# Return 0 \n\t\t# Else, if player black won the game...\n\t\telse:\n\t\t\toutcome_batch.append(-1)\t# Return -1\n\n\t# Return outcome batch\n\toutcome_batch = np.array(outcome_batch)\n\treturn outcome_batch\n\n\n# ----------------------------------------------------\n# Importing Session Parameters\n# ----------------------------------------------------\n# Create placeholders for inputs and target values\n# Input dimensions: 8 x 8 x 12\n# Target dimensions: 1 x 1\ninputs = tf.placeholder(tf.float32,[None,768],name='Inputs')\ntargets = tf.placeholder(tf.float32,shape=(None,1),name='Targets')\n\n\n# ----------------------------------------------------\n# Implementing Feedforward NN\n# ----------------------------------------------------\n# First fully-connected layer\nhidden1 = tf.contrib.layers.fully_connected(inputs,num_outputs=HIDDEN_UNITS)\n\n# Second fully-connected layer\nhidden2 = tf.contrib.layers.fully_connected(hidden1,num_outputs=HIDDEN_UNITS)\n\n# Output layer\npredictions = tf.contrib.layers.fully_connected(hidden2,num_outputs=1,activation_fn=None)\n\n\n# ----------------------------------------------------\n# Run Session\n# ----------------------------------------------------\nsaver = tf.train.Saver()\t# Instantiate Saver class\noutcomes = []\t\t\t\t# Initialize placeholder for outcomes\nwith tf.Session() as sess:\n\n\t# Create Tensorboard graph\n\t#writer = tf.summary.FileWriter(filewriter_path, sess.graph)\n\t#merged = tf.summary.merge_all()\n\n\t# Restore saved session\n\tsaver.restore(sess, load_path)\n\n\t# Obtain start time\n\tstart_time = t.time()\n\n\t# For each training step, generate a random board\n\tfor step in range(0,NUM_TESTING):\n\n\t\t# Run game and determine outcome\n\t\toutcome = generate_outcome(batch_size=BATCH_SIZE,max_moves=MAX_MOVES,epsilon=EPSILON,visualize=VISUALIZE,print_move=PRINT,algebraic=ALGEBRAIC)\n\t\toutcomes.append(outcome)\n\n\n\t\t# Conditional statement for calculating time remaining and percent completion\n\t\tif step % 1 == 0:\n\n\t\t\t# Report percent completion\n\t\t\tp_completion = 100*step/NUM_TESTING\n\t\t\tprint(\"\\nPercent Completion: %.3f%%\" % p_completion)\n\n\t\t\t# Print time remaining\n\t\t\tavg_elapsed_time = (t.time() - start_time)/(step+1)\n\t\t\tsec_remaining = avg_elapsed_time*(NUM_TESTING-step)\n\t\t\tmin_remaining = round(sec_remaining/60)\n\t\t\tprint(\"Time Remaining: %d minutes\" % min_remaining)\n\n\t\t\t# Print mean outcome\n\t\t\tprint(outcome)\n\t\t\tprint(\"Mean Outcome: %.3f\" % np.mean(outcomes))\n\n\t# Write outcomes to file\n\toutcomes = np.array(outcomes)\n\twith open(outcome_file, 'a') as file_object:\n\t\tnp.savetxt(file_object, outcomes)\n\n\t# Close the writer\n\t# writer.close()"
] |
[
[
"numpy.reshape",
"tensorflow.placeholder",
"tensorflow.contrib.layers.fully_connected",
"numpy.mean",
"tensorflow.name_scope",
"tensorflow.Session",
"tensorflow.train.Saver",
"numpy.array",
"numpy.zeros",
"numpy.savetxt"
]
] |
cjs220/madminer
|
[
"5422880d5f05cb551dcf8ace956ef9a365d39c30"
] |
[
"madminer/fisherinformation.py"
] |
[
"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport numpy as np\nimport os\nimport random\nfrom scipy.interpolate import griddata, LinearNDInterpolator, CloughTocher2DInterpolator\nfrom scipy.stats import chi2\n\nfrom madminer.analysis import DataAnalyzer\nfrom madminer.utils.various import math_commands, weighted_quantile, sanitize_array, mdot\nfrom madminer.utils.various import separate_information_blocks, less_logging\nfrom madminer.utils.various import load_and_check\nfrom madminer.ml import ParameterizedRatioEstimator, ScoreEstimator, Ensemble, load_estimator\n\nlogger = logging.getLogger(__name__)\n\n\nclass FisherInformation(DataAnalyzer):\n \"\"\"\n Functions to calculate expected Fisher information matrices.\n\n After inializing a `FisherInformation` instance with the filename of a MadMiner file, different information matrices\n can be calculated:\n\n * `FisherInformation.truth_information()` calculates the full truth-level Fisher information.\n This is the information in an idealized measurement where all parton-level particles with their charges, flavours,\n and four-momenta can be accessed with perfect accuracy.\n * `FisherInformation.full_information()` calculates the full Fisher information in\n realistic detector-level observations, estimated with neural networks. In addition to the MadMiner file, this\n requires a trained SALLY or SALLINO estimator as well as an unweighted evaluation sample.\n * `FisherInformation.rate_information()` calculates the Fisher information in the total cross\n section.\n * `FisherInformation.histo_information()` calculates the Fisher information in the histogram of\n one (parton-level or detector-level) observable.\n * `FisherInformation.histo_information_2d()` calculates the Fisher information in a two-dimensional\n histogram of two (parton-level or detector-level) observables.\n * `FisherInformation.histogram_of_information()` calculates the full truth-level Fisher information in\n different slices of one observable (the \"distribution of the Fisher information\").\n\n Finally, don't forget that in the presence of nuisance parameters the constraint terms also affect the Fisher\n information. This term is given by `FisherInformation.calculate_fisher_information_nuisance_constraints()`.\n\n Parameters\n ----------\n filename : str\n Path to MadMiner file (for instance the output of `madminer.delphes.DelphesProcessor.save()`).\n\n include_nuisance_parameters : bool, optional\n If True, nuisance parameters are taken into account. Default value: True.\n\n \"\"\"\n\n def __init__(self, filename, include_nuisance_parameters=True):\n super(FisherInformation, self).__init__(filename, False, include_nuisance_parameters)\n\n def truth_information(\n self, theta, luminosity=300000.0, cuts=None, efficiency_functions=None, include_nuisance_parameters=True\n ):\n \"\"\"\n Calculates the full Fisher information at parton / truth level. This is the information in an idealized\n measurement where all parton-level particles with their charges, flavours, and four-momenta can be accessed with\n perfect accuracy, i.e. the latent variables `z_parton` can be measured directly.\n\n Parameters\n ----------\n theta : ndarray\n Parameter point `theta` at which the Fisher information matrix `I_ij(theta)` is evaluated.\n\n luminosity : float\n Luminosity in pb^-1.\n\n cuts : None or list of str, optional\n Cuts. Each entry is a parseable Python expression that returns a bool (True if the event should pass a cut,\n False otherwise). Default value: None.\n\n efficiency_functions : list of str or None\n Efficiencies. Each entry is a parseable Python expression that returns a float for the efficiency of one\n component. Default value: None.\n\n include_nuisance_parameters : bool, optional\n If True, nuisance parameters are taken into account. Default value: True.\n\n Returns\n -------\n fisher_information : ndarray\n Expected full truth-level Fisher information matrix with shape `(n_parameters, n_parameters)`.\n\n fisher_information_uncertainty : ndarray\n Covariance matrix of the Fisher information matrix with shape\n `(n_parameters, n_parameters, n_parameters, n_parameters)`, calculated with plain Gaussian error\n propagation.\n\n \"\"\"\n\n # Input\n if cuts is None:\n cuts = []\n if efficiency_functions is None:\n efficiency_functions = []\n include_nuisance_parameters = include_nuisance_parameters and (self.nuisance_parameters is not None)\n\n # Loop over batches\n n_all_parameters = self.n_parameters\n if include_nuisance_parameters:\n n_all_parameters += self.n_nuisance_parameters\n\n fisher_info = np.zeros((n_all_parameters, n_all_parameters))\n covariance = np.zeros((n_all_parameters, n_all_parameters, n_all_parameters, n_all_parameters))\n\n for observations, weights in self.event_loader():\n # Cuts\n cut_filter = [self._pass_cuts(obs_event, cuts) for obs_event in observations]\n observations = observations[cut_filter]\n weights = weights[cut_filter]\n\n # Efficiencies\n efficiencies = np.array(\n [self._eval_efficiency(obs_event, efficiency_functions) for obs_event in observations]\n )\n weights *= efficiencies[:, np.newaxis]\n\n # Fisher information\n this_fisher_info, this_covariance = self._calculate_fisher_information(\n theta,\n weights,\n luminosity,\n sum_events=True,\n calculate_uncertainty=True,\n include_nuisance_parameters=include_nuisance_parameters,\n )\n fisher_info += this_fisher_info\n covariance += this_covariance\n\n return fisher_info, covariance\n\n def full_information(\n self,\n theta,\n model_file,\n unweighted_x_sample_file=None,\n luminosity=300000.0,\n include_xsec_info=True,\n mode=\"score\",\n calculate_covariance=True,\n batch_size=100000,\n test_split=0.2,\n ):\n \"\"\"\n Calculates the full Fisher information in realistic detector-level observations, estimated with neural networks.\n In addition to the MadMiner file, this requires a trained SALLY or SALLINO estimator.\n\n Nuisance parameter are taken into account automatically if the SALLY / SALLINO model was trained with them.\n\n Parameters\n ----------\n theta : ndarray\n Parameter point `theta` at which the Fisher information matrix `I_ij(theta)` is evaluated.\n\n model_file : str\n Filename of a trained local score regression model that was trained on samples from `theta` (see\n `madminer.ml.Estimator`).\n\n unweighted_x_sample_file : str or None\n Filename of an unweighted x sample that is sampled according to theta and obeys the cuts\n (see `madminer.sampling.SampleAugmenter.extract_samples_train_local()`). If None, the Fisher information\n is instead calculated on the full, weighted samples (the data in the MadMiner file). Default value: None.\n\n luminosity : float, optional\n Luminosity in pb^-1. Default value: 300000.\n\n include_xsec_info : bool, optional\n Whether the rate information is included in the returned Fisher information. Default value: True.\n\n mode : {\"score\", \"information\"}, optional\n How the ensemble uncertainty on the kinematic Fisher information is calculated. If mode is \"information\",\n the Fisher information for each estimator is calculated individually and only then\n are the sample mean and covariance calculated. If mode is \"score\", the sample mean is\n calculated for the score for each event. Default value: \"score\".\n\n calculate_covariance : bool, optional\n If True, the covariance between the different estimators is calculated. Default value: True.\n\n batch_size : int, optional\n Batch size. Default value: 100000.\n\n test_split : float or None, optional\n If unweighted_x_sample_file is None, this determines the fraction of weighted events used for evaluation.\n If None, all events are used (this will probably include events used during training!). Default value: 0.2.\n\n Returns\n -------\n fisher_information : ndarray or list of ndarray\n Estimated expected full detector-level Fisher information matrix with shape `(n_parameters, n_parameters)`.\n If more then one value ensemble_vote_expectation_weight is given, this is a list with results for all\n entries in ensemble_vote_expectation_weight.\n\n fisher_information_uncertainty : ndarray or list of ndarray or None\n Covariance matrix of the Fisher information matrix with shape\n `(n_parameters, n_parameters, n_parameters, n_parameters)`. If more then one value\n ensemble_vote_expectation_weight is given, this is a list with results for all entries in\n ensemble_vote_expectation_weight.\n\n \"\"\"\n\n # Check input\n if mode not in [\"score\", \"information\", \"modified_score\"]:\n raise ValueError(\"Unknown mode {}, has to be 'score', 'modified_score', or 'information'!\".format(mode))\n\n # Load Estimator model\n if os.path.isdir(model_file) and os.path.exists(model_file + \"/ensemble.json\"):\n model_is_ensemble = True\n model = Ensemble()\n model.load(model_file)\n if isinstance(model.estimators[0], ParameterizedRatioEstimator):\n model_type = \"Parameterized Ratio Ensemble\"\n elif isinstance(model.estimators[0], ScoreEstimator):\n model_type = \"Score Ensemble\"\n else:\n raise RuntimeError(\"Ensemble is not a score or parameterized_ratio type!\")\n else:\n model_is_ensemble = False\n model = load_estimator(model_file)\n\n if isinstance(model, ParameterizedRatioEstimator):\n model_type = \"Parameterized Ratio Estimator\"\n elif isinstance(model, ScoreEstimator):\n model_type = \"Score Estimator\"\n else:\n raise RuntimeError(\"Estimator is not a score or parameterized_ratio type!\")\n\n # Nuisance parameters?\n if model.n_parameters == self.n_parameters:\n logger.info(\n \"Found %s parameters in %s model, matching %s physical parameters in MadMiner file\",\n model.n_parameters,\n model_type,\n self.n_parameters,\n )\n include_nuisance_parameters = False\n elif model.n_parameters == self.n_parameters + self.n_nuisance_parameters:\n logger.info(\n \"Found %s parameters in %s model, matching %s physical parameters + %s nuisance parameters\"\n + \" in MadMiner file\",\n model.n_parameters,\n model_type,\n self.n_parameters,\n self.n_nuisance_parameters,\n )\n include_nuisance_parameters = True\n else:\n raise RuntimeError(\n \"Inconsistent numbers of parameters! Found %s in %s model, %s physical parameters in \"\n \"MadMiner file, and %s nuisance parameters in MadMiner file.\",\n model.n_parameters,\n model_type,\n self.n_parameters,\n self.n_nuisance_parameters,\n )\n\n if include_nuisance_parameters:\n logger.debug(\"Including nuisance parameters\")\n else:\n logger.debug(\"Not including nuisance parameters\")\n\n # Total xsec\n total_xsec = self._calculate_xsec(theta=theta)\n logger.debug(\"Total cross section: %s pb\", total_xsec)\n\n # Rate part of Fisher information\n fisher_info_rate = 0.0\n rate_covariance = 0.0\n if include_xsec_info:\n logger.info(\"Evaluating rate Fisher information\")\n fisher_info_rate, rate_covariance = self.rate_information(\n theta=theta, luminosity=luminosity, include_nuisance_parameters=include_nuisance_parameters\n )\n\n # Evaluation from weighted events\n if unweighted_x_sample_file is None:\n\n # Which events to sum over\n if test_split is None or test_split <= 0.0 or test_split >= 1.0:\n start_event = 0\n else:\n start_event = int(round((1.0 - test_split) * self.n_samples, 0)) + 1\n\n if start_event > 0:\n total_sum_weights_theta = self._calculate_xsec(theta=theta, start_event=start_event)\n else:\n total_sum_weights_theta = total_xsec\n\n # Theta morphing matrix\n theta_matrix = self._get_theta_benchmark_matrix(theta)\n\n # Prepare output\n fisher_info_kin = None\n covariance = None\n\n # Number of batches\n n_batches = int(np.ceil((self.n_samples - start_event) / batch_size))\n n_batches_verbose = max(int(round(n_batches / 10, 0)), 1)\n\n for i_batch, (observations, weights_benchmarks) in enumerate(\n self.event_loader(\n batch_size=batch_size, start=start_event, include_nuisance_parameters=include_nuisance_parameters\n )\n ):\n if (i_batch + 1) % n_batches_verbose == 0:\n logger.info(\"Evaluating kinematic Fisher information on batch %s / %s\", i_batch + 1, n_batches)\n else:\n logger.debug(\"Evaluating kinematic Fisher information on batch %s / %s\", i_batch + 1, n_batches)\n\n weights_theta = mdot(theta_matrix, weights_benchmarks)\n\n # Calculate Fisher info on this batch\n if model_is_ensemble:\n with less_logging():\n this_fisher_info, this_covariance = model.calculate_fisher_information(\n x=observations,\n theta=theta,\n obs_weights=weights_theta,\n n_events=luminosity * total_xsec * np.sum(weights_theta) / total_sum_weights_theta,\n calculate_covariance=calculate_covariance,\n mode=mode,\n )\n else:\n with less_logging():\n this_fisher_info = model.calculate_fisher_information(\n x=observations,\n theta=theta,\n weights=weights_theta,\n n_events=luminosity * total_xsec * np.sum(weights_theta) / total_sum_weights_theta,\n )\n this_covariance = None\n # Sum up results\n if fisher_info_kin is None:\n fisher_info_kin = this_fisher_info\n elif isinstance(fisher_info_kin, list):\n for i in range(len(fisher_info_kin)):\n fisher_info_kin[i] += this_fisher_info[i]\n else:\n fisher_info_kin += this_fisher_info\n\n if this_covariance is not None:\n if covariance is None:\n covariance = this_covariance\n elif isinstance(covariance, list):\n for i in range(len(covariance)):\n covariance[i] += this_covariance[i]\n else:\n covariance += this_covariance\n\n # Evaluation from unweighted event sample\n else:\n with less_logging():\n if model_is_ensemble:\n fisher_info_kin, covariance = model.calculate_fisher_information(\n x=unweighted_x_sample_file,\n theta=theta,\n n_events=luminosity * total_xsec,\n mode=mode,\n calculate_covariance=calculate_covariance,\n )\n else:\n fisher_info_kin = model.calculate_fisher_information(\n x=unweighted_x_sample_file, n_events=luminosity * total_xsec, theta=theta\n )\n covariance = None\n\n # Returns\n if model_is_ensemble:\n return fisher_info_rate + fisher_info_kin, rate_covariance + covariance\n\n return fisher_info_rate + fisher_info_kin, rate_covariance\n\n def rate_information(\n self, theta, luminosity, cuts=None, efficiency_functions=None, include_nuisance_parameters=True\n ):\n \"\"\"\n Calculates the Fisher information in a measurement of the total cross section (without any kinematic\n information).\n\n Parameters\n ----------\n theta : ndarray\n Parameter point `theta` at which the Fisher information matrix `I_ij(theta)` is evaluated.\n\n luminosity : float\n Luminosity in pb^-1.\n\n cuts : None or list of str, optional\n Cuts. Each entry is a parseable Python expression that returns a bool (True if the event should pass a cut,\n False otherwise). Default value: None.\n\n efficiency_functions : list of str or None\n Efficiencies. Each entry is a parseable Python expression that returns a float for the efficiency of one\n component. Default value: None.\n\n include_nuisance_parameters : bool, optional\n If True, nuisance parameters are taken into account. Default value: True.\n\n Returns\n -------\n fisher_information : ndarray\n Expected Fisher information in the total cross section with shape `(n_parameters, n_parameters)`.\n\n fisher_information_uncertainty : ndarray\n Covariance matrix of the Fisher information matrix with shape\n `(n_parameters, n_parameters, n_parameters, n_parameters)`, calculated with plain Gaussian error\n propagation.\n\n \"\"\"\n include_nuisance_parameters = include_nuisance_parameters and (self.nuisance_parameters is not None)\n\n # Get weights at benchmarks\n weights_benchmarks, weights_benchmark_uncertainties = self._calculate_xsec(\n cuts=cuts,\n efficiency_functions=efficiency_functions,\n return_benchmark_xsecs=True,\n return_error=True,\n include_nuisance_parameters=include_nuisance_parameters,\n )\n\n weights_benchmarks = weights_benchmarks.reshape((1, -1))\n weights_benchmark_uncertainties = weights_benchmark_uncertainties.reshape((1, -1))\n\n # Get Fisher information\n fisher_info, covariance = self._calculate_fisher_information(\n theta=theta,\n weights_benchmarks=weights_benchmarks,\n luminosity=luminosity,\n sum_events=True,\n calculate_uncertainty=True,\n weights_benchmark_uncertainties=weights_benchmark_uncertainties,\n include_nuisance_parameters=include_nuisance_parameters,\n )\n\n return fisher_info, covariance\n\n def histo_information(\n self,\n theta,\n luminosity,\n observable,\n bins,\n histrange=None,\n cuts=None,\n efficiency_functions=None,\n n_events_dynamic_binning=None,\n ):\n \"\"\"\n Calculates the Fisher information in the one-dimensional histogram of an (parton-level or detector-level,\n depending on how the observations in the MadMiner file were calculated) observable.\n\n Parameters\n ----------\n theta : ndarray\n Parameter point `theta` at which the Fisher information matrix `I_ij(theta)` is evaluated.\n\n luminosity : float\n Luminosity in pb^-1.\n\n observable : str\n Expression for the observable to be histogrammed. The str will be parsed by Python's `eval()` function\n and can use the names of the observables in the MadMiner files.\n\n bins : int or ndarray\n If int: number of bins in the histogram, excluding overflow bins. Otherwise, defines the bin boundaries\n (excluding overflow bins).\n\n histrange : tuple of float or None, optional\n Minimum and maximum value of the histogram in the form `(min, max)`. Overflow bins are always added. If\n None and bins is an int, variable-width bins with equal cross section are constructed automatically.\n Default value: None.\n\n cuts : None or list of str, optional\n Cuts. Each entry is a parseable Python expression that returns a bool (True if the event should pass a cut,\n False otherwise). Default value: None.\n\n efficiency_functions : list of str or None\n Efficiencies. Each entry is a parseable Python expression that returns a float for the efficiency of one\n component. Default value: None.\n\n n_events_dynamic_binning : int or None, optional\n Number of events used to calculate the dynamic binning (if histrange is None). If None, all events are used.\n Note that these events are not shuffled, so if the events in the MadMiner file are sorted, using a value\n different from None can cause issues. Default value: None.\n\n Returns\n -------\n fisher_information : ndarray\n Expected Fisher information in the histogram with shape `(n_parameters, n_parameters)`.\n\n fisher_information_uncertainty : ndarray\n Covariance matrix of the Fisher information matrix with shape\n `(n_parameters, n_parameters, n_parameters, n_parameters)`, calculated with plain Gaussian error\n propagation.\n\n \"\"\"\n\n # Input\n if cuts is None:\n cuts = []\n if efficiency_functions is None:\n efficiency_functions = []\n\n # Binning\n bin_boundaries, n_bins_total = self._calculate_binning(\n bins, cuts, efficiency_functions, histrange, n_events_dynamic_binning, observable, theta\n )\n\n # Loop over batches\n weights_benchmarks = np.zeros((n_bins_total, self.n_benchmarks))\n weights_squared_benchmarks = np.zeros((n_bins_total, self.n_benchmarks))\n\n for observations, weights in self.event_loader():\n # Cuts\n cut_filter = [self._pass_cuts(obs_event, cuts) for obs_event in observations]\n observations = observations[cut_filter]\n weights = weights[cut_filter]\n\n # Efficiencies\n efficiencies = np.array(\n [self._eval_efficiency(obs_event, efficiency_functions) for obs_event in observations]\n )\n weights *= efficiencies[:, np.newaxis]\n\n # Evaluate histogrammed observable\n histo_observables = np.asarray([self._eval_observable(obs_event, observable) for obs_event in observations])\n\n # Find bins\n i_bins = np.searchsorted(bin_boundaries, histo_observables)\n assert ((0 <= i_bins) & (i_bins < n_bins_total)).all(), \"Wrong bin {}\".format(i_bins)\n\n # Add up\n for i in range(n_bins_total):\n if len(weights[i_bins == i]) > 0:\n weights_benchmarks[i] += np.sum(weights[i_bins == i], axis=0)\n weights_squared_benchmarks[i] += np.sum(weights[i_bins == i] ** 2, axis=0)\n\n weights_benchmark_uncertainties = weights_squared_benchmarks ** 0.5\n\n # Check cross sections per bin\n self._check_binning_stats(weights_benchmarks, weights_benchmark_uncertainties, theta)\n\n # Calculate Fisher information in histogram\n fisher_info, covariance = self._calculate_fisher_information(\n theta,\n weights_benchmarks,\n luminosity,\n sum_events=True,\n weights_benchmark_uncertainties=weights_benchmark_uncertainties,\n calculate_uncertainty=True,\n )\n return fisher_info, covariance\n\n def histo_information_2d(\n self,\n theta,\n luminosity,\n observable1,\n bins1,\n observable2,\n bins2,\n histrange1=None,\n histrange2=None,\n cuts=None,\n efficiency_functions=None,\n n_events_dynamic_binning=None,\n ):\n\n \"\"\"\n Calculates the Fisher information in a two-dimensional histogram of two (parton-level or detector-level,\n depending on how the observations in the MadMiner file were calculated) observables.\n\n Parameters\n ----------\n theta : ndarray\n Parameter point `theta` at which the Fisher information matrix `I_ij(theta)` is evaluated.\n\n luminosity : float\n Luminosity in pb^-1.\n\n observable1 : str\n Expression for the first observable to be histogrammed. The str will be parsed by Python's `eval()` function\n and can use the names of the observables in the MadMiner files.\n\n bins1 : int or ndarray\n If int: number of bins along the first axis in the histogram in the histogram, excluding overflow bins.\n Otherwise, defines the bin boundaries along the first axis in the histogram (excluding overflow bins).\n\n observable2 : str\n Expression for the first observable to be histogrammed. The str will be parsed by Python's `eval()` function\n and can use the names of the observables in the MadMiner files.\n\n bins2 : int or ndarray\n If int: number of bins along the second axis in the histogram in the histogram, excluding overflow bins.\n Otherwise, defines the bin boundaries along the second axis in the histogram (excluding overflow bins).\n\n histrange1 : tuple of float or None, optional\n Minimum and maximum value of the first axis of the histogram in the form `(min, max)`. Overflow bins are\n always added. If None, variable-width bins with equal cross section are constructed automatically. Default\n value: None.\n\n histrange2 : tuple of float or None, optional\n Minimum and maximum value of the first axis of the histogram in the form `(min, max)`. Overflow bins are\n always added. If None, variable-width bins with equal cross section are constructed automatically. Default\n value: None.\n\n cuts : None or list of str, optional\n Cuts. Each entry is a parseable Python expression that returns a bool (True if the event should pass a cut,\n False otherwise). Default value: None.\n\n efficiency_functions : list of str or None\n Efficiencies. Each entry is a parseable Python expression that returns a float for the efficiency of one\n component. Default value: None.\n\n n_events_dynamic_binning : int or None, optional\n Number of events used to calculate the dynamic binning (if histrange is None). If None, all events are used.\n Note that these events are not shuffled, so if the events in the MadMiner file are sorted, using a value\n different from None can cause issues. Default value: None.\n\n Returns\n -------\n fisher_information : ndarray\n Expected Fisher information in the histogram with shape `(n_parameters, n_parameters)`.\n\n fisher_information_uncertainty : ndarray\n Covariance matrix of the Fisher information matrix with shape\n `(n_parameters, n_parameters, n_parameters, n_parameters)`, calculated with plain Gaussian error\n propagation.\n\n \"\"\"\n\n # Input\n if cuts is None:\n cuts = []\n if efficiency_functions is None:\n efficiency_functions = []\n\n # Binning\n bin1_boundaries, n_bins1_total = self._calculate_binning(\n bins1, cuts, efficiency_functions, histrange1, n_events_dynamic_binning, observable1, theta\n )\n bin2_boundaries, n_bins2_total = self._calculate_binning(\n bins2, cuts, efficiency_functions, histrange2, n_events_dynamic_binning, observable2, theta\n )\n\n # Loop over batches\n weights_benchmarks = np.zeros((n_bins1_total, n_bins2_total, self.n_benchmarks))\n weights_squared_benchmarks = np.zeros((n_bins1_total, n_bins2_total, self.n_benchmarks))\n\n for observations, weights in self.event_loader():\n # Cuts\n cut_filter = [self._pass_cuts(obs_event, cuts) for obs_event in observations]\n observations = observations[cut_filter]\n weights = weights[cut_filter]\n\n # Efficiencies\n efficiencies = np.array(\n [self._eval_efficiency(obs_event, efficiency_functions) for obs_event in observations]\n )\n weights *= efficiencies[:, np.newaxis]\n\n # Evaluate histogrammed observable\n histo1_observables = np.asarray(\n [self._eval_observable(obs_event, observable1) for obs_event in observations]\n )\n histo2_observables = np.asarray(\n [self._eval_observable(obs_event, observable2) for obs_event in observations]\n )\n\n # Find bins\n i_bins1 = np.searchsorted(bin1_boundaries, histo1_observables)\n i_bins2 = np.searchsorted(bin2_boundaries, histo2_observables)\n\n assert ((0 <= i_bins1) & (i_bins1 < n_bins1_total)).all(), \"Wrong bin {}\".format(i_bins1)\n assert ((0 <= i_bins2) & (i_bins2 < n_bins1_total)).all(), \"Wrong bin {}\".format(i_bins2)\n\n # Add up\n for i in range(n_bins1_total):\n for j in range(n_bins2_total):\n if len(weights[(i_bins1 == i) & (i_bins2 == j)]) > 0:\n weights_benchmarks[i, j] += np.sum(weights[(i_bins1 == i) & (i_bins2 == j)], axis=0)\n weights_squared_benchmarks[i, j] += np.sum(\n weights[(i_bins1 == i) & (i_bins2 == j)] ** 2, axis=0\n )\n\n weights_benchmark_uncertainties = weights_squared_benchmarks ** 0.5\n\n # Calculate Fisher information in histogram\n weights_benchmarks = weights_benchmarks.reshape(-1, self.n_benchmarks)\n weights_benchmark_uncertainties = weights_benchmark_uncertainties.reshape(-1, self.n_benchmarks)\n\n self._check_binning_stats(\n weights_benchmarks, weights_benchmark_uncertainties, theta, n_bins_last_axis=n_bins2_total\n )\n\n fisher_info, covariance = self._calculate_fisher_information(\n theta,\n weights_benchmarks,\n luminosity,\n sum_events=True,\n weights_benchmark_uncertainties=weights_benchmark_uncertainties,\n calculate_uncertainty=True,\n )\n\n return fisher_info, covariance\n\n def histogram_of_information(\n self,\n theta,\n observable,\n nbins,\n histrange,\n model_file=None,\n luminosity=300000.0,\n cuts=None,\n efficiency_functions=None,\n batch_size=100000,\n test_split=0.2,\n ):\n \"\"\"\n Calculates the full and rate-only Fisher information in slices of one observable. For the full\n information, it will return the truth-level information if model_file is None, and otherwise the\n detector-level information based on the SALLY-type score estimator saved in model_file.\n\n Parameters\n ----------\n theta : ndarray\n Parameter point `theta` at which the Fisher information matrix `I_ij(theta)` is evaluated.\n\n observable : str\n Expression for the observable to be sliced. The str will be parsed by Python's `eval()` function\n and can use the names of the observables in the MadMiner files.\n\n nbins : int\n Number of bins in the slicing, excluding overflow bins.\n\n histrange : tuple of float\n Minimum and maximum value of the slicing in the form `(min, max)`. Overflow bins are always added.\n\n model_file : str or None, optional\n If None, the truth-level Fisher information is calculated. If str, filename of a trained local score\n regression model that was trained on samples from `theta` (see `madminer.ml.Estimator`). Default value:\n None.\n\n luminosity : float, optional\n Luminosity in pb^-1. Default value: 300000.\n\n cuts : None or list of str, optional\n Cuts. Each entry is a parseable Python expression that returns a bool (True if the event should pass a cut,\n False otherwise). Default value: None.\n\n efficiency_functions : list of str or None\n Efficiencies. Each entry is a parseable Python expression that returns a float for the efficiency of one\n component. Default value: None.\n\n batch_size : int, optional\n If model_file is not None: Batch size. Default value: 100000.\n\n test_split : float or None, optional\n If model_file is not None: If unweighted_x_sample_file is None, this determines the fraction of weighted\n events used for evaluation.\n If None, all events are used (this will probably include events used during training!). Default value: 0.2.\n\n\n Returns\n -------\n bin_boundaries : ndarray\n Observable slice boundaries.\n\n sigma_bins : ndarray\n Cross section in pb in each of the slices.\n\n fisher_infos_rate : ndarray\n Expected rate-only Fisher information for each slice. Has shape `(n_slices, n_parameters, n_parameters)`.\n\n fisher_infos_full : ndarray\n Expected full Fisher information for each slice. Has shape\n `(n_slices, n_parameters, n_parameters)`.\n\n \"\"\"\n\n # Input\n if cuts is None:\n cuts = []\n if efficiency_functions is None:\n efficiency_functions = []\n\n # Theta morphing matrix\n theta_matrix = self._get_theta_benchmark_matrix(theta)\n\n # Number of bins\n n_bins_total = nbins + 2\n bin_boundaries = np.linspace(histrange[0], histrange[1], num=nbins + 1)\n\n # Prepare output\n weights_benchmarks_bins = np.zeros((n_bins_total, self.n_benchmarks))\n fisher_info_full_bins = np.zeros((n_bins_total, self.n_parameters, self.n_parameters))\n\n # Main loop: truth-level case\n if model_file is None:\n for observations, weights in self.event_loader():\n # Cuts\n cut_filter = [self._pass_cuts(obs_event, cuts) for obs_event in observations]\n observations = observations[cut_filter]\n weights = weights[cut_filter]\n\n # Efficiencies\n efficiencies = np.array(\n [self._eval_efficiency(obs_event, efficiency_functions) for obs_event in observations]\n )\n weights *= efficiencies[:, np.newaxis]\n\n # Fisher info per event\n fisher_info_events = self._calculate_fisher_information(theta, weights, luminosity, sum_events=False)\n\n # Evaluate histogrammed observable\n histo_observables = np.asarray(\n [self._eval_observable(obs_event, observable) for obs_event in observations]\n )\n\n # Get rid of nuisance parameters\n fisher_info_events = fisher_info_events[:, : self.n_parameters, : self.n_parameters]\n\n # Find bins\n bins = np.searchsorted(bin_boundaries, histo_observables)\n assert ((0 <= bins) & (bins < n_bins_total)).all(), \"Wrong bin {}\".format(bins)\n\n # Add up\n for i in range(n_bins_total):\n if len(weights[bins == i]) > 0:\n weights_benchmarks_bins[i] += np.sum(weights[bins == i], axis=0)\n fisher_info_full_bins[i] += np.sum(fisher_info_events[bins == i], axis=0)\n\n # ML case\n else:\n # Load SALLY model\n if os.path.isdir(model_file) and os.path.exists(model_file + \"/ensemble.json\"):\n model_is_ensemble = True\n model = Ensemble()\n model.load(model_file)\n else:\n model_is_ensemble = False\n model = ScoreEstimator()\n model.load(model_file)\n\n # Nuisance parameters?\n if model.n_parameters == self.n_parameters:\n logger.debug(\n \"Found %s parameters in SALLY model, matching %s physical parameters in MadMiner file\",\n model.n_parameters,\n self.n_parameters,\n )\n include_nuisance_parameters = False\n elif model.n_parameters == self.n_parameters + self.n_nuisance_parameters:\n logger.debug(\n \"Found %s parameters in SALLY model, matching %s physical parameters + %s nuisance parameters\"\n + \" in MadMiner file\",\n model.n_parameters,\n self.n_parameters,\n self.n_nuisance_parameters,\n )\n include_nuisance_parameters = True\n else:\n raise RuntimeError(\n \"Inconsistent numbers of parameters! Found %s in SALLY model, %s physical parameters in \"\n \"MadMiner file, and %s nuisance parameters in MadMiner file.\",\n model.n_parameters,\n self.n_parameters,\n self.n_nuisance_parameters,\n )\n\n # Total xsec\n total_xsec = self._calculate_xsec(theta=theta)\n logger.debug(\"Total cross section: %s pb\", total_xsec)\n\n # Which events to sum over\n if test_split is None or test_split <= 0.0 or test_split >= 1.0:\n start_event = 0\n else:\n start_event = int(round((1.0 - test_split) * self.n_samples, 0)) + 1\n\n if start_event > 0:\n total_sum_weights_theta = self._calculate_xsec(theta=theta, start_event=start_event)\n else:\n total_sum_weights_theta = total_xsec\n\n # Number of batches\n n_batches = int(np.ceil((self.n_samples - start_event) / batch_size))\n n_batches_verbose = max(int(round(n_batches / 10, 0)), 1)\n\n # ML main loop\n for i_batch, (observations, weights_benchmarks) in enumerate(\n self.event_loader(\n batch_size=batch_size, start=start_event, include_nuisance_parameters=include_nuisance_parameters\n )\n ):\n if (i_batch + 1) % n_batches_verbose == 0:\n logger.info(\"Evaluating kinematic Fisher information on batch %s / %s\", i_batch + 1, n_batches)\n else:\n logger.debug(\"Evaluating kinematic Fisher information on batch %s / %s\", i_batch + 1, n_batches)\n\n # Cuts\n cut_filter = [self._pass_cuts(obs_event, cuts) for obs_event in observations]\n observations = observations[cut_filter]\n weights_benchmarks = weights_benchmarks[cut_filter]\n\n # Efficiencies\n efficiencies = np.array(\n [self._eval_efficiency(obs_event, efficiency_functions) for obs_event in observations]\n )\n weights_benchmarks *= efficiencies[:, np.newaxis]\n\n # Rescale for test_split\n if test_split is not None:\n correction = np.array([1.0 / test_split for obs_event in observations])\n weights_benchmarks *= correction[:, np.newaxis]\n\n weights_theta = mdot(theta_matrix, weights_benchmarks)\n\n # Calculate Fisher info on this batch\n if model_is_ensemble:\n fisher_info_events, _ = model.calculate_fisher_information(\n x=observations,\n obs_weights=weights_theta,\n n_events=luminosity * np.sum(weights_theta),\n mode=\"score\",\n calculate_covariance=False,\n sum_events=False,\n )\n else:\n fisher_info_events = model.calculate_fisher_information(\n x=observations,\n weights=weights_theta,\n n_events=luminosity * np.sum(weights_theta),\n sum_events=False,\n )\n\n # Get rid of nuisance parameters\n if include_nuisance_parameters:\n fisher_info_events = fisher_info_events[:, : self.n_parameters, : self.n_parameters]\n\n # Evaluate histogrammed observable\n histo_observables = np.asarray(\n [self._eval_observable(obs_event, observable) for obs_event in observations]\n )\n\n # Find bins\n bins = np.searchsorted(bin_boundaries, histo_observables)\n assert ((0 <= bins) & (bins < n_bins_total)).all(), \"Wrong bin {}\".format(bins)\n\n # Add up\n for i in range(n_bins_total):\n if len(weights_benchmarks[bins == i]) > 0:\n weights_benchmarks_bins[i] += np.sum(weights_benchmarks[bins == i], axis=0)\n fisher_info_full_bins[i] += np.sum(fisher_info_events[bins == i], axis=0)\n\n # Calculate xsecs in bins\n sigma_bins = mdot(theta_matrix, weights_benchmarks_bins) # (n_bins,)\n\n # Calculate rate-only Fisher informations in bins\n fisher_info_rate_bins = self._calculate_fisher_information(\n theta, weights_benchmarks_bins, luminosity, sum_events=False\n )\n\n # Get rid of nuisance parameters\n fisher_info_rate_bins = fisher_info_rate_bins[:, : self.n_parameters, : self.n_parameters]\n\n # If ML: xsec info is still missing !\n if model_file is not None:\n fisher_info_full_bins += fisher_info_rate_bins\n\n return bin_boundaries, sigma_bins, fisher_info_rate_bins, fisher_info_full_bins\n\n def histogram_of_sigma_dsigma(self, theta, observable, nbins, histrange, cuts=None, efficiency_functions=None):\n \"\"\"\n Fills events into histograms and calculates the cross section and first derivative for each bin\n \n Parameters\n ----------\n theta : ndarray\n Parameter point `theta` at which the Fisher information matrix `I_ij(theta)` is evaluated.\n \n observable : str\n Expression for the observable to be sliced. The str will be parsed by Python's `eval()` function\n and can use the names of the observables in the MadMiner files.\n \n nbins : int\n Number of bins in the slicing, excluding overflow bins.\n \n histrange : tuple of float\n Minimum and maximum value of the slicing in the form `(min, max)`. Overflow bins are always added.\n \n cuts : None or list of str, optional\n Cuts. Each entry is a parseable Python expression that returns a bool (True if the event should pass a cut,\n False otherwise). Default value: None.\n \n efficiency_functions : list of str or None\n Efficiencies. Each entry is a parseable Python expression that returns a float for the efficiency of one\n component. Default value: None.\n\n Returns\n -------\n bin_boundaries : ndarray\n Observable slice boundaries.\n \n sigma_bins : ndarray\n Cross section in pb in each of the slices.\n \n dsigma_bins : ndarray\n Cross section in pb in each of the slices.\n \"\"\"\n\n # Input\n if cuts is None:\n cuts = []\n if efficiency_functions is None:\n efficiency_functions = []\n\n # Binning\n dynamic_binning = histrange is None\n if dynamic_binning:\n n_bins_total = nbins\n bin_boundaries = self._calculate_dynamic_binning(observable, theta, nbins, None, cuts, efficiency_functions)\n else:\n n_bins_total = nbins + 2\n bin_boundaries = np.linspace(histrange[0], histrange[1], num=nbins + 1)\n\n # # Number of bins\n # n_bins_total = nbins + 2\n # bin_boundaries = np.linspace(histrange[0], histrange[1], num=nbins + 1)\n\n # Prepare output\n weights_benchmarks_bins = np.zeros((n_bins_total, self.n_benchmarks))\n\n # Main loop: truth-level case\n for observations, weights in self.event_loader():\n\n # Cuts\n cut_filter = [self._pass_cuts(obs_event, cuts) for obs_event in observations]\n observations = observations[cut_filter]\n weights = weights[cut_filter]\n\n # Efficiencies\n efficiencies = np.array(\n [self._eval_efficiency(obs_event, efficiency_functions) for obs_event in observations]\n )\n weights *= efficiencies[:, np.newaxis]\n\n # Evaluate histogrammed observable\n histo_observables = np.asarray([self._eval_observable(obs_event, observable) for obs_event in observations])\n\n # Find bins\n bins = np.searchsorted(bin_boundaries, histo_observables)\n assert ((0 <= bins) & (bins < n_bins_total)).all(), \"Wrong bin {}\".format(bins)\n\n # Add up\n for i in range(n_bins_total):\n if len(weights[bins == i]) > 0:\n weights_benchmarks_bins[i] += np.sum(weights[bins == i], axis=0)\n\n # Get morphing matrices\n theta_matrix = self._get_theta_benchmark_matrix(theta, zero_pad=False) # (n_benchmarks_phys,)\n dtheta_matrix = self._get_dtheta_benchmark_matrix(theta, zero_pad=False) # (n_parameters, n_benchmarks_phys)\n\n # Calculate xsecs in bins\n sigma_bins = mdot(theta_matrix, weights_benchmarks_bins) # (n_bins,)\n dsigma_bins = mdot(dtheta_matrix, weights_benchmarks_bins) # (n_parameters,n_bins,)\n\n return bin_boundaries, sigma_bins, dsigma_bins\n\n def nuisance_constraint_information(self):\n \"\"\" Builds the Fisher information term representing the Gaussian constraints on the nuisance parameters \"\"\"\n\n diagonal = np.array([0.0 for _ in range(self.n_parameters)] + [1.0 for _ in range(self.n_nuisance_parameters)])\n return np.diag(diagonal)\n\n def _check_binning_stats(\n self, weights_benchmarks, weights_benchmark_uncertainties, theta, report=5, n_bins_last_axis=None\n ):\n theta_matrix = self._get_theta_benchmark_matrix(theta, zero_pad=False) # (n_benchmarks_phys,)\n sigma = mdot(theta_matrix, weights_benchmarks) # Shape (n_bins,)\n sigma_uncertainties = mdot(theta_matrix, weights_benchmark_uncertainties) # Shape (n_bins,)\n rel_uncertainties = sigma_uncertainties / np.maximum(sigma, 1.0e-12)\n\n order = np.argsort(rel_uncertainties)[::-1]\n\n logger.info(\"Bins with largest statistical uncertainties on rates:\")\n for i_bin in order[:report]:\n bin_nd = i_bin + 1\n if n_bins_last_axis is not None:\n bin_nd = (i_bin // n_bins_last_axis + 1, i_bin % n_bins_last_axis + 1)\n logger.info(\n \" Bin %s: (%.5f +/- %.5f) fb (%.0f %%)\",\n bin_nd,\n 1000.0 * sigma[i_bin],\n 1000.0 * sigma_uncertainties[i_bin],\n 100.0 * rel_uncertainties[i_bin],\n )\n\n def _calculate_binning(\n self, bins, cuts, efficiency_functions, histrange, n_events_dynamic_binning, observable, theta\n ):\n dynamic_binning = histrange is None and isinstance(bins, int)\n if dynamic_binning:\n n_bins_total = bins\n bin_boundaries = self._calculate_dynamic_binning(\n observable, theta, bins, n_events_dynamic_binning, cuts, efficiency_functions\n )\n logger.debug(\"Automatic dynamic binning: bin boundaries %s\", bin_boundaries)\n elif isinstance(bins, int):\n n_bins_total = bins + 2\n bin_boundaries = np.linspace(histrange[0], histrange[1], num=bins + 1)\n else:\n bin_boundaries = bins\n n_bins_total = len(bins) + 1\n return bin_boundaries, n_bins_total\n\n def _calculate_fisher_information(\n self,\n theta,\n weights_benchmarks,\n luminosity=300000.0,\n include_nuisance_parameters=True,\n sum_events=False,\n calculate_uncertainty=False,\n weights_benchmark_uncertainties=None,\n ):\n \"\"\"\n Low-level function that calculates a list of full Fisher information matrices for a given parameter point and\n benchmark weights. Do not use this function directly, instead use the other `FisherInformation` functions.\n\n Parameters\n ----------\n theta : ndarray\n Parameter point.\n\n weights_benchmarks : ndarray\n Benchmark weights. Shape (n_events, n_benchmark).\n\n luminosity : float, optional\n Luminosity in pb^-1. Default value: 300000.\n\n include_nuisance_parameters : bool, optional\n If True, nuisance parameters are taken into account. Default value: True.\n\n sum_events : bool, optional\n If True, returns the summed FIsher information. Otherwise, a list of Fisher\n information matrices for each event. Default value: False.\n\n calculate_uncertainty : bool, optional\n Whether an uncertainty of the result is calculated. Note that this uncertainty is currently only\n implemented for the \"physical\" part of the FIsher information, not for the nuisance parameters. Default\n value: False.\n\n weights_benchmark_uncertainties : ndarray or None, optional\n If calculate_uncertainty is True, weights_benchmark_uncertainties sets the uncertainties on each entry of\n weights_benchmarks. If None, weights_benchmark_uncertainties = weights_benchmarks is assumed.\n\n Returns\n -------\n fisher_information : ndarray\n If sum_events is True, the return value is an nxn matrix, the total Fisher information\n summed over all events. Otherwise, a n_events x n_parameters x n_parameters tensor is returned that\n includes the Fisher information matrices for each event separately.\n\n fisher_information_uncertainty : ndarray\n Only returned if calculate_uncertainty is True. Covariance matrix of the Fisher information. Note that this\n does not take into account any uncertainty on the nuisance parameter part of the Fisher information, and\n correlations between events are neglected. Note that independent of sum_events, the covariance matrix is\n always summed over the events.\n\n \"\"\"\n\n include_nuisance_parameters = include_nuisance_parameters and self.include_nuisance_parameters\n\n # Get morphing matrices\n theta_matrix = self._get_theta_benchmark_matrix(theta, zero_pad=False) # (n_benchmarks_phys,)\n dtheta_matrix = self._get_dtheta_benchmark_matrix(theta, zero_pad=False) # (n_parameters, n_benchmarks_phys)\n\n # Get differential xsec per event, and the derivative wrt to theta\n sigma = mdot(theta_matrix, weights_benchmarks) # Shape (n_events,)\n total_xsec = np.sum(sigma)\n inv_sigma = sanitize_array(1.0 / sigma) # Shape (n_events,)\n dsigma = mdot(dtheta_matrix, weights_benchmarks) # Shape (n_parameters, n_events)\n\n # Calculate physics Fisher info for this event\n fisher_info_phys = luminosity * np.einsum(\"n,in,jn->nij\", inv_sigma, dsigma, dsigma)\n\n # Nuisance parameter Fisher info\n if include_nuisance_parameters:\n nuisance_a = self.nuisance_morpher.calculate_a(weights_benchmarks) # Shape (n_nuisance_params, n_events)\n # grad_i dsigma(x), where i is a nuisance parameter, is given by\n # sigma[np.newaxis, :] * a\n\n fisher_info_nuisance = luminosity * np.einsum(\"n,in,jn->nij\", sigma, nuisance_a, nuisance_a)\n fisher_info_mix = luminosity * np.einsum(\"in,jn->nij\", dsigma, nuisance_a)\n fisher_info_mix_transposed = luminosity * np.einsum(\"in,jn->nji\", dsigma, nuisance_a)\n\n n_all_parameters = self.n_parameters + self.n_nuisance_parameters\n fisher_info = np.zeros((fisher_info_phys.shape[0], n_all_parameters, n_all_parameters))\n fisher_info[:, : self.n_parameters, : self.n_parameters] = fisher_info_phys\n fisher_info[:, : self.n_parameters, self.n_parameters :] = fisher_info_mix\n fisher_info[:, self.n_parameters :, : self.n_parameters] = fisher_info_mix_transposed\n fisher_info[:, self.n_parameters :, self.n_parameters :] = fisher_info_nuisance\n\n else:\n n_all_parameters = self.n_parameters\n fisher_info = fisher_info_phys\n\n # Error propagation\n if calculate_uncertainty:\n if weights_benchmarks.shape[1] > self.n_benchmarks_phys:\n weights_benchmarks_phys = weights_benchmarks[:, np.logical_not(self.benchmark_is_nuisance)]\n else:\n weights_benchmarks_phys = weights_benchmarks\n\n n_events = weights_benchmarks_phys.shape[0]\n\n # Input uncertainties\n if weights_benchmark_uncertainties is None:\n weights_benchmark_uncertainties = weights_benchmarks_phys # Shape (n_events, n_benchmarks_phys)\n\n # Build covariance matrix of inputs\n # We assume full correlation between weights_benchmarks[i, b1] and weights_benchmarks[i, b2]\n covariance_inputs = np.zeros((n_events, self.n_benchmarks_phys, self.n_benchmarks_phys))\n for i in range(n_events):\n for b1 in range(self.n_benchmarks_phys):\n for b2 in range(self.n_benchmarks_phys):\n\n if b1 == b2: # Diagonal\n covariance_inputs[i, b1, b2] = weights_benchmark_uncertainties[i, b1] ** 2\n\n else: # Off-diagonal, same event\n covariance_inputs[i, b1, b2] = (\n weights_benchmark_uncertainties[i, b1] * weights_benchmark_uncertainties[i, b2]\n )\n\n # Jacobian\n temp1 = np.einsum(\"ib,jn,n->ijnb\", dtheta_matrix, dsigma, inv_sigma)\n temp2 = np.einsum(\"jb,in,n->ijnb\", dtheta_matrix, dsigma, inv_sigma)\n temp3 = np.einsum(\"b,in,jn,n,n->ijnb\", theta_matrix, dsigma, dsigma, inv_sigma, inv_sigma)\n\n temp1, temp2, temp3 = sanitize_array(temp1), sanitize_array(temp2), sanitize_array(temp3)\n\n jacobian = luminosity * (temp1 + temp2 + temp3) # (n_parameters, n_parameters, n_events, n_benchmarks_phys)\n\n # Covariance of information\n covariance_information_phys = np.einsum(\"ijnb,nbc,klnc->ijkl\", jacobian, covariance_inputs, jacobian)\n\n if include_nuisance_parameters:\n covariance_information = np.zeros(\n (n_all_parameters, n_all_parameters, n_all_parameters, n_all_parameters)\n )\n covariance_information[\n : self.n_parameters, : self.n_parameters, : self.n_parameters, : self.n_parameters\n ] = covariance_information_phys\n else:\n covariance_information = covariance_information_phys\n\n if sum_events:\n return np.sum(fisher_info, axis=0), covariance_information\n return fisher_info, covariance_information\n\n if sum_events:\n return np.sum(fisher_info, axis=0)\n return fisher_info\n\n def _pass_cuts(self, observations, cuts=None):\n \"\"\"\n Checks if an event, specified by a list of observations, passes a set of cuts.\n\n Parameters\n ----------\n observations : list of float\n list of float. Values of the observables for a single event.\n\n cuts : list of str or None, optional\n Each entry is a parseable Python expression that returns a bool (True if the event should pass a cut,\n False otherwise). Default value: None.\n\n Returns\n -------\n passes : bool\n True if the event passes all cuts, False otherwise.\n\n \"\"\"\n\n # Check inputs\n if cuts is None:\n cuts = []\n\n assert len(observations) == len(self.observables), \"Mismatch between observables and observations\"\n\n # Variables that can be used in cuts\n variables = math_commands()\n\n for observable_name, observable_value in zip(self.observables, observations):\n variables[observable_name] = observable_value\n\n # Check cuts\n for cut in cuts:\n if not bool(eval(cut, variables)):\n return False\n\n return True\n\n def _eval_efficiency(self, observations, efficiency_functions=None):\n \"\"\"\n Calculates the efficiency for an event.\n\n Parameters\n ----------\n observations : list of float\n Values of the observables.\n\n efficiency_functions : list of str or None\n Each entry is a parseable Python expression that returns a float for the efficiency of one component.\n Default value: None.\n\n Returns\n -------\n efficiency : float\n Efficiency (0. <= efficiency <= 1.), product of the results of the calls to all entries in\n efficiency_functions.\n\n \"\"\"\n\n # Check inputs\n if efficiency_functions is None:\n efficiency_functions = []\n\n assert len(observations) == len(self.observables), \"Mismatch between observables and observations\"\n\n # Variables that can be used in efficiency functions\n variables = math_commands()\n\n for observable_name, observable_value in zip(self.observables, observations):\n variables[observable_name] = observable_value\n\n # Check cuts\n efficiency = 1.0\n for efficency_function in efficiency_functions:\n efficiency *= float(eval(efficency_function, variables))\n\n return efficiency\n\n def _eval_observable(self, observations, observable_definition):\n \"\"\"\n Calculates an observable expression for an event.\n\n Parameters\n ----------\n observations : ndarray\n Values of the observables for an event, should have shape `(n_observables,)`.\n\n observable_definition : str\n A parseable Python expression that returns the value of the observable to be calculated.\n\n Returns\n -------\n observable_value : float\n Value of the observable defined in observable_definition.\n\n \"\"\"\n\n assert len(observations) == len(self.observables), \"Mismatch between observables and observations\"\n\n # Variables that can be used in efficiency functions\n variables = math_commands()\n\n for observable_name, observable_value in zip(self.observables, observations):\n variables[observable_name] = observable_value\n\n # Check cuts\n return float(eval(observable_definition, variables))\n\n def _calculate_xsec(\n self,\n theta=None,\n cuts=None,\n efficiency_functions=None,\n return_benchmark_xsecs=False,\n return_error=False,\n include_nuisance_parameters=True,\n start_event=0,\n ):\n \"\"\"\n Calculates the total cross section for a parameter point.\n\n Parameters\n ----------\n theta : ndarray or None, optional\n The parameter point. If None, return_benchmark_xsecs should be True. Default value: None.\n\n cuts : list of str or None, optional\n Cuts. Each entry is a parseable Python expression that returns a bool (True if the event should pass a cut,\n False otherwise). Default value: None.\n\n efficiency_functions : list of str or None\n Efficiencies. Each entry is a parseable Python expression that returns a float for the efficiency of one\n component. Default value: None.\n\n return_benchmark_xsecs : bool, optional\n If True, this function returns the benchmark xsecs. Otherwise, it returns the xsec at theta. Default value:\n False.\n\n return_error : bool, optional\n If True, this function also returns the square root of the summed squared weights.\n\n include_nuisance_parameters : bool, optional\n If True and if return_benchmark_xsecs is True, the nuisance benchmarks are included in the output. Default\n value: True.\n\n start_event : int, optional\n Index of first event in MadMiner file to consider. Default value: 0.\n\n Returns\n -------\n xsec : ndarray or float\n If return_benchmark_xsecs is True, an ndarray of benchmark xsecs in pb is returned. Otherwise, the cross\n section at theta in pb is returned.\n\n xsec_uncertainty : ndarray or float\n Only returned if return_error is True. Uncertainty (square root of the summed squared weights) on xsec.\n\n \"\"\"\n\n logger.debug(\"Calculating total cross section for theta = %s\", theta)\n\n # Input\n if cuts is None:\n cuts = []\n if efficiency_functions is None:\n efficiency_functions = []\n\n assert (theta is not None) or return_benchmark_xsecs, \"Please supply theta or set return_benchmark_xsecs=True\"\n\n # Total xsecs for benchmarks\n xsecs_benchmarks = None\n xsecs_uncertainty_benchmarks = None\n\n for observations, weights in self.event_loader(\n start=start_event, include_nuisance_parameters=include_nuisance_parameters\n ):\n # Cuts\n cut_filter = [self._pass_cuts(obs_event, cuts) for obs_event in observations]\n observations = observations[cut_filter]\n weights = weights[cut_filter]\n\n # Efficiencies\n efficiencies = np.array(\n [self._eval_efficiency(obs_event, efficiency_functions) for obs_event in observations]\n )\n weights *= efficiencies[:, np.newaxis]\n\n # xsecs\n if xsecs_benchmarks is None:\n xsecs_benchmarks = np.sum(weights, axis=0)\n xsecs_uncertainty_benchmarks = np.sum(weights ** 2, axis=0)\n else:\n xsecs_benchmarks += np.sum(weights, axis=0)\n xsecs_uncertainty_benchmarks += np.sum(weights ** 2, axis=0)\n\n assert xsecs_benchmarks is not None, \"No events passed cuts\"\n\n xsecs_uncertainty_benchmarks = xsecs_uncertainty_benchmarks ** 0.5\n\n logger.debug(\"Benchmarks xsecs [pb]: %s\", xsecs_benchmarks)\n\n if return_benchmark_xsecs:\n if return_error:\n return xsecs_benchmarks, xsecs_uncertainty_benchmarks\n return xsecs_benchmarks\n\n # Translate to xsec for theta\n theta_matrix = self._get_theta_benchmark_matrix(theta)\n xsec = mdot(theta_matrix, xsecs_benchmarks)\n xsec_error = mdot(theta_matrix, xsecs_uncertainty_benchmarks)\n\n logger.debug(\"Theta matrix: %s\", theta_matrix)\n logger.debug(\"Cross section at theta: %s pb\", xsec)\n\n if return_error:\n return xsec, xsec_error\n return xsec\n\n def _calculate_dynamic_binning(\n self, observable, theta, n_bins, n_events=None, cuts=None, efficiency_functions=None\n ):\n\n if cuts is None:\n cuts = []\n if efficiency_functions is None:\n efficiency_functions = []\n\n # Quantile values\n quantile_values = np.linspace(0.0, 1.0, n_bins + 1)\n\n # Get data\n x_pilot, weights_pilot = next(self.event_loader(batch_size=n_events))\n\n # Cuts\n cut_filter = [self._pass_cuts(x, cuts) for x in x_pilot]\n x_pilot = x_pilot[cut_filter]\n weights_pilot = weights_pilot[cut_filter]\n\n # Efficiencies\n efficiencies = np.array([self._eval_efficiency(x, efficiency_functions) for x in x_pilot])\n weights_pilot *= efficiencies[:, np.newaxis]\n\n # Evaluate histogrammed observable\n histo_observables_pilot = np.asarray([self._eval_observable(x, observable) for x in x_pilot])\n\n # Weights at theta\n theta_matrix = self._get_theta_benchmark_matrix(theta)\n weight_theta_pilot = mdot(theta_matrix, weights_pilot)\n\n # Bin boundaries\n bin_boundaries = weighted_quantile(histo_observables_pilot, quantile_values, weight_theta_pilot)\n bin_boundaries = bin_boundaries[1:-1]\n\n return bin_boundaries\n\n # Aliases for backward compatibility\n calculate_fisher_information_full_truth = truth_information\n calculate_fisher_information_full_detector = full_information\n calculate_fisher_information_rate = rate_information\n calculate_fisher_information_hist1d = histo_information\n calculate_fisher_information_hist2d = histo_information_2d\n histogram_of_fisher_information = histogram_of_information\n calculate_fisher_information_nuisance_constraints = nuisance_constraint_information\n\n\ndef project_information(fisher_information, remaining_components, covariance=None):\n \"\"\"\n Calculates projections of a Fisher information matrix, that is, \"deletes\" the rows and columns corresponding to\n some parameters not of interest.\n\n Parameters\n ----------\n fisher_information : ndarray\n Original n x n Fisher information.\n\n remaining_components : list of int\n List with m entries, each an int with 0 <= remaining_compoinents[i] < n. Denotes which parameters are kept, and\n their new order. All other parameters or projected out.\n\n covariance : ndarray or None, optional\n The covariance matrix of the original Fisher information with shape (n, n, n, n). If None, the error on the\n profiled information is not calculated. Default value: None.\n\n Returns\n -------\n projected_fisher_information : ndarray\n Projected m x m Fisher information, where the `i`-th row or column corresponds to the\n `remaining_components[i]`-th row or column of fisher_information.\n\n profiled_fisher_information_covariance : ndarray\n Covariance matrix of the projected Fisher information matrix with shape (m, m, m, m). Only returned if\n covariance is not None.\n\n \"\"\"\n n_new = len(remaining_components)\n fisher_information_new = np.zeros([n_new, n_new])\n\n # Project information\n for xnew, xold in enumerate(remaining_components):\n for ynew, yold in enumerate(remaining_components):\n fisher_information_new[xnew, ynew] = fisher_information[xold, yold]\n\n # Project covariance matrix\n if covariance is not None:\n covariance_new = np.zeros([n_new, n_new, n_new, n_new])\n for xnew, xold in enumerate(remaining_components):\n for ynew, yold in enumerate(remaining_components):\n for znew, zold in enumerate(remaining_components):\n for zznew, zzold in enumerate(remaining_components):\n covariance_new[xnew, ynew, znew, zznew] = covariance[xold, yold, zold, zzold]\n\n return fisher_information_new, covariance_new\n\n return fisher_information_new\n\n\ndef profile_information(\n fisher_information,\n remaining_components,\n covariance=None,\n error_propagation_n_ensemble=1000,\n error_propagation_factor=1.0e-3,\n):\n \"\"\"\n Calculates the profiled Fisher information matrix as defined in Appendix A.4 of arXiv:1612.05261.\n\n Parameters\n ----------\n fisher_information : ndarray\n Original n x n Fisher information.\n\n remaining_components : list of int\n List with m entries, each an int with 0 <= remaining_compoinents[i] < n. Denotes which parameters are kept, and\n their new order. All other parameters or profiled out.\n\n covariance : ndarray or None, optional\n The covariance matrix of the original Fisher information with shape (n, n, n, n). If None, the error on the\n profiled information is not calculated. Default value: None.\n\n error_propagation_n_ensemble : int, optional\n If covariance is not None, this sets the number of Fisher information matrices drawn from a normal distribution\n for the Monte-Carlo error propagation. Default value: 1000.\n\n error_propagation_factor : float, optional\n If covariance is not None, this factor multiplies the covariance of the distribution of Fisher information\n matrices. Smaller factors can avoid problems with ill-behaved Fisher information matrices. Default value: 1.e-3.\n\n Returns\n -------\n profiled_fisher_information : ndarray\n Profiled m x m Fisher information, where the `i`-th row or column corresponds to the\n `remaining_components[i]`-th row or column of fisher_information.\n\n profiled_fisher_information_covariance : ndarray\n Covariance matrix of the profiled Fishere information matrix with shape (m, m, m, m).\n\n \"\"\"\n\n logger.debug(\"Profiling Fisher information\")\n n_components = len(fisher_information)\n n_remaining_components = len(remaining_components)\n\n _, information_phys, information_mix, information_nuisance = separate_information_blocks(\n fisher_information, remaining_components\n )\n\n # Error propagation\n if covariance is not None:\n # Central value\n profiled_information = profile_information(\n fisher_information, remaining_components=remaining_components, covariance=None\n )\n\n # Draw toys\n information_toys = np.random.multivariate_normal(\n mean=fisher_information.reshape((-1,)),\n cov=error_propagation_factor * covariance.reshape(n_components ** 2, n_components ** 2),\n size=error_propagation_n_ensemble,\n )\n information_toys = information_toys.reshape(-1, n_components, n_components)\n\n # Profile each toy\n profiled_information_toys = np.array(\n [\n profile_information(info, remaining_components=remaining_components, covariance=None)\n for info in information_toys\n ]\n )\n\n # Calculate ensemble covariance\n toy_covariance = np.cov(profiled_information_toys.reshape(-1, n_remaining_components ** 2).T)\n toy_covariance = toy_covariance.reshape(\n (n_remaining_components, n_remaining_components, n_remaining_components, n_remaining_components)\n )\n profiled_information_covariance = toy_covariance / error_propagation_factor\n\n # Cross-check: toy mean\n toy_mean = np.mean(profiled_information_toys, axis=0)\n logger.debug(\"Central Fisher info:\\n%s\\nToy mean Fisher info:\\n%s\", profiled_information, toy_mean)\n\n return profiled_information, profiled_information_covariance\n\n # Calculate profiled information\n inverse_information_nuisance = np.linalg.inv(information_nuisance)\n profiled_information = information_phys - information_mix.T.dot(inverse_information_nuisance.dot(information_mix))\n\n return profiled_information\n\n\nclass InformationGeometry:\n\n \"\"\"\n Functions to calculate limits using Information Geometry.\n \n After initializing the `InformationGeometry` class, a Fisher Information needs to be provided using\n one of the following functions\n \n * `InformationGeometry.information_from_formula()` defines the Fisher Information\n explicitly as function of the theory paramters `theta`.\n * `InformationGeometry.information_from_grid()` loads a grid of Fisher Informations\n which is then interpolated.\n \n Using information geometrical methods, the function `InformationGeometry.distance_contours()` then\n calculates the distance contours and equivalently the p-values throughout parameter space.\n \n \"\"\"\n\n def __init__(self):\n self.infotype = None\n self.dimension = 0\n self.information_formula = None\n self.inverse = \"exact\"\n\n def information_from_formula(self, formula, dimension):\n \"\"\"\n Explicitly defines the Fisher Information as function of the theory parameter `theta`\n through a formula that can be avaulated using `eval()`.\n \n Parameters\n ----------\n formula : str\n Explicit definition of the Fisher Information as ndarray, which can be a function of\n the n-dimensional theory parameter `theta`.\n Example: formula=\"np.array([[1+theta[0],1],[1,2*theta[1]**2]])\"\n \n dimension : int\n Dimensionality of the theory parameter space.\n \"\"\"\n\n self.infotype = \"formula\"\n self.dimension = dimension\n self.information_formula = formula\n\n def information_from_grid(self, theta_grid, fisherinformation_grid, option=\"smooth\", inverse=\"exact\"):\n \"\"\"\n Loads a grid of coordinates and corresponding Fisher Information, which is then interpolated.\n \n Parameters\n ----------\n theta_grid : ndarray\n List if parameter points `theta` at which the Fisher information matrices `I_ij(theta)`\n is evaluated. Shape (n_gridpoints, n_dimension).\n \n fisherinformation_grid : ndarray\n List if Fisher information matrices `I_ij(theta)`. Shape (n_gridpoints, n_dimension, n_dimension).\n \n option : {\"smooth\", \"linear\"}\n Defines if the Fisher Information is interpolated smoothly using the function\n CloughTocher2DInterpolator() or piecewise linear using LinearNDInterpolator().\n Default = 'smooth'.\n \n inverse : {\"exact\", \"interpolate\"}\n Defines if the inverse Fisher Information is obtained by either first interpolating\n the Fisher Information and then inverting it (\"exact\") or by first inverting the grid\n of Fisher Informations and then interpolating the inverse (\"interpolate\"). Default = 'exact'.\n \"\"\"\n\n self.infotype = \"grid\"\n self.inverse = inverse\n\n # load from file\n theta_grid = load_and_check(theta_grid)\n fisherinformation_grid = load_and_check(fisherinformation_grid)\n self.dimension = len(fisherinformation_grid[0])\n\n # Interpolate Information\n if option == \"linear\":\n self.infofunction = LinearNDInterpolator(points=theta_grid, values=np.array(fisherinformation_grid))\n elif option == \"smooth\":\n self.infofunction = CloughTocher2DInterpolator(points=theta_grid, values=np.array(fisherinformation_grid))\n else:\n RuntimeError(\"Option %s unknown\", option)\n\n # Interpolate inverse information\n if self.inverse == \"interpolate\":\n inv_fisherinformation_grid = np.array([np.linalg.inv(info) for info in fisherinformation_grid])\n if option == \"linear\":\n self.infofunction_inv = LinearNDInterpolator(points=theta_grid, values=inv_fisherinformation_grid)\n elif option == \"smooth\":\n self.infofunction_inv = CloughTocher2DInterpolator(points=theta_grid, values=inv_fisherinformation_grid)\n\n def _information(self, theta):\n \"\"\"\n Low level function that calculates the Fisher Information as function of\n the theory parameter `theta`\n \n Parameters\n ----------\n theta : ndarray\n Parameter point `theta` at which the Fisher information matrix `I_ij(theta)` is evaluated.\n \n Returns\n -------\n fisher_information : ndarray\n Fisher information matrix with shape `(n_dimension, n_dimension)`.\n \"\"\"\n\n # check input format\n assert len(theta) == self.dimension, \"theta should have length %r, not %r\" % (self.dimension, len(theta))\n\n # calculate information\n if self.infotype == \"formula\":\n information = eval(self.information_formula)\n elif self.infotype == \"grid\":\n information = self.infofunction(tuple(theta))\n else:\n raise RuntimeError(\"Information not defined yet\")\n\n # check output format\n assert np.shape(information) == (self.dimension, self.dimension), \"information should have shape %r, not %r\" % (\n (self.dimension, self.dimension),\n np.shape(information),\n )\n\n return information\n\n def _information_inv(self, theta):\n \"\"\"\n Low level function that calculates the inverse Fisher Information as function of\n the theory parameter `theta`.\n \n Parameters\n ----------\n theta : ndarray\n Parameter point `theta` at which the inverse Fisher information\n matrix `I^{-1}_ij(theta)` is evaluated.\n \n Returns\n -------\n inverse_fisher_information : ndarray\n Inverse Fisher information matrix with shape `(n_dimension, n_dimension)`.\n \"\"\"\n\n if self.inverse == \"interpolate\":\n return self.infofunction_inv(tuple(theta))\n else:\n return np.linalg.inv(self._information(theta))\n\n def _information_derivative(self, theta):\n \"\"\"\n Low level function that calculates the derivative of Fisher Information\n `\\partial_k I_{ij}` at the theory parameter `theta`.\n \n Parameters\n ----------\n theta : ndarray\n Parameter point `theta` at which the derivative of the Fisher information\n matrix is evaluated.\n \n Returns\n -------\n fisher_information_derivative : ndarray\n Derivative of Fisher information matrix with shape `(n_dimension, n_dimension, n_dimension)`.\n \"\"\"\n\n epsilon = 10 ** -3\n dtheta = np.identity(len(theta)) * epsilon\n return np.array(\n [(self._information(theta + dtheta[k]) - self._information(theta)) / epsilon for k in range(len(theta))]\n )\n\n def _christoffel(self, theta):\n \"\"\"\n Low level function that calculates the Christoffel symbol (2nd kind) Gamma^i_jk at\n the theory parameter `theta`. Here Gamma^i_jk=0.5*I^{im}(\\partial_k I_{mj}\n + \\partial_j I_{mk} - \\partial_m I_{jk})\n \n Parameters\n ----------\n theta : ndarray\n Parameter point `theta` at which the Christoffel symbol is evaluated.\n \n Returns\n -------\n christoffel_symbol : ndarray\n Christoffel symbol with shape `(n_dimension, n_dimension, n_dimension)`.\n \"\"\"\n\n term1 = np.einsum(\"ad,cdb->abc\", self._information_inv(theta), self._information_derivative(theta))\n term2 = np.einsum(\"ad,bdc->abc\", self._information_inv(theta), self._information_derivative(theta))\n term3 = np.einsum(\"ad,bcd->abc\", self._information_inv(theta), self._information_derivative(theta))\n return 0.5 * (term1 + term2 - term3)\n\n def find_trajectory(self, theta0, dtheta0, limits, stepsize=1):\n \"\"\"\n Finds the geodesic trajectory starting at a parameter point theta0 going in the\n initial direction dtheta0.\n \n Parameters\n ----------\n theta0 : ndarray\n Parameter point `theta0` at which the geodesic trajectory starts.\n \n dtheta0 : ndarray\n Initial direction `dtheta0` of the geodesic\n \n limits : list of (tuple of float)\n Specifies the boundaries of the parameter grid in which the trajectory\n is evaulated. It should be `[[min, max], [min, max], ..., [min, max]`,\n where the list goes over all parameters and `min` and `max` are float.\n \n stepsize : int, optional\n Maximal stepsize `|Delta theta|` during numerical integration in parameter space.\n $Default: 1\n \n Returns\n -------\n list_of_theta : ndarray\n List of parameter points theta `(n_points, n_dimension)`.\n \n list_of_distance : ndarray\n List of distances from the staring point theta0 `(n_points, )`.\n \n \"\"\"\n\n # initiate starting point\n theta = 1.0 * theta0\n dtheta = 1.0 * dtheta0\n dist = 0\n output_theta = [1.0 * theta]\n output_dist = [0]\n\n # calculate free-fall trajectory\n counter = 0\n in_grid = True\n while in_grid and counter < 200:\n counter += 1\n # normalize dtheta to stepsize\n dtheta = dtheta / np.linalg.norm(dtheta)\n\n # calculate ddtheta and distance\n ddtheta = -1.0 * np.einsum(\"abc,b,c->a\", self._christoffel(theta), dtheta, dtheta)\n ddist = np.sqrt(np.einsum(\"ab,a,b\", self._information(theta), dtheta, dtheta))\n\n # determine stepsize to be used\n max_stepsize = 0.05 * np.linalg.norm(dtheta) / np.linalg.norm(ddtheta)\n use_stepsize = min(max_stepsize, stepsize)\n\n # update theta,dtheta, dist\n theta += dtheta * use_stepsize\n dtheta += ddtheta * use_stepsize\n dist += ddist * use_stepsize\n\n # save\n theta = np.array(theta)\n if np.isnan(dist):\n break\n output_theta.append(theta * 1.0)\n output_dist.append(dist * 1.0)\n\n # check if outside range\n for th, lim in zip(theta, limits):\n if th < lim[0] or th > lim[1]:\n in_grid = False\n\n return np.array(output_theta), output_dist\n\n def distance_contours(\n self,\n theta0,\n grid_ranges,\n grid_resolutions,\n stepsize=None,\n ntrajectories=None,\n continous_sampling=False,\n return_trajectories=False,\n ):\n \"\"\"\n Finds the distance values from the point theta0 and the corresponding p-value\n within the parameter space bounded by `grid_ranges`.\n \n Parameters\n ----------\n theta0 : ndarray\n Parameter point `theta0` at which the geodesic trajectory starts.\n \n grid_ranges : list of (tuple of float)\n Specifies the boundaries of the parameter grid in which the trajectory\n is evaulated. It should be `[[min, max], [min, max], ..., [min, max]`,\n where the list goes over all parameters and `min` and `max` are float.\n \n grid_resolutions : list of int\n Resolution of the parameter space grid on which the p-values are evaluated.\n The individual entries specify the number of points along each parameter individually.\n \n stepsize : float or None, optional\n Maximal stepsize `|Delta theta|` during numerical integration in parameter space.\n If None, stepsize = min([(max-min)/20 for (min,max) in grid_ranges]). Default: None\n \n ntrajectories : int or None, optional\n Number of sampled trajectories. If None, ntrajectories = 20 times the\n number of dimensions. Default: None\n \n continous_sampling : bool, optional\n If n_dimension is 2, the trajectories are sampled continously in the angular\n direction. Default: False\n \n return_trajectories : bool, optional\n Returns the trajectories (parameter points and distances). Default: False\n \n Returns\n -------\n theta_grid : ndarray\n Parameter points at which the p-values are evaluated with shape `(n_grid_points, n_dimension)`.\n \n p_values : ndarray\n Observed p-values for each parameter point on the grid, with shape `(n_grid_points,)`.\n \n p_values : ndarray\n Interpolated distance from theta0 for each parameter point on the grid,\n with shape `(n_grid_points,)`.\n \n (list_of_theta, list_of_distance) : (ndarray,ndarray)\n Only returned if return_trajectories is True. List of parameter points\n theta `(n_points, n_dimension)` and List of distances from the\n staring point theta0 `(n_points, )`.\n \n \"\"\"\n\n # automatic setting of stepsize and ntrajectories\n if stepsize == None:\n stepsize = min([(limit[1] - limit[0]) / 20.0 for limit in grid_ranges])\n if ntrajectories == None:\n ntrajectories = 20 * self.dimension\n if self.dimension is not 2:\n continous_sampling = False\n limits = (1.0 + 2.0 * stepsize) * np.array(grid_ranges)\n\n # determine trajectories\n thetas = []\n distances = []\n for i in range(ntrajectories):\n if continous_sampling:\n angle = 2.0 * np.pi / float(ntrajectories) * i\n dth0 = np.array([np.cos(angle), np.sin(angle)])\n else:\n dth0 = np.array([random.uniform(-1, 1) for _ in range(self.dimension)])\n logger.debug(\"Calculate Trajectory Number %s with dtheta0=%s\", i, dth0)\n ths, ds = self.find_trajectory(theta0, dth0, limits, stepsize)\n for th in ths:\n thetas.append(th)\n for d in ds:\n distances.append(d)\n thetas = np.array(thetas)\n\n # Create Theta Grid\n theta_grid_each = self._make_theta_grid_each(grid_ranges, grid_resolutions)\n theta_grid = self._make_theta_grid(grid_ranges, grid_resolutions)\n\n # Create Distance Grid\n distance_grid = griddata(thetas, distances, (theta_grid_each[0], theta_grid_each[1]), method=\"linear\")\n\n # Create p-value Grid\n p_value_grid = self._asymptotic_p_value(distance_grid)\n\n # return\n if return_trajectories:\n return theta_grid, p_value_grid, distance_grid, (thetas, distances)\n else:\n return theta_grid, p_value_grid, distance_grid\n\n def _make_theta_grid_each(self, grid_ranges, grid_resolutions):\n theta_each = []\n for resolution, (theta_min, theta_max) in zip(grid_resolutions, grid_ranges):\n theta_each.append(np.linspace(theta_min, theta_max, resolution))\n theta_grid_each = np.meshgrid(*theta_each, indexing=\"ij\")\n return theta_grid_each\n\n def _make_theta_grid(self, grid_ranges, grid_resolutions):\n theta_grid_each = self._make_theta_grid_each(grid_ranges, grid_resolutions)\n theta_grid_each = [theta.flatten() for theta in theta_grid_each]\n theta_grid = np.vstack(theta_grid_each).T\n return theta_grid\n\n def _asymptotic_p_value(self, dist):\n \"\"\"\n Low level function to convert distances in p-values\n \"\"\"\n p_value = chi2.sf(x=dist * dist, df=self.dimension)\n return p_value\n"
] |
[
[
"numpy.diag",
"numpy.linspace",
"numpy.einsum",
"numpy.mean",
"numpy.searchsorted",
"scipy.interpolate.griddata",
"numpy.sin",
"scipy.interpolate.CloughTocher2DInterpolator",
"numpy.ceil",
"numpy.zeros",
"numpy.logical_not",
"numpy.linalg.inv",
"numpy.isnan",
"scipy.interpolate.LinearNDInterpolator",
"numpy.argsort",
"numpy.meshgrid",
"numpy.array",
"numpy.sum",
"numpy.maximum",
"numpy.linalg.norm",
"numpy.cos",
"numpy.shape",
"scipy.stats.chi2.sf",
"numpy.vstack"
]
] |
aume1/SatelliteTracker
|
[
"62725e1d1a72a1350b2af15d9e33fcd574ceb3a2"
] |
[
"GPS.py"
] |
[
"import pigpio\nimport numpy as np\n\n\nclass GPS:\n def __init__(self, pi, default_lat_long_alt= [-33.85670, 151.21521, 5]):\n super().__init__()\n self.pi = pi\n self.ser = self.pi.serial_open('/dev/serial0', 9600)\n self.previous_lat_long_alt = default_lat_long_alt\n self.values = np.zeros(8)\n self.time = 0\n self.lat = 0\n self.long = 0\n self.alt = 0\n self.update()\n\n def update(self):\n available = self.pi.serial_data_available(self.ser)\n if available == 0:\n return self.previous_lat_long_alt\n (b, d) = self.pi.serial_read(self.ser, available)\n if b <= 0:\n return self.previous_lat_long_alt\n try:\n d = d.decode('utf-8')\n except UnicodeDecodeError:\n return self.previous_lat_long_alt\n if '$GPRMC' in d:\n d = d.split('$GPRMC')[1].split(',')\n if len(d) >= 9 and d[3] != '':\n # print(d)\n self.time = d[1]\n\n lat_deg = int(d[3][:2])\n lat_min = float(d[3][2:])/60\n self.lat = lat_deg + lat_min\n if d[4] == 'S':\n self.lat = -self.lat\n\n long_deg = int(d[5][:3])\n long_min = float(d[5][3:])/60\n self.long = long_deg + long_min\n if d[6] == \"W\":\n self.long = -self.long\n\n self.alt = float(d[8])\n self.previous_lat_long_alt = self.lat, self.long, self.alt\n\n return self.previous_lat_long_alt\n\n def close(self):\n self.pi.serial_close(self.ser)\n\n\nif __name__ == \"__main__\":\n print('GPS Testing')\n pi = pigpio.pi('192.168.178.229')\n print('connected to pi')\n gps = GPS(pi)\n import time\n while True:\n gps.update()\n print(gps.lat, gps.long)\n time.sleep(1.0)\n"
] |
[
[
"numpy.zeros"
]
] |
lhmartin/peptimizer
|
[
"ee96a52d5a7df38cf521c684ac57700d545014f8"
] |
[
"utils/utils_common/calc_charge.py"
] |
[
"import numpy as np\nimport math\n\ndef net_charge(sequence):\n \n '''\n Utility function to calculate net charge of a sequence\n Reference: http://www.chem.ucalgary.ca/courses/351/Carey5th/Ch27/ch27-1-4-2.html\n\n Parameters\n ----------\n sequence: str\n peptide sequence\n\n Returns\n -------\n charge: float\n net charge of sequence\n '''\n\n acidic = [sequence.count('D'), sequence.count('E'), sequence.count('C'), sequence.count('Y')]\n basic = [sequence.count('R'), sequence.count('K'), sequence.count('H')]\n\n acidic_pKa = [math.pow(10, 3.65), math.pow(10, 4.25), math.pow(10, 8.37), math.pow(10, 10.46)]\n basic_pKa = [math.pow(10, 10.76), math.pow(10, 9.74), math.pow(10, 7.59)]\n\n basic_coeff = [x*(1/(x+math.pow(10, 7))) for x in basic_pKa]\n acidic_coeff = [math.pow(10, 7)/(x+math.pow(10, 7)) for x in acidic_pKa]\n\n charge = - sum(np.multiply(acidic_coeff, acidic)) + sum(np.multiply(basic_coeff, basic))\n return charge"
] |
[
[
"numpy.multiply"
]
] |
jhapreis/MuonDecay
|
[
"2fc54cc7203f8f5815f8a13b9e8ddbf5253e75e7"
] |
[
"Analyze/modules/root_file/assemble_root_files.py"
] |
[
"import os\n\nimport ROOT as root\n\nimport pandas as pd\n\nfrom array import array\n\nfrom modules.out_file.read_output_file import Get_AcquisitionParameters\n\nfrom modules.out_file.convert_values import Convert_UnitsToMiliVolts_ScopeParameters\n\n\n\"\"\"\nFolder\n ROOT File\n TTree\n Branch\n Waveform\n Point on the waveform (ADChannel)\n\"\"\"\n\n\n\n#====================================================================================================\ndef unify_data_files(\n \n path_to_folders: \"list[str]\", \n\n tree_name: \"str\" = 'tree_waveforms',\n \n out_file: \"str\" = 'output.txt',\n \n outroot_folder_path: \"str\" = './',\n\n outroot_file_path: \"str\" = \"./muondecay.root\",\n \n number_ADChannels: \"int\" = 2500\n \n ) -> \"int\":\n \n\n #----------------------------------------------------------------------------------------------------\n event_name = array('i', [0])\n \n waveform_in_mv = array('f', [0]*number_ADChannels)\n \n \n #----------------------------------------------------------------------------------------------------\n out_root_file = root.TFile(outroot_file_path, \"RECREATE\")\n \n tree_waveforms = root.TTree(tree_name, \"waveforms\")\n \n tree_waveforms.Branch(\"names\" , event_name , \"name/I\")\n \n tree_waveforms.Branch(\"waveforms\", waveform_in_mv, f\"waveforms[{number_ADChannels}]/F\")\n \n df = pd.DataFrame()\n \n \n #---------------------------------------------------------------------------------------------------- \n for folder in path_to_folders:\n\n print(f' folder: {folder}')\n\n\n df_output = Get_AcquisitionParameters(folder+'/'+out_file)\n \n df = pd.concat([df, df_output], axis=0)\n \n \n root_files_in_folder = [(folder+_) for _ in os.listdir(folder) if _.endswith(\".root\")] \n \n if len(root_files_in_folder) == 0:\n\n print(' Não foram achados arquivos .root.')\n\n continue\n \n #---------------------------------------------------------------------------------------------------- \n chain = root.TChain(tree_name)\n \n for file in root_files_in_folder:\n \n chain.Add(file)\n \n wvfrm = array('i', [0]*number_ADChannels)\n \n name = array('i', [0])\n \n chain.SetBranchAddress(\"waveforms\", wvfrm)\n \n chain.SetBranchAddress(\"names\" , name )\n \n \n #----------------------------------------------------------------------------------------------------\n entries = chain.GetEntries()\n \n for i in range(entries):\n \n chain.GetEntry(i)\n \n for j in range(number_ADChannels):\n \n event_name[0] = name[0]\n \n waveform_in_mv[j] = wvfrm[j]\n \n '''\n O gargalo da função está aqui, nesse pedaço, que eu não consegui simplificar\n '''\n waveform_in_mv[j] = Convert_UnitsToMiliVolts_ScopeParameters(\n y_units=wvfrm[j],\n y_zero =df_output['y_zero'][0],\n y_off =df_output['y_off' ][0],\n y_mult =df_output['y_mult'][0]\n )\n \n tree_waveforms.Fill()\n \n \n \n \n #----------------------------------------------------------------------------------------------------\n out_root_file.Write()\n \n out_root_file.Close()\n \n df.index = [str(i) for i in range(df.shape[0])]\n \n df.T.to_csv(outroot_folder_path+'/output.csv')\n \n \n return 0\n"
] |
[
[
"pandas.concat",
"pandas.DataFrame"
]
] |
rgooler/MountainCheckHours
|
[
"13f0d33727a4ba408b0b35bd7ffe348b1edf78c3"
] |
[
"MountainCheckHours.py"
] |
[
"import numpy\nfrom os import path\nimport os\n\nsavefile = \"apsdfpboasdfhsa.sav\"\n\ndef find_savedir():\n if path.isfile(savefile):\n return '.'\n\n winpath = path.expandvars(r\"%USERPROFILE%\\\\AppData\\\\LocalLow\\\\David OReilly\\\\Mountain\")\n if path.isdir(winpath):\n return winpath\n\n linpath = path.expandvars(r\"~/.steam/steam/steamapps/compatdata/897330/pfx/dosdevices/z:/home\")\n linpath_x = \"/.config/unity3d/David OReilly/Mountain\"\n if path.isdir(linpath):\n for x in os.listdir(linpath):\n if os.path.isdir(x):\n fullpath = \"%s/%s/%s\" % (linpath, x, linpath_x)\n if path.isdir(fullpath):\n return fullpath\n\nif __name__ == \"__main__\":\n path = find_savedir()\n if path is None:\n print(\"Cannot find savegame. Please move this exe/script to your save folder for Mountain.\")\n else:\n filename = \"%s/%s\" % (path, savefile)\n a = numpy.fromfile(filename, dtype=numpy.int32, count=-1, sep='')\n hours_done = a[11]\n print(\"%s of 987 hours complete\" % hours_done)\n print(\"\")\n input(\"Press enter to exit program...\")\n"
] |
[
[
"numpy.fromfile"
]
] |
wizelab8/SmartMirror
|
[
"bad186d4eceb6b6adfdcef90e7d93abfc04d9d61"
] |
[
"BLENDER/FacialMotionCapture_v2/OpenCVAnimOperator.py"
] |
[
"import bpy\nimport cv2\nimport time\nimport numpy\n\n# Download trained model (lbfmodel.yaml)\n# https://github.com/kurnianggoro/GSOC2017/tree/master/data\n\n# Install prerequisites:\n\n# Linux: (may vary between distro's and installation methods)\n# This is for manjaro with Blender installed from the package manager\n# python3 -m ensurepip\n# python3 -m pip install --upgrade pip --user\n# python3 -m pip install opencv-contrib-python numpy --user\n\n# MacOS\n# open the Terminal\n# cd /Applications/Blender.app/Contents/Resources/2.81/python/bin\n# ./python3.7m -m ensurepip\n# ./python3.7m -m pip install --upgrade pip --user\n# ./python3.7m -m pip install opencv-contrib-python numpy --user\n\n# Windows:\n# Open Command Prompt as Administrator\n# cd \"C:\\Program Files\\Blender Foundation\\Blender 2.81\\2.81\\python\\bin\"\n# python -m pip install --upgrade pip\n# python -m pip install opencv-contrib-python numpy\n\nclass OpenCVAnimOperator(bpy.types.Operator):\n \"\"\"Operator which runs its self from a timer\"\"\"\n bl_idname = \"wm.opencv_operator\"\n bl_label = \"OpenCV Animation Operator\"\n \n # Set paths to trained models downloaded above\n face_detect_path = cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\"\n #landmark_model_path = \"/home/username/Documents/Vincent/lbfmodel.yaml\" #Linux\n #landmark_model_path = \"/Users/username/Downloads/lbfmodel.yaml\" #Mac\n landmark_model_path = \"C:\\\\Users\\\\username\\\\Downloads\\\\lbfmodel.yaml\" #Windows\n \n # Load models\n fm = cv2.face.createFacemarkLBF()\n fm.loadModel(landmark_model_path)\n cas = cv2.CascadeClassifier(face_detect_path)\n \n _timer = None\n _cap = None\n stop = False\n \n # Webcam resolution:\n width = 640\n height = 480\n \n # 3D model points. \n model_points = numpy.array([\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 ], dtype = numpy.float32)\n # Camera internals\n camera_matrix = numpy.array(\n [[height, 0.0, width/2],\n [0.0, height, height/2],\n [0.0, 0.0, 1.0]], dtype = numpy.float32\n )\n \n # Keeps a moving average of given length\n def smooth_value(self, name, length, value):\n if not hasattr(self, 'smooth'):\n self.smooth = {}\n if not name in self.smooth:\n self.smooth[name] = numpy.array([value])\n else:\n self.smooth[name] = numpy.insert(arr=self.smooth[name], obj=0, values=value)\n if self.smooth[name].size > length:\n self.smooth[name] = numpy.delete(self.smooth[name], self.smooth[name].size-1, 0)\n sum = 0\n for val in self.smooth[name]:\n sum += val\n return sum / self.smooth[name].size\n\n # Keeps min and max values, then returns the value in a range 0 - 1\n def get_range(self, name, value):\n if not hasattr(self, 'range'):\n self.range = {}\n if not name in self.range:\n self.range[name] = numpy.array([value, value])\n else:\n self.range[name] = numpy.array([min(value, self.range[name][0]), max(value, self.range[name][1])] )\n val_range = self.range[name][1] - self.range[name][0]\n if val_range != 0:\n return (value - self.range[name][0]) / val_range\n else:\n return 0.0\n \n # The main \"loop\"\n def modal(self, context, event):\n\n if (event.type in {'RIGHTMOUSE', 'ESC'}) or self.stop == True:\n self.cancel(context)\n return {'CANCELLED'}\n\n if event.type == 'TIMER':\n self.init_camera()\n _, image = self._cap.read()\n #gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n #gray = cv2.equalizeHist(gray)\n \n # find faces\n faces = self.cas.detectMultiScale(image, \n scaleFactor=1.05, \n minNeighbors=3, \n flags=cv2.CASCADE_SCALE_IMAGE, \n minSize=(int(self.width/5), int(self.width/5)))\n \n #find biggest face, and only keep it\n if type(faces) is numpy.ndarray and faces.size > 0: \n biggestFace = numpy.zeros(shape=(1,4))\n for face in faces:\n if face[2] > biggestFace[0][2]:\n print(face)\n biggestFace[0] = face\n \n # find the landmarks.\n _, landmarks = self.fm.fit(image, faces=biggestFace)\n for mark in landmarks:\n shape = mark[0]\n \n #2D image points. If you change the image, you need to change vector\n image_points = numpy.array([shape[30], # Nose tip - 31\n shape[8], # Chin - 9\n shape[36], # Left eye left corner - 37\n shape[45], # Right eye right corne - 46\n shape[48], # Left Mouth corner - 49\n shape[54] # Right mouth corner - 55\n ], dtype = numpy.float32)\n \n dist_coeffs = numpy.zeros((4,1)) # Assuming no lens distortion\n \n # determine head rotation\n if hasattr(self, 'rotation_vector'):\n (success, self.rotation_vector, self.translation_vector) = cv2.solvePnP(self.model_points, \n image_points, self.camera_matrix, dist_coeffs, flags=cv2.SOLVEPNP_ITERATIVE, \n rvec=self.rotation_vector, tvec=self.translation_vector, \n useExtrinsicGuess=True)\n else:\n (success, self.rotation_vector, self.translation_vector) = cv2.solvePnP(self.model_points, \n image_points, self.camera_matrix, dist_coeffs, flags=cv2.SOLVEPNP_ITERATIVE, \n useExtrinsicGuess=False)\n \n if not hasattr(self, 'first_angle'):\n self.first_angle = numpy.copy(self.rotation_vector)\n \n # set bone rotation/positions\n bones = bpy.data.objects[\"RIG-Vincent\"].pose.bones\n \n # head rotation \n bones[\"head_fk\"].rotation_euler[0] = self.smooth_value(\"h_x\", 5, (self.rotation_vector[0] - self.first_angle[0])) / 1 # Up/Down\n bones[\"head_fk\"].rotation_euler[2] = self.smooth_value(\"h_y\", 5, -(self.rotation_vector[1] - self.first_angle[1])) / 1.5 # Rotate\n bones[\"head_fk\"].rotation_euler[1] = self.smooth_value(\"h_z\", 5, (self.rotation_vector[2] - self.first_angle[2])) / 1.3 # Left/Right\n \n bones[\"head_fk\"].keyframe_insert(data_path=\"rotation_euler\", index=-1)\n \n # mouth position\n bones[\"mouth_ctrl\"].location[2] = self.smooth_value(\"m_h\", 2, -self.get_range(\"mouth_height\", numpy.linalg.norm(shape[62] - shape[66])) * 0.06 )\n bones[\"mouth_ctrl\"].location[0] = self.smooth_value(\"m_w\", 2, (self.get_range(\"mouth_width\", numpy.linalg.norm(shape[54] - shape[48])) - 0.5) * -0.04)\n \n bones[\"mouth_ctrl\"].keyframe_insert(data_path=\"location\", index=-1)\n \n #eyebrows\n bones[\"brow_ctrl_L\"].location[2] = self.smooth_value(\"b_l\", 3, (self.get_range(\"brow_left\", numpy.linalg.norm(shape[19] - shape[27])) -0.5) * 0.04)\n bones[\"brow_ctrl_R\"].location[2] = self.smooth_value(\"b_r\", 3, (self.get_range(\"brow_right\", numpy.linalg.norm(shape[24] - shape[27])) -0.5) * 0.04)\n \n bones[\"brow_ctrl_L\"].keyframe_insert(data_path=\"location\", index=2)\n bones[\"brow_ctrl_R\"].keyframe_insert(data_path=\"location\", index=2)\n \n # eyelids\n l_open = self.smooth_value(\"e_l\", 2, self.get_range(\"l_open\", -numpy.linalg.norm(shape[48] - shape[44])) )\n r_open = self.smooth_value(\"e_r\", 2, self.get_range(\"r_open\", -numpy.linalg.norm(shape[41] - shape[39])) )\n eyes_open = (l_open + r_open) / 2.0 # looks weird if both eyes aren't the same...\n bones[\"eyelid_up_ctrl_R\"].location[2] = -eyes_open * 0.025 + 0.005\n bones[\"eyelid_low_ctrl_R\"].location[2] = eyes_open * 0.025 - 0.005\n bones[\"eyelid_up_ctrl_L\"].location[2] = -eyes_open * 0.025 + 0.005\n bones[\"eyelid_low_ctrl_L\"].location[2] = eyes_open * 0.025 - 0.005\n \n bones[\"eyelid_up_ctrl_R\"].keyframe_insert(data_path=\"location\", index=2)\n bones[\"eyelid_low_ctrl_R\"].keyframe_insert(data_path=\"location\", index=2)\n bones[\"eyelid_up_ctrl_L\"].keyframe_insert(data_path=\"location\", index=2)\n bones[\"eyelid_low_ctrl_L\"].keyframe_insert(data_path=\"location\", index=2)\n \n # draw face markers\n for (x, y) in shape:\n cv2.circle(image, (x, y), 2, (0, 255, 255), -1)\n \n # draw detected face\n for (x,y,w,h) in faces:\n cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),1)\n \n # Show camera image in a window \n cv2.imshow(\"Output\", image)\n cv2.waitKey(1)\n\n return {'PASS_THROUGH'}\n \n def init_camera(self):\n if self._cap == None:\n self._cap = cv2.VideoCapture(0)\n self._cap.set(cv2.CAP_PROP_FRAME_WIDTH, self.width)\n self._cap.set(cv2.CAP_PROP_FRAME_HEIGHT, self.height)\n self._cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)\n time.sleep(1.0)\n \n def stop_playback(self, scene):\n print(format(scene.frame_current) + \" / \" + format(scene.frame_end))\n if scene.frame_current == scene.frame_end:\n bpy.ops.screen.animation_cancel(restore_frame=False)\n \n def execute(self, context):\n bpy.app.handlers.frame_change_pre.append(self.stop_playback)\n\n wm = context.window_manager\n self._timer = wm.event_timer_add(0.01, window=context.window)\n wm.modal_handler_add(self)\n return {'RUNNING_MODAL'}\n\n def cancel(self, context):\n wm = context.window_manager\n wm.event_timer_remove(self._timer)\n cv2.destroyAllWindows()\n self._cap.release()\n self._cap = None\n\ndef register():\n bpy.utils.register_class(OpenCVAnimOperator)\n\ndef unregister():\n bpy.utils.unregister_class(OpenCVAnimOperator)\n\nif __name__ == \"__main__\":\n register()\n\n # test call\n #bpy.ops.wm.opencv_operator()\n\n\n\n"
] |
[
[
"numpy.linalg.norm",
"numpy.copy",
"numpy.delete",
"numpy.insert",
"numpy.array",
"numpy.zeros"
]
] |
CGCL-codes/naturalcc
|
[
"9c3329dd8387c8242deb52bf590ebe3ac795f8de"
] |
[
"run/retrieval/nbow/predictor.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\n\"\"\"\nEvaluate the perplexity of a trained language model.\n\"\"\"\nimport os\nimport re\nimport torch\nfrom ncc import tasks\nfrom ncc.utils import utils\nfrom ncc.utils.checkpoint_utils import load_checkpoint_to_cpu\n\n\ndef main(model_path, input):\n state = load_checkpoint_to_cpu(model_path, arg_overrides={})\n args = state[\"args\"]\n task = tasks.setup_task(args) # load src/tgt dicts\n model = task.build_model(args)\n model.load_state_dict(state[\"model\"])\n use_cuda = torch.cuda.is_available() and not args['common']['cpu']\n if use_cuda:\n torch.cuda.empty_cache()\n torch.cuda.set_device(torch.cuda.device_count() - 1)\n model.cuda()\n if args['common']['fp16'] and use_cuda:\n model.half()\n model.eval()\n\n # TODO: source tensor should be handled in corresponding task scripts. here we only use seq2seq pipeline for instance.\n src_input_ids = task.src_dict.encode_line(input, line_tokenizer=None, add_if_not_exist=False)\n src_input_ids = torch.cat(\n [src_input_ids[:args['task']['max_source_positions'] - 1], torch.Tensor([task.src_dict.eos()]).long()]\n )\n padding_size = args['task']['max_source_positions'] - len(src_input_ids)\n if padding_size > 0:\n src_input_ids = torch.cat([src_input_ids, torch.Tensor([task.src_dict.pad()] * padding_size).long()])\n if use_cuda:\n src_input_ids = src_input_ids.unsqueeze(dim=0).cuda()\n sample = {\n 'net_input': {\n 'src_tokens': src_input_ids,\n 'src_lengths': torch.LongTensor([s.numel() for s in src_input_ids]),\n },\n }\n sample = utils.move_to_cuda(sample) if use_cuda else sample\n generator = task.build_generator(args)\n pred_sentence_ids = generator.generate(models=[model], sample=sample)\n pred_sentence = task.tgt_dict.string(pred_sentence_ids[0][0]['tokens'])\n return pred_sentence\n\n\ndef cli_main():\n import argparse\n parser = argparse.ArgumentParser(\n description=\"Command Interface\")\n\n parser.add_argument(\n \"--model\", \"-m\", type=str, help=\"pytorch model path\",\n default=os.path.expanduser(\n \"~/.ncc/code_search_net/retrieval/csn/data-mmap/ruby/nbow/checkpoints/checkpoint_best.pt\")\n )\n code = \"def resource_patch(context, data_dict):\\n\\t_check_access('resource_patch', context, data_dict)\\n\\tshow_context = {'model': context['model'], 'session': context['session'], 'user': context['user'], 'auth_user_obj': context['auth_user_obj']}\\n\\tresource_dict = _get_action('resource_show')(show_context, {'id': _get_or_bust(data_dict, 'id')})\\n\\tpatched = dict(resource_dict)\\n\\tpatched.update(data_dict)\\n\\treturn _update.resource_update(context, patched)\\n\"\n\n pattern = re.compile(r\"\\s+\")\n tokenized_code = pattern.sub(\"_\", code).lower().split(\"_\")\n print(tokenized_code)\n from dataset.csn.utils.util import split_identifier\n import itertools\n tokenized_code = [split_identifier(token) for token in tokenized_code if len(token) > 0]\n tokenized_code = list(itertools.chain(*tokenized_code))\n print(tokenized_code)\n\n code_tokens = [\"def\", \"resource\", \"patch\", \"context\", \"data\", \"dict\", \"check\", \"access\", \"'resource\", \"patch'\",\n \"context\", \"data\", \"dict\", \"show\", \"context\", \"{'model'\", \"context['model']\", \"'session'\",\n \"context['session']\", \"'user'\", \"context['user']\", \"'auth\", \"user\", \"obj'\", \"context['auth\", \"user\",\n \"obj']}resource\", \"dict\", \"get\", \"action\", \"'resource\", \"show'\", \"show\", \"context\", \"{'id'\", \"get\",\n \"or\", \"bust\", \"data\", \"dict\", \"'id'\", \"}\", \"patched\", \"dict\", \"resource\", \"dict\", \"patched\",\n \"update\", \"data\", \"dict\", \"return\", \"update\", \"resource\", \"update\", \"context\", \"patched\"]\n docstring = \"patch a resource .\"\n parser.add_argument(\n \"--input\", \"-i\", type=str, help=\"model input\",\n # default=code_tokens\n default=tokenized_code,\n )\n args = parser.parse_args()\n pred_sentence = main(args.model, args.input)\n print(pred_sentence)\n\n\nif __name__ == '__main__':\n cli_main()\n"
] |
[
[
"torch.cuda.device_count",
"torch.cuda.empty_cache",
"torch.cuda.is_available"
]
] |
jakelever/corona-ml
|
[
"8ceb22af50d7277ebf05f2fd21bbbf68c080ed76"
] |
[
"paper/ml_logs.py"
] |
[
"#!/usr/bin/env python\n\nimport os\nimport json\nimport pandas as pd\n\ndir_name = 'ml_logs'\nlog_files = [ os.path.join(dir_name,f) for f in os.listdir(dir_name) if f.endswith('txt' )]\nprint(len(log_files))\n\nlog_data = []\nfor log_file in log_files:\n with open(log_file) as f:\n curly_lines = [ line for line in f if line.startswith('{') ]\n assert len(curly_lines) == 1\n json_data = json.loads(curly_lines[0])\n log_data.append(json_data)\n\nprint(len(log_data))\n\nml_data = []\nfor l in log_data:\n epochs, learning_rate = None,None\n \n is_bert = l['params']['clf'] == 'BERT'\n if is_bert:\n model = l['params']['clf_model']\n epochs = l['params']['clf_epochs']\n learning_rate = l['params']['clf_learning_rate']\n #if epochs < 16 or learning_rate > 4e-5:\n # continue\n else:\n model = l['params']['clf']\n #epochs = l['params']['clf_epochs']\n #learning_rate = l['params']['clf_learning_rate']\n \n if model == '/home/groups/rbaltman/jlever/bluebert/base_uncased_pubmedANDmimicIII/':\n model = 'bluebert/base_uncased'\n \n model = model.replace('microsoft/BiomedNLP-PubMedBERT-base-uncased-','microsoft/PubMedBERT-')\n \n macro_f1 = l['results']['MACRO']['f1_score']\n ml_data.append([is_bert,model,epochs,learning_rate,macro_f1])\n\nml_df = pd.DataFrame(ml_data,columns=['is_bert','model','epochs','learning_rate','macro_f1'])\n"
] |
[
[
"pandas.DataFrame"
]
] |
timmahrt/ProMo
|
[
"015c83ca937a967be5b15eec531a7b61e47e176c"
] |
[
"promo/morph_utils/interpolation.py"
] |
[
"'''\nCreated on Jun 29, 2016\n\n@author: Tim\n'''\n\ntry:\n import numpy as np\nexcept ImportError:\n hasNumpy = False\nelse:\n hasNumpy = True\n\n \ndef _numpyCheck():\n if not hasNumpy:\n raise ImportError(\"Numpy required to do data interpolation. \"\n \"Install numpy or don't use data interpolation\")\n\n\ndef quadraticInterpolation(valueList2d, numDegrees, n,\n startTime=None, endTime=None):\n '''\n Generates a series of points on a smooth curve that cross the given points\n \n numDegrees - the degrees of the fitted polynomial\n - the curve gets weird if this value is too high for the input\n n - number of points to output\n startTime/endTime/n - n points will be generated at evenly spaced\n intervals between startTime and endTime\n '''\n _numpyCheck()\n \n x, y = zip(*valueList2d)\n \n if startTime is None:\n startTime = x[0]\n if endTime is None:\n endTime = x[-1]\n \n polyFunc = np.poly1d(np.polyfit(x, y, numDegrees))\n \n newX = np.linspace(startTime, endTime, n)\n \n retList = [(n, polyFunc(n)) for n in newX]\n \n return retList\n"
] |
[
[
"numpy.polyfit",
"numpy.linspace"
]
] |
LCAV/FRIDA
|
[
"ff5d51e498805b862c342dd216ccfffb22444b7f"
] |
[
"tools/mkl_fft.py"
] |
[
"''' \nWrapper for the MKL FFT routines.\n\nInspiration from:\nhttp://stackoverflow.com/questions/11752898/threaded-fft-in-enthought-python\n'''\n\nimport numpy as np\nimport ctypes as _ctypes\nimport os\n\nfrom dftidefs import *\n\ndef load_libmkl():\n if os.name == 'posix':\n try:\n lib_mkl = os.getenv('LIBMKL')\n return _ctypes.cdll.LoadLibrary(lib_mkl)\n except:\n pass\n try:\n return _ctypes.cdll.LoadLibrary(\"libmkl_rt.dylib\")\n except:\n raise ValueError('MKL Library not found')\n\n else:\n try:\n return _ctypes.cdll.LoadLibrary(\"mk2_rt.dll\")\n except:\n raise ValueError('MKL Library not found')\n\nmkl = load_libmkl()\n\n\ndef mkl_rfft(a, n=None, axis=-1, norm=None, direction='forward', out=None):\n ''' \n Forward one-dimensional double-precision real-complex FFT.\n Uses the Intel MKL libraries distributed with Anaconda Python.\n Normalisation is different from Numpy!\n By default, allocates new memory like 'a' for output data.\n Returns the array containing output data.\n '''\n\n if axis == -1:\n axis = a.ndim-1\n\n # This code only works for 1D and 2D arrays\n assert a.ndim < 3\n assert (axis < a.ndim and axis >= -1)\n assert (direction == 'forward' or direction == 'backward')\n if direction == 'forward':\n assert a.dtype == np.float32 or a.dtype == np.float64\n else:\n assert a.dtype == np.complex64 or a.dtype == np.complex128\n\n order = 'C'\n if a.flags['F_CONTIGUOUS'] and not a.flags['C_CONTIGUOUS']:\n order = 'F'\n\n # Add zero padding or truncate if needed (incurs memory copy)\n if n is not None:\n m = n if direction == 'forward' else (n//2 + 1)\n if a.shape[axis] < m:\n # pad axis with zeros\n pad_width = np.zeros((a.ndim, 2), dtype=np.int)\n pad_width[axis,1] = m - a.shape[axis]\n a = np.pad(a, pad_width, mode='constant')\n elif a.shape[axis] > m:\n # truncate along axis\n b = np.swapaxes(a, axis, 0)[:m,]\n a = np.swapaxes(b, 0, axis).copy()\n elif direction == 'forward':\n n = a.shape[axis]\n\n elif direction == 'backward':\n n = 2*(a.shape[axis]-1)\n\n # determine output type\n if direction == 'backward':\n out_type = np.float64\n if a.dtype == np.complex64:\n out_type = np.float32\n elif direction == 'forward':\n out_type = np.complex128\n if a.dtype == np.float32:\n out_type = np.complex64\n\n # Configure output array\n assert a is not out\n if out is not None:\n assert out.dtype == out_type\n for i in xrange(a.ndim):\n if i != axis:\n assert a.shape[i] == out.shape[i]\n if direction == 'forward':\n assert (n//2 + 1) == out.shape[axis]\n else:\n assert out.shape[axis] == n\n assert not np.may_share_memory(a, out)\n else:\n size = list(a.shape)\n size[axis] = n//2 + 1 if direction == 'forward' else n\n out = np.empty(size, dtype=out_type, order=order)\n\n # Define length, number of transforms strides\n length = _ctypes.c_int(n)\n n_transforms = _ctypes.c_int(np.prod(a.shape)/a.shape[axis])\n\n # For strides, the C type used *must* be int64\n strides = (_ctypes.c_int64*2)(0, a.strides[axis]/a.itemsize)\n if a.ndim == 2:\n if axis == 0:\n distance = _ctypes.c_int(a.strides[1]/a.itemsize)\n out_distance = _ctypes.c_int(out.strides[1]/out.itemsize)\n else:\n distance = _ctypes.c_int(a.strides[0]/a.itemsize)\n out_distance = _ctypes.c_int(out.strides[0]/out.itemsize)\n\n double_precision = True\n if (direction == 'forward' and a.dtype == np.float32) or (direction == 'backward' and a.dtype == np.complex64):\n double_precision = False\n\n # Create the description handle\n Desc_Handle = _ctypes.c_void_p(0)\n if not double_precision:\n mkl.DftiCreateDescriptor(_ctypes.byref(Desc_Handle), DFTI_SINGLE, DFTI_REAL, _ctypes.c_int(1), length)\n else:\n mkl.DftiCreateDescriptor(_ctypes.byref(Desc_Handle), DFTI_DOUBLE, DFTI_REAL, _ctypes.c_int(1), length)\n\n # set the storage type\n mkl.DftiSetValue(Desc_Handle, DFTI_CONJUGATE_EVEN_STORAGE, DFTI_COMPLEX_COMPLEX)\n\n # set normalization factor\n if norm == 'ortho':\n if not double_precision:\n scale = _ctypes.c_double(1/np.sqrt(n))\n else:\n scale = _ctypes.c_double(1/np.sqrt(n))\n mkl.DftiSetValue(Desc_Handle, DFTI_FORWARD_SCALE, scale)\n mkl.DftiSetValue(Desc_Handle, DFTI_BACKWARD_SCALE, scale)\n elif norm is None:\n if not double_precision:\n scale = _ctypes.c_double(1./n)\n else:\n scale = _ctypes.c_double(1./n)\n mkl.DftiSetValue(Desc_Handle, DFTI_BACKWARD_SCALE, scale)\n\n # set all values if necessary\n if a.ndim != 1:\n mkl.DftiSetValue(Desc_Handle, DFTI_NUMBER_OF_TRANSFORMS, n_transforms)\n mkl.DftiSetValue(Desc_Handle, DFTI_INPUT_DISTANCE, distance)\n mkl.DftiSetValue(Desc_Handle, DFTI_OUTPUT_DISTANCE, out_distance)\n mkl.DftiSetValue(Desc_Handle, DFTI_INPUT_STRIDES, _ctypes.byref(strides))\n mkl.DftiSetValue(Desc_Handle, DFTI_OUTPUT_STRIDES, _ctypes.byref(strides))\n\n if direction == 'forward':\n fft_func = mkl.DftiComputeForward\n elif direction == 'backward':\n fft_func = mkl.DftiComputeBackward\n else:\n assert False\n\n # Not-in-place FFT\n mkl.DftiSetValue(Desc_Handle, DFTI_PLACEMENT, DFTI_NOT_INPLACE)\n\n mkl.DftiCommitDescriptor(Desc_Handle)\n \n fft_func(Desc_Handle, a.ctypes.data_as(_ctypes.c_void_p), out.ctypes.data_as(_ctypes.c_void_p) )\n\n mkl.DftiFreeDescriptor(_ctypes.byref(Desc_Handle))\n\n return out\n\n\ndef mkl_fft(a, n=None, axis=-1, norm=None, direction='forward', out=None):\n ''' \n Forward/Backward one-dimensional single/double-precision complex-complex FFT.\n Uses the Intel MKL libraries distributed with Anaconda Python.\n Normalisation is different from Numpy!\n By default, allocates new memory like 'a' for output data.\n Returns the array containing output data.\n '''\n\n # This code only works for 1D and 2D arrays\n assert a.ndim < 3\n assert axis < a.ndim and axis >= -1\n\n # Add zero padding if needed (incurs memory copy)\n if n is not None and n != a.shape[axis]:\n pad_width = np.zeros((a.ndim, 2), dtype=np.int)\n pad_width[axis,1] = n - a.shape[axis]\n a = np.pad(a, pad_width, mode='constant')\n\n if n is not None:\n if a.shape[axis] < n:\n # pad axis with zeros\n pad_width = np.zeros((a.ndim, 2))\n pad_width[axis,1] = m - a.shape[axis]\n a = np.pad(x, pad_width, mode='constant')\n elif a.shape[axis] > n:\n # truncate along axis\n b = np.swapaxes(a, axis, 0)[:m,]\n a = np.swapaxes(b, 0, axis).copy()\n\n # Convert input to complex data type if real (also memory copy)\n if a.dtype != np.complex128 and a.dtype != np.complex64:\n if a.dtype == np.int64 or a.dtype == np.uint64 or a.dtype == np.float64:\n a = np.array(a, dtype=np.complex128)\n else:\n a = np.array(a, dtype=np.complex64)\n\n # Configure in-place vs out-of-place\n inplace = False\n if out is a:\n inplace = True\n elif out is not None:\n assert out.dtype == a.dtype\n assert a.shape == out.shape\n assert not np.may_share_memory(a, out)\n else:\n out = np.empty_like(a)\n\n # Define length, number of transforms strides\n length = _ctypes.c_int(a.shape[axis])\n n_transforms = _ctypes.c_int(np.prod(a.shape)/a.shape[axis])\n \n # For strides, the C type used *must* be int64\n strides = (_ctypes.c_int64*2)(0, a.strides[axis]/a.itemsize)\n if a.ndim == 2:\n if axis == 0:\n distance = _ctypes.c_int(a.strides[1]/a.itemsize)\n else:\n distance = _ctypes.c_int(a.strides[0]/a.itemsize)\n\n # Create the description handle\n Desc_Handle = _ctypes.c_void_p(0)\n if a.dtype == np.complex64:\n mkl.DftiCreateDescriptor(_ctypes.byref(Desc_Handle), DFTI_SINGLE, DFTI_COMPLEX, _ctypes.c_int(1), length)\n elif a.dtype == np.complex128:\n mkl.DftiCreateDescriptor(_ctypes.byref(Desc_Handle), DFTI_DOUBLE, DFTI_COMPLEX, _ctypes.c_int(1), length)\n\n # Set normalization factor\n if norm == 'ortho':\n if a.dtype == np.complex64:\n scale = _ctypes.c_float(1/np.sqrt(a.shape[axis]))\n else:\n scale = _ctypes.c_double(1/np.sqrt(a.shape[axis]))\n \n mkl.DftiSetValue(Desc_Handle, DFTI_FORWARD_SCALE, scale)\n mkl.DftiSetValue(Desc_Handle, DFTI_BACKWARD_SCALE, scale)\n elif norm is None:\n if a.dtype == np.complex64:\n scale = _ctypes.c_float(1./a.shape[axis])\n else:\n scale = _ctypes.c_double(1./a.shape[axis])\n \n mkl.DftiSetValue(Desc_Handle, DFTI_BACKWARD_SCALE, scale)\n\n # set all values if necessary\n if a.ndim != 1:\n mkl.DftiSetValue(Desc_Handle, DFTI_NUMBER_OF_TRANSFORMS, n_transforms)\n mkl.DftiSetValue(Desc_Handle, DFTI_INPUT_DISTANCE, distance)\n mkl.DftiSetValue(Desc_Handle, DFTI_OUTPUT_DISTANCE, distance)\n mkl.DftiSetValue(Desc_Handle, DFTI_INPUT_STRIDES, _ctypes.byref(strides))\n mkl.DftiSetValue(Desc_Handle, DFTI_OUTPUT_STRIDES, _ctypes.byref(strides))\n\n if direction == 'forward':\n fft_func = mkl.DftiComputeForward\n elif direction == 'backward':\n fft_func = mkl.DftiComputeBackward\n else:\n assert False\n\n if inplace:\n # In-place FFT\n mkl.DftiCommitDescriptor(Desc_Handle)\n fft_func(Desc_Handle, a.ctypes.data_as(_ctypes.c_void_p) )\n\n else:\n # Not-in-place FFT\n mkl.DftiSetValue(Desc_Handle, DFTI_PLACEMENT, DFTI_NOT_INPLACE)\n\n mkl.DftiCommitDescriptor(Desc_Handle)\n fft_func(Desc_Handle, a.ctypes.data_as(_ctypes.c_void_p), out.ctypes.data_as(_ctypes.c_void_p) )\n\n\n mkl.DftiFreeDescriptor(_ctypes.byref(Desc_Handle))\n\n return out\n\n\ndef mkl_fft2(a, norm=None, direction='forward', out=None):\n ''' \n Forward two-dimensional double-precision complex-complex FFT.\n Uses the Intel MKL libraries distributed with Enthought Python.\n Normalisation is different from Numpy!\n By default, allocates new memory like 'a' for output data.\n Returns the array containing output data.\n '''\n\n # convert input to complex data type if real (also memory copy)\n if a.dtype != np.complex128 and a.dtype != np.complex64:\n if a.dtype == np.int64 or a.dtype == np.uint64 or a.dtype == np.float64:\n a = np.array(a, dtype=np.complex128)\n else:\n a = np.array(a, dtype=np.complex64)\n\n # Configure in-place vs out-of-place\n inplace = False\n if out is a:\n inplace = True\n elif out is not None:\n assert out.dtype == a.dtype\n assert a.shape == out.shape\n assert not np.may_share_memory(a, out)\n else:\n out = np.empty_like(a)\n\n # Create the description handle\n Desc_Handle = _ctypes.c_void_p(0)\n dims = (_ctypes.c_int64*2)(*a.shape)\n \n if a.dtype == np.complex64:\n mkl.DftiCreateDescriptor(_ctypes.byref(Desc_Handle), DFTI_SINGLE, DFTI_COMPLEX, _ctypes.c_int(2), dims)\n elif a.dtype == np.complex128:\n mkl.DftiCreateDescriptor(_ctypes.byref(Desc_Handle), DFTI_DOUBLE, DFTI_COMPLEX, _ctypes.c_int(2), dims)\n\n\n # Set normalization factor\n if norm == 'ortho':\n if a.dtype == np.complex64:\n scale = _ctypes.c_double(1.0/np.sqrt(np.prod(a.shape)))\n else:\n scale = _ctypes.c_double(1.0/np.sqrt(np.prod(a.shape)))\n \n mkl.DftiSetValue(Desc_Handle, DFTI_FORWARD_SCALE, scale)\n mkl.DftiSetValue(Desc_Handle, DFTI_BACKWARD_SCALE, scale)\n elif norm is None:\n if a.dtype == np.complex64:\n scale = _ctypes.c_double(1.0/np.prod(a.shape))\n else:\n scale = _ctypes.c_double(1.0/np.prod(a.shape))\n \n mkl.DftiSetValue(Desc_Handle, DFTI_BACKWARD_SCALE, scale)\n\n\n # Set input strides if necessary\n if not a.flags['C_CONTIGUOUS']:\n in_strides = (_ctypes.c_int*3)(0, a.strides[0]/a.itemsize, a.strides[1]/a.itemsize)\n mkl.DftiSetValue(Desc_Handle, DFTI_INPUT_STRIDES, _ctypes.byref(in_strides))\n\n if direction == 'forward':\n fft_func = mkl.DftiComputeForward\n elif direction == 'backward':\n fft_func = mkl.DftiComputeBackward\n else:\n assert False\n\n if inplace:\n # In-place FFT\n mkl.DftiCommitDescriptor(Desc_Handle)\n fft_func(Desc_Handle, a.ctypes.data_as(_ctypes.c_void_p) )\n\n\n else:\n # Not-in-place FFT\n mkl.DftiSetValue(Desc_Handle, DFTI_PLACEMENT, DFTI_NOT_INPLACE)\n\n # Set output strides if necessary\n if not out.flags['C_CONTIGUOUS']:\n out_strides = (_ctypes.c_int*3)(0, out.strides[0]/out.itemsize, out.strides[1]/out.itemsize)\n mkl.DftiSetValue(Desc_Handle, DFTI_OUTPUT_STRIDES, _ctypes.byref(out_strides))\n\n mkl.DftiCommitDescriptor(Desc_Handle)\n fft_func(Desc_Handle, a.ctypes.data_as(_ctypes.c_void_p), out.ctypes.data_as(_ctypes.c_void_p) )\n\n mkl.DftiFreeDescriptor(_ctypes.byref(Desc_Handle))\n\n return out\n\ndef rfft(a, n=None, axis=-1, norm=None, out=None):\n return mkl_rfft(a, n=n, axis=axis, norm=norm, direction='forward', out=out)\n\ndef irfft(a, n=None, axis=-1, norm=None, out=None):\n return mkl_rfft(a, n=n, axis=axis, norm=norm, direction='backward', out=out)\n\ndef fft(a, n=None, axis=-1, norm=None, out=None):\n return mkl_fft(a, n=n, axis=axis, norm=norm, direction='forward', out=out)\n\ndef ifft(a, n=None, axis=-1, norm=None, out=None):\n return mkl_fft(a, n=n, axis=axis, norm=norm, direction='backward', out=out)\n\ndef fft2(a, norm=None, out=None):\n return mkl_fft2(a, norm=norm, direction='forward', out=out)\n\ndef ifft2(a, norm=None, out=None):\n return mkl_fft2(a, norm=norm, direction='backward', out=out)\n\n\ndef cce2full(A):\n\n # Assume all square for now\n\n N = A.shape\n N_half = N[0]//2 + 1\n out = np.empty((A.shape[0], A.shape[0]), dtype=A.dtype)\n out[:, :N_half] = A\n\n out[1:, N_half:] = np.rot90(A[1:, 1:-1], 2).conj()\n\n # Complete the first row\n out[0, N_half:] = A[0, -2:0:-1].conj()\n\n return out\n\n\ndef mkl_rfft2(a, norm=None, direction='forward', out=None):\n ''' \n Forward two-dimensional double-precision complex-complex FFT.\n Uses the Intel MKL libraries distributed with Enthought Python.\n Normalisation is different from Numpy!\n By default, allocates new memory like 'a' for output data.\n Returns the array containing output data.\n '''\n\n assert (a.dtype == np.float32) or (a.dtype == np.float64)\n\n out_type = np.complex128\n if a.dtype == np.float32:\n out_type = np.complex64\n\n n = a.shape[1]\n\n # Allocate memory if needed\n if out is not None:\n assert out.dtype == out_type\n assert out.shape[1] == n//2 + 1\n assert not np.may_share_memory(a, out)\n else:\n size = list(a.shape)\n size[1] = n//2 + 1\n out = np.empty(size, dtype=out_type)\n\n # Create the description handle\n Desc_Handle = _ctypes.c_void_p(0)\n dims = (_ctypes.c_int64*2)(*a.shape)\n \n if a.dtype == np.float32:\n mkl.DftiCreateDescriptor(_ctypes.byref(Desc_Handle), DFTI_SINGLE, DFTI_REAL, _ctypes.c_int(2), dims)\n elif a.dtype == np.float64:\n mkl.DftiCreateDescriptor(_ctypes.byref(Desc_Handle), DFTI_DOUBLE, DFTI_REAL, _ctypes.c_int(2), dims)\n\n # Set the storage type\n mkl.DftiSetValue(Desc_Handle, DFTI_CONJUGATE_EVEN_STORAGE, DFTI_COMPLEX_COMPLEX)\n\n # Set normalization factor\n if norm == 'ortho':\n if a.dtype == np.float32:\n scale = _ctypes.c_float(1.0/np.sqrt(np.prod(a.shape)))\n else:\n scale = _ctypes.c_double(1.0/np.sqrt(np.prod(a.shape)))\n \n mkl.DftiSetValue(Desc_Handle, DFTI_FORWARD_SCALE, scale)\n mkl.DftiSetValue(Desc_Handle, DFTI_BACKWARD_SCALE, scale)\n elif norm is None:\n if a.dtype == np.float64:\n scale = _ctypes.c_float(1.0/np.prod(a.shape))\n else:\n scale = _ctypes.c_double(1.0/np.prod(a.shape))\n \n mkl.DftiSetValue(Desc_Handle, DFTI_BACKWARD_SCALE, scale)\n \n # For strides, the C type used *must* be int64\n in_strides = (_ctypes.c_int64*3)(0, a.strides[0]/a.itemsize, a.strides[1]/a.itemsize)\n out_strides = (_ctypes.c_int64*3)(0, out.strides[0]/out.itemsize, out.strides[1]/out.itemsize)\n \n # mkl.DftiSetValue(Desc_Handle, DFTI_INPUT_STRIDES, _ctypes.byref(in_strides))\n mkl.DftiSetValue(Desc_Handle, DFTI_OUTPUT_STRIDES, _ctypes.byref(out_strides))\n\n if direction == 'forward':\n fft_func = mkl.DftiComputeForward\n elif direction == 'backward':\n fft_func = mkl.DftiComputeBackward\n else:\n assert False\n\n # Not-in-place FFT\n mkl.DftiSetValue(Desc_Handle, DFTI_PLACEMENT, DFTI_NOT_INPLACE)\n\n # Set output strides if necessary\n if not out.flags['C_CONTIGUOUS']:\n out_strides = (_ctypes.c_int*3)(0, out.strides[0]/out.itemsize, out.strides[1]/out.itemsize)\n mkl.DftiSetValue(Desc_Handle, DFTI_OUTPUT_STRIDES, _ctypes.byref(out_strides))\n\n mkl.DftiCommitDescriptor(Desc_Handle)\n fft_func(Desc_Handle, a.ctypes.data_as(_ctypes.c_void_p), out.ctypes.data_as(_ctypes.c_void_p) )\n\n mkl.DftiFreeDescriptor(_ctypes.byref(Desc_Handle))\n\n return out\n\n\nif __name__ == \"__main__\":\n\n import time\n\n n_iter = 200\n N = 256\n\n np.seterr(all='raise')\n\n A = np.complex64(np.random.randn(N, N))\n C = np.zeros((N, N), dtype='complex64')\n start_time = time.time()\n for i in range(n_iter):\n C += np.fft.fft(A)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n A = np.complex64(np.random.randn(N, N))\n C = np.zeros((N, N), dtype='complex64')\n start_time = time.time()\n for i in range(n_iter):\n C += fft(A)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n A = np.float32(np.random.randn(N, N))\n C = np.zeros((N, N//2+1), dtype='complex64')\n start_time = time.time()\n for i in range(n_iter):\n C += mkl_rfft(A)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n"
] |
[
[
"numpy.rot90",
"numpy.swapaxes",
"numpy.pad",
"numpy.fft.fft",
"numpy.may_share_memory",
"numpy.sqrt",
"numpy.empty_like",
"numpy.seterr",
"numpy.random.randn",
"numpy.prod",
"numpy.array",
"numpy.zeros",
"numpy.empty"
]
] |
chandana1332/incubator-mxnet
|
[
"3f4f3d578c23388c850c1691e3e77ab5d6e81ee1"
] |
[
"tests/python/unittest/test_gluon.py"
] |
[
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport tempfile\n\nimport mxnet as mx\nfrom mxnet import gluon\nfrom mxnet.gluon import nn\nfrom mxnet.test_utils import assert_almost_equal\nfrom mxnet.ndarray.ndarray import _STORAGE_TYPE_STR_TO_ID\nfrom common import (setup_module, with_seed, assertRaises, teardown,\n assert_raises_cudnn_not_satisfied)\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nfrom nose.tools import raises, assert_raises\nfrom copy import deepcopy\nimport warnings\nimport json\nimport unittest\n\n@with_seed()\ndef test_parameter():\n p = gluon.Parameter('weight', shape=(10, 10))\n p.initialize(init='xavier', ctx=[mx.cpu(0), mx.cpu(1)])\n assert len(p.list_data()) == 2\n assert len(p.list_grad()) == 2\n assert p.data(mx.cpu(1)).context == mx.cpu(1)\n assert p.data(mx.cpu(0)).shape == (10, 10)\n assert p.var().name == 'weight'\n assert p.grad(mx.cpu(0)).stype == 'default'\n assert p.data(mx.cpu(0)).stype == 'default'\n\n p.reset_ctx(ctx=[mx.cpu(1), mx.cpu(2)])\n assert p.list_ctx() == [mx.cpu(1), mx.cpu(2)]\n\n@with_seed()\n@raises(AssertionError)\ndef test_invalid_parameter_stype():\n p = gluon.Parameter('weight', shape=(10, 10), stype='invalid')\n\n@with_seed()\n@raises(AssertionError)\ndef test_invalid_parameter_grad_stype():\n p = gluon.Parameter('weight', shape=(10, 10), grad_stype='invalid')\n\n@with_seed()\ndef test_sparse_parameter():\n p = gluon.Parameter('weight', shape=(10, 10), stype='row_sparse', grad_stype='row_sparse')\n p.initialize(init='xavier', ctx=[mx.cpu(0), mx.cpu(1)])\n row_id = mx.nd.arange(0, 10, ctx=mx.cpu(1))\n assert len(p.list_grad()) == 2\n # getting row_sparse data without trainer throws an exception\n assertRaises(RuntimeError, p.list_row_sparse_data, row_id)\n trainer = mx.gluon.Trainer([p], 'sgd')\n assert len(p.list_row_sparse_data(row_id)) == 2\n weight = p.row_sparse_data(row_id)\n assert weight.context == mx.cpu(1)\n assert weight.shape == (10, 10)\n assert weight.stype == 'row_sparse'\n assert p.var().name == 'weight'\n assert p.var().attr('__storage_type__') == str(_STORAGE_TYPE_STR_TO_ID['row_sparse'])\n assert p.grad(mx.cpu(0)).stype == 'row_sparse'\n\n p.reset_ctx(ctx=[mx.cpu(1), mx.cpu(2)])\n assert p.list_ctx() == [mx.cpu(1), mx.cpu(2)]\n\n@with_seed()\ndef test_parameter_invalid_access():\n # cannot call data on row_sparse parameters\n p0 = gluon.Parameter('weight', shape=(10, 10), stype='row_sparse', grad_stype='row_sparse')\n p0.initialize(init='xavier', ctx=[mx.cpu(0), mx.cpu(1)])\n assertRaises(RuntimeError, p0.data)\n assertRaises(RuntimeError, p0.list_data)\n row_id = mx.nd.arange(0, 10)\n # cannot call row_sparse_data on dense parameters\n p1 = gluon.Parameter('weight', shape=(10, 10))\n p1.initialize(init='xavier', ctx=[mx.cpu(0), mx.cpu(1)])\n assertRaises(RuntimeError, p1.row_sparse_data, row_id.copyto(mx.cpu(0)))\n assertRaises(RuntimeError, p1.list_row_sparse_data, row_id)\n\n@with_seed()\ndef test_paramdict():\n ctx = mx.cpu(1)\n params0 = gluon.ParameterDict('net_')\n params0.get('w0', shape=(10, 10))\n params0.get('w1', shape=(10, 10), stype='row_sparse')\n all_row_ids = mx.nd.arange(0, 10, ctx=ctx)\n # check param names\n assert list(params0.keys()) == ['net_w0', 'net_w1']\n params0.initialize(ctx=ctx)\n trainer0 = mx.gluon.Trainer(params0, 'sgd')\n prev_w0 = params0.get('w0').data(ctx)\n prev_w1 = params0.get('w1').row_sparse_data(all_row_ids)\n # save params\n params0.save('test_paramdict.params')\n\n # load params\n params1 = gluon.ParameterDict('net_')\n params1.get('w0', shape=(10, 10))\n params1.get('w1', shape=(10, 10), stype='row_sparse')\n params1.load('test_paramdict.params', ctx)\n trainer1 = mx.gluon.Trainer(params1, 'sgd')\n\n # compare the values before and after save/load\n cur_w0 = params1.get('w0').data(ctx)\n cur_w1 = params1.get('w1').row_sparse_data(all_row_ids)\n mx.test_utils.assert_almost_equal(prev_w0.asnumpy(), cur_w0.asnumpy())\n mx.test_utils.assert_almost_equal(prev_w1.asnumpy(), cur_w1.asnumpy())\n\n # create a new param dict with dense params, and load from the checkpoint\n # of sparse & dense params\n params2 = gluon.ParameterDict('net_')\n params2.get('w0', shape=(10, 10))\n params2.get('w1', shape=(10, 10))\n params2.load('test_paramdict.params', ctx)\n\n # compare the values before and after save/load\n cur_w0 = params2.get('w0').data(ctx)\n cur_w1 = params2.get('w1').data(ctx)\n mx.test_utils.assert_almost_equal(prev_w0.asnumpy(), cur_w0.asnumpy())\n mx.test_utils.assert_almost_equal(prev_w1.asnumpy(), cur_w1.asnumpy())\n\n\n@with_seed()\ndef test_parameter_row_sparse_data():\n ctx0 = mx.cpu(1)\n ctx1 = mx.cpu(2)\n dim0 = 4\n x = gluon.Parameter('x', shape=(dim0, 2), stype='row_sparse')\n x.initialize(init='xavier', ctx=[ctx0, ctx1])\n trainer = gluon.Trainer([x], 'sgd')\n x_param = x._data[0].copy()\n assert x_param.stype == 'row_sparse'\n row_id_0 = mx.nd.array([0,1], ctx=ctx0)\n retained_0 = x.row_sparse_data(row_id_0)\n retained_target_0 = mx.nd.sparse.retain(x_param, row_id_0.as_in_context(ctx0))\n mx.test_utils.assert_almost_equal(retained_0.asnumpy(), retained_target_0.asnumpy())\n assert retained_0.context == ctx0\n row_id_1 = mx.nd.arange(0, dim0, ctx=ctx1)\n retained_1 = x.row_sparse_data(row_id_1)\n retained_target_1 = x_param\n mx.test_utils.assert_almost_equal(retained_1.asnumpy(), retained_target_1.asnumpy())\n assert retained_1.context == ctx1\n row_id_2 = mx.nd.array([0,1,2])\n retained_2 = x.list_row_sparse_data(row_id_2)\n retained_target_2 = mx.nd.sparse.retain(x_param, row_id_2.as_in_context(ctx0))\n mx.test_utils.assert_almost_equal(retained_2[0].asnumpy(), retained_target_2.asnumpy())\n\n\n@with_seed()\ndef test_constant():\n class Test(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Test, self).__init__(**kwargs)\n self.value = np.asarray([[1,2], [3,4]])\n self.const = self.params.get_constant('const', self.value)\n\n def hybrid_forward(self, F, x, const):\n return x + const\n\n test = Test()\n test.initialize()\n trainer = gluon.Trainer(test.collect_params(), 'sgd',\n {'learning_rate': 1.0, 'momentum': 0.5})\n\n with mx.autograd.record():\n x = mx.nd.ones((2,2))\n x.attach_grad()\n y = test(x)\n y.backward()\n\n trainer.step(1)\n\n assert (test.const.data().asnumpy() == test.value).all()\n assert (x.grad.asnumpy() == 1).all()\n\n\n@with_seed()\ndef test_parameter_sharing():\n class Net(gluon.Block):\n def __init__(self, in_units=0, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.dense0 = nn.Dense(5, in_units=in_units)\n self.dense1 = nn.Dense(5, in_units=in_units)\n\n def forward(self, x):\n return self.dense1(self.dense0(x))\n\n net1 = Net(prefix='net1_', in_units=5)\n net2 = Net(prefix='net2_', params=net1.collect_params())\n net1.collect_params().initialize()\n net2(mx.nd.zeros((3, 5)))\n\n net1.save_parameters('net1.params')\n\n net3 = Net(prefix='net3_')\n net3.load_parameters('net1.params', mx.cpu())\n\n net4 = Net(prefix='net4_')\n net5 = Net(prefix='net5_', in_units=5, params=net4.collect_params())\n net4.collect_params().initialize()\n net5(mx.nd.zeros((3, 5)))\n\n net4.save_parameters('net4.params')\n\n net6 = Net(prefix='net6_')\n net6.load_parameters('net4.params', mx.cpu())\n\n\n@with_seed()\ndef test_parameter_str():\n class Net(gluon.Block):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.dense0 = nn.Dense(10, in_units=5, use_bias=False)\n\n net = Net(prefix='net1_')\n lines = str(net.collect_params()).splitlines()\n\n assert lines[0] == 'net1_ ('\n assert 'net1_dense0_weight' in lines[1]\n assert '(10, 5)' in lines[1]\n assert 'float32' in lines[1]\n assert lines[2] == ')'\n\n\n@with_seed()\ndef test_collect_paramters():\n net = nn.HybridSequential(prefix=\"test_\")\n with net.name_scope():\n net.add(nn.Conv2D(10, 3))\n net.add(nn.Dense(10, activation='relu'))\n assert set(net.collect_params().keys()) == \\\n set(['test_conv0_weight', 'test_conv0_bias','test_dense0_weight','test_dense0_bias'])\n assert set(net.collect_params('.*weight').keys()) == \\\n set(['test_conv0_weight', 'test_dense0_weight'])\n assert set(net.collect_params('test_conv0_bias|test_dense0_bias').keys()) == \\\n set(['test_conv0_bias', 'test_dense0_bias'])\n\n@with_seed()\ndef test_basic():\n model = nn.Sequential()\n model.add(nn.Dense(128, activation='tanh', in_units=10, flatten=False))\n model.add(nn.Dropout(0.5))\n model.add(nn.Dense(64, activation='tanh', in_units=256),\n nn.Dense(32, in_units=64))\n model.add(nn.Activation('relu'))\n\n # symbol\n x = mx.sym.var('data')\n y = model(x)\n assert len(y.list_arguments()) == 7\n\n # ndarray\n model.collect_params().initialize(mx.init.Xavier(magnitude=2.24))\n x = model(mx.nd.zeros((32, 2, 10)))\n assert x.shape == (32, 32)\n x.wait_to_read()\n\n model.collect_params().setattr('grad_req', 'null')\n assert list(model.collect_params().values())[0]._grad is None\n model.collect_params().setattr('grad_req', 'write')\n assert list(model.collect_params().values())[0]._grad is not None\n\n\n@with_seed()\ndef test_dense():\n model = nn.Dense(128, activation='tanh', in_units=10, flatten=False, prefix='test_')\n inputs = mx.sym.Variable('data')\n outputs = model(inputs)\n assert set(model.collect_params().keys()) == set(['test_weight', 'test_bias'])\n assert outputs.list_outputs() == ['test_tanh_fwd_output']\n args, outs, auxs = outputs.infer_shape(data=(2, 3, 10))\n assert outs == [(2, 3, 128)]\n\n model = nn.Dense(128, activation='relu', in_units=30, flatten=True, prefix='test2_')\n inputs = mx.sym.Variable('data')\n outputs = model(inputs)\n assert set(model.collect_params().keys()) == set(['test2_weight', 'test2_bias'])\n assert outputs.list_outputs() == ['test2_relu_fwd_output']\n args, outs, auxs = outputs.infer_shape(data=(17, 2, 5, 3))\n assert outs == [(17, 128)]\n\n\n@with_seed()\ndef test_symbol_block():\n model = nn.HybridSequential()\n model.add(nn.Dense(128, activation='tanh'))\n model.add(nn.Dropout(0.5))\n model.add(nn.Dense(64, activation='tanh'),\n nn.Dense(32, in_units=64))\n model.add(nn.Activation('relu'))\n\n model.initialize()\n\n inputs = mx.sym.var('data')\n outputs = model(inputs).get_internals()\n\n smodel = gluon.SymbolBlock(outputs, inputs, params=model.collect_params())\n\n assert len(smodel(mx.nd.zeros((16, 10)))) == 14\n\n out = smodel(mx.sym.var('in'))\n assert len(out) == len(outputs.list_outputs())\n\n class Net(nn.HybridBlock):\n def __init__(self, model):\n super(Net, self).__init__()\n self.model = model\n\n def hybrid_forward(self, F, x):\n out = self.model(x)\n return F.add_n(*[i.sum() for i in out])\n\n net = Net(smodel)\n net.hybridize()\n assert isinstance(net(mx.nd.zeros((16, 10))), mx.nd.NDArray)\n\n inputs = mx.sym.var('data')\n outputs = model(inputs)\n smodel = gluon.SymbolBlock(outputs, inputs, params=model.collect_params())\n net = Net(smodel)\n net.hybridize()\n assert isinstance(net(mx.nd.zeros((16, 10))), mx.nd.NDArray)\n\n # Test case to verify if initializing the SymbolBlock from a model with params\n # other than fp32 param dtype.\n\n # 1. Load a resnet model, cast it to fp64 and export\n tmp = tempfile.mkdtemp()\n tmpfile = os.path.join(tmp, 'resnet34_fp64')\n ctx = mx.cpu(0)\n\n net_fp32 = mx.gluon.model_zoo.vision.resnet34_v2(pretrained=True, ctx=ctx, root=tmp)\n net_fp32.cast('float64')\n net_fp32.hybridize()\n data = mx.nd.zeros((1,3,224,224), dtype='float64', ctx=ctx)\n net_fp32.forward(data)\n net_fp32.export(tmpfile, 0)\n\n # 2. Load the saved model and verify if all the params are loaded correctly.\n # and choose one of the param to verify the type if fp64.\n sm = mx.sym.load(tmpfile + '-symbol.json')\n inputs = mx.sym.var('data', dtype='float64')\n net_fp64 = mx.gluon.SymbolBlock(sm, inputs)\n net_fp64.collect_params().load(tmpfile + '-0000.params', ctx=ctx)\n # 3. Get a conv layer's weight parameter name. Conv layer's weight param is\n # expected to be of dtype casted, fp64.\n for param_name in net_fp64.params.keys():\n if 'conv' in param_name and 'weight' in param_name:\n break\n assert np.dtype(net_fp64.params[param_name].dtype) == np.dtype(np.float64)\n\n # Cast the symbol block to FP32 and try to forward a FP32 data.\n # This will verify SymbolBlock.cast() functionality.\n net_fp64.cast('float32')\n fp32_data = mx.nd.zeros((1,3,224,224), dtype='float32', ctx=ctx)\n prediction = net_fp64.forward(fp32_data)\n assert np.dtype(prediction.dtype) == np.dtype(np.float32)\n\n@with_seed()\n@raises(AssertionError)\ndef test_sparse_symbol_block():\n data = mx.sym.var('data')\n weight = mx.sym.var('weight', stype='row_sparse')\n bias = mx.sym.var('bias')\n out = mx.sym.broadcast_add(mx.sym.dot(data, weight), bias)\n # an exception is expected when creating a SparseBlock w/ sparse param\n net = gluon.SymbolBlock(out, data)\n\n@with_seed()\n@raises(RuntimeError)\ndef test_sparse_hybrid_block():\n params = gluon.ParameterDict('net_')\n params.get('weight', shape=(5,5), stype='row_sparse', dtype='float32')\n params.get('bias', shape=(5), dtype='float32')\n net = gluon.nn.Dense(5, params=params)\n net.initialize()\n x = mx.nd.ones((2,5))\n # an exception is expected when forwarding a HybridBlock w/ sparse param\n y = net(x)\n\n@with_seed()\ndef check_layer_forward(layer, dshape):\n print(\"checking layer {}\\nshape: {}.\".format(layer, dshape))\n layer.collect_params().initialize()\n x = mx.nd.ones(shape=dshape)\n x.attach_grad()\n with mx.autograd.record():\n out = layer(x)\n out.backward()\n\n np_out = out.asnumpy()\n np_dx = x.grad.asnumpy()\n\n layer.hybridize()\n\n x = mx.nd.ones(shape=dshape)\n x.attach_grad()\n with mx.autograd.record():\n out = layer(x)\n out.backward()\n\n mx.test_utils.assert_almost_equal(np_out, out.asnumpy(), rtol=1e-5, atol=1e-6)\n mx.test_utils.assert_almost_equal(np_dx, x.grad.asnumpy(), rtol=1e-5, atol=1e-6)\n\n@with_seed()\ndef test_conv():\n layers1d = [\n nn.Conv1D(16, 3, in_channels=4),\n nn.Conv1D(16, 3, groups=2, in_channels=4),\n nn.Conv1D(16, 3, strides=3, groups=2, in_channels=4),\n ]\n for layer in layers1d:\n check_layer_forward(layer, (1, 4, 10))\n\n\n layers2d = [\n nn.Conv2D(16, (3, 4), in_channels=4),\n nn.Conv2D(16, (5, 4), in_channels=4),\n nn.Conv2D(16, (3, 4), groups=2, in_channels=4),\n nn.Conv2D(16, (3, 4), strides=4, in_channels=4),\n nn.Conv2D(16, (3, 4), dilation=4, in_channels=4),\n nn.Conv2D(16, (3, 4), padding=4, in_channels=4),\n ]\n for layer in layers2d:\n check_layer_forward(layer, (1, 4, 20, 20))\n\n\n layers3d = [\n nn.Conv3D(16, (1, 8, 4), in_channels=4, activation='relu'),\n nn.Conv3D(16, (5, 4, 3), in_channels=4),\n nn.Conv3D(16, (3, 3, 3), groups=2, in_channels=4),\n nn.Conv3D(16, 4, strides=4, in_channels=4),\n nn.Conv3D(16, (3, 3, 3), padding=4, in_channels=4),\n ]\n for layer in layers3d:\n check_layer_forward(layer, (1, 4, 10, 10, 10))\n\n\n layer = nn.Conv2D(16, (3, 3), layout='NHWC', in_channels=4)\n # check_layer_forward(layer, (1, 10, 10, 4))\n\n layer = nn.Conv3D(16, (3, 3, 3), layout='NDHWC', in_channels=4)\n # check_layer_forward(layer, (1, 10, 10, 10, 4))\n\n\n@with_seed()\ndef test_deconv():\n # layers1d = [\n # nn.Conv1DTranspose(16, 3, in_channels=4),\n # nn.Conv1DTranspose(16, 3, groups=2, in_channels=4),\n # nn.Conv1DTranspose(16, 3, strides=3, groups=2, in_channels=4),\n # ]\n # for layer in layers1d:\n # check_layer_forward(layer, (1, 4, 10))\n\n\n layers2d = [\n nn.Conv2DTranspose(16, (3, 4), in_channels=4),\n nn.Conv2DTranspose(16, (5, 4), in_channels=4),\n nn.Conv2DTranspose(16, (3, 4), groups=2, in_channels=4),\n nn.Conv2DTranspose(16, (3, 4), strides=4, in_channels=4),\n nn.Conv2DTranspose(16, (3, 4), dilation=4, in_channels=4),\n # nn.Conv2DTranspose(16, (3, 4), padding=4, in_channels=4),\n nn.Conv2DTranspose(16, (3, 4), strides=4, output_padding=3, in_channels=4),\n ]\n for layer in layers2d:\n check_layer_forward(layer, (1, 4, 20, 20))\n\n\n # layers3d = [\n # nn.Conv3DTranspose(16, (1, 8, 4), in_channels=4),\n # nn.Conv3DTranspose(16, (5, 4, 3), in_channels=4),\n # nn.Conv3DTranspose(16, (3, 3, 3), groups=2, in_channels=4),\n # nn.Conv3DTranspose(16, 4, strides=4, in_channels=4),\n # nn.Conv3DTranspose(16, (3, 3, 3), padding=4, in_channels=4),\n # ]\n # for layer in layers3d:\n # check_layer_forward(layer, (1, 4, 10, 10, 10))\n #\n #\n # layer = nn.Conv2DTranspose(16, (3, 3), layout='NHWC', in_channels=4)\n # # check_layer_forward(layer, (1, 10, 10, 4))\n #\n # layer = nn.Conv3DTranspose(16, (3, 3, 3), layout='NDHWC', in_channels=4)\n # # check_layer_forward(layer, (1, 10, 10, 10, 4))\n\n\n@with_seed()\ndef test_pool():\n # transpose shape to bring feature dimension 'c' from 2nd position to last\n def transpose(shape):\n return (shape[0],) + shape[2:] + (shape[1],)\n\n for layout in ['NCW', 'NWC']:\n shape1d = (1, 2, 10)\n if layout == 'NWC':\n shape1d = transpose(shape1d)\n layers1d = [\n nn.MaxPool1D(layout=layout),\n nn.MaxPool1D(3, layout=layout),\n nn.MaxPool1D(3, 2, layout=layout),\n nn.AvgPool1D(layout=layout),\n nn.AvgPool1D(count_include_pad=False, layout=layout),\n nn.GlobalAvgPool1D(layout=layout),\n ]\n for layer in layers1d:\n check_layer_forward(layer, shape1d)\n\n\n for layout in ['NCHW', 'NHWC']:\n shape2d = (1, 2, 10, 10)\n if layout == 'NHWC':\n shape2d = transpose(shape2d)\n layers2d = [\n nn.MaxPool2D(layout=layout),\n nn.MaxPool2D((3, 3), layout=layout),\n nn.MaxPool2D(3, 2, layout=layout),\n nn.AvgPool2D(layout=layout),\n nn.AvgPool2D(count_include_pad=False, layout=layout),\n nn.GlobalAvgPool2D(layout=layout),\n ]\n for layer in layers2d:\n check_layer_forward(layer, shape2d)\n\n for layout in ['NCDHW', 'NDHWC']:\n shape3d = (1, 2, 10, 10, 10)\n if layout == 'NDHWC':\n shape3d = transpose(shape3d)\n layers3d = [\n nn.MaxPool3D(layout=layout),\n nn.MaxPool3D((3, 3, 3), layout=layout),\n nn.MaxPool3D(3, 2, layout=layout),\n nn.AvgPool3D(layout=layout),\n nn.AvgPool3D(count_include_pad=False, layout=layout),\n nn.GlobalAvgPool3D(layout=layout),\n ]\n for layer in layers3d:\n check_layer_forward(layer, shape3d)\n\n # test ceil_mode\n for layout in ['NCHW', 'NHWC']:\n xshape = (2, 2, 10, 10)\n noceil_out_shape = (2, 2, 3, 3)\n ceil_out_shape = (2, 2, 4, 4)\n if layout == 'NHWC':\n xshape = transpose(xshape)\n noceil_out_shape = transpose(noceil_out_shape)\n ceil_out_shape = transpose(ceil_out_shape)\n\n x = mx.nd.zeros(xshape)\n\n layer = nn.MaxPool2D(3, ceil_mode=False, layout=layout)\n layer.collect_params().initialize()\n assert (layer(x).shape==noceil_out_shape)\n\n layer = nn.MaxPool2D(3, ceil_mode=True, layout=layout)\n layer.collect_params().initialize()\n assert (layer(x).shape==ceil_out_shape)\n\n\n@with_seed()\ndef test_batchnorm():\n layer = nn.BatchNorm(in_channels=10)\n check_layer_forward(layer, (2, 10, 10, 10))\n\n\n@with_seed()\ndef test_sync_batchnorm():\n def _check_batchnorm_result(input, num_devices=1, cuda=False):\n from mxnet.gluon.utils import split_and_load\n\n def _find_bn(module):\n if isinstance(module, (mx.gluon.nn.BatchNorm, mx.gluon.contrib.nn.SyncBatchNorm)):\n return module\n elif isinstance(module.module, (mx.gluon.nn.BatchNorm, mx.gluon.contrib.nn.SyncBatchNorm)):\n return module.module\n\n raise RuntimeError('BN not found')\n\n def _syncParameters(bn1, bn2, ctx):\n ctx = input.context\n bn2.gamma.set_data(bn1.gamma.data(ctx))\n bn2.beta.set_data(bn1.beta.data(ctx))\n bn2.running_mean.set_data(bn1.running_mean.data(ctx))\n bn2.running_var.set_data(bn1.running_var.data(ctx))\n\n input1 = input.copy()\n input2 = input.copy()\n\n if cuda:\n input1 = input.as_in_context(mx.gpu(0))\n ctx_list = [mx.gpu(i) for i in range(num_devices)]\n else:\n ctx_list = [mx.cpu(0) for _ in range(num_devices)]\n\n nch = input.shape[1] if input.ndim > 1 else 1\n bn1 = mx.gluon.nn.BatchNorm(in_channels=nch)\n bn2 = mx.gluon.contrib.nn.SyncBatchNorm(\n in_channels=nch, num_devices=num_devices)\n\n bn1.initialize(ctx=ctx_list[0])\n bn2.initialize(ctx=ctx_list)\n\n # using the same values for gamma and beta\n #_syncParameters(_find_bn(bn1), _find_bn(bn2), ctx_list[0])\n\n input1.attach_grad()\n inputs2 = split_and_load(input2, ctx_list, batch_axis=0)\n for xi in inputs2:\n xi.attach_grad()\n\n with mx.autograd.record():\n output1 = bn1(input1)\n output2 = [bn2(xi) for xi in inputs2]\n loss1 = (output1 ** 2).sum()\n loss2 = [(output ** 2).sum() for output in output2]\n mx.autograd.backward(loss1)\n mx.autograd.backward(loss2)\n\n output2 = mx.nd.concat(*[output.as_in_context(input.context)\n for output in output2], dim=0)\n # check bn1\n\n momentum = 0.9\n epsilon = 1e-5\n axis = 1\n data = input1\n running_mean = mx.nd.zeros(nch, ctx=data.context)\n running_var = mx.nd.ones(nch, ctx=data.context)\n\n data_mean = data.mean(\n axis=axis, exclude=True, keepdims=True)\n data_var = (data - data_mean).square().mean(axis=axis,\n exclude=True, keepdims=True)\n\n target_output = (data - data_mean) / (data_var + epsilon).sqrt()\n\n # squeeze data_mean and data_var\n data_mean_flat = data_mean.squeeze()\n data_var_flat = data_var.squeeze()\n\n running_mean = running_mean * momentum + \\\n data_mean_flat * (1 - momentum)\n running_var = running_var * momentum + \\\n data_var_flat * (1 - momentum)\n\n atol = 1e-2\n rtol = 1e-2\n assert_almost_equal(output1.asnumpy(), target_output.asnumpy(),\n atol=atol, rtol=rtol)\n assert_almost_equal(_find_bn(bn1).running_mean.data(ctx_list[0]).asnumpy(),\n running_mean.asnumpy(),\n atol=atol, rtol=rtol)\n assert_almost_equal(_find_bn(bn1).running_var.data(ctx_list[0]).asnumpy(),\n running_var.asnumpy(),\n atol=atol, rtol=rtol)\n # assert forwarding\n assert_almost_equal(input1.asnumpy(), input2.asnumpy(),\n atol=atol, rtol=rtol)\n assert_almost_equal(output1.asnumpy(),\n output2.asnumpy(), atol=atol, rtol=rtol)\n assert_almost_equal(_find_bn(bn1).running_mean.data(ctx_list[0]).asnumpy(),\n _find_bn(bn2).running_mean.data(ctx_list[0]).asnumpy(),\n atol=atol, rtol=rtol)\n assert_almost_equal(_find_bn(bn1).running_var.data(ctx_list[0]).asnumpy(),\n _find_bn(bn2).running_var.data(ctx_list[0]).asnumpy(),\n atol=atol, rtol=rtol)\n input2grad = mx.nd.concat(\n *[output.grad.as_in_context(input.context) for output in inputs2], dim=0)\n assert_almost_equal(input1.grad.asnumpy(),\n input2grad.asnumpy(), atol=atol, rtol=rtol)\n\n cfgs = [(1, False)]\n num_gpus = mx.context.num_gpus()\n for i in range(1, num_gpus + 1):\n cfgs.append((i, True))\n for ndev, cuda in cfgs:\n # check with unsync version\n for shape in [(24, 2), (24, 3, 4), (24, 4, 4, 4), (24, 5, 6, 4, 4)]:\n print(str((ndev, cuda, shape)))\n for i in range(10):\n _check_batchnorm_result(mx.nd.random.uniform(shape=shape,\n ctx=mx.cpu(0)),\n num_devices=ndev, cuda=cuda)\n\n\n@with_seed()\ndef test_instancenorm():\n layer = nn.InstanceNorm(in_channels=10)\n check_layer_forward(layer, (2, 10, 10, 10))\n\n@with_seed()\ndef test_layernorm():\n layer = nn.LayerNorm(in_channels=10)\n check_layer_forward(layer, (2, 10, 10, 10))\n\n\n@with_seed()\ndef test_reflectionpad():\n layer = nn.ReflectionPad2D(3)\n check_layer_forward(layer, (2, 3, 24, 24))\n\n\n@with_seed()\ndef test_reshape():\n x = mx.nd.ones((2, 4, 10, 10))\n layer = nn.Conv2D(10, 2, in_channels=4)\n layer.collect_params().initialize()\n with mx.autograd.record():\n x = layer(x)\n x = x.reshape((-1,))\n x = x + 10\n x.backward()\n\n\n@with_seed()\ndef test_slice():\n x = mx.nd.ones((5, 4, 10, 10))\n layer = nn.Conv2D(10, 2, in_channels=4)\n layer.collect_params().initialize()\n with mx.autograd.record():\n x = layer(x)\n x = x[1:3]\n x = x + 10\n x.backward()\n\n\n@with_seed()\ndef test_at():\n x = mx.nd.ones((5, 4, 10, 10))\n layer = nn.Conv2D(10, 2, in_channels=4)\n layer.collect_params().initialize()\n with mx.autograd.record():\n x = layer(x)\n x = x[1]\n x = x + 10\n x.backward()\n\n\n@with_seed()\ndef test_deferred_init():\n x = mx.nd.ones((5, 4, 10, 10))\n layer = nn.Conv2D(10, 2)\n layer.collect_params().initialize()\n layer(x)\n\n\ndef check_split_data(x, num_slice, batch_axis, **kwargs):\n res = gluon.utils.split_data(x, num_slice, batch_axis, **kwargs)\n assert len(res) == num_slice\n mx.test_utils.assert_almost_equal(mx.nd.concat(*res, dim=batch_axis).asnumpy(),\n x.asnumpy())\n\n\n@with_seed()\ndef test_split_data():\n x = mx.nd.random.uniform(shape=(128, 33, 64))\n\n check_split_data(x, 8, 0)\n check_split_data(x, 3, 1)\n check_split_data(x, 4, 1, even_split=False)\n check_split_data(x, 15, 1, even_split=False)\n try:\n check_split_data(x, 4, 1)\n except ValueError:\n return\n assert False, \"Should have failed\"\n\n\n@with_seed()\ndef test_flatten():\n flatten = nn.Flatten()\n x = mx.nd.zeros((3,4,5,6))\n assert flatten(x).shape == (3, 4*5*6)\n x = mx.nd.zeros((3,6))\n assert flatten(x).shape == (3, 6)\n x = mx.nd.zeros((3,))\n assert flatten(x).shape == (3, 1)\n\n@with_seed()\ndef test_block_attr_hidden():\n b = gluon.Block()\n\n # regular attributes can change types\n b.a = None\n b.a = 1\n\n\n@raises(TypeError)\n@with_seed()\ndef test_block_attr_block():\n b = gluon.Block()\n\n # regular variables can't change types\n b.b = gluon.Block()\n b.b = (2,)\n\n\n@raises(TypeError)\n@with_seed()\ndef test_block_attr_param():\n b = gluon.Block()\n\n # regular variables can't change types\n b.b = gluon.Parameter()\n b.b = (2,)\n\n\n@with_seed()\ndef test_block_attr_regular():\n b = gluon.Block()\n\n # set block attribute also sets _children\n b.c = gluon.Block()\n c2 = gluon.Block()\n b.c = c2\n assert b.c is c2 and list(b._children.values())[0] is c2\n\n\n@with_seed()\ndef test_block_attr_list_of_block():\n class Model1(gluon.Block):\n def __init__(self, **kwargs):\n super(Model1, self).__init__(**kwargs)\n with self.name_scope():\n self.layers = [nn.Dense(i * 10) for i in range(6)]\n\n class Model2(gluon.Block):\n def __init__(self, **kwargs):\n super(Model2, self).__init__(**kwargs)\n with self.name_scope():\n self.layers = dict()\n self.layers['a'] = [nn.Dense(10), nn.Dense(10)]\n\n class Model3(gluon.Block):\n def __init__(self, **kwargs):\n super(Model3, self).__init__(**kwargs)\n with self.name_scope():\n self.layers = nn.Sequential()\n self.layers.add(*[nn.Dense(i * 10) for i in range(6)])\n\n class Model4(gluon.Block):\n def __init__(self, **kwargs):\n super(Model4, self).__init__(**kwargs)\n with self.name_scope():\n self.data = {'a': '4', 'b': 123}\n\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n model = Model1()\n model.collect_params()\n assert len(w) > 0\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n model = Model2()\n model.collect_params()\n assert len(w) > 0\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n model = Model3()\n model.collect_params()\n assert len(w) == 0\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n model = Model4()\n model.collect_params()\n assert len(w) == 0\n\ndef check_sequential(net):\n dense1 = gluon.nn.Dense(10)\n net.add(dense1)\n dense2 = gluon.nn.Dense(10)\n net.add(dense2)\n dense3 = gluon.nn.Dense(10)\n net.add(dense3)\n\n assert net[1] is dense2\n assert net[-1] is dense3\n slc = net[1:3]\n assert len(slc) == 2 and slc[0] is dense2 and slc[1] is dense3\n assert isinstance(slc, type(net))\n\n@with_seed()\ndef test_sequential():\n check_sequential(gluon.nn.Sequential())\n check_sequential(gluon.nn.HybridSequential())\n\n@with_seed()\ndef test_sequential_warning():\n with warnings.catch_warnings(record=True) as w:\n # The following line permits the test to pass if run multiple times\n warnings.simplefilter('always')\n b = gluon.nn.Sequential()\n b.add(gluon.nn.Dense(20))\n b.hybridize()\n assert len(w) == 1\n\n\n@with_seed()\ndef test_global_norm_clip():\n stypes = ['default', 'row_sparse']\n def check_global_norm_clip(stype, check_isfinite):\n x1 = mx.nd.ones((3,3)).tostype(stype)\n x2 = mx.nd.ones((4,4)).tostype(stype)\n norm = gluon.utils.clip_global_norm([x1, x2], 1.0, check_isfinite=check_isfinite)\n assert norm == 5.0\n assert_almost_equal(x1.asnumpy(), np.ones((3,3))/5)\n assert_almost_equal(x2.asnumpy(), np.ones((4,4))/5)\n\n x3 = mx.nd.array([1.0, 2.0, float('nan')]).tostype(stype)\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n gluon.utils.clip_global_norm([x1, x3], 2.0, check_isfinite=check_isfinite)\n assert len(w) == check_isfinite\n\n for stype in stypes:\n for check_isfinite in [True, False]:\n check_global_norm_clip(stype, check_isfinite)\n\n@with_seed()\ndef test_embedding():\n def check_embedding(sparse_grad):\n layer = gluon.nn.Embedding(10, 100, sparse_grad=sparse_grad)\n layer.initialize()\n x = mx.nd.array([3,4,2,0,1])\n with mx.autograd.record():\n y = layer(x)\n y.backward()\n assert (layer.weight.grad().asnumpy()[:5] == 1).all()\n assert (layer.weight.grad().asnumpy()[5:] == 0).all()\n\n def check_embedding_large_input(sparse_grad):\n embedding = mx.gluon.nn.Embedding(10, 1, sparse_grad=True)\n embedding.initialize()\n embedding.hybridize()\n shape = (20481,)\n with mx.autograd.record():\n emb_in = embedding(mx.nd.ones(shape))\n loss = emb_in.sum()\n loss.backward()\n assert embedding.weight.grad().data.sum().asscalar() == 20481\n\n check_embedding(True)\n check_embedding(False)\n check_embedding_large_input(True)\n check_embedding_large_input(False)\n\n@with_seed()\ndef test_export():\n ctx = mx.context.current_context()\n model = gluon.model_zoo.vision.resnet18_v1(\n prefix='resnet', ctx=ctx, pretrained=True)\n model.hybridize()\n data = mx.nd.random.normal(shape=(1, 3, 32, 32))\n out = model(data)\n\n model.export('gluon')\n\n module = mx.mod.Module.load('gluon', 0, label_names=None, context=ctx)\n module.bind(data_shapes=[('data', data.shape)])\n module.forward(mx.io.DataBatch([data], None), is_train=False)\n mod_out, = module.get_outputs()\n\n assert_almost_equal(out.asnumpy(), mod_out.asnumpy())\n\n model2 = gluon.model_zoo.vision.resnet18_v1(prefix='resnet', ctx=ctx)\n model2.collect_params().load('gluon-0000.params', ctx)\n out2 = model2(data)\n\n assert_almost_equal(out.asnumpy(), out2.asnumpy())\n\n@with_seed()\ndef test_import():\n ctx = mx.context.current_context()\n net1 = gluon.model_zoo.vision.resnet18_v1(\n prefix='resnet', ctx=ctx, pretrained=True)\n net1.hybridize()\n data = mx.nd.random.normal(shape=(1, 3, 32, 32))\n out1 = net1(data)\n\n net1.export('net1', epoch=1)\n\n net2 = gluon.SymbolBlock.imports(\n 'net1-symbol.json', ['data'], 'net1-0001.params', ctx)\n out2 = net2(data)\n lines = str(net2).splitlines()\n\n assert_almost_equal(out1.asnumpy(), out2.asnumpy())\n assert lines[0] == 'SymbolBlock('\n assert lines[1]\n assert lines[2] == ')'\n\n\n@with_seed()\ndef test_hybrid_stale_cache():\n net = mx.gluon.nn.HybridSequential()\n with net.name_scope():\n net.add(mx.gluon.nn.Dense(10, weight_initializer='zeros', bias_initializer='ones', flatten=False))\n\n net.hybridize()\n net.initialize()\n net(mx.nd.ones((2,3,5)))\n\n net.add(mx.gluon.nn.Flatten())\n assert net(mx.nd.ones((2,3,5))).shape == (2, 30)\n\n net = mx.gluon.nn.HybridSequential()\n with net.name_scope():\n net.fc1 = mx.gluon.nn.Dense(10, weight_initializer='zeros',\n bias_initializer='ones', flatten=False)\n net.fc2 = mx.gluon.nn.Dense(10, weight_initializer='zeros',\n bias_initializer='ones', flatten=False)\n net.hybridize()\n net.initialize()\n net(mx.nd.ones((2,3,5)))\n\n net.fc2 = mx.gluon.nn.Dense(10, weight_initializer='zeros',\n bias_initializer='ones', flatten=True)\n net.initialize()\n assert net(mx.nd.ones((2,3,5))).shape == (2, 10)\n\n\n@with_seed()\ndef test_lambda():\n net1 = mx.gluon.nn.HybridSequential()\n net1.add(nn.Activation('tanh'),\n nn.LeakyReLU(0.1))\n\n net2 = mx.gluon.nn.HybridSequential()\n op3 = lambda F, x, *args: F.LeakyReLU(x, *args, slope=0.1)\n net2.add(nn.HybridLambda('tanh'),\n nn.HybridLambda(op3))\n\n op4 = lambda x: mx.nd.LeakyReLU(x, slope=0.1)\n net3 = mx.gluon.nn.Sequential()\n net3.add(nn.Lambda('tanh'),\n nn.Lambda(op4))\n\n input_data = mx.nd.random.uniform(shape=(2, 3, 5, 7))\n out1, out2, out3 = net1(input_data), net2(input_data), net3(input_data)\n assert_almost_equal(out1.asnumpy(), out2.asnumpy(), rtol=1e-3, atol=1e-3)\n assert_almost_equal(out1.asnumpy(), out3.asnumpy(), rtol=1e-3, atol=1e-3)\n\n\n@with_seed()\ndef test_fill_shape_deferred():\n net = nn.HybridSequential()\n with net.name_scope():\n net.add(nn.Conv2D(64, kernel_size=2, padding=1),\n nn.BatchNorm(),\n nn.Dense(10))\n net.hybridize()\n net.initialize()\n net(mx.nd.ones((2,3,5,7)))\n assert net[0].weight.shape[1] == 3, net[0].weight.shape[1]\n assert net[1].gamma.shape[0] == 64, net[1].gamma.shape[0]\n assert net[2].weight.shape[1] == 3072, net[2].weight.shape[1]\n\n\n@with_seed()\ndef test_dtype():\n net = mx.gluon.model_zoo.vision.resnet18_v1()\n net.initialize()\n net.cast('float64')\n with mx.autograd.record():\n y = net(mx.nd.ones((16, 3, 32, 32), dtype='float64'))\n y.backward()\n\n net = mx.gluon.model_zoo.vision.resnet18_v1()\n net.initialize()\n net.hybridize()\n net(mx.nd.ones((16, 3, 32, 32), dtype='float32'))\n\n net.cast('float64')\n net(mx.nd.ones((16, 3, 32, 32), dtype='float64'))\n\n mx.nd.waitall()\n\n class Net(gluon.Block):\n def __init__(self, in_dim, output_dim):\n super(Net, self).__init__()\n with self.name_scope():\n self.embed = gluon.nn.Embedding(input_dim=in_dim, output_dim=output_dim,dtype=np.float64)\n self.dense = gluon.nn.Dense(2, dtype=np.float64)\n\n def forward(self, x):\n e = self.embed(x)\n assert(e.dtype == np.float64)\n y = self.dense(e)\n assert(y.dtype == np.float64)\n return y\n\n net = Net(5, 10)\n net.initialize()\n out = net(mx.nd.ones((3,), dtype=np.float64))\n mx.nd.waitall()\n\n@with_seed()\ndef test_fill_shape_load():\n ctx = mx.context.current_context()\n net1 = nn.HybridSequential()\n with net1.name_scope():\n net1.add(nn.Conv2D(64, kernel_size=2, padding=1),\n nn.BatchNorm(),\n nn.Dense(10))\n net1.hybridize()\n net1.initialize(ctx=ctx)\n net1(mx.nd.ones((2,3,5,7), ctx))\n net1.save_parameters('net_fill.params')\n\n net2 = nn.HybridSequential()\n with net2.name_scope():\n net2.add(nn.Conv2D(64, kernel_size=2, padding=1),\n nn.BatchNorm(),\n nn.Dense(10))\n net2.hybridize()\n net2.initialize()\n net2.load_parameters('net_fill.params', ctx)\n assert net2[0].weight.shape[1] == 3, net2[0].weight.shape[1]\n assert net2[1].gamma.shape[0] == 64, net2[1].gamma.shape[0]\n assert net2[2].weight.shape[1] == 3072, net2[2].weight.shape[1]\n\n\n@with_seed()\ndef test_inline():\n net = mx.gluon.nn.HybridSequential()\n with net.name_scope():\n net.add(mx.gluon.nn.Dense(10))\n net.add(mx.gluon.nn.Dense(10))\n net.add(mx.gluon.nn.Dense(10))\n\n net.initialize()\n net.hybridize(inline_limit=3)\n with mx.autograd.record():\n y = net(mx.nd.zeros((1,10)))\n\n len_1 = len(json.loads(mx.autograd.get_symbol(y).tojson())['nodes'])\n y.backward()\n\n net.hybridize(inline_limit=0)\n with mx.autograd.record():\n y = net(mx.nd.zeros((1,10)))\n\n len_2 = len(json.loads(mx.autograd.get_symbol(y).tojson())['nodes'])\n y.backward()\n\n assert len_1 == len_2 + 2\n\n\n@with_seed()\ndef test_activations():\n point_to_validate = mx.nd.array([-0.1, 0.1] * 3)\n\n swish = mx.gluon.nn.Swish()\n def swish_test(x):\n return x * mx.nd.sigmoid(x)\n\n for test_point, ref_point in zip(swish_test(point_to_validate), swish(point_to_validate)):\n assert test_point == ref_point\n\n elu = mx.gluon.nn.ELU()\n def elu_test(x):\n def elu(x):\n return mx.nd.expm1(x) if x <= 0.0 else x\n return [elu(x_i) for x_i in x]\n\n for test_point, ref_point in zip(elu_test(point_to_validate), elu(point_to_validate)):\n assert test_point == ref_point\n\n selu = mx.gluon.nn.SELU()\n def selu_test(x):\n def selu(x):\n scale, alpha = 1.0507009873554804934193349852946, 1.6732632423543772848170429916717\n return scale * x if x >= 0 else scale * alpha * mx.nd.expm1(x)\n return [selu(x_i) for x_i in x]\n\n for test_point, ref_point in zip(selu_test(point_to_validate), selu(point_to_validate)):\n assert test_point == ref_point\n\n prelu = mx.gluon.nn.PReLU()\n prelu.initialize()\n x = point_to_validate.reshape((1, 3, 2))\n assert_almost_equal(prelu(x).asnumpy(), mx.nd.where(x >= 0, x, 0.25 * x).asnumpy())\n\n gelu = mx.gluon.nn.GELU()\n def gelu_test(x):\n CUBE_CONSTANT = 0.044715\n ROOT_TWO_OVER_PI = 0.7978845608028654\n def g(x):\n return ROOT_TWO_OVER_PI * (x + CUBE_CONSTANT * x * x * x)\n def f(x):\n return 1.0 + mx.nd.tanh(g(x))\n def gelu(x):\n return 0.5 * x * f(x)\n for test_point, ref_point in zip(gelu_test(point_to_validate), gelu(point_to_validate)):\n assert test_point == ref_point\n\n\n@with_seed()\ndef test_dropout():\n def get_slice(x, axis, idx):\n ix = ()\n for i in range(x.ndim):\n if i == axis:\n ix += (idx,)\n else:\n ix += (slice(None, None, None),)\n return x[ix]\n\n def check_dropout_axes(ratio, shape, axes):\n compactshape = list(shape)\n for axis in axes:\n compactshape[axis] = 1\n compactx = mx.random.uniform(shape=tuple(compactshape))\n broadcastx = compactx.broadcast_to(shape)\n dropouty = mx.gluon.nn.Dropout(rate=ratio, axes=axes)(broadcastx)\n for axis in axes:\n target = get_slice(dropouty, axis, 0).asnumpy()\n for i in range(1, shape[axis]):\n assert(get_slice(dropouty, axis, i).asnumpy() == target).all()\n\n nshape = (10, 10, 10, 10)\n with mx.autograd.train_mode():\n check_dropout_axes(0.25, nshape, axes = (0,))\n check_dropout_axes(0.25, nshape, axes = (1,))\n check_dropout_axes(0.25, nshape, axes = (2,))\n check_dropout_axes(0.25, nshape, axes = (3,))\n check_dropout_axes(0.25, nshape, axes = (0, 1))\n check_dropout_axes(0.25, nshape, axes = (0, 2))\n check_dropout_axes(0.25, nshape, axes = (0, 3))\n check_dropout_axes(0.25, nshape, axes = (1, 2))\n check_dropout_axes(0.25, nshape, axes = (1, 3))\n check_dropout_axes(0.25, nshape, axes = (2, 3))\n check_dropout_axes(0.25, nshape, axes = (0, 1, 2))\n check_dropout_axes(0.25, nshape, axes = (0, 2, 3))\n check_dropout_axes(0.25, nshape, axes = (1, 2, 3))\n\n@with_seed()\ndef test_req():\n data = mx.nd.random.uniform(shape=(1,3,224,224))\n label = mx.nd.random.uniform(shape=(1))\n label[:] = 1\n loss = gluon.loss.SoftmaxCrossEntropyLoss()\n\n net = nn.HybridSequential()\n net1 = nn.HybridSequential()\n net1.add(nn.Dense(4))\n net2 = nn.HybridSequential()\n net2.add(nn.Dense(3))\n net2.add(nn.Dense(2))\n net.add(net1)\n net.add(net2)\n net.initialize()\n\n net.hybridize()\n\n for v in net.collect_params().values():\n v.grad_req = 'add'\n\n net.collect_params().zero_grad()\n with mx.autograd.record():\n pred = net(data)\n l = loss(pred, label)\n l.backward()\n grad = net[0][0].weight.grad().mean().asnumpy()\n # run twice to check req = add\n pred = net(data)\n l = loss(pred, label)\n l.backward()\n\n grad_double = net[0][0].weight.grad().mean().asnumpy()\n assert_almost_equal(grad * 2, grad_double)\n\n\n@with_seed()\ndef test_save_load():\n net = mx.gluon.model_zoo.vision.get_resnet(1, 18, pretrained=True)\n net.save_parameters('test_save_load.params')\n\n net = mx.gluon.model_zoo.vision.get_resnet(1, 18)\n net.output = mx.gluon.nn.Dense(1000)\n\n net.load_parameters('test_save_load.params')\n\n class Network(gluon.Block):\n def __init__(self, **kwargs):\n super(Network, self).__init__(**kwargs)\n with self.name_scope():\n self.encoders = gluon.nn.Sequential()\n with self.encoders.name_scope():\n for _ in range(2):\n lstm = mx.gluon.rnn.LSTM(200, 1, bidirectional=True)\n self.encoders.add(lstm)\n\n def forward(self, x):\n for i in range(2):\n x = self.encoders[i](x)\n return x\n net = Network()\n net.initialize(mx.init.Xavier(), ctx=mx.cpu())\n net.hybridize()\n x = np.random.rand(32, 10, 10)\n x = mx.nd.array(x).as_in_context(mx.cpu())\n net(x)\n net.save_parameters('tmp.params')\n net2 = Network()\n net2.load_parameters('tmp.params')\n\n@with_seed()\ndef test_symbol_block_save_load():\n class Net(gluon.HybridBlock):\n def __init__(self):\n super(Net, self).__init__()\n with self.name_scope():\n backbone = gluon.model_zoo.vision.resnet18_v1()\n data = mx.sym.var('data')\n featnames = ['stage1_activation0', 'stage2_activation0', 'stage3_activation0']\n out_names = ['_'.join([backbone.name, featname, 'output']) for featname in featnames]\n internals = backbone(data).get_internals()\n outs = [internals[out_name] for out_name in out_names]\n self.backbone = gluon.SymbolBlock(outs, data, params=backbone.collect_params())\n self.body = nn.Conv2D(3, 1)\n\n def hybrid_forward(self, F, x):\n x = self.body(x)\n return self.backbone(x)\n\n net1 = Net()\n net1.initialize(mx.init.Normal())\n net1.hybridize()\n net1(mx.nd.random.normal(shape=(1, 3, 32, 32)))\n net1.save_parameters('./test_symbol_block_save_load.params')\n\n net2 = Net()\n net2.load_parameters('./test_symbol_block_save_load.params', ctx=mx.cpu())\n\n\n@with_seed()\ndef test_hybrid_multi_context():\n net = mx.gluon.model_zoo.vision.get_resnet(1, 18)\n net.initialize(ctx=[mx.cpu(0), mx.cpu(1)])\n net.hybridize()\n net(mx.nd.zeros((1, 3, 32, 32), ctx=mx.cpu(0))).asnumpy()\n\n@with_seed()\ndef test_zero_grad():\n data = mx.nd.random.uniform(shape=(3,3))\n net = nn.Embedding(3, 4, sparse_grad=True, prefix='test_zero_grad_')\n net.initialize()\n with mx.autograd.record():\n l = net(data)\n l.backward()\n net.collect_params().zero_grad()\n grad = net.collect_params()['test_zero_grad_weight'].grad()\n assert_almost_equal(grad.asnumpy(), grad.asnumpy() * 0)\n\ndef check_hybrid_static_memory(**kwargs):\n x = mx.nd.random.uniform(shape=(2, 3, 32, 32))\n x.attach_grad()\n\n net1 = gluon.model_zoo.vision.get_resnet(\n 1, 18, pretrained=True, prefix='net_', ctx=mx.context.current_context())\n net2 = gluon.model_zoo.vision.get_resnet(\n 1, 18, pretrained=True, prefix='net_', ctx=mx.context.current_context())\n net2.hybridize(**kwargs)\n net1(x)\n net2(x)\n\n def test(net, x):\n with mx.autograd.record():\n y = net(x) + net(x)\n y.backward()\n\n grads = {k: v.grad() for k, v in net.collect_params().items() if v.grad_req != 'null'}\n\n return y, grads\n\n y1, grads1 = test(net1, x)\n y2, grads2 = test(net2, x)\n\n assert_almost_equal(y1.asnumpy(), y2.asnumpy(), rtol=1e-3, atol=1e-5)\n for key in grads1:\n assert_almost_equal(grads1[key].asnumpy(), grads2[key].asnumpy(), rtol=1e-3, atol=1e-5)\n\n@with_seed()\ndef test_hybrid_static_memory():\n check_hybrid_static_memory()\n check_hybrid_static_memory(static_alloc=True)\n check_hybrid_static_memory(static_alloc=True, static_shape=True)\n\ndef check_hybrid_static_memory_switching(**kwargs):\n net = gluon.model_zoo.vision.get_resnet(\n 1, 18, pretrained=True, ctx=mx.context.current_context())\n net.hybridize(**kwargs)\n\n x = mx.nd.random.uniform(shape=(4, 3, 32, 32))\n net(x)\n with mx.autograd.record():\n y = net(x)\n y.backward()\n x = mx.nd.random.uniform(shape=(2, 3, 32, 32))\n net(x)\n with mx.autograd.record():\n y = net(x)\n y.backward()\n mx.nd.waitall()\n\n@with_seed()\ndef test_hybrid_static_memory_switching():\n check_hybrid_static_memory_switching()\n check_hybrid_static_memory_switching(static_alloc=True)\n check_hybrid_static_memory_switching(static_alloc=True, static_shape=True)\n\n@with_seed()\ndef test_hook():\n global hook_call_count\n hook_call_count = 0\n global pre_hook_call_count\n pre_hook_call_count = 0\n\n def call_hook(block, x, y):\n global hook_call_count\n hook_call_count += 1\n\n def call_pre_hook(block, x):\n global pre_hook_call_count\n pre_hook_call_count += 1\n\n block = nn.Dense(10)\n block.initialize()\n handle = block.register_forward_hook(call_hook)\n pre_handle = block.register_forward_pre_hook(call_pre_hook)\n block(mx.nd.ones((3, 5)))\n\n assert hook_call_count == 1\n assert pre_hook_call_count == 1\n\n handle.detach()\n block(mx.nd.ones((3, 5)))\n\n assert hook_call_count == 1\n assert pre_hook_call_count == 2\n\n pre_handle.detach()\n block(mx.nd.ones((3, 5)))\n assert hook_call_count == 1\n assert pre_hook_call_count == 2\n\n\n@with_seed()\ndef test_apply():\n global called_blocks\n called_blocks = []\n\n def record_name(block):\n global called_blocks\n called_blocks.append(block.name)\n\n block = nn.HybridSequential(prefix='test_')\n with block.name_scope():\n block.add(nn.Dense(10))\n block.add(nn.Dropout(0.5))\n block.apply(record_name)\n\n assert called_blocks == ['test_dense0', 'test_dropout0', 'test']\n\n\n@with_seed()\n@assert_raises_cudnn_not_satisfied(min_version='5.1.10')\ndef test_summary():\n net = gluon.model_zoo.vision.resnet50_v1()\n net.initialize()\n net.summary(mx.nd.ones((32, 3, 224, 224)))\n\n net2 = nn.Sequential()\n with net2.name_scope():\n net2.add(nn.Embedding(40, 30))\n net2.add(gluon.rnn.LSTM(30))\n net2.add(nn.Dense(40, flatten=False, params=net2[0].params))\n net2.initialize()\n net2.summary(mx.nd.ones((80, 32)))\n\n net3 = gluon.rnn.LSTM(30)\n net3.initialize()\n begin_state = net3.begin_state(32)\n net3.summary(mx.nd.ones((80, 32, 5)), begin_state)\n\n net.hybridize()\n assert_raises(AssertionError, net.summary, mx.nd.ones((32, 3, 224, 224)))\n\n\n@with_seed()\ndef test_legacy_save_params():\n net = gluon.nn.HybridSequential(prefix='')\n with net.name_scope():\n net.add(gluon.nn.Conv2D(10, (3, 3)))\n net.add(gluon.nn.Dense(50))\n net.initialize()\n net(mx.nd.ones((1,1,50,50)))\n a = net(mx.sym.var('data'))\n a.save('test.json')\n net.save_params('test.params')\n model = gluon.nn.SymbolBlock(outputs=mx.sym.load_json(open('test.json', 'r').read()),\n inputs=mx.sym.var('data'))\n model.load_params('test.params', ctx=mx.cpu())\n\n\n@with_seed()\ndef test_sparse_hybrid_block_grad():\n class Embedding(mx.gluon.HybridBlock):\n def __init__(self, num_tokens, embedding_size):\n super(Embedding, self).__init__()\n self.num_tokens = num_tokens\n\n with self.name_scope():\n self.embedding = mx.gluon.nn.Embedding(\n num_tokens, embedding_size, sparse_grad=True)\n\n def hybrid_forward(self, F, words):\n emb = self.embedding(words)\n return emb + F.ones_like(emb)\n\n embedding = Embedding(20, 3)\n embedding.initialize()\n embedding.hybridize()\n\n with mx.autograd.record():\n emb0 = embedding(mx.nd.arange(10)).sum()\n emb1 = embedding(mx.nd.arange(10)).sum()\n loss = emb0 + emb1\n loss.backward()\n grad = embedding.embedding.weight.grad().asnumpy()\n assert (grad[:10] == 2).all()\n assert (grad[10:] == 0).all()\n\n@with_seed()\ndef test_sparse_hybrid_block():\n class Linear(mx.gluon.HybridBlock):\n def __init__(self, units):\n super(Linear, self).__init__()\n with self.name_scope():\n self.w = self.params.get('w', shape=(units, units))\n\n def hybrid_forward(self, F, x, w):\n return F.dot(x, w)\n\n class SparseBlock(mx.gluon.HybridBlock):\n def __init__(self, units):\n super(SparseBlock, self).__init__()\n with self.name_scope():\n self.net = Linear(units)\n\n def hybrid_forward(self, F, x):\n return self.net(x) * x\n\n block = SparseBlock(2)\n block.initialize()\n block.hybridize()\n x = mx.nd.ones((2,2)).tostype('csr')\n with mx.autograd.record():\n z = block(x) + block(x)\n z.backward()\n assert (block.net.w.grad().asnumpy() == 4).all()\n\ndef test_hybrid_static_memory_recording():\n net = gluon.model_zoo.vision.get_resnet(\n 1, 18, pretrained=True, ctx=mx.context.current_context())\n net.hybridize(static_alloc=True)\n\n x = mx.nd.random.uniform(shape=(1, 3, 32, 32))\n with mx.autograd.record(True):\n net(x)\n net(x)\n\n\ndef test_share_inputs_outputs():\n class TestIOBackward(gluon.HybridBlock):\n def __init__(self, prefix=None, params=None):\n super(TestIOBackward, self).__init__(prefix=prefix, params=params)\n\n def hybrid_forward(self, F, in1, in2):\n return in1 + in2\n\n class TestIOForward(gluon.HybridBlock):\n def __init__(self, prefix=None, params=None):\n super(TestIOForward, self).__init__(prefix=prefix, params=params)\n\n def hybrid_forward(self, F, in1):\n return in1\n\n d1 = mx.nd.arange(10)\n d2 = mx.nd.arange(10)\n\n params=[{'inline_limit':0},\n {'inline_limit':0, 'static_alloc':True},\n {'inline_limit':0, 'static_alloc':True, 'static_shape':True}]\n # Test the case that inputs and outputs of a forward graph share NDArrays.\n for param in params:\n t = TestIOForward()\n t.hybridize(**param)\n for i in range(5):\n d1.attach_grad()\n out_grad = mx.nd.random.uniform(shape=(10))\n res = t(d1)\n assert_almost_equal(res.asnumpy(), d1.asnumpy())\n\n param = deepcopy(params[2])\n param['param_indices'] = (1)\n param['data_indices'] = (0)\n params.append(param)\n # Test the case that inputs and outputs of a backward graph share NDArrays.\n for param in params:\n t = TestIOBackward()\n t.hybridize(**param)\n for i in range(5):\n d1.attach_grad()\n d2.attach_grad()\n out_grad = mx.nd.random.uniform(shape=(10))\n with mx.autograd.record():\n res = t(d1, d2)\n res.backward(out_grad=out_grad)\n assert_almost_equal(out_grad.asnumpy(), d1.grad.asnumpy())\n assert_almost_equal(out_grad.asnumpy(), d2.grad.asnumpy())\n\n\ndef test_grad_graph_change():\n class Model(mx.gluon.HybridBlock):\n def hybrid_forward(self, F, array, index):\n row = array.take(index)\n return row, index\n array = mx.nd.arange(3)\n index = mx.nd.array([2])\n array.attach_grad()\n model = Model()\n model.hybridize(inline_limit=0)\n with mx.autograd.record(train_mode=True):\n row, _ = model(array, index)\n row.backward()\n\n\ndef check_layer_forward_withinput(net, x):\n x_hybrid = x.copy()\n x.attach_grad()\n x_hybrid.attach_grad()\n net.collect_params().initialize()\n with mx.autograd.record():\n out1 = net(x)\n out1.backward()\n net.hybridize()\n with mx.autograd.record():\n out2 = net(x_hybrid)\n out2.backward()\n mx.test_utils.assert_almost_equal(x.grad.asnumpy(), x_hybrid.grad.asnumpy(), rtol=1e-5, atol=1e-6)\n mx.test_utils.assert_almost_equal(out1.asnumpy(), out2.asnumpy(), rtol=1e-5, atol=1e-6)\n\n@with_seed()\ndef test_conv2d_16c():\n chn_list = [16, 256]\n kernel_list = [1, 3]\n kernel_list.append(224)\n batch_size = 4\n class Net(gluon.HybridBlock):\n def __init__(self,\n chn_num,\n kernel,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.conv0 = gluon.nn.Conv2D(chn_num, (kernel, kernel))\n\n def hybrid_forward(self, F, x):\n out = self.conv0(x)\n return out\n\n x = mx.nd.random.uniform(-1.0, 1.0, shape=(batch_size, 3, 224, 224))\n for i in range(len(chn_list)):\n for j in range(len(kernel_list)):\n net = Net(chn_list[i], kernel_list[j])\n check_layer_forward_withinput(net, x)\n\n@with_seed()\ndef test_group_conv2d_16c():\n grp_list = [16]\n input_size_list = np.random.randint(low=3, high=65, size=10).tolist()\n kernel_list = [1, 3]\n batch_size = 4\n class Net(gluon.HybridBlock):\n def __init__(self,\n chn_num,\n kernel,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.conv0 = gluon.nn.Conv2D(chn_num, (1, 1))\n self.conv1 = gluon.nn.Conv2D(chn_num, (kernel, kernel), groups=chn_num)\n\n def hybrid_forward(self, F, x):\n y = self.conv0(x)\n out = self.conv1(y)\n return out\n\n for i in range(len(input_size_list)):\n x = mx.nd.random.uniform(-1.0, 1.0, shape=(batch_size, 3, input_size_list[i], input_size_list[i]))\n for j in range(len(grp_list)):\n for k in range(len(kernel_list)):\n net = Net(grp_list[j], kernel_list[k])\n check_layer_forward_withinput(net, x)\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_deconv2d_16c():\n in_chn_list = [1024, 512, 256, 128, 64, 32, 16]\n out_chn_list = [512, 256, 128, 64, 32, 16, 3]\n kernel_list = [1, 3, 5, 7]\n in_shape = [4, 8, 16, 32, 64, 224]\n batch_size = 4\n class Net(gluon.HybridBlock):\n def __init__(self, chn_num, kernel, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.deconv0 = gluon.nn.Conv2DTranspose(chn_num, (kernel, kernel))\n\n def hybrid_forward(self, F, x):\n out = self.deconv0(x)\n return out\n for i in range(len(in_shape)):\n x = mx.nd.random.uniform(-1.0, 1.0, shape=(batch_size, in_chn_list[i], in_shape[i], in_shape[i]))\n for j in range(len(kernel_list)):\n net = Net(out_chn_list[i], kernel_list[j])\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_batchnorm_16c():\n chn_list = [16, 1024]\n shape = np.random.randint(low=1, high=300, size=10)\n shape_list = []\n for i in range(len(shape)):\n shape_list.append((shape[i], shape[i]))\n batch_size = 4\n class Net(gluon.HybridBlock):\n def __init__(self,\n chn_num,\n kernel,\n axis,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.conv0 = gluon.nn.Conv2D(chn_num, (kernel, kernel))\n self.bn0 = gluon.nn.BatchNorm(axis=axis)\n\n def hybrid_forward(self, F, x):\n conv = self.conv0(x)\n out = self.bn0(conv)\n return out\n\n for i in range(len(chn_list)):\n for j in range(len(shape_list)):\n shape = (batch_size, ) + (3,) + shape_list[j]\n x = mx.nd.random.uniform(-1.0, 1.0, shape=shape)\n net = Net(chn_list[i], 1, 1)\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\ndef test_concat():\n chn_list = [16, 64]\n shapes = [1, 3, 5]\n input_num = np.random.randint(low=2, high=11)\n shape_list = []\n for i in range(len(shapes)):\n shape_list.append((shapes[i], shapes[i]))\n batch_size = 4\n class Net(gluon.HybridBlock):\n def __init__(self,\n check_dim,\n input_num,\n chn_num,\n kernel,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n from mxnet.gluon.contrib.nn import HybridConcurrent\n self.concat = HybridConcurrent(axis=check_dim)\n for i in range(input_num):\n self.concat.add(gluon.nn.Conv2D(chn_num, (kernel, kernel)))\n\n def hybrid_forward(self, F, x):\n return self.concat(x)\n\n for s in range(len(shape_list)):\n shape = (batch_size,) + (3,) + shape_list[i]\n x = mx.nd.random.uniform(-1.0, 1.0, shape=shape)\n for i in range(len(chn_list)):\n for axis in range(4):\n net = Net(axis, input_num, chn_list[i], 1)\n check_layer_forward_withinput(net, x)\n\n@with_seed()\ndef test_reshape_conv():\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.conv0 = nn.Conv2D(64, (3, 3))\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape((0, 0, 128, 32))\n out = self.conv0(x_reshape)\n return out\n x = mx.nd.random.uniform(shape=(4, 3, 64, 64))\n net = Net()\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_reshape_conv_reshape_conv():\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.conv0 = nn.Conv2D(64, (3, 3))\n self.conv1 = nn.Conv2D(128, (3, 3))\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape((0, 0, 128, 32))\n y = self.conv0(x_reshape)\n \"spatial shape of y is (62, 62)\"\n y_reshape = y.reshape((0, 0, 124, 31))\n out = self.conv1(y_reshape)\n return out\n x = mx.nd.random.uniform(shape=(4, 3, 64, 64))\n net = Net()\n check_layer_forward_withinput(net, x)\n\n@with_seed()\ndef test_slice_conv():\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.conv0 = nn.Conv2D(16, (3, 3))\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=(0, 2, 0, 0), end=(4, 5, 32, 32))\n out = self.conv0(x_slice)\n return out\n x = mx.nd.random.uniform(shape=(8, 6, 32, 32))\n net = Net()\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\ndef test_slice_conv_slice_conv():\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.conv0 = nn.Conv2D(32, (3, 3))\n self.conv1 = nn.Conv2D(16, (1, 1))\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=(0, 0, 0, 0), end=(4, 16, 16, 16))\n y = self.conv0(x_slice)\n \"shape of y is (4, 32, 14, 14)\"\n y_slice = y.slice(begin=(0, 0, 0, 0), end=(4, 16, 3, 3))\n out = self.conv1(y_slice)\n return out\n x = mx.nd.random.uniform(shape=(4, 32, 32, 32))\n net = Net()\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_slice_conv_reshape_conv():\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.conv0 = nn.Conv2D(64, (3, 3))\n self.conv1 = nn.Conv2D(128, (3, 3))\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=(0, 0, 1, 1), end=(4, 16, 33, 33))\n y = self.conv0(x_slice)\n \"shape of y is (4, 64, 30, 30)\"\n y_reshape = y.reshape((0, 0, 60, 15))\n out = self.conv1(y_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(4, 32, 64, 64))\n net = Net()\n check_layer_forward_withinput(net, x)\n\n@with_seed()\ndef test_reshape_conv_slice_conv():\n \"\"\"\n This test will test gluon Conv2d computation with ndarray reshape and slice\n \"\"\"\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.conv0 = nn.Conv2D(16, (3, 3))\n self.conv1 = nn.Conv2D(32, (3, 3))\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape((0, 0, 64, 16))\n y = self.conv0(x_reshape)\n \"shape of y is (4, 16, 62, 14)\"\n y_slice = y.slice(begin=(0, 0, 0, 0), end=(2, 16, 14, 14))\n out = self.conv1(y_slice)\n return out\n x = mx.nd.random.uniform(shape=(4, 3, 32, 32))\n net = Net()\n check_layer_forward_withinput(net, x)\n\n@with_seed()\ndef test_reshape_dense():\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n channel0 = np.random.randint(1, 17)\n self.dense0 = nn.Dense(channel0)\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape((8, 64, 128, -1))\n out = self.dense0(x_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(4, 32, 64, 64))\n net = Net()\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\ndef test_slice_dense():\n class Net(gluon.HybridBlock):\n def __init__(self, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n channel0 = np.random.randint(1, 17)\n self.dense0 = nn.Dense(channel0)\n self.slice = slice\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=tuple(self.slice[0]),\n end=tuple(self.slice[1]))\n out = self.dense0(x_slice)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 32, 64, 64))\n slice = [[0, 16, 0, 0], [4, 32, 32, 32]]\n net = Net(slice)\n check_layer_forward_withinput(net, x)\n\n@with_seed()\ndef test_slice_dense_slice_dense():\n class Net(gluon.HybridBlock):\n def __init__(self, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n channel0 = 32\n channel1 = np.random.randint(1, 17)\n self.dense0 = nn.Dense(channel0)\n self.dense1 = nn.Dense(channel1)\n self.slice = slice\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=tuple(self.slice[0]), end=tuple(self.slice[1]))\n y = self.dense0(x_slice)\n y_slice = y.slice(begin=(1, 0), end=(3, 10))\n out = self.dense1(y_slice)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 32, 64, 64))\n slice = [[0, 16, 0, 0], [4, 32, 32, 32]]\n net = Net(slice)\n check_layer_forward_withinput(net, x)\n\n@with_seed()\ndef test_reshape_dense_reshape_dense():\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n channel0 = np.random.randint(1, 17)\n channel1 = np.random.randint(1, 33)\n self.dense0 = nn.Dense(channel0)\n self.dense1 = nn.Dense(channel1)\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape((4, 16, 128, 32))\n y = self.dense0(x_reshape)\n y_reshape = y.reshape((1, -1))\n out = self.dense1(y_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(4, 16, 64, 64))\n net = Net()\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\ndef test_slice_dense_reshape_dense():\n class Net(gluon.HybridBlock):\n def __init__(self, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n channel0 = np.random.randint(1, 17)\n channel1 = np.random.randint(1, 17)\n self.dense0 = nn.Dense(channel0)\n self.dense1 = nn.Dense(channel1)\n self.slice = slice\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=tuple(self.slice[0]), end=tuple(self.slice[1]))\n y = self.dense0(x_slice)\n y_reshape = y.reshape((1, -1))\n out = self.dense1(y_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 32, 64, 64))\n slice = [[0, 16, 0, 0], [4, 32, 32, 32]]\n net = Net(slice)\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\ndef test_reshape_dense_slice_dense():\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n channel0 = 64\n channel1 = np.random.randint(1, 17)\n self.dense0 = nn.Dense(channel0)\n self.dense1 = nn.Dense(channel1)\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape((4, 16, 128, 32))\n y = self.dense0(x_reshape)\n y_slice = y.slice(begin=(1, 32), end=(3, 64))\n out = self.dense1(y_slice)\n return out\n\n x = mx.nd.random.uniform(shape=(4, 16, 64, 64))\n net = Net()\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_reshape_batchnorm():\n class Net(gluon.HybridBlock):\n def __init__(self, shape, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.conv0 = nn.Conv2D(96, (1, 1))\n self.bn0 = nn.BatchNorm()\n self.reshape = shape\n\n def hybrid_forward(self, F, x):\n x_in = self.conv0(x)\n x_reshape = x_in.reshape(self.reshape)\n out = self.bn0(x_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(4, 32, 64, 64))\n shape = (4, 64, 64, -1)\n net = Net(shape)\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\ndef test_slice_batchnorm():\n class Net(gluon.HybridBlock):\n def __init__(self, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.conv0 = nn.Conv2D(128, (1, 1))\n self.bn0 = nn.BatchNorm()\n self.slice = slice\n\n def hybrid_forward(self, F, x):\n x_in = self.conv0(x)\n x_slice = x_in.slice(begin=tuple(self.slice[0]),\n end=tuple(self.slice[1]))\n out = self.bn0(x_slice)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 128, 256, 256))\n slice = [[0, 0, 0, 0], [4, 32, 32, 32]]\n net = Net(slice)\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_slice_batchnorm_slice_batchnorm():\n class Net(gluon.HybridBlock):\n def __init__(self, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.conv0 = nn.Conv2D(128, (1, 1))\n self.bn0 = nn.BatchNorm()\n self.bn1 = nn.BatchNorm()\n self.slice = slice\n\n def hybrid_forward(self, F, x):\n x_in = self.conv0(x)\n x_slice = x_in.slice(begin=tuple(self.slice[0][0]), end=tuple(self.slice[0][1]))\n y = self.bn0(x_slice)\n y_slice = y.slice(begin=tuple(self.slice[1][0]), end=tuple(self.slice[1][1]))\n out = self.bn1(y_slice)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 128, 256, 256))\n slice = [[[0, 0, 0, 0], [4, 32, 32, 32]], [[0, 0, 0, 0], [2, 64, 16, 16]]]\n net = Net(slice)\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_reshape_batchnorm_reshape_batchnorm():\n class Net(gluon.HybridBlock):\n def __init__(self, shape, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.conv0 = nn.Conv2D(128, (1, 1))\n self.bn0 = nn.BatchNorm()\n self.bn1 = nn.BatchNorm()\n self.reshape = shape\n\n def hybrid_forward(self, F, x):\n x_in = self.conv0(x)\n x_reshape = x_in.reshape(self.reshape[0])\n y = self.bn0(x_reshape)\n y_reshape = y.reshape(self.reshape[1])\n out = self.bn1(y_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(4, 32, 64, 64))\n shape = [(4, 64, 64, -1), (4, 128, -1, 32)]\n net = Net(shape)\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\ndef test_slice_batchnorm_reshape_batchnorm():\n class Net(gluon.HybridBlock):\n def __init__(self, shape, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.conv0 = nn.Conv2D(128, (1, 1))\n self.bn0 = nn.BatchNorm()\n self.bn1 = nn.BatchNorm()\n self.reshape = shape\n self.slice = slice\n\n def hybrid_forward(self, F, x):\n x_in = self.conv0(x)\n x_slice = x_in.slice(begin=tuple(self.slice[0]), end=tuple(self.slice[1]))\n y = self.bn0(x_slice)\n y_reshape = y.reshape(self.reshape)\n out = self.bn1(y_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 128, 256, 256))\n slice = [[0, 0, 0, 0], [4, 32, 32, 32]]\n shape = (1, 128, 64, -1)\n net = Net(shape, slice)\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_reshape_batchnorm_slice_batchnorm():\n class Net(gluon.HybridBlock):\n def __init__(self, shape, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.conv0 = nn.Conv2D(128, (1, 1))\n self.bn0 = nn.BatchNorm()\n self.bn1 = nn.BatchNorm()\n self.reshape = shape\n self.slice = slice\n\n def hybrid_forward(self, F, x):\n x_in = self.conv0(x)\n x_reshape = x_in.reshape(self.reshape)\n y = self.bn0(x_reshape)\n y_slice = y.slice(begin=tuple(self.slice[0]), end=tuple(self.slice[1]))\n out = self.bn1(y_slice)\n return out\n\n x = mx.nd.random.uniform(shape=(4, 32, 64, 64))\n slice = [[0, 0, 0, 0], [2, 64, 32, 32]]\n shape = (4, 64, 64, -1)\n net = Net(shape, slice)\n check_layer_forward_withinput(net, x)\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_reshape_pooling2d():\n max_pooling = nn.MaxPool2D(strides=(2, 3), padding=(1, 1))\n avg_pooling = nn.AvgPool2D(strides=(2, 2), padding=(1, 1))\n global_maxpooling = nn.GlobalMaxPool2D()\n global_avgpooling = nn.GlobalAvgPool2D()\n pooling_layers = [max_pooling, avg_pooling, global_maxpooling, global_avgpooling]\n class Net(gluon.HybridBlock):\n def __init__(self,\n shape,\n pooling_layer,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.reshape = shape\n self.pool0 = pooling_layer\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape)\n out = self.pool0(x_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(4, 32, 32, 32))\n shape = (4, 64, 64, -1)\n for i in range(len(pooling_layers)):\n net = Net(shape, pooling_layers[i])\n check_layer_forward_withinput(net, x)\n\n@with_seed()\ndef test_slice_pooling2d():\n # transpose shape to bring feature dimension 'c' from 2nd position to last\n def transpose(shape):\n return (shape[0],) + shape[2:] + (shape[1],)\n\n for layout in ['NCHW', 'NHWC']:\n max_pooling = nn.MaxPool2D(strides=(2, 3), padding=(1, 1), layout=layout)\n avg_pooling = nn.AvgPool2D(strides=(2, 2), padding=(1, 1), layout=layout)\n global_maxpooling = nn.GlobalMaxPool2D(layout=layout)\n global_avgpooling = nn.GlobalAvgPool2D(layout=layout)\n pooling_layers = [max_pooling, avg_pooling, global_maxpooling, global_avgpooling]\n class Net(gluon.HybridBlock):\n def __init__(self,\n slice,\n pooling_layer,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.slice = slice\n self.pool0 = pooling_layer\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0], end=self.slice[1])\n out = self.pool0(x_slice)\n return out\n\n xshape = (16, 128, 256, 256)\n slice_shape = (4, 16, 32, 64)\n if layout == 'NHWC':\n xshape = transpose(xshape)\n slice_shape = transpose(slice_shape)\n x = mx.nd.random.uniform(shape=xshape)\n slice = [(0, 0, 0, 0), slice_shape]\n for i in range(len(pooling_layers)):\n net = Net(slice, pooling_layers[i])\n check_layer_forward_withinput(net, x)\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_reshape_pooling2d_reshape_pooling2d():\n max_pooling = nn.MaxPool2D(strides=(2, 2), padding=(1, 1))\n avg_pooling = nn.AvgPool2D(strides=(2, 2), padding=(1, 1))\n global_maxpooling = nn.GlobalMaxPool2D()\n global_avgpooling = nn.GlobalAvgPool2D()\n pooling_layers = [max_pooling, avg_pooling, global_maxpooling, global_avgpooling]\n class Net(gluon.HybridBlock):\n def __init__(self,\n shape,\n pooling_layer1,\n pooling_layer2,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.reshape = shape\n self.pool0 = pooling_layer1\n self.pool1 = pooling_layer2\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape[0])\n y = self.pool0(x_reshape)\n y_reshape = y.reshape(self.reshape[1])\n out = self.pool1(y_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 128, 256, 256))\n shape = [(128, 256, 64, -1), (128, 256, 11, -1)]\n for i in range(len(pooling_layers)):\n for j in range(len(pooling_layers)):\n if isinstance(pooling_layers[i], (nn.GlobalMaxPool2D, nn.GlobalAvgPool2D)):\n shape[1] = (256, 128, 1, 1)\n net = Net(shape, pooling_layers[i], pooling_layers[j])\n check_layer_forward_withinput(net, x)\n\n@with_seed()\ndef test_slice_pooling2d_slice_pooling2d():\n max_pooling = nn.MaxPool2D(strides=(2, 3), padding=(1, 1))\n avg_pooling = nn.AvgPool2D(strides=(2, 2), padding=(1, 1))\n global_maxpooling = nn.GlobalMaxPool2D()\n global_avgpooling = nn.GlobalAvgPool2D()\n pooling_layers = [max_pooling, avg_pooling, global_maxpooling, global_avgpooling]\n class Net(gluon.HybridBlock):\n def __init__(self,\n slice,\n pooling_layer1,\n pooling_layer2,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.slice = slice\n self.pool0 = pooling_layer1\n self.pool1 = pooling_layer2\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0][0], end=self.slice[0][1])\n y = self.pool0(x_slice)\n y_slice = y.slice(begin=self.slice[1][0], end=self.slice[1][1])\n out = self.pool1(y_slice)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 128, 256, 256))\n slice = [[(8, 0, 100, 50), (16, -1, -1, -1)], [(0, 64, 0, 50), (2, -1, -1, -1)]]\n for i in range(len(pooling_layers)):\n for j in range(len(pooling_layers)):\n if isinstance(pooling_layers[i], (nn.GlobalMaxPool2D, nn.GlobalAvgPool2D)):\n slice[1] = [(0, 64, 0, 0), (2, -1, 1, 1)]\n net = Net(slice, pooling_layers[i], pooling_layers[j])\n check_layer_forward_withinput(net, x)\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_slice_pooling2d_reshape_pooling2d():\n max_pooling = nn.MaxPool2D(strides=(2, 3), padding=(1, 1))\n avg_pooling = nn.AvgPool2D(strides=(2, 2), padding=(1, 1))\n global_maxpooling = nn.GlobalMaxPool2D()\n global_avgpooling = nn.GlobalAvgPool2D()\n pooling_layers = [max_pooling, avg_pooling, global_maxpooling, global_avgpooling]\n class Net(gluon.HybridBlock):\n def __init__(self,\n shape,\n slice,\n pooling_layer1,\n pooling_layer2,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.reshape = shape\n self.slice = slice\n self.pool0 = pooling_layer1\n self.pool1 = pooling_layer2\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0], end=self.slice[1])\n y = self.pool0(x_slice)\n y_reshape = y.reshape(self.reshape)\n out = self.pool1(y_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 128, 256, 256))\n slice = [(8, 0, 100, 50), (16, 128, 256, 256)]\n shape = (32, -1, 0, 0)\n for i in range(len(pooling_layers)):\n for j in range(len(pooling_layers)):\n net = Net(shape, slice, pooling_layers[i], pooling_layers[j])\n check_layer_forward_withinput(net, x)\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_reshape_pooling2d_slice_pooling2d():\n max_pooling = nn.MaxPool2D(strides=(2, 3), padding=(1, 1))\n avg_pooling = nn.AvgPool2D(strides=(2, 2), padding=(1, 1))\n global_maxpooling = nn.GlobalMaxPool2D()\n global_avgpooling = nn.GlobalAvgPool2D()\n pooling_layers = [max_pooling, avg_pooling, global_maxpooling, global_avgpooling]\n class Net(gluon.HybridBlock):\n def __init__(self,\n shape,\n slice,\n pooling_layer1,\n pooling_layer2,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.reshape = shape\n self.slice = slice\n self.pool0 = pooling_layer1\n self.pool1 = pooling_layer2\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape)\n y = self.pool0(x_reshape)\n y_slice = y.slice(begin=self.slice[0], end=self.slice[1])\n out = self.pool1(y_slice)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 128, 256, 256))\n shape = (0, 512, 64, -1)\n slice = [(8, 256, 10, 20), (-1, -1, -1, 70)]\n for i in range(len(pooling_layers)):\n for j in range(len(pooling_layers)):\n if isinstance(pooling_layers[i], (nn.GlobalMaxPool2D, nn.GlobalAvgPool2D)):\n slice = [(8, 256, 0, 0), (-1, -1, 1, 1)]\n net = Net(shape, slice, pooling_layers[i], pooling_layers[j])\n check_layer_forward_withinput(net, x)\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_reshape_deconv():\n class Net(gluon.HybridBlock):\n def __init__(self, shape, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.reshape = shape\n self.conv0 = nn.Conv2DTranspose(64, (3, 3))\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape)\n out = self.conv0(x_reshape)\n return out\n x = mx.nd.random.uniform(shape=(4, 16, 32, 32))\n shape = (4, 16, 64, -1)\n net = Net(shape)\n check_layer_forward_withinput(net, x)\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_slice_deconv():\n class Net(gluon.HybridBlock):\n def __init__(self, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.slice = slice\n self.conv0 = nn.Conv2DTranspose(64, (3, 3))\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0], end=self.slice[1])\n out = self.conv0(x_slice)\n return out\n x = mx.nd.random.uniform(shape=(8, 32, 64, 64))\n slice = [(0, 16, 0, 0), (4, 32, 32, 32)]\n net = Net(slice)\n check_layer_forward_withinput(net, x)\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_reshape_deconv_reshape_deconv():\n class Net(gluon.HybridBlock):\n def __init__(self, shape, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.reshape = shape\n self.conv0 = nn.Conv2DTranspose(32, (3, 3))\n self.conv1 = nn.Conv2DTranspose(64, (3, 3), strides=(2, 2))\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape[0])\n y = self.conv0(x_reshape)\n \"shape of y is (4, 32, 66, 18)\"\n y_reshape = y.reshape(self.reshape[1])\n out = self.conv1(y_reshape)\n return out\n x = mx.nd.random.uniform(shape=(4, 16, 32, 32))\n shape = [(4, 16, 64, -1), (4, 32, 33, -1)]\n net = Net(shape)\n check_layer_forward_withinput(net, x)\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_slice_deconv_slice_deconv():\n class Net(gluon.HybridBlock):\n def __init__(self, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.slice = slice\n self.conv0 = nn.Conv2DTranspose(32, (3, 3))\n self.conv1 = nn.Conv2DTranspose(64, (3, 3), strides=(2, 2))\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0][0], end=self.slice[0][1])\n y = self.conv0(x_slice)\n \"shape of y is (4, 32, 66, 18)\"\n y_slice = y.slice(begin=self.slice[1][0], end=self.slice[1][1])\n out = self.conv1(y_slice)\n return out\n x = mx.nd.random.uniform(shape=(8, 32, 64, 64))\n slice = [[(0, 0, 0, 0), (4, 16, 32, 32)], [(0, 0, 0, 0), (2, 16, 16, 16)]]\n net = Net(slice)\n check_layer_forward_withinput(net, x)\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_reshape_deconv_slice_deconv():\n class Net(gluon.HybridBlock):\n def __init__(self, shape, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.reshape = shape\n self.slice = slice\n self.conv0 = nn.Conv2DTranspose(32, (3, 3))\n self.conv1 = nn.Conv2DTranspose(64, (3, 3), strides=(2, 2))\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape)\n y = self.conv0(x_reshape)\n \"shape of y is (4, 32, 66, 18)\"\n y_slice = y.slice(begin=self.slice[0], end=self.slice[1])\n out = self.conv1(y_slice)\n return out\n x = mx.nd.random.uniform(shape=(4, 16, 32, 32))\n shape = (4, 16, 64, -1)\n slice = [(0, 0, 0, 0), (2, 16, 16, 16)]\n net = Net(shape, slice)\n check_layer_forward_withinput(net, x)\n\n@with_seed()\n@unittest.skip('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_slice_deconv_reshape_deconv():\n class Net(gluon.HybridBlock):\n def __init__(self, shape, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.reshape = shape\n self.slice = slice\n self.conv0 = nn.Conv2DTranspose(32, (3, 3))\n self.conv1 = nn.Conv2DTranspose(96, (3, 3), strides=(2, 2))\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0], end=self.slice[1])\n y = self.conv0(x_slice)\n \"shape of y is (4, 32, 34, 34)\"\n y_reshape = y.reshape(self.reshape)\n out = self.conv1(y_reshape)\n return out\n x = mx.nd.random.uniform(shape=(8, 32, 64, 64))\n shape = (4, 64, 34, -1)\n slice = [(4, 0, 0, 0), (8, 16, 32, 32)]\n net = Net(shape, slice)\n check_layer_forward_withinput(net, x)\n\n@with_seed()\ndef test_reshape_activation():\n class Net(gluon.HybridBlock):\n def __init__(self, act, shape, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.reshape = shape\n self.act = nn.Activation(act)\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape)\n out = self.act(x_reshape)\n return out\n acts = [\"relu\", \"sigmoid\", \"tanh\", \"softrelu\", \"softsign\"]\n for act in acts:\n x = mx.nd.random.uniform(-1, 1, shape=(4, 16, 32, 32))\n shape = (4, 32, 32, -1)\n net = Net(act, shape)\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\ndef test_slice_activation():\n class Net(gluon.HybridBlock):\n def __init__(self, act, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.slice = slice\n self.act = nn.Activation(act)\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0], end=self.slice[1])\n out = self.act(x_slice)\n return out\n\n acts = [\"relu\", \"sigmoid\", \"tanh\", \"softrelu\", \"softsign\"]\n for act in acts:\n x = mx.nd.random.uniform(-1, 1, shape=(8, 32, 64, 64))\n slice = [(0, 16, 32, 32), (4, 32, 64, 64)]\n net = Net(act, slice)\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\ndef test_reshape_activation_reshape_activation():\n class Net(gluon.HybridBlock):\n def __init__(self, act0, act1, shape, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.reshape = shape\n self.act0 = nn.Activation(act0)\n self.act1 = nn.Activation(act1)\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape[0])\n y = self.act0(x_reshape)\n y_reshape = y.reshape(self.reshape[1])\n out = self.act1(y_reshape)\n return out\n acts = [\"relu\", \"sigmoid\", \"tanh\", \"softrelu\", \"softsign\"]\n for idx0, act0 in enumerate(acts):\n for idx1, act1 in enumerate(acts):\n if idx1 == idx0:\n continue\n x = mx.nd.random.uniform(-1, 1, shape=(4, 16, 32, 32))\n shape = [(4, 32, 32, -1), (4, 32, 16, -1)]\n net = Net(act0, act1, shape)\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\ndef test_slice_activation_slice_activation():\n class Net(gluon.HybridBlock):\n def __init__(self, act0, act1, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.slice = slice\n self.act0 = nn.Activation(act0)\n self.act1 = nn.Activation(act1)\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0][0], end=self.slice[0][1])\n y = self.act0(x_slice)\n y_slice = y.slice(begin=self.slice[1][0], end=self.slice[1][1])\n out = self.act1(y_slice)\n return out\n acts = [\"relu\", \"sigmoid\", \"tanh\", \"softrelu\", \"softsign\"]\n for idx0, act0 in enumerate(acts):\n for idx1, act1 in enumerate(acts):\n if idx1 == idx0:\n continue\n x = mx.nd.random.uniform(-1, 1, shape=(8, 32, 64, 64))\n slice = [[(0, 16, 32, 32), (4, 32, 64, 64)], [(2, 0, 16, 16), (4, 16, 32, 32)]]\n net = Net(act0, act1, slice)\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\ndef test_reshape_activation_slice_activation():\n class Net(gluon.HybridBlock):\n def __init__(self, act0, act1, shape, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.reshape = shape\n self.slice = slice\n self.act0 = nn.Activation(act0)\n self.act1 = nn.Activation(act1)\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape)\n y = self.act0(x_reshape)\n y_slice = y.slice(begin=self.slice[0], end=self.slice[1])\n out = self.act1(y_slice)\n return out\n acts = [\"relu\", \"sigmoid\", \"tanh\", \"softrelu\", \"softsign\"]\n for idx0, act0 in enumerate(acts):\n for idx1, act1 in enumerate(acts):\n if idx1 == idx0:\n continue\n x = mx.nd.random.uniform(-1, 1, shape=(4, 16, 32, 32))\n shape = (4, 32, 32, -1)\n slice = [(0, 0, 0, 0), (2, 16, 16, 16)]\n net = Net(act0, act1, shape, slice)\n check_layer_forward_withinput(net, x)\n\n\n@with_seed()\ndef test_slice_activation_reshape_activation():\n class Net(gluon.HybridBlock):\n def __init__(self, act0, act1, shape, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n with self.name_scope():\n self.reshape = shape\n self.slice = slice\n self.act0 = nn.Activation(act0)\n self.act1 = nn.Activation(act1)\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0], end=self.slice[1])\n y = self.act0(x_slice)\n y_reshape = y.reshape(self.reshape)\n out = self.act1(y_reshape)\n return out\n acts = [\"relu\", \"sigmoid\", \"tanh\", \"softrelu\", \"softsign\"]\n for idx0, act0 in enumerate(acts):\n for idx1, act1 in enumerate(acts):\n if idx1 == idx0:\n continue\n x = mx.nd.random.uniform(-1, 1, shape=(8, 32, 64, 64))\n slice = [(0, 16, 32, 32), (4, 32, 64, 64)]\n shape = (4, 32, 32, -1)\n net = Net(act0, act1, shape, slice)\n check_layer_forward_withinput(net, x)\n\n@with_seed()\ndef test_np_shape_parameters():\n class Foo(gluon.Block):\n def __init__(self, **kwargs):\n super(Foo, self).__init__(**kwargs)\n self.dense = gluon.nn.Dense(16)\n def forward(self, x):\n return self.dense(x)\n\n with mx.np_shape(True):\n z = mx.nd.zeros((2,2016))\n print(z.shape)\n foo = Foo()\n foo.initialize()\n print(foo(z).shape)\n\nif __name__ == '__main__':\n import nose\n nose.runmodule()\n"
] |
[
[
"numpy.asarray",
"numpy.dtype",
"numpy.ones",
"numpy.random.rand",
"numpy.random.randint"
]
] |
alxgrin/kaggle
|
[
"e460e00490ae3e047b0d8d8f78b680966bc3e8b6"
] |
[
"_dlcourse-ai/assignments/assignment2/model.py"
] |
[
"import numpy as np\n\nfrom layers import (\n FullyConnectedLayer,\n ReLULayer,\n softmax_with_cross_entropy,\n l2_regularization,\n)\n\n\nclass Param:\n \"\"\"\n Trainable parameter of the model\n Captures both parameter value and the gradient\n \"\"\"\n\n def __init__(self, value):\n self.value = value\n self.grad = np.zeros_like(value)\n\n\nclass TwoLayerNet:\n \"\"\"\n Neural network with two fully connected layers\n see: https://usmanr149.github.io/urmlblog/cs231n%20assignments/2020/03/16/two-layer-NN.html\n .. https://github.com/AlexanderPolyakov/dlcourse_ai/blob/master/assignments/assignment2/model.py\n \"\"\"\n\n def __init__(self, n_input, n_output, hidden_layer_size, reg):\n \"\"\"\n Initializes the neural network\n\n W1: First layer weights; has shape (D, H)\n b1: First layer biases; has shape (H,)\n W2: Second layer weights; has shape (H, C)\n b2: Second layer biases; has shape (C,)\n\n Arguments:\n n_input, int - dimension of the model input\n n_output, int - number of classes to predict\n hidden_layer_size, int - number of neurons in the hidden layer\n reg, float - L2 regularization strength\n \"\"\"\n self.n_input = n_input\n self.n_output = n_output\n self.hidden_layer_size = hidden_layer_size\n self.reg = reg\n\n # TODO Create necessary layers\n self.fc_1 = FullyConnectedLayer(n_input, hidden_layer_size)\n self.relu_1 = ReLULayer()\n self.fc_2 = FullyConnectedLayer(hidden_layer_size, n_output)\n\n def compute_loss_and_gradients(self, X, y):\n \"\"\"\n Computes total loss and updates parameter gradients\n on a batch of training examples\n\n Arguments:\n X, np array (batch_size, input_features) - input data\n y, np array of int (batch_size) - classes\n \"\"\"\n # Before running forward and backward pass through the model,\n # clear parameter gradients aggregated from the previous pass\n # TODO Set parameter gradient to zeros\n # Hint: using self.params() might be useful!\n for _, param in self.params().items():\n param.grad[:] = 0.0\n\n # TODO Compute loss and fill param gradients\n # by running forward and backward passes through the model\n res = X\n\n # forward\n res = self.fc_1.forward(res)\n res = self.relu_1.forward(res)\n res = self.fc_2.forward(res)\n\n # loss\n loss, grad = softmax_with_cross_entropy(res, y)\n\n # backward\n grad = self.fc_2.backward(grad)\n grad = self.relu_1.backward(grad)\n grad = self.fc_1.backward(grad)\n\n # After that, implement l2 regularization on all params\n # Hint: self.params() is useful again!\n for _, param in self.params().items():\n l2_loss, l2_grad = l2_regularization(param.value, self.reg)\n loss += l2_loss\n param.grad += l2_grad\n\n return loss\n\n def predict(self, X):\n \"\"\"\n Produces classifier predictions on the set\n\n Arguments:\n X, np array (test_samples, num_features)\n\n Returns:\n y_pred, np.array of int (test_samples)\n \"\"\"\n # TODO: Implement predict\n # Hint: some of the code of the compute_loss_and_gradients\n # can be reused\n pred = np.zeros(X.shape[0], np.int)\n\n res = self.fc_1.forward(X)\n res = self.relu_1.forward(res)\n res = self.fc_2.forward(res)\n\n # softmax\n probs = []\n for i in range(res.shape[0]):\n pred = res[i]\n ex = np.exp(pred - np.max(pred))\n probs.append(ex / np.sum(ex))\n pred = np.argmax(probs, axis=1)\n\n return pred\n\n def params(self):\n result = {}\n\n # TODO Implement aggregating all of the params\n\n result[\"fc_1.W\"] = self.fc_1.W\n result[\"fc_1.B\"] = self.fc_1.B\n result[\"fc_2.W\"] = self.fc_2.W\n result[\"fc_2.B\"] = self.fc_2.B\n\n return result\n"
] |
[
[
"numpy.max",
"numpy.argmax",
"numpy.zeros_like",
"numpy.zeros",
"numpy.sum"
]
] |
UoB-HPC/scaling-ml-approaches-to-amg
|
[
"40bb00f85f49f78a29ae262450967938f1b61b9a"
] |
[
"dataset/export_matrices.py"
] |
[
"from dolfin import *\nimport time\nfrom mshr import *\nimport numpy as np\nfrom tqdm.notebook import tqdm\nfrom scipy.sparse import csr_matrix, save_npz\nimport matplotlib.pyplot as plt\nimport json\nimport time\nimport dolfin\nimport petsc4py\nfrom pathlib import Path\nimport os\nimport logging\nimport sys\nimport re\nimport random\n\n\n\nlogger = logging.getLogger('GEN_MAT')\nlogger.setLevel(logging.INFO)\n\n\nstdout_logger = logging.getLogger('GEN_MAT_STDOUT')\nstdout_logger.setLevel(logging.INFO)\n\n\nhandler = logging.StreamHandler(sys.stdout)\nhandler.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\nstdout_logger.addHandler(handler)\n\nfileHandler = logging.FileHandler(\"{0}/{1}-{2}.log\".format(\".\", \"generate-matrices\", time.localtime()))\nfileHandler.setFormatter(formatter)\nlogger.addHandler(fileHandler)\n\n\nlogger.info(\"Installed FEniCS krylov precondtioners: {}\".format(krylov_solver_preconditioners()))\nlogger.info(\"Current FEniCS Linear Algebra backend: {}\".format(parameters.to_dict()['linear_algebra_backend']))\n\n\n# Print log messages only from the root process in parallel\nparameters[\"std_out_all_processes\"] = True;\nmpi_comm = MPI.comm_world\nmy_rank = MPI.rank(mpi_comm)\n\ndef walk_models_paper():\n for file in os.listdir(\"0_FIGURE_EXAMPLES\"):\n if file.startswith(\"figure\"):\n filename = \"0_FIGURE_EXAMPLES/{}/output.msh.xdmf\".format(file)\n if Path(filename).is_file():\n yield file, filename\n else:\n logger.warning(\"Looks like {} doesn't have a mesh file in the expected place\".format(file))\n\n\ndef walk_models_real(max_models=10001):\n count = 0\n all_files = [x for x in os.listdir(\"ftetwild_output_msh\") if x.endswith(\".xdmf\")]\n random.shuffle(all_files)\n for file in all_files:\n if file.endswith(\"xdmf\"):\n count += 1\n if count > max_models:\n break\n filename = \"ftetwild_output_msh/{}\".format(file)\n if Path(filename).is_file():\n file = file.split('.')[0]\n yield file, filename\n else:\n logger.warning(\"Looks like {} doesn't have a mesh file in the expected place\".format(file))\n \n \ndef load_mesh( filename) -> Mesh:\n mesh = Mesh()\n f = XDMFFile(mpi_comm, filename)\n f.read(mesh)\n return mesh\n\ndef matrix_shape(m):\n return as_backend_type(m).mat().size\n \ndef mkdir_if_not_exist(dirname):\n Path(dirname).mkdir(parents=True, exist_ok=True)\n\n\ndef assemble_matrices(mesh):\n # Define function spaces (P2-P1)\n \"P tetrahedron 1\"\n\n V = VectorFunctionSpace(mesh, \"P\", 2)\n Q = FunctionSpace(mesh, \"P\", 1)\n\n # Define trial and test functions\n u = TrialFunction(V)\n p = TrialFunction(Q)\n v = TestFunction(V)\n q = TestFunction(Q)\n\n # Set parameter values\n dt = 0.01\n T = 0.06\n nu = 0.01\n\n # Define time-dependent pressure boundary condition\n p_in = Expression(\"sin(3.0*t)\", t=0.0, degree=2)\n\n # Define boundary conditions\n noslip = DirichletBC(V, (0, 0, 0),\n \"on_boundary\")\n inflow = DirichletBC(Q, p_in, \"x[0] < 0.1 - DOLFIN_EPS\")\n outflow = DirichletBC(Q, 0, \"x[0] > {} - DOLFIN_EPS\".format(mesh.hmax()))\n bcu = [noslip]\n bcp = [inflow, outflow]\n\n # Create functions\n u0 = Function(V)\n u1 = Function(V)\n p1 = Function(Q)\n\n set_log_level(LogLevel.DEBUG)\n\n vertex_values = u0.compute_vertex_values(mesh)\n logger.info(\"Number of DoF: {}\".format(len(vertex_values)))\n dof = len(vertex_values)\n\n\n # Define coefficients\n k = Constant(dt)\n f = Constant((0, 0, 0))\n\n # Tentative velocity step\n F1 = (1/k)*inner(u - u0, v)*dx + inner(grad(u0)*u0, v)*dx + nu*inner(grad(u), grad(v))*dx - inner(f, v)*dx\n a1 = lhs(F1)\n L1 = rhs(F1)\n\n # Pressure update\n a2 = inner(grad(p), grad(q))*dx\n L2 = -(1/k)*div(u1)*q*dx\n\n # Velocity update\n a3 = inner(u, v)*dx\n L3 = inner(u1, v)*dx - k*inner(grad(p1), v)*dx\n\n # Assemble matrices\n A1 = assemble(a1)\n A2 = assemble(a2)\n A3 = assemble(a3)\n\n # Use amg preconditioner if available\n prec = \"amg\" if has_krylov_solver_preconditioner(\"amg\") else \"default\"\n\n # Use nonzero guesses - essential for CG with non-symmetric BC\n parameters['krylov_solver']['nonzero_initial_guess'] = True\n\n logger.info(\"A1: {}\".format(matrix_shape(A1)))\n logger.info(\"A2: {}\".format(matrix_shape(A2)))\n logger.info(\"A3: {}\".format(matrix_shape(A3)))\n\n # Time-stepping\n t = dt\n max_num_timesteps = 10\n num_timesteps = 0\n while num_timesteps < max_num_timesteps:\n num_timesteps += 1\n # Update pressure boundary condition\n p_in.t = t\n\n # Compute tentative velocity step\n begin(\"Computing tentative velocity\")\n b1 = assemble(L1)\n [bc.apply(A1, b1) for bc in bcu]\n solve(A1, u1.vector(), b1, \"gmres\", \"hypre_amg\")\n end()\n\n # Pressure correction\n begin(\"Computing pressure correction\")\n b2 = assemble(L2)\n [bc.apply(A2, b2) for bc in bcp]\n [bc.apply(p1.vector()) for bc in bcp]\n solve(A2, p1.vector(), b2, \"gmres\", \"hypre_amg\")\n end()\n\n # Velocity correction\n begin(\"Computing velocity correction\")\n b3 = assemble(L3)\n [bc.apply(A3, b3) for bc in bcu]\n solve(A3, u1.vector(), b3, \"gmres\", \"hypre_amg\")\n end()\n\n # Move to next time step\n u0.assign(u1)\n t += dt\n \n return A1, A2, A3, b1, b2, b3, dof\n \n\ndef save_matrix_plot(mat, name, filename):\n fig, ax = plt.subplots(1,1, figsize=(5,5))\n ax.spy(mat)\n ax.set_title(name)\n plt.savefig(filename, dpi=150)\n\n\ndef write_matrices(A1, A2, A3, b1, b2, b3, dof, problem):\n json_dict = {}\n json_dict['problem'] = problem\n json_dict['matrices'] = []\n\n for obj, name in [(A1, \"velocity_A\"), (b1, \"velocity_b\"), \n (A2, \"pressure_A\"), (b2, \"pressure_b\"),\n (A3, \"velocity_correction_A\"), (b3, \"velocity_correction_b\")]:\n if type(obj) is dolfin.cpp.la.Vector:\n v = as_backend_type(obj).vec()\n as_csr = csr_matrix(v.getArray())\n else:\n A_mat = as_backend_type(obj).mat()\n as_csr = csr_matrix(A_mat.getValuesCSR()[::-1], shape = A_mat.size)\n\n save_npz(\"output/{}/{}-{}.npz\".format(problem, problem, name), as_csr, compressed=True)\n this_json_dict={}\n this_json_dict['name'] = name\n this_json_dict['nnz'] = as_csr.nnz\n this_json_dict['shape'] = as_csr.shape\n this_json_dict['sparsity_percent'] = as_csr.nnz/(as_csr.shape[0]*as_csr.shape[1])*100\n json_dict['matrices'].append(this_json_dict)\n\n json_dict[\"degrees_of_freedom\"] = dof\n\n with open(\"output/{}/{}.json\".format(problem, problem), 'w') as outfile: \n json.dump(json_dict, outfile)\n\n\nif __name__==\"__main__\":\n mkdir_if_not_exist('output')\n for problem, mesh_filename in walk_models_real():\n logger.info(\"=======PROBLEM \" + problem)\n stdout_logger.info(\"=======PROBLEM \" + problem)\n mkdir_if_not_exist('output/{}'.format(problem))\n if Path(\"output/{}/{}.json\".format(problem, problem)).is_file():\n logger.info(\"Skipping {}, an output file already exists for it\".format(problem))\n else:\n try:\n mesh = load_mesh(mesh_filename)\n A1, A2, A3, b1, b2, b3, dof = assemble_matrices(mesh)\n write_matrices(A1, A2, A3, b1, b2, b3, dof, problem)\n except Exception as e:\n logger.error(\"Something went wrong processing {}\".format(problem), exc_info=e)\n\n"
] |
[
[
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig"
]
] |
aidenylmz/vbm655_car_price_prediction
|
[
"f577e9b0e7a46f4d16259af70b123f96c4bc9976"
] |
[
"sample/dataset.py"
] |
[
"import pandas as pd\nfrom datetime import datetime\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import ExtraTreesRegressor\nfrom helpers.extensions import sort_features\n\n\ndef load_transformed_car_data():\n '''\n It loads the car data from docs, prints some descriptions,\n drops car name and year (after calculating age from year) columns,\n converts categorical columns into indicators, and saves heatmap file.\n '''\n data = pd.read_csv(\n 'docs/car_data.csv')\n\n all_cols = data.columns\n numerical_cols = data._get_numeric_data().columns.to_list()\n categorical_cols = list(set(all_cols) - set(numerical_cols))\n\n (row_size, column_size) = data.shape\n print(f'Rows: {row_size}, Columns: {column_size}.')\n\n print(f'Numerical columns: {numerical_cols}\\n')\n print(f'Categorical columns: {categorical_cols}\\n')\n\n data.drop(['Car_Name'], inplace=True, axis=1)\n\n this_year = datetime.today().year\n\n data['Car_Age'] = this_year - data.Year\n data.drop(['Year'], inplace=True, axis=1)\n\n print('Before converting categorical column')\n print('---------------------------------------')\n print(data.head())\n print('---------------------------------------\\n')\n\n data = pd.get_dummies(data, drop_first=True)\n\n print('After converting categorical column')\n print('---------------------------------------')\n print(data.head())\n print('---------------------------------------')\n\n plt.figure(figsize=(18, 8))\n sns.heatmap(data.corr(), annot=True)\n plt.xticks(rotation=0, fontsize=8)\n plt.yticks(fontsize=8)\n plt.savefig('docs/correlation_heatmap.png')\n\n return data\n\n\ndef plot_feature_importance(x, y):\n\n model = ExtraTreesRegressor()\n model.fit(x, y)\n plt.figure(figsize=(18, 8))\n\n sorted_features = sort_features(\n model.feature_importances_, x.columns)\n\n sns.barplot(x=sorted_features, y=sorted(\n model.feature_importances_, reverse=True))\n plt.savefig('docs/feature_importance.png')\n"
] |
[
[
"matplotlib.pyplot.yticks",
"pandas.read_csv",
"matplotlib.pyplot.savefig",
"sklearn.ensemble.ExtraTreesRegressor",
"matplotlib.pyplot.xticks",
"pandas.get_dummies",
"matplotlib.pyplot.figure"
]
] |
hicala/pyro
|
[
"bc607f8cf817a8ee7cdebc83dfa51c233d5f13ae"
] |
[
"examples/contrib/forecast/bart.py"
] |
[
"# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nimport argparse\nimport logging\n\nimport numpy as np\nimport torch\n\nimport pyro\nimport pyro.distributions as dist\nfrom pyro.contrib.examples.bart import load_bart_od\nfrom pyro.contrib.forecast import ForecastingModel, backtest\nfrom pyro.ops.tensor_utils import periodic_cumsum, periodic_repeat\n\nlogging.getLogger(\"pyro\").setLevel(logging.DEBUG)\nlogging.getLogger(\"pyro\").handlers[0].setLevel(logging.DEBUG)\n\n\ndef preprocess(args):\n \"\"\"\n Extract a tensor of (arrivals,departures) to Embarcadero station.\n \"\"\"\n print(\"Loading data\")\n dataset = load_bart_od()\n\n # The full dataset has all station->station ridership counts for all of 50\n # train stations. In this simple example we will model only the aggretate\n # counts to and from a single station, Embarcadero.\n i = dataset[\"stations\"].index(\"EMBR\")\n arrivals = dataset[\"counts\"][:, :, i].sum(-1)\n departures = dataset[\"counts\"][:, i, :].sum(-1)\n data = torch.stack([arrivals, departures], dim=-1)\n\n # This simple example uses no covariates, so we will construct a\n # zero-element tensor of the correct length as empty covariates.\n covariates = torch.zeros(len(data), 0)\n\n return data, covariates\n\n\n# We define a model by subclassing the ForecastingModel class and implementing\n# a single .model() method.\nclass Model(ForecastingModel):\n # The .model() method inputs two tensors: a fake tensor zero_data that is\n # the same size and dtype as the real data (but of course the generative\n # model shouldn't depend on the value of the data it generates!), and a\n # tensor of covariates. Our simple model depends on no covariates, so we\n # simply pass in an empty tensor (see the preprocess() function above).\n def model(self, zero_data, covariates):\n period = 24 * 7\n duration, dim = zero_data.shape[-2:]\n assert dim == 2 # Data is bivariate: (arrivals, departures).\n\n # Sample global parameters.\n noise_scale = pyro.sample(\"noise_scale\",\n dist.LogNormal(torch.full((dim,), -3.), 1.).to_event(1))\n assert noise_scale.shape[-1:] == (dim,)\n trans_timescale = pyro.sample(\"trans_timescale\",\n dist.LogNormal(torch.zeros(dim), 1).to_event(1))\n assert trans_timescale.shape[-1:] == (dim,)\n\n trans_loc = pyro.sample(\"trans_loc\", dist.Cauchy(0, 1 / period))\n trans_loc = trans_loc.unsqueeze(-1).expand(trans_loc.shape + (dim,))\n assert trans_loc.shape[-1:] == (dim,)\n trans_scale = pyro.sample(\"trans_scale\",\n dist.LogNormal(torch.zeros(dim), 0.1).to_event(1))\n trans_corr = pyro.sample(\"trans_corr\",\n dist.LKJCorrCholesky(dim, torch.ones(())))\n trans_scale_tril = trans_scale.unsqueeze(-1) * trans_corr\n assert trans_scale_tril.shape[-2:] == (dim, dim)\n\n obs_scale = pyro.sample(\"obs_scale\",\n dist.LogNormal(torch.zeros(dim), 0.1).to_event(1))\n obs_corr = pyro.sample(\"obs_corr\",\n dist.LKJCorrCholesky(dim, torch.ones(())))\n obs_scale_tril = obs_scale.unsqueeze(-1) * obs_corr\n assert obs_scale_tril.shape[-2:] == (dim, dim)\n\n # Note the initial seasonality should be sampled in a plate with the\n # same dim as the time_plate, dim=-1. That way we can repeat the dim\n # below using periodic_repeat().\n with pyro.plate(\"season_plate\", period, dim=-1):\n season_init = pyro.sample(\"season_init\",\n dist.Normal(torch.zeros(dim), 1).to_event(1))\n assert season_init.shape[-2:] == (period, dim)\n\n # Sample independent noise at each time step.\n with self.time_plate:\n season_noise = pyro.sample(\"season_noise\",\n dist.Normal(0, noise_scale).to_event(1))\n assert season_noise.shape[-2:] == (duration, dim)\n\n # Construct a prediction. This prediction has an exactly repeated\n # seasonal part plus slow seasonal drift. We use two deterministic,\n # linear functions to transform our diagonal Normal noise to nontrivial\n # samples from a Gaussian process.\n prediction = (periodic_repeat(season_init, duration, dim=-2) +\n periodic_cumsum(season_noise, period, dim=-2))\n assert prediction.shape[-2:] == (duration, dim)\n\n # Construct a joint noise model. This model is a GaussianHMM, whose\n # .rsample() and .log_prob() methods are parallelized over time; this\n # this entire model is parallelized over time.\n init_dist = dist.Normal(torch.zeros(dim), 100).to_event(1)\n trans_mat = trans_timescale.neg().exp().diag_embed()\n trans_dist = dist.MultivariateNormal(trans_loc, scale_tril=trans_scale_tril)\n obs_mat = torch.eye(dim)\n obs_dist = dist.MultivariateNormal(torch.zeros(dim), scale_tril=obs_scale_tril)\n noise_model = dist.GaussianHMM(init_dist, trans_mat, trans_dist, obs_mat, obs_dist,\n duration=duration)\n assert noise_model.event_shape == (duration, dim)\n\n # The final statement registers our noise model and prediction.\n self.predict(noise_model, prediction)\n\n\ndef main(args):\n pyro.enable_validation(__debug__)\n data, covariates = preprocess(args)\n\n # We will model positive count data by log1p-transforming it into real\n # valued data. But since we want to evaluate back in the count domain, we\n # will also define a transform to apply during evaluation, transforming\n # from real back to count-valued data. Truth is mapped by the log1p()\n # inverse expm1(), but the prediction will be sampled from a Poisson\n # distribution.\n data = data.log1p()\n\n def transform(pred, truth):\n pred = torch.poisson(pred.clamp(min=1e-4).expm1())\n truth = truth.expm1()\n return pred, truth\n\n # The backtest() function automatically trains and evaluates our model on\n # different windows of data.\n forecaster_options = {\n \"num_steps\": args.num_steps,\n \"learning_rate\": args.learning_rate,\n \"log_every\": args.log_every,\n \"dct_gradients\": args.dct,\n }\n metrics = backtest(data, covariates, Model,\n train_window=args.train_window,\n test_window=args.test_window,\n stride=args.stride,\n num_samples=args.num_samples,\n forecaster_options=forecaster_options)\n\n for name in [\"mae\", \"rmse\", \"crps\"]:\n values = [m[name] for m in metrics]\n mean = np.mean(values)\n std = np.std(values)\n print(\"{} = {:0.3g} +- {:0.3g}\".format(name, mean, std))\n return metrics\n\n\nif __name__ == \"__main__\":\n assert pyro.__version__.startswith('1.5.0')\n parser = argparse.ArgumentParser(description=\"Bart Ridership Forecasting Example\")\n parser.add_argument(\"--train-window\", default=2160, type=int)\n parser.add_argument(\"--test-window\", default=336, type=int)\n parser.add_argument(\"--stride\", default=168, type=int)\n parser.add_argument(\"-n\", \"--num-steps\", default=501, type=int)\n parser.add_argument(\"-lr\", \"--learning-rate\", default=0.05, type=float)\n parser.add_argument(\"--dct\", action=\"store_true\")\n parser.add_argument(\"--num-samples\", default=100, type=int)\n parser.add_argument(\"--log-every\", default=50, type=int)\n parser.add_argument(\"--seed\", default=1234567890, type=int)\n args = parser.parse_args()\n main(args)\n"
] |
[
[
"torch.ones",
"torch.full",
"torch.zeros",
"torch.eye",
"numpy.std",
"numpy.mean",
"torch.stack"
]
] |
thepooons/pytorch-lightning
|
[
"a053d758d03558d2aa5a328b2f6befbc133a0ebc"
] |
[
"tests/trainer/optimization/test_parity_manual_optimization.py"
] |
[
"# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom collections import Callable\nfrom copy import deepcopy\nfrom typing import Optional\nfrom unittest.mock import patch\n\nimport numpy as np\nimport pytest\nimport torch\nfrom torch.optim import Optimizer\n\nfrom pytorch_lightning import seed_everything, Trainer\nfrom pytorch_lightning.core.optimizer import LightningOptimizer\nfrom tests.base.boring_model import BoringModel\nfrom tests.trainer.optimization.test_parity_automatic_optimization import (\n assert_model_equality,\n run_lightning_optimizer_equality,\n should_accumulate,\n)\n\n\"\"\"\nTODO:\nFor both Manual / manual optimization\n - Test dp, ddp, ddp2\n - Apex\n - Random accumulated_grad_batches (bug)\n - Multiple optimizers\n\"\"\"\n\n\nclass BaseParityManualOptimizationModel(BoringModel):\n\n def __init__(self, optimizer_cls, optimizer_is_mocked=False, accumulate_grad_batches=None):\n super().__init__()\n self.optimizer_cls = optimizer_cls\n self.losses = []\n self.grads = []\n self.on_before_zero_grad_count = 0\n self.optimizer_is_mocked = optimizer_is_mocked\n self.grad_checked = False\n self.accumulate_grad_batches = accumulate_grad_batches\n\n def on_before_zero_grad(self, optimizer):\n self.on_before_zero_grad_count += 1\n if self.layer.weight.grad is not None:\n self.grads.append(self.layer.weight.grad.clone())\n\n def configure_optimizers(self):\n optimizer = self.optimizer_cls(self.layer.parameters(), lr=0.1)\n assert isinstance(optimizer, Optimizer)\n return optimizer\n\n def training_step(self, batch, batch_idx):\n opt = self.optimizers()\n if not isinstance(opt, LightningOptimizer):\n opt = LightningOptimizer.to_lightning_optimizer(opt, self.trainer)\n output = self.layer(batch)\n loss = self.loss(batch, output)\n self.losses.append(loss.detach().item())\n self.manual_backward(loss, opt)\n opt.step()\n\n\nclass ManualOptimizationPurePytorchOptimizerModel(BaseParityManualOptimizationModel):\n\n def training_step(self, batch, batch_idx):\n optimizer = self.optimizers(use_pl_optimizer=False)\n output = self.layer(batch)\n loss = self.loss(batch, output)\n self.losses.append(loss.detach().item())\n loss /= float(self.accumulate_grad_batches)\n loss.backward()\n\n if should_accumulate(self.trainer, self.accumulate_grad_batches):\n return\n\n self.grad_checked = True\n assert torch.abs(self.layer.weight.grad).sum() > 0\n optimizer.step()\n\n self.on_before_zero_grad_count += 1\n optimizer.zero_grad()\n\n if not self.optimizer_is_mocked:\n assert torch.abs(self.layer.weight.grad).sum() == 0\n\n\nclass ManualOptimizationPurePytorchAMPOptimizerModel(BaseParityManualOptimizationModel):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.scaler = torch.cuda.amp.GradScaler()\n\n def training_step(self, batch, batch_idx):\n optimizer = self.optimizers(use_pl_optimizer=False)\n with torch.cuda.amp.autocast():\n output = self.layer(batch)\n loss = self.loss(batch, output)\n self.losses.append(loss.detach().item())\n loss /= float(self.accumulate_grad_batches)\n loss = self.scaler.scale(loss)\n loss.backward()\n\n if should_accumulate(self.trainer, self.accumulate_grad_batches):\n return\n\n self.scaler.unscale_(optimizer)\n self.grad_checked = True\n\n assert torch.abs(self.layer.weight.grad).sum() > 0\n self.scaler.step(optimizer)\n self.scaler.update()\n self.on_before_zero_grad_count += 1\n optimizer.zero_grad()\n\n if not self.optimizer_is_mocked:\n assert torch.abs(self.layer.weight.grad).sum() == 0\n\n\n@pytest.mark.parametrize([\"precision\", \"amp_backend\", \"gpus\"], [\n pytest.param(32, \"native\", 0),\n pytest.param(16, \"native\", 1, marks=pytest.mark.skipif(not torch.cuda.is_available(), reason='Requires GPU')),\n])\n@pytest.mark.parametrize('accumulate_grad_batches', [1, 7])\ndef test_lightning_optimizer_and_no_lightning_optimizer_equality(\n tmpdir,\n precision,\n amp_backend,\n gpus,\n accumulate_grad_batches):\n\n if accumulate_grad_batches > 1:\n accumulate_grad_batches = np.random.randint(1, accumulate_grad_batches)\n\n vanilla_model_cls = ManualOptimizationPurePytorchAMPOptimizerModel if precision == 16 \\\n else ManualOptimizationPurePytorchOptimizerModel\n\n run_lightning_optimizer_equality(\n BaseParityManualOptimizationModel,\n vanilla_model_cls,\n precision=precision,\n default_root_dir=tmpdir,\n max_epochs=1,\n limit_train_batches=5,\n accumulate_grad_batches=accumulate_grad_batches,\n amp_backend=amp_backend,\n gpus=gpus,\n automatic_optimization=False\n )\n\n\n@pytest.mark.parametrize([\"precision\", \"amp_backend\", \"gpus\"], [\n pytest.param(32, \"native\", 0),\n])\n@pytest.mark.parametrize('accumulate_grad_batches', [1])\ndef test_lightning_optimizer_and_no_lightning_optimizer_equality_check_optim_calls(\n tmpdir,\n precision,\n amp_backend,\n gpus,\n accumulate_grad_batches,\n):\n\n vanilla_model_cls = ManualOptimizationPurePytorchAMPOptimizerModel if precision == 16 \\\n else ManualOptimizationPurePytorchOptimizerModel\n\n with patch(\"torch.optim.SGD.step\") as mock_sgd_step, \\\n patch(\"torch.optim.Adam.step\") as mock_adam_step, \\\n patch(\"torch.optim.SGD.zero_grad\") as mock_sgd_zero_grad, \\\n patch(\"torch.optim.Adam.zero_grad\") as mock_adam_zero_grad:\n\n max_epochs = 2\n limit_train_batches = 10\n\n # Run equality test using Lightning Optimizer\n\n run_lightning_optimizer_equality(\n BaseParityManualOptimizationModel,\n vanilla_model_cls,\n default_root_dir=tmpdir,\n optimizer_is_mocked=True,\n accumulate_grad_batches=accumulate_grad_batches,\n max_epochs=max_epochs,\n limit_train_batches=limit_train_batches,\n amp_backend=amp_backend,\n precision=precision,\n gpus=gpus,\n automatic_optimization=False\n )\n\n expected_num_batches = max_epochs * limit_train_batches\n assert mock_sgd_step.call_count == (expected_num_batches // accumulate_grad_batches)\n assert mock_sgd_zero_grad.call_count == (expected_num_batches // accumulate_grad_batches)\n assert mock_sgd_step.call_count == mock_adam_step.call_count\n assert mock_sgd_zero_grad.call_count == mock_adam_zero_grad.call_count\n"
] |
[
[
"torch.abs",
"torch.cuda.amp.autocast",
"torch.cuda.amp.GradScaler",
"torch.cuda.is_available",
"numpy.random.randint"
]
] |
mathkann/understanding-random-forests
|
[
"d2c5e0174d1a778be37a495083d756b2829160ec"
] |
[
"scripts/ch7_bias_depth.py"
] |
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport brewer2mpl\n\nfrom itertools import product\nfrom functools import partial\nfrom demo import entropy\n\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom ID3 import RandomizedID3Classifier, RandomizedID3Ensemble\n\nimport brewer2mpl\ncmap = brewer2mpl.get_map('RdYlGn', 'diverging', 5).mpl_colors\n\n\ndef feature_importances(X, y, cls, n_trees=500):\n clf = cls(n_estimators=n_trees).fit(X, y)\n\n if isinstance(clf, RandomizedID3Ensemble):\n imp = np.sum(clf.feature_importances_, axis=1)\n\n else:\n imp = np.zeros(X.shape[1])\n\n for tree in clf.estimators_:\n imp += tree.tree_.compute_feature_importances(normalize=False)\n\n imp = imp / n_trees\n\n return imp\n\ndef generate_strobl_power(n_samples=120, relevance=0.2):\n X = np.array([v for v in product(range(2), range(4), range(10), range(20))]).astype(np.int32)\n X = np.hstack((np.random.rand(len(X), 1), X))\n\n y = np.zeros(len(X))\n mask = (X[:, 1] == 1)\n y[mask] = np.random.rand(mask.sum()) < 0.5-relevance\n y[~mask] = np.random.rand((~mask).sum()) < 0.5+relevance\n\n indices = np.random.permutation(X.shape[0])[:n_samples]\n return X[indices], y[indices].astype(np.int32)\n\n return X, y\n\n# Generate all importances\n#cls = partial(ExtraTreesClassifier, max_features=1, criterion=\"entropy\")\ncls = partial(RandomForestClassifier, max_features=5, criterion=\"entropy\")\n\nrelevances = [0.0, 0.1, 0.2, 0.3]\ndepths = range(1, 10)\n\n\nfor i, relevance in enumerate(relevances):\n imp_all = []\n\n for n in range(10):\n imp = []\n X, y = generate_strobl_power(relevance=relevance)\n\n for q in depths:\n c = partial(cls, max_depth=q)\n imp.append(feature_importances(X, y, cls=c))\n\n imp = np.array(imp)\n imp_all.append(imp)\n\n imp = np.mean(imp_all, axis=0)\n\n for q in range(imp.shape[0]):\n imp[q] /= np.sum(imp[q, :])\n\n plt.subplot(2, 2, i + 1)\n\n for j in range(X.shape[1]):\n plt.plot(depths, imp[:, j], \"o-\", label=\"$X_%d$\" % j, color=cmap[j])\n\n plt.ylim([0., 1.0])\n plt.title(\"Relevance = %.1f\" % relevance)\n\n if i == 0:\n plt.legend(loc=\"best\")\n\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.subplot",
"numpy.mean",
"numpy.random.permutation",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.zeros",
"numpy.sum"
]
] |
julietteBrt/CyberbattleSim
|
[
"37c9befb06f4d6fea733b358fb1e356e4b25bb10"
] |
[
"cyberbattle/simulation/generate_network.py"
] |
[
"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\n\"\"\" Generating random graphs\"\"\"\nfrom cyberbattle.simulation.model import Identifiers, NodeID, CredentialID, PortName, FirewallConfiguration, FirewallRule, RulePermission\nimport numpy as np\nimport networkx as nx\nfrom cyberbattle.simulation import model as m\nimport random\nfrom typing import List, Optional, Tuple, DefaultDict\n\nfrom collections import defaultdict\n\nENV_IDENTIFIERS = Identifiers(\n properties=[\n 'breach_node'\n ],\n ports=['SMB', 'HTTP', 'RDP'],\n local_vulnerabilities=[\n 'ScanWindowsCredentialManagerForRDP',\n 'ScanWindowsExplorerRecentFiles',\n 'ScanWindowsCredentialManagerForSMB'\n ],\n remote_vulnerabilities=[\n 'Traceroute'\n ]\n)\n\n\ndef generate_random_traffic_network(\n n_clients: int = 200,\n n_servers={\n \"SMB\": 1,\n \"HTTP\": 1,\n \"RDP\": 1,\n },\n seed: Optional[int] = 0,\n tolerance: np.float32 = np.float32(1e-3),\n alpha=np.array([(0.1, 0.3), (0.18, 0.09)], dtype=float),\n beta=np.array([(100, 10), (10, 100)], dtype=float),\n) -> nx.DiGraph:\n \"\"\"\n Randomly generate a directed multi-edge network graph representing\n fictitious SMB, HTTP, and RDP traffic.\n\n Arguments:\n n_clients: number of workstation nodes that can initiate sessions with server nodes\n n_servers: dictionary indicatin the numbers of each nodes listening to each protocol\n seed: seed for the psuedo-random number generator\n tolerance: absolute tolerance for bounding the edge probabilities in [tolerance, 1-tolerance]\n alpha: beta distribution parameters alpha such that E(edge prob) = alpha / beta\n beta: beta distribution parameters beta such that E(edge prob) = alpha / beta\n\n Returns:\n (nx.classes.multidigraph.MultiDiGraph): the randomly generated network from the hierarchical block model\n \"\"\"\n edges_labels = defaultdict(set) # set backed multidict\n\n for protocol in list(n_servers.keys()):\n sizes = [n_clients, n_servers[protocol]]\n # sample edge probabilities from a beta distribution\n np.random.seed(seed)\n probs: np.ndarray = np.random.beta(a=alpha, b=beta, size=(2, 2))\n # don't allow probs too close to zero or one\n probs = np.clip(probs, a_min=tolerance, a_max=np.float32(1.0 - tolerance))\n\n # scale by edge type\n if protocol == \"SMB\":\n probs = 3 * probs\n if protocol == \"RDP\":\n probs = 4 * probs\n\n # sample edges using block models given edge probabilities\n di_graph_for_protocol = nx.stochastic_block_model(\n sizes=sizes, p=probs, directed=True, seed=seed)\n\n for edge in di_graph_for_protocol.edges:\n edges_labels[edge].add(protocol)\n\n digraph = nx.DiGraph()\n for (u, v), port in list(edges_labels.items()):\n digraph.add_edge(u, v, protocol=port)\n return digraph\n\n\ndef cyberbattle_model_from_traffic_graph(\n traffic_graph: nx.DiGraph,\n cached_smb_password_probability=0.75,\n cached_rdp_password_probability=0.8,\n cached_accessed_network_shares_probability=0.6,\n cached_password_has_changed_probability=0.1,\n traceroute_discovery_probability=0.5,\n probability_two_nodes_use_same_password_to_access_given_resource=0.8\n) -> nx.DiGraph:\n \"\"\"Generate a random CyberBattle network model from a specified traffic (directed multi) graph.\n\n The input graph can for instance be generated with `generate_random_traffic_network`.\n Each edge of the input graph indicates that a communication took place\n between the two nodes with the protocol specified in the edge label.\n\n Returns a CyberBattle network with the same nodes and implanted vulnerabilities\n to be used to instantiate a CyverBattleSim gym.\n\n Arguments:\n\n cached_smb_password_probability, cached_rdp_password_probability:\n probability that a password used for authenticated traffic was cached by the OS for SMB and RDP\n cached_accessed_network_shares_probability:\n probability that a network share accessed by the system was cached by the OS\n cached_password_has_changed_probability:\n probability that a given password cached on a node has been rotated on the target node\n (typically low has people tend to change their password infrequently)\n probability_two_nodes_use_same_password_to_access_given_resource:\n as the variable name says\n traceroute_discovery_probability:\n probability that a target node of an SMB/RDP connection get exposed by a traceroute attack\n \"\"\"\n # convert node IDs to string\n graph = nx.relabel_nodes(traffic_graph, {i: str(i) for i in traffic_graph.nodes})\n\n password_counter: int = 0\n\n def generate_password() -> CredentialID:\n nonlocal password_counter\n password_counter = password_counter + 1\n return f'unique_pwd{password_counter}'\n\n def traffic_targets(source_node: NodeID, protocol: str) -> List[NodeID]:\n neighbors = [t for (s, t) in graph.edges()\n if s == source_node and protocol in graph.edges[(s, t)]['protocol']]\n return neighbors\n\n # Map (node, port name) -> assigned pwd\n assigned_passwords: DefaultDict[Tuple[NodeID, PortName],\n List[CredentialID]] = defaultdict(list)\n\n def assign_new_valid_password(node: NodeID, port: PortName) -> CredentialID:\n pwd = generate_password()\n assigned_passwords[node, port].append(pwd)\n return pwd\n\n def reuse_valid_password(node: NodeID, port: PortName) -> CredentialID:\n \"\"\"Reuse a password already assigned to that node an port, if none is already\n assigned create and assign a new valid password\"\"\"\n if (node, port) not in assigned_passwords:\n return assign_new_valid_password(node, port)\n\n # reuse any of the existing assigne valid password for that node/port\n return random.choice(assigned_passwords[node, port])\n\n def create_cached_credential(node: NodeID, port: PortName) -> CredentialID:\n if random.random() < cached_password_has_changed_probability:\n # generate a new invalid password\n return generate_password()\n else:\n if random.random() < probability_two_nodes_use_same_password_to_access_given_resource:\n return reuse_valid_password(node, port)\n else:\n return assign_new_valid_password(node, port)\n\n def add_leak_neighbors_vulnerability(\n node_id: m.NodeID,\n library: m.VulnerabilityLibrary = {}) -> m.VulnerabilityLibrary:\n \"\"\"Create random vulnerabilities\n that reveals immediate traffic neighbors from a given node\"\"\"\n\n rdp_neighbors = traffic_targets(node_id, 'RDP')\n\n if len(rdp_neighbors) > 0:\n library['ScanWindowsCredentialManagerForRDP'] = m.VulnerabilityInfo(\n description=\"Look for RDP credentials in the Windows Credential Manager\",\n type=m.VulnerabilityType.LOCAL,\n outcome=m.LeakedCredentials(credentials=[\n m.CachedCredential(node=target_node, port='RDP',\n credential=create_cached_credential(target_node, 'RDP'))\n for target_node in rdp_neighbors\n if random.random() < cached_rdp_password_probability\n ]),\n reward_string=\"Discovered creds in the Windows Credential Manager\",\n cost=2.0\n )\n\n smb_neighbors = traffic_targets(node_id, 'SMB')\n\n if len(smb_neighbors) > 0:\n library['ScanWindowsExplorerRecentFiles'] = m.VulnerabilityInfo(\n description=\"Look for network shares in the Windows Explorer Recent files\",\n type=m.VulnerabilityType.LOCAL,\n outcome=m.LeakedNodesId(\n [target_node\n for target_node in smb_neighbors\n if random.random() < cached_accessed_network_shares_probability\n ]\n ),\n reward_string=\"Windows Explorer Recent Files revealed network shares\",\n cost=1.0\n )\n\n library['ScanWindowsCredentialManagerForSMB'] = m.VulnerabilityInfo(\n description=\"Look for network credentials in the Windows Credential Manager\",\n type=m.VulnerabilityType.LOCAL,\n outcome=m.LeakedCredentials(credentials=[\n m.CachedCredential(node=target_node, port='SMB',\n credential=create_cached_credential(target_node, 'SMB'))\n for target_node in smb_neighbors\n if random.random() < cached_smb_password_probability\n ]),\n reward_string=\"Discovered SMB creds in the Windows Credential Manager\",\n cost=2.0\n )\n\n if len(smb_neighbors) > 0 and len(rdp_neighbors) > 0:\n library['Traceroute'] = m.VulnerabilityInfo(\n description=\"Attempt to discvover network nodes using Traceroute\",\n type=m.VulnerabilityType.REMOTE,\n outcome=m.LeakedNodesId(\n [target_node\n for target_node in smb_neighbors or rdp_neighbors\n if random.random() < traceroute_discovery_probability\n ]\n ),\n reward_string=\"Discovered new network nodes via traceroute\",\n cost=5.0\n )\n\n return library\n\n def create_vulnerabilities_from_traffic_data(node_id: m.NodeID):\n return add_leak_neighbors_vulnerability(node_id=node_id)\n\n firewall_conf = FirewallConfiguration(\n [FirewallRule(\"RDP\", RulePermission.ALLOW), FirewallRule(\"SMB\", RulePermission.ALLOW)],\n [FirewallRule(\"RDP\", RulePermission.ALLOW), FirewallRule(\"SMB\", RulePermission.ALLOW)])\n\n # Pick a random node as the agent entry node\n entry_node_index = random.randrange(len(graph.nodes))\n entry_node_id, entry_node_data = list(graph.nodes(data=True))[entry_node_index]\n graph.nodes[entry_node_id].clear()\n graph.nodes[entry_node_id].update(\n {'data': m.NodeInfo(services=[],\n value=0,\n properties=[\"breach_node\"],\n vulnerabilities=create_vulnerabilities_from_traffic_data(entry_node_id),\n agent_installed=True,\n firewall=firewall_conf,\n reimagable=False)})\n\n def create_node_data(node_id: m.NodeID):\n return m.NodeInfo(\n services=[m.ListeningService(name=port, allowedCredentials=assigned_passwords[(target_node, port)])\n for (target_node, port) in assigned_passwords.keys()\n if target_node == node_id\n ],\n value=random.randint(0, 100),\n vulnerabilities=create_vulnerabilities_from_traffic_data(node_id),\n agent_installed=False,\n firewall=firewall_conf\n )\n\n for node in list(graph.nodes):\n if node != entry_node_id:\n graph.nodes[node].clear()\n graph.nodes[node].update({'data': create_node_data(node)})\n\n return graph\n\n\ndef new_environment(n_servers_per_protocol: int):\n \"\"\"Create a new simulation environment based on\n a randomly generated network topology.\n\n NOTE: the probabilities and parameter values used\n here for the statistical generative model\n were arbirarily picked. We recommend exploring different values for those parameters.\n \"\"\"\n traffic = generate_random_traffic_network(seed=None,\n n_clients=50,\n n_servers={\n \"SMB\": n_servers_per_protocol,\n \"HTTP\": n_servers_per_protocol,\n \"RDP\": n_servers_per_protocol,\n },\n alpha=[(1, 1), (0.2, 0.5)],\n beta=[(1000, 10), (10, 100)])\n\n network = cyberbattle_model_from_traffic_graph(\n traffic,\n cached_rdp_password_probability=0.8,\n cached_smb_password_probability=0.7,\n cached_accessed_network_shares_probability=0.8,\n cached_password_has_changed_probability=0.01,\n probability_two_nodes_use_same_password_to_access_given_resource=0.9)\n return m.Environment(network=network,\n vulnerability_library=dict([]),\n identifiers=ENV_IDENTIFIERS)\n"
] |
[
[
"numpy.random.beta",
"numpy.array",
"numpy.random.seed",
"numpy.float32"
]
] |
AppleHolic/multiband_melgan
|
[
"e0864d0fc205c3bdf5e19c77753e105e29a2641b"
] |
[
"multiband_melgan/dataset.py"
] |
[
"import numpy as np\nimport librosa\nimport os\nfrom pytorch_sound.data.meta.ljspeech import LJSpeechMeta\nfrom torch.utils.data import Dataset, DataLoader\nfrom typing import Tuple\n\n\nclass AudioDataset(Dataset):\n\n def __init__(self, meta_frame, crop_length: int, seed: int = 1234):\n self.meta_frame = meta_frame\n self.column_name = 'audio_filename'\n self.crop_length = crop_length\n self.seed = seed\n np.random.seed(seed)\n\n def __getitem__(self, idx):\n # get selected file path\n file_path = self.meta_frame.iloc[idx][self.column_name]\n\n # load audio\n wav, _ = librosa.load(file_path, sr=None)\n # wav = librosa.effects.trim(wav)[0]\n\n # random crop\n if self.crop_length:\n rand_start = np.random.randint(0, (len(wav) - self.crop_length))\n cropped_wav = wav[rand_start:rand_start + self.crop_length]\n\n # crop on voiced part\n while np.abs(cropped_wav).max() < 0.05 and np.random.randint(5):\n rand = np.random.randint(0, max(len(wav) - 1 - self.crop_length, 1))\n cropped_wav = wav[rand:rand + self.crop_length]\n\n wav = cropped_wav\n\n # make mask\n wav_mask = np.ones_like(wav)\n\n return wav, wav_mask\n\n def __len__(self):\n return len(self.meta_frame)\n\n\ndef get_datasets(meta_dir: str, batch_size: int, num_workers: int, crop_length: int, random_seed: int\n ) -> Tuple[DataLoader, DataLoader]:\n assert os.path.isdir(meta_dir), '{} is not valid directory path!'\n\n train_file, valid_file = LJSpeechMeta.frame_file_names[1:]\n\n # load meta file\n train_meta = LJSpeechMeta(os.path.join(meta_dir, train_file))\n valid_meta = LJSpeechMeta(os.path.join(meta_dir, valid_file))\n\n # create dataset\n train_dataset = AudioDataset(train_meta, crop_length=crop_length, seed=random_seed)\n valid_dataset = AudioDataset(valid_meta, crop_length=crop_length, seed=random_seed)\n\n # create data loader\n train_loader = DataLoader(train_dataset, batch_size=batch_size, num_workers=num_workers, shuffle=True)\n valid_loader = DataLoader(valid_dataset, batch_size=batch_size, num_workers=num_workers)\n\n return train_loader, valid_loader\n"
] |
[
[
"numpy.ones_like",
"numpy.abs",
"numpy.random.seed",
"torch.utils.data.DataLoader",
"numpy.random.randint"
]
] |
nce3xin/spam
|
[
"908421d5cf2dd103e2a7044bf1c8586aaf5f2ada"
] |
[
"models/model_RNN_LSTM_GRU.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 29 15:07:58 2018\n\n@author: nce3xin\n\"\"\"\n\nimport torch\nimport torch.nn as nn\n\n#use_cuda = not hyperparams.no_cuda and torch.cuda.is_available()\n#device = torch.device(\"cuda\" if use_cuda else \"cpu\")\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nclass BaseModel(nn.Module):\n\n def __init__(self, inputDim, hiddenNum, outputDim, layerNum, cell):\n\n super(BaseModel, self).__init__()\n self.hiddenNum = hiddenNum\n self.inputDim = inputDim\n self.outputDim = outputDim\n self.layerNum = layerNum\n\n if cell == \"RNN\":\n self.cell = nn.RNN(input_size=self.inputDim, hidden_size=self.hiddenNum,\n num_layers=self.layerNum, dropout=0.0,\n nonlinearity=\"tanh\", batch_first=True,)\n if cell == \"LSTM\":\n self.cell = nn.LSTM(input_size=self.inputDim, hidden_size=self.hiddenNum,\n num_layers=self.layerNum, dropout=0.0,\n batch_first=True, )\n if cell == \"GRU\":\n self.cell = nn.GRU(input_size=self.inputDim, hidden_size=self.hiddenNum,\n num_layers=self.layerNum, dropout=0.0,\n batch_first=True, )\n print(self.cell)\n self.fc = nn.Linear(self.hiddenNum, self.outputDim)\n\n# standard RNN model\nclass RNNModel(BaseModel):\n\n def __init__(self, inputDim, hiddenNum, outputDim, layerNum, cell):\n\n super(RNNModel, self).__init__(inputDim, hiddenNum, outputDim, layerNum, cell)\n\n def forward(self, x, batchSize):\n h0 = torch.zeros(self.layerNum * 1, batchSize, self.hiddenNum).to(device)\n x=x.float()\n h0=h0.float()\n rnnOutput, hn = self.cell(x, h0) # rnnOutput 12,20,50 hn 1,20,50\n hn = hn.view(batchSize, self.hiddenNum).to(device)\n fcOutput = self.fc(hn)\n fcOutput=fcOutput.to(device)\n\n return fcOutput\n \n# LSTM model\nclass LSTMModel(BaseModel):\n\n def __init__(self, inputDim, hiddenNum, outputDim, layerNum, cell):\n super(LSTMModel, self).__init__(inputDim, hiddenNum, outputDim, layerNum, cell)\n\n # if batch_first is true, then the input and output tensors are provided as (batch,seq,feature)\n # else input of shape (seq_len, batch, input_size)\n # h_0,h_n of shape (num_layers*num_directions,batch,hidden_size)\n # c_0,c_n of shape (num_layers*num_directions,batch,hidden_size)\n def forward(self, x, batchSize):\n\n h0 = torch.zeros(self.layerNum * 1, batchSize, self.hiddenNum).to(device)\n c0 = torch.zeros(self.layerNum * 1, batchSize, self.hiddenNum).to(device)\n \n x=x.float()\n h0=h0.float()\n c0=c0.float()\n \n \n rnnOutput, hn = self.cell(x, (h0, c0)) # rnnOutput 12,20,50 hn 1,20,50\n hn = hn[0].view(batchSize, self.hiddenNum).to(device)\n fcOutput = self.fc(hn)\n\n return fcOutput\n \n# GRU model\nclass GRUModel(BaseModel):\n\n def __init__(self, inputDim, hiddenNum, outputDim, layerNum, cell):\n super(GRUModel, self).__init__(inputDim, hiddenNum, outputDim, layerNum, cell)\n\n # if batch_first is true, then the input and output tensors are provided as (batch,seq,feature)\n # else input of shape (seq_len, batch, input_size)\n # h_0,h_n of shape (num_layers*num_directions,batch,hidden_size)\n def forward(self, x, batchSize):\n\n h0 = torch.zeros(self.layerNum * 1, batchSize, self.hiddenNum).to(device)\n x=x.float()\n h0=h0.float()\n rnnOutput, hn = self.cell(x, h0) # rnnOutput 12,20,50 hn 1,20,50\n hn = hn.view(batchSize, self.hiddenNum).to(device)\n fcOutput = self.fc(hn)\n\n return fcOutput"
] |
[
[
"torch.nn.LSTM",
"torch.zeros",
"torch.nn.GRU",
"torch.nn.RNN",
"torch.nn.Linear",
"torch.cuda.is_available"
]
] |
taipahuchu/language-Identification-
|
[
"68660bc110d374f0d8802b942792b15f8782e647"
] |
[
"code/models.py"
] |
[
"import tensorflow as tf\nimport numpy as np\n\n\nclass BaseModel(object):\n \"\"\"Holds code shared between all the different model variants.\"\"\"\n\n def __init__(self, batch_size, max_sequence_len, out_vocab_size, c2v,\n dropout_keep_prob=0.0):\n self._batch_size = batch_size\n self._dropout_keep_prob = dropout_keep_prob\n self._out_vocab_size = out_vocab_size\n\n self.x = tf.placeholder(tf.int32, [batch_size, max_sequence_len],\n name='x')\n self.y = tf.placeholder(tf.float32, [batch_size, out_vocab_size],\n name='y')\n # The bidirectional rnn code requires seq_lens as int64\n self.seq_lens = tf.placeholder(tf.int64, [batch_size], name='seq_lens')\n self.example_weights = tf.placeholder(tf.float32, [batch_size],\n name='example_weights')\n\n embeddings = c2v.GetEmbeddings(self.x)\n self._inputs = [tf.squeeze(input_, [1]) for input_ in\n tf.split(1, max_sequence_len, embeddings)]\n\n # Need to prepare a mask to zero out the padding symbols.\n\n # Make a batch_size x max_sequence_len matrix where each\n # row contains the length repeated max_sequence_len times.\n lengths_transposed = tf.expand_dims(tf.to_int32(self.seq_lens), 1)\n lengths_tiled = tf.tile(lengths_transposed, [1, max_sequence_len])\n\n # Make a matrix where each row contains [0, 1, ..., max_sequence_len]\n r = tf.range(0, max_sequence_len, 1)\n range_row = tf.expand_dims(r, 0)\n range_tiled = tf.tile(range_row, [batch_size, 1])\n\n # Use the logical operations to create a mask\n indicator = tf.less(range_tiled, lengths_tiled)\n sz = [batch_size, max_sequence_len]\n self._mask = tf.select(indicator, tf.ones(sz), tf.zeros(sz))\n\n def _DoPredictions(self, in_size, mats, class_weights=None):\n \"\"\"Takes in an array of states and calculates predictions.\n\n Get the cross-entropy for each example in the vector self._xent.\n\n Args:\n in_size: size of the hidden state vectors\n mats: list of hidden state vectors\n \"\"\"\n pred_mat = tf.get_variable('pred_mat',\n [in_size, self._out_vocab_size])\n pred_bias = tf.get_variable('pred_bias', [self._out_vocab_size])\n\n # Make a prediction on every word.\n def GetWordPred(o_):\n logits = tf.nn.xw_plus_b(o_, pred_mat, pred_bias)\n return tf.nn.softmax(logits)\n\n self.preds_by_word = tf.pack([GetWordPred(o_) for o_ in mats])\n self.cs = self._mask / tf.reduce_sum(self._mask, 1, keep_dims=True)\n\n # The final prediction is the average of the predictions for each word\n # weighted by the individual confidence/utility scores.\n preds_weighted = tf.mul(tf.reshape(tf.transpose(self.cs), [-1, 1]),\n tf.reshape(self.preds_by_word,\n [-1, self._out_vocab_size]))\n preds_weighted_reshaped = tf.reshape(preds_weighted,\n self.preds_by_word.get_shape())\n self.probs = tf.reduce_sum(preds_weighted_reshaped, 0)\n self._xent = _SafeXEnt(self.y, self.probs, class_weights=class_weights)\n\n\nclass WordAvgModel(BaseModel): #formerly SimpleModel\n \"\"\"A bag of word /predictions/.\"\"\"\n\n def __init__(self, out_vocab_size=None,\n batch_size=10,\n model_params=None,\n c2v=None,\n max_sequence_len=None,\n dropout_keep_prob=None,\n weights=None):\n\n super(WordAvgModel, self).__init__(batch_size, max_sequence_len,\n out_vocab_size, c2v)\n\n super(WordAvgModel, self)._DoPredictions(c2v.embedding_dims,\n self._inputs)\n self.cost = tf.reduce_mean(self.example_weights * self._xent)\n\n\nclass WordSeqModel(BaseModel):\n \"\"\"A bag of word embeddings.\"\"\"\n def __init__(self, out_vocab_size=None,\n batch_size=10,\n model_params=None,\n c2v=None,\n max_sequence_len=None,\n dropout_keep_prob=None,\n weights=None):\n\n super(WordSeqModel, self).__init__(batch_size, max_sequence_len,\n out_vocab_size, c2v)\n in_size = self._inputs[0].get_shape()[1].value\n\n # Also, output confidence scores at every word.\n confidence_mat = tf.get_variable('confidence_mat', [in_size, 1])\n confidence_scores = tf.concat(1, [tf.matmul(o_, confidence_mat)\n for o_ in self._inputs])\n\n # dropout on confidence_scores\n random_tensor = (1.0 - self._dropout_keep_prob +\n tf.random_uniform(tf.shape(confidence_scores)))\n binary_tensor = -50.0 * tf.floor(random_tensor)\n\n csshape = confidence_scores.get_shape()\n self.cs = tf.nn.softmax(tf.constant(1.0, shape=csshape))\n\n # The final prediction is the average of the predictions for each word\n # weighted by the individual confidence/utility scores.\n\n wvs = tf.pack(self._inputs)\n wvs_weighted = tf.mul(tf.reshape(tf.transpose(self.cs), [-1, 1]),\n tf.reshape(wvs, [-1, in_size]))\n wvs_weighted_reshaped = tf.reshape(wvs_weighted, wvs.get_shape())\n wvsum = tf.reduce_sum(wvs_weighted_reshaped,0)\n\n pred_mat = tf.get_variable('pred_mat', [in_size, self._out_vocab_size])\n pred_bias = tf.get_variable('pred_bias', [self._out_vocab_size])\n\n # Make a prediction for each tweet.\n def GetWordPred(o_):\n logits = tf.nn.xw_plus_b(o_, pred_mat, pred_bias)\n return tf.nn.softmax(logits)\n\n preds = GetWordPred(wvsum)\n z = tf.tile(tf.reshape(tf.reduce_sum(preds,1),[-1,1]), [1, out_vocab_size])\n self.preds, self.z = preds, z\n self.probs = tf.div(preds, z) #normalize\n self.unweighted_xent = _SafeXEnt(self.y, self.probs)\n\n self._xent = _SafeXEnt(self.y, self.probs, class_weights=weights)\n\n self.cost = tf.reduce_mean(self.example_weights * self._xent)\n\n\nclass TweetSeqModel(BaseModel): #formerly SeqModel\n \"\"\"Single layer LSTM on top of the word embeddings.\n\n Lang id predictions are done on each word and then combined via\n a weighted average.\n \"\"\"\n\n def __init__(self, out_vocab_size=None,\n batch_size=10, model_params=None,\n c2v=None,\n max_sequence_len=None,\n dropout_keep_prob=None,\n weights=None):\n \"\"\"Initialize the TweetSeqModel\n\n Args:\n out_vocab_size: how many languages we are predicting\n batch_size: minibatch size\n model_params: dictionary of other model parameters\n c2v: char2vec class instance\n max_sequence_len: length of all the input sequences\n dropout_keep_prob: dropout probability indicator\n weights: class weights\n \"\"\"\n hidden_size = model_params['model_hidden_size']\n proj_size = model_params['model_proj_size'] # optional, can be None\n\n super(TweetSeqModel, self).__init__(batch_size, max_sequence_len,\n out_vocab_size, c2v,\n dropout_keep_prob)\n\n weights = tf.constant(weights, dtype=tf.float32, name='class_weights')\n\n def GetCell():\n \"\"\"Creates an LSTM cell with dropout.\"\"\"\n c = tf.nn.rnn_cell.LSTMCell(hidden_size,\n use_peepholes=model_params['peepholes'],\n num_proj=proj_size)\n if dropout_keep_prob is not None:\n c = tf.nn.rnn_cell.DropoutWrapper(c, input_keep_prob=dropout_keep_prob)\n return c\n\n # Create the bi-directional LSTM\n with tf.variable_scope('wordrnn'):\n with tf.variable_scope('fw'):\n cell_fw = GetCell()\n with tf.variable_scope('bw'):\n cell_bw = GetCell()\n\n rnnout, _, _ = tf.nn.bidirectional_rnn(cell_fw, cell_bw, self._inputs,\n dtype=tf.float32,\n sequence_length=self.seq_lens)\n if proj_size:\n out_size = 2 * proj_size\n else:\n out_size = 2 * hidden_size\n super(TweetSeqModel, self)._DoPredictions(out_size, rnnout, class_weights=weights)\n\n self.cost = tf.reduce_mean(self.example_weights * self._xent)\n\n\nclass CharSeqModel(object): #formerly TweetSeqModel\n \"\"\"\n Treats each document (tweet) as a single \"word,\" which is fed through c2v,\n and the output \"embedding\" sized to be a vector of language predictions.\n \"\"\"\n def __init__(self, out_vocab_size=None,\n batch_size=10, model_params=None, c2v=None,\n max_sequence_len=None,\n dropout_keep_prob=None,\n weights=None):\n self.params = model_params\n self._out_vocab_size = out_vocab_size # num. of languages\n self.weights = tf.constant(weights, dtype=tf.float32, name='class_weights')\n\n with tf.variable_scope(\"tweetff\"):\n hidden = tf.get_variable(\"ff_hidden\",\n [c2v.embedding_dims, out_vocab_size])\n bias = tf.get_variable('ff_bias', [out_vocab_size])\n\n #probably useless. at least I don't want to use it\n self.seq_lens = tf.placeholder(tf.int64, [batch_size], name='seq_lens')\n\n self.x = tf.placeholder(tf.int32, [batch_size, max_sequence_len],\n name='x')\n self.y = tf.placeholder(tf.float32, [batch_size, out_vocab_size],\n name='y')\n self.example_weights = tf.placeholder(tf.float32, [batch_size],\n name='example_weights')\n\n # get one 'word' embedding for the full tweet\n tweet_embedding = c2v.GetEmbeddings(self.x)[:,1,:]\n\n logits = tf.nn.xw_plus_b(tweet_embedding, hidden, bias)\n self.probs = tf.nn.softmax(logits)\n\n self._xent = tf.nn.softmax_cross_entropy_with_logits(logits, self.y)\n self.cost = tf.reduce_mean(self.example_weights * self._xent)\n\n\nclass WordLevelModel(object):\n \"\"\"\n Model to evaluate on word-level predictions\n\n Args:\n batch_size: minibatch size\n model_params: dictionary of other model parameters\n c2v: char2vec class instance\n max_sequence_len: length of all the input/output sequences\n out_vocab_size: how many languages we are predicting\n dropout_keep_prob: dropout probability indicator\n weights: class weights\n \"\"\"\n\n def __init__(self, batch_size, model_params, c2v, max_sequence_len,\n out_vocab_size, dropout_keep_prob=0.0, weights=None):\n self._batch_size = batch_size\n self._dropout_keep_prob = dropout_keep_prob\n self._out_vocab_size = out_vocab_size\n\n self.x = tf.placeholder(tf.int32, [batch_size, max_sequence_len],\n name='x')\n self.y = tf.placeholder(tf.float32,\n [batch_size, max_sequence_len, out_vocab_size],\n name='y')\n # The bidirectional rnn code requires seq_lens as int64\n self.seq_lens = tf.placeholder(tf.int64, [batch_size], name='seq_lens')\n self.example_weights = tf.placeholder(tf.float32, [batch_size],\n name='example_weights')\n\n embeddings = c2v.GetEmbeddings(self.x)\n self._inputs = [tf.squeeze(input_, [1]) for input_ in\n tf.split(1, max_sequence_len, embeddings)]\n\n # Need to prepare a mask to zero out the padding symbols.\n\n # Make a batch_size x max_sequence_len matrix where each\n # row contains the length repeated max_sequence_len times.\n lengths_transposed = tf.expand_dims(tf.to_int32(self.seq_lens), 1)\n lengths_tiled = tf.tile(lengths_transposed, [1, max_sequence_len])\n\n # Make a matrix where each row contains [0, 1, ..., max_sequence_len]\n r = tf.range(0, max_sequence_len, 1)\n range_row = tf.expand_dims(r, 0)\n range_tiled = tf.tile(range_row, [batch_size, 1])\n\n self.lengths_transposed = lengths_transposed\n self.lengths_tiled = lengths_tiled\n self.range_row = range_row\n self.range_tiled = range_tiled\n\n # Use the logical operations to create a mask\n indicator = tf.less(range_tiled, lengths_tiled+1) #i.e. where seq len is less than index\n trim = np.ones(indicator.get_shape())\n trim[:,0] = 0 #ignore start symbol\n indicator = tf.logical_and(indicator, trim.astype(bool))\n self.indicator = indicator\n\n sz = [batch_size, max_sequence_len]\n self._mask = tf.select(indicator, tf.ones(sz), tf.zeros(sz))\n\n #-------------------------------#\n\n self.weights = tf.constant(weights, dtype=tf.float32, name='class_weights')\n\n hidden_size = model_params['model_hidden_size']\n proj_size = model_params['model_proj_size'] # optional, can be None\n\n def GetCell():\n \"\"\"Creates an LSTM cell with dropout.\"\"\"\n c = tf.nn.rnn_cell.LSTMCell(hidden_size,\n use_peepholes=model_params['peepholes'],\n num_proj=proj_size)\n if dropout_keep_prob is not None:\n c = tf.nn.rnn_cell.DropoutWrapper(c, input_keep_prob=dropout_keep_prob)\n return c\n\n # Create the bi-directional LSTM\n with tf.variable_scope('wordrnn'):\n with tf.variable_scope('fw'):\n cell_fw = GetCell()\n with tf.variable_scope('bw'):\n cell_bw = GetCell()\n\n rnnout, _, _ = tf.nn.bidirectional_rnn(cell_fw, cell_bw, self._inputs,\n dtype=tf.float32,\n sequence_length=self.seq_lens)\n if proj_size:\n out_size = 2 * proj_size\n else:\n out_size = 2 * hidden_size\n self._DoPredictions(out_size, rnnout, self.weights)\n\n self.cost = tf.reduce_mean(self.example_weights * self._xent)\n\n def _DoPredictions(self, in_size, mats, class_weights=None):\n \"\"\"Takes in an array of states and calculates predictions.\n\n Get the cross-entropy for each example in the vector self._xent.\n\n Args:\n in_size: size of the hidden state vectors\n mats: list of hidden state vectors\n \"\"\"\n pred_mat = tf.get_variable('pred_mat',\n [in_size, self._out_vocab_size])\n pred_bias = tf.get_variable('pred_bias', [self._out_vocab_size])\n\n # Make a prediction on every word.\n def GetWordPred(o_):\n logits = tf.nn.xw_plus_b(o_, pred_mat, pred_bias)\n return tf.nn.softmax(logits)\n\n #self.preds_by_word1 = tf.pack([GetWordPred(o_) for o_ in mats])\n #self.preds_by_word = tf.reshape(self.preds_by_word1, self.y.get_shape())\n #self.probs = tf.mul(tf.expand_dims(self._mask,2), self.preds_by_word)\n\n self.preds_by_word = tf.pack([GetWordPred(o_) for o_ in mats])\n self.preds_by_instance = tf.pack([self.preds_by_word[:,i,:] for i in range(self.preds_by_word.get_shape()[1])])\n self.probs = tf.mul(tf.expand_dims(self._mask,2), self.preds_by_instance)\n\n self._xent = _SafeXEnt(self.y, self.probs, class_weights=class_weights, sumd=[1,2])\n\n\ndef _SafeXEnt(y, probs, eps=0.0001, class_weights=None, sumd=[1]):\n \"\"\"Version of cross entropy loss that should not produce NaNs.\n\n If the predicted proability for the true class is near zero then when\n taking the log it can produce a NaN, which ruins everything. This\n function ensures each probability is at least eps and no more than one\n before taking the log.\n\n Args:\n y: matrix of true probabilities same size as probs\n probs: matrix of probabilities for the minibatch\n eps: value to clip the probabilities at\n class_weights: vector of relative weights to be assigned to each class\n sumd: dimensions along which to sum the x-ent matrix\n\n Returns:\n cross entropy loss for each example in the minibatch\n \"\"\"\n adjusted_probs = tf.clip_by_value(probs, eps, 1.0 - eps)\n xent_mat = -y * tf.log(adjusted_probs)\n if class_weights is not None:\n xent_mat *= class_weights\n\n return tf.reduce_sum(xent_mat, sumd)\n\n\ndef _SafeNegEntropy(probs, batch_size, eps=0.0001):\n \"\"\"Computes negative entropy in a way that will not overflow.\"\"\"\n adjusted_probs = tf.clip_by_value(probs, eps, 1.0 - eps)\n entropy = tf.mul(probs, tf.log(adjusted_probs))\n return tf.reduce_sum(entropy) / batch_size\n"
] |
[
[
"tensorflow.get_variable",
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.zeros",
"tensorflow.reduce_sum",
"tensorflow.to_int32",
"tensorflow.pack",
"tensorflow.floor",
"tensorflow.squeeze",
"tensorflow.div",
"tensorflow.tile",
"tensorflow.nn.xw_plus_b",
"tensorflow.matmul",
"tensorflow.less",
"tensorflow.shape",
"tensorflow.placeholder",
"tensorflow.split",
"tensorflow.clip_by_value",
"tensorflow.nn.softmax",
"tensorflow.constant",
"tensorflow.transpose",
"tensorflow.range",
"tensorflow.reduce_mean",
"tensorflow.nn.rnn_cell.DropoutWrapper",
"tensorflow.nn.rnn_cell.LSTMCell",
"tensorflow.reshape",
"tensorflow.expand_dims",
"tensorflow.ones",
"tensorflow.log",
"tensorflow.nn.bidirectional_rnn",
"tensorflow.variable_scope"
]
] |
Captain-Hong/UDA-via-joint-adversarial-learning-and-self-learning
|
[
"628871c19a0e6eeaa5a2ff3a08cbb061d3feae60"
] |
[
"main.py"
] |
[
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Dec 16 17:14:55 2020\r\n\r\n@author: 11627\r\n\"\"\"\r\nimport os.path as osp\r\nfrom networks.discriminator import get_done_entropy_discriminator,get_done_discriminator,get_exit_discriminator\r\nimport numpy as np\r\nfrom torch.utils.data import DataLoader\r\nfrom torch.utils import data\r\nfrom datasets import CT_liver,MR_liver\r\nfrom networks.u_net import U_Net\r\nfrom networks.student_model import S_Unet\r\nfrom networks.att_u_net import AttU_Net\r\nfrom networks.att_student_model import AttS_Net\r\nfrom networks.final_model import AttSS_Net\r\nfrom networks.temp_model import temp_Net\r\nimport os,sys\r\nfrom tqdm import tqdm\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.backends.cudnn as cudnn\r\nfrom utils.loss import SoftDiceLoss,entropy_loss,bce_loss,EntropyLoss\r\nimport torch.nn.functional as F\r\nfrom utils.metrics import diceCoeffv2\r\nfrom utils.pamr import PAMR\r\nimport imageio\r\n\r\n#need two GPUs, 11GB respectively\r\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0,1\"\r\nseed = 2020\r\nnp.random.seed(seed)\r\ntorch.manual_seed(seed)\r\ntorch.cuda.manual_seed_all(seed)\r\ndef initialize_weights(*models):\r\n for model in models:\r\n for module in model.modules():\r\n if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear):\r\n nn.init.kaiming_normal_(module.weight)\r\n if module.bias is not None:\r\n module.bias.data.zero_()\r\n elif isinstance(module, nn.BatchNorm2d):\r\n module.weight.data.fill_(1)\r\n module.bias.data.zero_()\r\n\r\n \r\n\r\n\r\ndef pseudo_gtmask(output1, exitlos):\r\n \"\"\"Convert continuous mask into binary mask\"\"\"\r\n bs,c,h,w = output1.size()\r\n output1=output1.numpy()\r\n ave_output=np.zeros(shape=(1,c,h,w))\r\n for jj in range(bs):\r\n ave_output[0,:,:,:]=ave_output[0,:,:,:]+(1/bs)*output1[jj,:,:,:]\r\n \r\n \r\n pseudo_gt=np.zeros(shape=(bs,c,h,w))\r\n for j in range(bs):\r\n if exitlos[j]<0.5:\r\n pseudo_gt[j,:,:,:]=ave_output\r\n else:\r\n pseudo_gt[j,:,:,:]=output1[j,:,:,:]\r\n \r\n pseudo_gt=torch.from_numpy(np.array(pseudo_gt, dtype=np.float32))\r\n pseudo_gt = torch.sigmoid(pseudo_gt)\r\n pseudo_gt[pseudo_gt < 0.5] = 0\r\n pseudo_gt[pseudo_gt > 0.5] = 1\r\n\r\n return pseudo_gt\r\n\r\n\r\n\r\ndef main():\r\n batch_size=8\r\n pred_model=torch.load('./checkpoint/exp/pretrained_model_CT.pth')\r\n model_dict = pred_model.state_dict()\r\n #teacher_model indicates U1\r\n #student_model indicates U2\r\n #d_d1 indicates D1\r\n #d_d1en indicates D2\r\n #final_model indicatets the desired model U3 \r\n #temp_model indicates U4\r\n teacher_model=AttU_Net(img_ch=1, num_classes=1)\r\n teacher_model.load_state_dict(model_dict)\r\n student_model=AttS_Net(img_ch=1, num_classes=1)\r\n student_model.load_state_dict(model_dict)\r\n \r\n final_model=AttSS_Net(img_ch=1, num_classes=1)\r\n\r\n temp_model=temp_Net(img_ch=1, num_classes=1)\r\n # UDA TRAINING\r\n # Create the model and start the training.\r\n cudnn.benchmark = True\r\n cudnn.enabled = True\r\n torch.backends.cudnn.deterministic = True\r\n\r\n # freeze teacher network\r\n teacher_model.cuda(1)\r\n teacher_model.eval()\r\n\r\n \r\n student_model.cuda(0)\r\n student_model.train()\r\n\r\n\r\n # DISCRIMINATOR NETWORK\r\n # output discriminator\r\n d_d1 = get_done_discriminator(img_ch=1)\r\n d_d1.train()\r\n d_d1.apply(initialize_weights)\r\n\r\n d_d1en = get_done_entropy_discriminator(img_ch=1)\r\n d_d1en.train()\r\n d_d1en.apply(initialize_weights)\r\n \r\n\r\n weight_cliping_limit = 0.01\r\n learning_rate1=0.0001\r\n learning_rate2=0.0002\r\n learning_rate3=0.0002\r\n learning_rate4=0.00012\r\n learning_rate5=0.00015\r\n\r\n # labels for adversarial training\r\n one = torch.FloatTensor([1])\r\n mone = one * -1\r\n epochs=200\r\n PAMR_KERNEL = [1, 2, 4, 8]\r\n PAMR_ITER = 10\r\n criterion = SoftDiceLoss(activation='sigmoid')\r\n pamr_aff = PAMR(PAMR_ITER, PAMR_KERNEL)\r\n entropyloss_map=EntropyLoss(reduction='none')\r\n entropyloss=EntropyLoss(reduction='mean')\r\n maxpool=nn.MaxPool2d(kernel_size=256, stride=1)\r\n file_handle=open('record_PAMR.txt',mode='w')\r\n\r\n\r\n for epoch in range(epochs): \r\n ct_dataset = CT_liver.ct_liver('./CT')\r\n ct_loader = DataLoader(ct_dataset, batch_size=batch_size, shuffle=True)\r\n tealoader_iter = enumerate(ct_loader)\r\n mr_dataset = MR_liver.mr_liver('./MR','MR1.txt')\r\n mr_loader = DataLoader(mr_dataset, batch_size=batch_size, shuffle=True) \r\n\r\n dices1=[]\r\n dices2=[]\r\n dices3=[]\r\n\r\n for mr_imgs, mr_mask in mr_loader:\r\n mr_img=mr_imgs[:,:1,:,:]\r\n mr_img_trans=mr_imgs[:,1:2,:,:]\r\n mr_img_trans1=mr_imgs[:,:1,:,:]\r\n\r\n\r\n # OPTIMIZERS\r\n \r\n optimizer = torch.optim.RMSprop(student_model.parameters(), lr=learning_rate1, alpha=0.9)\r\n optimizer_d_d1 = torch.optim.RMSprop(d_d1.parameters(), lr=learning_rate2, alpha=0.9) \r\n optimizer_d_d1en = torch.optim.RMSprop(d_d1en.parameters(), lr=learning_rate3, alpha=0.9) \r\n optimizer_final = torch.optim.RMSprop(final_model.parameters(), lr=learning_rate4, alpha=0.9)\r\n optimizer_temp = torch.optim.RMSprop(temp_model.parameters(), lr=learning_rate5, alpha=0.9)\r\n\r\n # UDA Training\r\n # only train discriminators. Don't accumulate grads in student_model\r\n\r\n for param in teacher_model.parameters():\r\n param.requires_grad = False \r\n for param in d_d1.parameters():\r\n param.requires_grad = True \r\n for param in d_d1en.parameters():\r\n param.requires_grad = True \r\n # reset optimizers\r\n optimizer_d_d1.zero_grad()\r\n optimizer_d_d1en.zero_grad()\r\n \r\n \r\n \r\n for param in d_d1.parameters():\r\n param.data.clamp_(-weight_cliping_limit, weight_cliping_limit) \r\n for param in d_d1en.parameters():\r\n param.data.clamp_(-weight_cliping_limit, weight_cliping_limit) \r\n # Train with ct images\r\n _, ct_batch= tealoader_iter.__next__()\r\n ct_img, ct_mask= ct_batch\r\n _, _, _, ct_d1 = teacher_model(ct_img.cuda(1)) \r\n \r\n ct_d11=ct_d1.detach()\r\n ct_en=entropyloss_map(ct_d11)\r\n d_d1.cuda(1)\r\n d_loss_d1_ct = d_d1(ct_d11.cuda(1))\r\n d_loss_d1_ct = d_loss_d1_ct.mean(0).view(1)\r\n d_loss_d1_ct=d_loss_d1_ct\r\n d_loss_d1_ct.backward(one.cuda(1)) \r\n \r\n d_d1en.cuda(1)\r\n d_loss_d1en_ct = d_d1en(ct_en.cuda(1))\r\n d_loss_d1en_ct = d_loss_d1en_ct.mean(0).view(1)\r\n d_loss_d1en_ct=d_loss_d1en_ct/2\r\n d_loss_d1en_ct.backward(one.cuda(1))\r\n \r\n # Train with mr images\r\n _, _, _, mr_d1 = student_model(mr_img.cuda(0)) \r\n mr_d11=mr_d1.detach()\r\n mr_en=entropyloss_map(mr_d11) \r\n d_d1.cuda(1)\r\n d_loss_d1_mr = d_d1(mr_d11.cuda(1))\r\n d_loss_d1_mr = d_loss_d1_mr.mean(0).view(1)\r\n d_loss_d1_mr=d_loss_d1_mr/2\r\n d_loss_d1_mr.backward(mone.cuda(1)) \r\n \r\n \r\n d_d1en.cuda(1)\r\n d_loss_d1en_mr = d_d1en(mr_en.cuda(1))\r\n d_loss_d1en_mr = d_loss_d1en_mr.mean(0).view(1)\r\n d_loss_d1en_mr=d_loss_d1en_mr/2\r\n d_loss_d1en_mr.backward(mone.cuda(1))\r\n\r\n # Train with mr_trans images\r\n final_model.cuda(1) \r\n _, _, _, mr_d1_final = final_model(mr_img_trans.cuda(1)) \r\n mr_d11_final=mr_d1_final.detach() \r\n d_d1.cuda(1)\r\n d_loss_d1_mr_final = d_d1(mr_d11_final.cuda(1))\r\n d_loss_d1_mr_final = d_loss_d1_mr_final.mean(0).view(1)\r\n d_loss_d1_mr_final=d_loss_d1_mr_final/2\r\n d_loss_d1_mr_final.backward(mone.cuda(1)) \r\n\r\n\r\n \r\n optimizer_d_d1.step()\r\n optimizer_d_d1en.step()\r\n\r\n\r\n\r\n# only train student_model. Don't accumulate grads in discriminators\r\n\r\n _, _, _, ct_d12 = student_model(ct_img.cuda(0)) \r\n \r\n for param in student_model.parameters():\r\n param.requires_grad = False \r\n for param in student_model.Conv1.parameters():\r\n param.requires_grad = True \r\n\r\n for param in d_d1.parameters():\r\n param.requires_grad = False \r\n for param in d_d1en.parameters():\r\n param.requires_grad = False \r\n optimizer.zero_grad() \r\n\r\n en=entropyloss_map(mr_d1)\r\n d_d1.cuda(0)\r\n g_loss_d1 = d_d1(mr_d1.cuda(0))\r\n\r\n mr_d11=mr_d1.detach().cpu()\r\n g_loss_d1 = g_loss_d1.mean(0).view(1)\r\n g_loss_d1.backward(one.cuda(0),retain_graph=True)\r\n\r\n mr_d1_mask = torch.sigmoid(mr_d11)\r\n exit_loss=maxpool(mr_d1_mask)\r\n exit_loss=exit_loss[:,0,0,0].numpy()\r\n\r\n d_d1en.cuda(0)\r\n g_loss_d1en = d_d1en(en.cuda(0))\r\n g_loss_d1en = g_loss_d1en.mean(0).view(1)\r\n g_loss_d1en.backward(one.cuda(0))\r\n\r\n ct_loss = criterion(ct_d12.cuda(0), ct_mask.cuda(0))\r\n ct_loss.backward() \r\n \r\n optimizer.step()\r\n \r\n \r\n \r\n\r\n\r\n final_model.train() \r\n temp_model.train()\r\n final_model.cuda(1)\r\n temp_model.cuda(1)\r\n for param in d_d1.parameters():\r\n param.requires_grad = False \r\n for param in d_d1en.parameters():\r\n param.requires_grad = False \r\n \r\n optimizer_final.zero_grad() \r\n optimizer_temp.zero_grad() \r\n \r\n _,_,_,mr_d1_final=final_model(mr_img_trans.cuda(1))\r\n\r\n _,_,_,mr_d1_temp=temp_model(mr_img_trans1.cuda(1))\r\n mr_d1_temp1=mr_d1_temp.detach()\r\n \r\n if epoch<70:\r\n pseudo_mask=pseudo_gtmask(mr_d11.cpu(),exit_loss) \r\n pseudo_mask_loss_final= criterion(mr_d1_final, pseudo_mask.detach().cuda(1))\r\n pseudo_mask_loss_final.backward(retain_graph=True)\r\n\r\n \r\n else:\r\n pseudo_mask1 = torch.sigmoid(mr_d1_temp1)\r\n pseudo_mask1[pseudo_mask1 < 0.5] = 0\r\n pseudo_mask1[pseudo_mask1 > 0.5] = 1\r\n pseudo_mask_loss_final1= criterion(mr_d1_final, pseudo_mask1.detach().cuda(1))\r\n pseudo_mask_loss_final1=pseudo_mask_loss_final1*5\r\n pseudo_mask_loss_final1.backward(retain_graph=True)\r\n\r\n\r\n d_d1.cuda(1)\r\n g_loss_d1_final = d_d1(mr_d1_final.cuda(1))\r\n g_loss_d1_final = g_loss_d1_final.mean(0).view(1)\r\n g_loss_d1_final.backward(one.cuda(1),retain_graph=True) \r\n\r\n\r\n en_loss=5*entropyloss(mr_d1_final)\r\n en_loss.backward(retain_graph=True)\r\n\r\n\r\n pamr_masks = torch.sigmoid(mr_d1_final.detach())\r\n pamr_aff.cuda(1)\r\n masks_dec = pamr_aff(mr_img_trans.detach().cuda(1), pamr_masks.detach())\r\n masks_dec[masks_dec < 0.5] = 0\r\n masks_dec[masks_dec > 0.5] = 1\r\n pamr_mask_loss=criterion(mr_d1_final, masks_dec.detach())\r\n pamr_mask_loss.backward()\r\n file_handle.write(str(pamr_mask_loss.item()))\r\n file_handle.write('\\t')\r\n\r\n\r\n\r\n\r\n\r\n#########################temp_model\r\n\r\n\r\n pseudo_mask1 = torch.sigmoid(mr_d1_final.detach())\r\n pseudo_mask1[pseudo_mask1 < 0.5] = 0\r\n pseudo_mask1[pseudo_mask1 > 0.5] = 1\r\n temp_mask_loss=criterion(mr_d1_temp, pseudo_mask1.detach().cuda(1))\r\n temp_mask_loss.backward()\r\n \r\n\r\n\r\n optimizer_final.step()\r\n optimizer_temp.step()\r\n final_model.eval()\r\n temp_model.eval()\r\n \r\n\r\n \r\n \r\n distance_d1=2*abs(d_loss_d1_mr.detach().cpu().item()-d_loss_d1_ct.detach().cpu().item())\r\n distance_d1en=2*abs(d_loss_d1en_mr.detach().cpu().item()-d_loss_d1en_ct.detach().cpu().item())\r\n\r\n distance_d1_final=2*abs(d_loss_d1_mr_final.detach().cpu().item()-d_loss_d1_ct.detach().cpu().item())\r\n\r\n\r\n\r\n mr_loss= criterion(mr_d1.detach().cpu(), mr_mask.detach().cpu())\r\n mr_loss_final= criterion(mr_d1_final.detach().cpu(), mr_mask.detach().cpu())\r\n mr_loss_temp= criterion(mr_d1_temp.detach().cpu(), mr_mask.detach().cpu())\r\n file_handle.write(str(mr_loss_final.item()))\r\n file_handle.write('\\n')\r\n \r\n mr_d11=mr_d1.detach().cpu()\r\n mr_d11 = torch.sigmoid(mr_d11)\r\n mr_d11[mr_d11 < 0.5] = 0\r\n mr_d11[mr_d11 > 0.5] = 1\r\n Liver_dice1 = diceCoeffv2(mr_d11, mr_mask.detach().cpu(), activation=None).cpu().item()\r\n dices1.append(Liver_dice1)\r\n\r\n mr_d11_final=mr_d1_final.detach().cpu()\r\n mr_d11_final = torch.sigmoid(mr_d11_final)\r\n mr_d11_final[mr_d11_final < 0.5] = 0\r\n mr_d11_final[mr_d11_final > 0.5] = 1\r\n Liver_dice2 = diceCoeffv2(mr_d11_final.detach().cpu(), mr_mask.detach().cpu(), activation=None).cpu().item()\r\n dices2.append(Liver_dice2)\r\n \r\n mr_d11_temp=mr_d1_temp.detach().cpu()\r\n mr_d11_temp = torch.sigmoid(mr_d11_temp)\r\n mr_d11_temp[mr_d11_temp < 0.5] = 0\r\n mr_d11_temp[mr_d11_temp > 0.5] = 1\r\n Liver_dice3 = diceCoeffv2(mr_d11_temp.detach().cpu(), mr_mask.detach().cpu(), activation=None).cpu().item()\r\n dices3.append(Liver_dice3)\r\n string_print = \"E=%d disd1=%.4f disd1f=%.4f disd1en=%.4f pmasklosf=%.4f pamrlos=%.4f tplos=%.4f masklos=%.4f masklosf=%.4f masklost=%.4f\"\\\r\n % (epoch, distance_d1,distance_d1_final,distance_d1en,pseudo_mask_loss_final.cpu().item(),pamr_mask_loss.cpu().item(),temp_mask_loss.cpu().item(),\r\n mr_loss.cpu().item(),mr_loss_final.cpu().item(),mr_loss_temp.cpu().item()) \r\n \r\n \r\n print(\"\\r\"+string_print,end = \"\",flush=True) \r\n\r\n \r\n \r\n sys.stdout.flush() \r\n\r\n \r\n print('\\ntaking snapshot ...')\r\n print('exp =', 'model')\r\n \r\n torch.save(temp_model,\r\n osp.join('./temp_model', f'temp_model_MR1_{epoch}.pth'))\r\n torch.save(final_model,\r\n osp.join('./final_model', f'final_model_MR1_{epoch}.pth'))\r\n torch.save(student_model,\r\n osp.join('./student_model', f'student_model_MR1_{epoch}.pth'))\r\n Liver_dice_average1 = np.mean(dices1)\r\n print('Train Liver Dice1 {:.4}'.format(Liver_dice_average1))\r\n \r\n Liver_dice_average2 = np.mean(dices2)\r\n print('Train Liver Dice2 {:.4}'.format(Liver_dice_average2)) \r\n \r\n Liver_dice_average3 = np.mean(dices3)\r\n print('Train Liver Dice3 {:.4}'.format(Liver_dice_average3)) \r\n file_handle.close()\r\nif __name__ == '__main__':\r\n main()\r\n"
] |
[
[
"torch.sigmoid",
"numpy.random.seed",
"torch.load",
"torch.manual_seed",
"torch.utils.data.DataLoader",
"torch.nn.MaxPool2d",
"torch.FloatTensor",
"numpy.mean",
"torch.cuda.manual_seed_all",
"numpy.array",
"numpy.zeros",
"torch.nn.init.kaiming_normal_"
]
] |
bayshore-intelligence-solutions/CogAlg
|
[
"36d883e5148153986e111e5905d620c901cd929b"
] |
[
"frame_2D_alg/alternative versions/frame_classes/angle_blobs.py"
] |
[
"import numpy as np\nfrom collections import deque\nfrom frame_2D_alg import Classes\nfrom frame_2D_alg.misc import get_filters\nget_filters(globals()) # imports all filters at once\n# --------------------------------------------------------------------------------\n'''\n angle_blob is a component of intra_blob\n'''\n# ***************************************************** ANGLE BLOBS FUNCTIONS *******************************************\n# Functions:\n# -blob_to_ablobs()\n# -get_angle()\n# -comp_angle()\n# ***********************************************************************************************************************\n\ndef blob_to_ablobs(blob): # compute and compare angle, define ablobs, accumulate a, da, ga in all reps within gblob\n ''' same functionality as image_to_blobs() in frame_blobs_ortho.py'''\n #\n\n global Y, X\n Y, X = blob.map.shape\n\n sub_blob = Classes.cl_frame(blob.dert__, num_dert=2, map=blob.map, copy_dert=True) # initialize sub_blob object per gblob\n seg_ = deque()\n dert_ = sub_blob.dert__[0]\n P_map_ = sub_blob.map[0]\n a_ = get_angle(dert_, P_map_) # compute angle of max gradients within gblob (contiguous area of same-sign gradient)\n\n for y in range(Y - 1):\n lower_dert_ = sub_blob.dert__[y + 1]\n lower_P_map_ = sub_blob.map[y + 1]\n lower_a_ = get_angle(lower_dert_, lower_P_map_, P_map_)\n\n P_ = comp_angle(y, a_, lower_a_, dert_, P_map_) # vertical and lateral angle comparison\n P_ = Classes.scan_P_(y, P_, seg_, sub_blob) # aP_ scans _aP_ from seg_\n seg_ = Classes.form_segment(y, P_, sub_blob) # form segments with P_ and their fork_s\n a_, dert_, P_map_ = lower_a_, lower_dert_, lower_P_map_ # buffers for next line\n\n y = Y - 1 # sub_blob ends, merge segs of last line into their blobs:\n while seg_: Classes.form_blob(y, seg_.popleft(), sub_blob)\n\n sub_blob.terminate() # delete sub_blob.dert__ and sub_blob.map\n blob.angle_sub_blob = sub_blob\n return sub_blob\n # ---------- blob_to_ablobs() end -----------------------------------------------------------------------------------\n\ndef get_angle(dert_, P_map_, _P_map_ = False): # default = False: no higher-line for first line\n \" compute angle of gradient in and adjacent to selected gblob\"\n\n a_ = np.full(P_map_.shape, -1)\n marg_angle_ = np.zeros(P_map_.shape, dtype=bool) # to compute angle in blob-marginal derts\n marg_angle_[0] = P_map_[0]\n marg_angle_[1:] = np.logical_or(P_map_[:-1], P_map_[1:]) # derts right-adjacent to blob, for lower-line lateral comp\n marg_angle_ = np.logical_or(marg_angle_, _P_map_) # derts down-adjacent to blob, for higher-line vertical comp\n dx_, dy_ = dert_ [:, 2:4].T # dx, dy as slices of dert_\n\n a_[marg_angle_] = np.arctan2(dy_[marg_angle_], dx_[marg_angle_]) * angle_coef + 128 # computes angle if marg_angle_== True\n return a_\n # ---------- get_angle() end ----------------------------------------------------------------------------------------\n\ndef comp_angle(y, a_, lower_a_, dert_, P_map_):\n \" compare angle of adjacent gradients within frame per gblob \"\n\n dxa_ = correct_da(np.abs(a_[1:] - a_[:-1]))\n dya_ = correct_da(np.abs(lower_a_[:-1] - a_[:-1]))\n ga_ = (dxa_ + dya_) - 2 * ave\n dert_[:, 4] = a_ # assign a_ to a slice of dert_\n dert_[:-1, 5] = ga_ # assign ga_ to a slice of dert_\n P_ = deque()\n x = 0\n while x < X - 1: # exclude last column\n while x < X - 1 and not P_map_[x]:\n x += 1\n if x < X - 1 and P_map_[x]:\n P = Classes.cl_P(x0=x, num_params=dert_.shape[1] + 1) # aP initialization\n while x < X - 1 and P_map_[x]:\n dert = dert_[x]\n ga = dert[5]\n s = ga > 0\n P = Classes.form_P(x, y, s, dert, P, P_)\n x += 1\n P.terminate(x, y) # aP' x_last\n P_.append(P)\n\n return P_\n # ---------- comp_angle() end ---------------------------------------------------------------------------------------\ndef correct_da(da):\n \" make da 0 - 128 instead of 0 - 255 \"\n where = da > 128\n da[where] = 256 - da[where]\n return da\n # ---------- correct_da() end ---------------------------------------------------------------------------------------"
] |
[
[
"numpy.abs",
"numpy.full",
"numpy.logical_or",
"numpy.arctan2",
"numpy.zeros"
]
] |
ngninbo/mamphi-administration
|
[
"8b6e16f6e054e4ed7d9ac7bd99ae413cdd7a007a"
] |
[
"mamphi-admin/admin/mamphi.py"
] |
[
"import pandas as pd\nimport sqlite3\n\n\nclass Mamphi:\n\n def __init__(self, path_to_center_sheet, path_to_consent_sheet, path_to_rand_w1_sheet, path_to_rand_w2_sheet,\n db_filename):\n self.path_to_center_sheet = path_to_center_sheet\n self.path_to_consent_sheet = path_to_consent_sheet\n self.path_to_rand_w1_sheet = path_to_rand_w1_sheet\n self.path_to_rand_w2_sheet = path_to_rand_w2_sheet\n self.db_filename = db_filename\n\n def create_center_table(self):\n center_data = pd.read_excel(self.path_to_center_sheet)\n\n # Create Table Center\n sql_center_table = \"\"\" CREATE TABLE IF NOT EXISTS Zentren(\n Zentrum_Id smallint,\n Land varchar(255),\n Ort varchar(255),\n Pruefer varchar(255),\n Monitor varchar(255)\n )\"\"\"\n\n # create connection to database\n conn = sqlite3.connect(self.db_filename)\n cursor = conn.cursor()\n cursor.execute(sql_center_table)\n\n # Create rows of value\n rows = center_data.values\n\n for row in rows:\n value = str(tuple(row))\n statement = \"INSERT INTO Zentren VALUES\" + value\n try:\n cursor.execute(statement)\n\n conn.commit()\n print(cursor.rowcount, \"record inserted.\")\n\n except EOFError:\n conn.rollback()\n\n conn.close()\n\n print('Successfully created database table center')\n\n def create_consent_table(self):\n\n consent_data = pd.read_excel(self.path_to_consent_sheet)\n\n connection = sqlite3.connect(self.db_filename)\n\n # prepare a cursor object\n cursor = connection.cursor()\n\n # Create Table Informed_consent\n patient_table_statement = \"\"\" CREATE TABLE IF NOT EXISTS Informed_consent(\n Patient_Id smallint,\n Zentrum smallint,\n Einwilligung varchar(255),\n Datum date\n )\"\"\"\n\n # print(patient_table_statement)\n cursor.execute(patient_table_statement)\n\n # Create rows of values\n rows = consent_data.values\n\n for row in rows:\n values = str(tuple(row))\n insert_statement = \"INSERT INTO Informed_consent VALUES\" + values\n\n try:\n # Execute SQL command\n cursor.execute(insert_statement)\n # Commit the change\n connection.commit()\n print(cursor.rowcount, \"record inserted.\")\n\n except EOFError:\n # Rollback in case there is any error\n connection.rollback()\n # if i !=len(rows)-2:\n # values_p +=','\n\n connection.close()\n print('Successfully created database table Informed_consent')\n\n def create_table_randomisation_week(self, week):\n\n random_week2_data = pd.read_excel(self.path_to_rand_w2_sheet)\n\n conn = sqlite3.connect(self.db_filename)\n cursor = conn.cursor()\n\n querie_create_table_rand_w2 = \"\"\"CREATE TABLE IF NOT EXISTS Random_Woche_{}(\n Patient_Id smallint,\n Zentrum smallint,\n Behandlungsarm varchar(255),\n Datum date\n )\"\"\".format(week)\n\n cursor.execute(querie_create_table_rand_w2)\n\n rows = random_week2_data.values\n\n for row in rows:\n value = str(tuple(row))\n\n sql = \"INSERT INTO Random_Woche_2 VALUES\" + value\n\n try:\n # Execute SQL Command\n cursor.execute(sql)\n # Commit changes\n conn.commit()\n print(cursor.rowcount, \"record inserted.\")\n except EOFError:\n conn.rollback()\n\n conn.close()\n\n print('Successfully created database table Random_Week_{}'.format(week))\n"
] |
[
[
"pandas.read_excel"
]
] |
vishalbelsare/probability
|
[
"99bdccd79ff4522427f6add5f436668910275932"
] |
[
"tensorflow_probability/python/sts/internal/util_test.py"
] |
[
"# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Tests for StructuralTimeSeries utilities.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow.compat.v1 as tf1\nimport tensorflow.compat.v2 as tf\nimport tensorflow_probability as tfp\n\nfrom tensorflow_probability import distributions as tfd\nfrom tensorflow_probability.python.internal import test_util\nfrom tensorflow_probability.python.sts.internal import missing_values_util\nfrom tensorflow_probability.python.sts.internal import util as sts_util\n\n\n@test_util.test_all_tf_execution_regimes\nclass MultivariateNormalUtilsTest(test_util.TestCase):\n\n def test_factored_joint_mvn_diag_full(self):\n batch_shape = [3, 2]\n\n mvn1 = tfd.MultivariateNormalDiag(\n loc=tf.zeros(batch_shape + [3]),\n scale_diag=tf.ones(batch_shape + [3]))\n\n mvn2 = tfd.MultivariateNormalFullCovariance(\n loc=tf.ones(batch_shape + [2]),\n covariance_matrix=(tf.ones(batch_shape + [2, 2]) *\n [[5., -2], [-2, 3.1]]))\n\n joint = sts_util.factored_joint_mvn([mvn1, mvn2])\n self.assertEqual(self.evaluate(joint.event_shape_tensor()),\n self.evaluate(mvn1.event_shape_tensor() +\n mvn2.event_shape_tensor()))\n\n joint_mean_ = self.evaluate(joint.mean())\n self.assertAllEqual(joint_mean_[..., :3], self.evaluate(mvn1.mean()))\n self.assertAllEqual(joint_mean_[..., 3:], self.evaluate(mvn2.mean()))\n\n joint_cov_ = self.evaluate(joint.covariance())\n self.assertAllEqual(joint_cov_[..., :3, :3],\n self.evaluate(mvn1.covariance()))\n self.assertAllEqual(joint_cov_[..., 3:, 3:],\n self.evaluate(mvn2.covariance()))\n\n def test_factored_joint_mvn_broadcast_batch_shape(self):\n # Test that combining MVNs with different but broadcast-compatible\n # batch shapes yields an MVN with the correct broadcast batch shape.\n random_with_shape = (\n lambda shape: np.random.standard_normal(shape).astype(np.float32))\n\n event_shape = [3]\n # mvn with batch shape [2]\n mvn1 = tfd.MultivariateNormalDiag(\n loc=random_with_shape([2] + event_shape),\n scale_diag=tf.exp(random_with_shape([2] + event_shape)))\n\n # mvn with batch shape [3, 2]\n mvn2 = tfd.MultivariateNormalDiag(\n loc=random_with_shape([3, 2] + event_shape),\n scale_diag=tf.exp(random_with_shape([1, 2] + event_shape)))\n\n # mvn with batch shape [1, 2]\n mvn3 = tfd.MultivariateNormalDiag(\n loc=random_with_shape([1, 2] + event_shape),\n scale_diag=tf.exp(random_with_shape([2] + event_shape)))\n\n joint = sts_util.factored_joint_mvn([mvn1, mvn2, mvn3])\n self.assertAllEqual(self.evaluate(joint.batch_shape_tensor()), [3, 2])\n\n joint_mean_ = self.evaluate(joint.mean())\n broadcast_means = tf.ones_like(joint.mean()[..., 0:1])\n self.assertAllEqual(joint_mean_[..., :3],\n self.evaluate(broadcast_means * mvn1.mean()))\n self.assertAllEqual(joint_mean_[..., 3:6],\n self.evaluate(broadcast_means * mvn2.mean()))\n self.assertAllEqual(joint_mean_[..., 6:9],\n self.evaluate(broadcast_means * mvn3.mean()))\n\n joint_cov_ = self.evaluate(joint.covariance())\n broadcast_covs = tf.ones_like(joint.covariance()[..., :1, :1])\n self.assertAllEqual(joint_cov_[..., :3, :3],\n self.evaluate(broadcast_covs * mvn1.covariance()))\n self.assertAllEqual(joint_cov_[..., 3:6, 3:6],\n self.evaluate(broadcast_covs * mvn2.covariance()))\n self.assertAllEqual(joint_cov_[..., 6:9, 6:9],\n self.evaluate(broadcast_covs * mvn3.covariance()))\n\n def test_sum_mvns(self):\n batch_shape = [4, 2]\n random_with_shape = (\n lambda shape: np.random.standard_normal(shape).astype(np.float32))\n\n mvn1 = tfd.MultivariateNormalDiag(\n loc=random_with_shape(batch_shape + [3]),\n scale_diag=np.exp(random_with_shape(batch_shape + [3])))\n mvn2 = tfd.MultivariateNormalDiag(\n loc=random_with_shape(batch_shape + [3]),\n scale_diag=np.exp(random_with_shape(batch_shape + [3])))\n\n sum_mvn = sts_util.sum_mvns([mvn1, mvn2])\n self.assertAllClose(self.evaluate(sum_mvn.mean()),\n self.evaluate(mvn1.mean() + mvn2.mean()))\n self.assertAllClose(self.evaluate(sum_mvn.covariance()),\n self.evaluate(mvn1.covariance() + mvn2.covariance()))\n\n def test_sum_mvns_broadcast_batch_shape(self):\n random_with_shape = (\n lambda shape: np.random.standard_normal(shape).astype(np.float32))\n\n event_shape = [3]\n mvn1 = tfd.MultivariateNormalDiag(\n loc=random_with_shape([2] + event_shape),\n scale_diag=np.exp(random_with_shape([2] + event_shape)))\n mvn2 = tfd.MultivariateNormalDiag(\n loc=random_with_shape([1, 2] + event_shape),\n scale_diag=np.exp(random_with_shape([3, 2] + event_shape)))\n mvn3 = tfd.MultivariateNormalDiag(\n loc=random_with_shape([3, 2] + event_shape),\n scale_diag=np.exp(random_with_shape([2] + event_shape)))\n\n sum_mvn = sts_util.sum_mvns([mvn1, mvn2, mvn3])\n self.assertAllClose(self.evaluate(sum_mvn.mean()),\n self.evaluate(mvn1.mean() + mvn2.mean() + mvn3.mean()))\n self.assertAllClose(self.evaluate(sum_mvn.covariance()),\n self.evaluate(mvn1.covariance() +\n mvn2.covariance() +\n mvn3.covariance()))\n\n\nclass _UtilityTests(test_util.TestCase):\n\n def test_broadcast_batch_shape(self):\n batch_shapes = ([2], [3, 2], [1, 2])\n distributions = [\n tfd.Normal(loc=self._build_tensor(np.zeros(batch_shape)),\n scale=self._build_tensor(np.ones(batch_shape)))\n for batch_shape in batch_shapes\n ]\n if self.use_static_shape:\n self.assertEqual(\n [3, 2], sts_util.broadcast_batch_shape(distributions))\n else:\n broadcast_batch_shape = sts_util.broadcast_batch_shape(distributions)\n # Broadcast shape in Eager can contain Python `int`s, so we need to\n # explicitly convert to Tensor.\n self.assertAllEqual([3, 2], self.evaluate(tf.convert_to_tensor(\n value=broadcast_batch_shape)))\n\n def test_maybe_expand_trailing_dim(self):\n for shape_in, expected_shape_out in [\n # pyformat: disable\n ([4, 3], [4, 3, 1]),\n ([4, 3, 1], [4, 3, 1]),\n ([4], [4, 1]),\n ([1], [1]),\n ([4, 1], [4, 1])\n # pyformat: enable\n ]:\n shape_out = self._shape_as_list(\n sts_util._maybe_expand_trailing_dim(\n self._build_tensor(np.zeros(shape_in))))\n self.assertAllEqual(shape_out, expected_shape_out)\n\n def test_empirical_statistics_accepts_masked_values(self):\n\n # Ensure that masks broadcast over batch shape by creating a batch of\n # time series.\n time_series = np.random.randn(3, 2, 5)\n mask = np.array([[True, False, False, True, False],\n [True, True, True, True, True]])\n\n masked_series = missing_values_util.MaskedTimeSeries(\n time_series=time_series, is_missing=mask)\n mean, stddev, initial = self.evaluate(\n sts_util.empirical_statistics(masked_series))\n\n # Should return default values when the series is completely masked.\n self.assertAllClose(mean[:, 1], tf.zeros_like(mean[:, 1]))\n self.assertAllClose(stddev[:, 1], tf.ones_like(stddev[:, 1]))\n self.assertAllClose(initial[:, 1], tf.zeros_like(initial[:, 1]))\n\n # Otherwise, should return the actual mean/stddev/initial values.\n time_series = time_series[:, 0, :]\n mask = mask[0, :]\n broadcast_mask = np.broadcast_to(mask, time_series.shape)\n unmasked_series = time_series[~broadcast_mask].reshape([3, 3])\n unmasked_mean, unmasked_stddev, unmasked_initial = self.evaluate(\n sts_util.empirical_statistics(unmasked_series))\n self.assertAllClose(mean[:, 0], unmasked_mean)\n self.assertAllClose(stddev[:, 0], unmasked_stddev)\n self.assertAllClose(initial[:, 0], unmasked_initial)\n\n # Run the same tests without batch shape.\n unbatched_time_series = time_series[0, :]\n masked_series = missing_values_util.MaskedTimeSeries(\n time_series=unbatched_time_series, is_missing=mask)\n mean, stddev, initial = self.evaluate(\n sts_util.empirical_statistics(masked_series))\n unmasked_mean, unmasked_stddev, unmasked_initial = self.evaluate(\n sts_util.empirical_statistics(unbatched_time_series[~mask]))\n self.assertAllClose(mean, unmasked_mean)\n self.assertAllClose(stddev, unmasked_stddev)\n self.assertAllClose(initial, unmasked_initial)\n\n def test_mix_over_posterior_draws(self):\n num_posterior_draws = 3\n batch_shape = [2, 1]\n means = np.random.randn(*np.concatenate([[num_posterior_draws],\n batch_shape]))\n variances = np.exp(np.random.randn(*np.concatenate(\n [[num_posterior_draws], batch_shape])))\n\n posterior_mixture_dist = sts_util.mix_over_posterior_draws(\n self._build_tensor(means),\n self._build_tensor(variances))\n\n # Compute the true statistics of the mixture distribution.\n mixture_mean = np.mean(means, axis=0)\n mixture_variance = np.mean(variances + means**2, axis=0) - mixture_mean**2\n\n self.assertAllClose(mixture_mean,\n self.evaluate(posterior_mixture_dist.mean()))\n self.assertAllClose(mixture_variance,\n self.evaluate(posterior_mixture_dist.variance()))\n\n def test_pad_batch_dimension_when_input_has_sample_shape(self):\n\n model_batch_shape = [3, 2]\n model = tfp.sts.LocalLevel(\n level_scale_prior=tfd.Normal(\n loc=self._build_tensor(np.random.randn(*model_batch_shape)),\n scale=1.))\n\n num_timesteps = 5\n sample_shape = [4]\n observed_time_series = self._build_tensor(np.random.randn(\n *(sample_shape + model_batch_shape + [num_timesteps, 1])))\n\n padded_observed_time_series = (\n sts_util.pad_batch_dimension_for_multiple_chains(\n observed_time_series, model=model, chain_batch_shape=[8, 2]))\n self.assertAllEqual(\n self._shape_as_list(padded_observed_time_series),\n sample_shape + [1, 1] + model_batch_shape + [num_timesteps, 1])\n\n def test_dont_pad_batch_dimension_when_input_has_no_sample_shape(self):\n\n model_batch_shape = [3, 2]\n model = tfp.sts.LocalLevel(\n level_scale_prior=tfd.Normal(\n loc=self._build_tensor(np.random.randn(*model_batch_shape)),\n scale=1.))\n\n num_timesteps = 5\n observed_time_series = self._build_tensor(\n np.random.randn(num_timesteps, 1))\n\n padded_observed_time_series = (\n sts_util.pad_batch_dimension_for_multiple_chains(\n observed_time_series, model=model, chain_batch_shape=[8, 2]))\n self.assertAllEqual(\n self._shape_as_list(padded_observed_time_series),\n self._shape_as_list(observed_time_series))\n\n def _shape_as_list(self, tensor):\n if self.use_static_shape:\n return tensor.shape.as_list()\n else:\n return list(self.evaluate(tf.shape(tensor)))\n\n def _build_tensor(self, ndarray):\n \"\"\"Convert a numpy array to a TF placeholder.\n\n Args:\n ndarray: any object convertible to a numpy array via `np.asarray()`.\n\n Returns:\n placeholder: a TensorFlow `placeholder` with default value given by the\n provided `ndarray`, dtype given by `self.dtype`, and shape specified\n statically only if `self.use_static_shape` is `True`.\n \"\"\"\n\n ndarray = np.asarray(ndarray).astype(self.dtype)\n return tf1.placeholder_with_default(\n ndarray, shape=ndarray.shape if self.use_static_shape else None)\n\n\nclass UtilityTestsDynamicFloat32(_UtilityTests):\n use_static_shape = False\n dtype = np.float32\n\n\n@test_util.test_all_tf_execution_regimes\nclass UtilityTestsStaticFloat64(_UtilityTests):\n use_static_shape = True\n dtype = np.float64\n\ndel _UtilityTests\n\nif __name__ == \"__main__\":\n tf.test.main()\n"
] |
[
[
"tensorflow.compat.v2.zeros_like",
"tensorflow.compat.v2.ones_like",
"tensorflow.compat.v2.test.main",
"numpy.asarray",
"numpy.random.standard_normal",
"numpy.ones",
"numpy.concatenate",
"tensorflow.compat.v2.convert_to_tensor",
"tensorflow.compat.v2.shape",
"tensorflow.compat.v2.zeros",
"numpy.mean",
"numpy.random.randn",
"numpy.broadcast_to",
"tensorflow.compat.v2.ones",
"numpy.array",
"tensorflow.compat.v1.placeholder_with_default",
"numpy.zeros"
]
] |
lleon95/NanoSciTracker-Python
|
[
"f682c1f3b9b9f76a6de8ea816df910715539edf1"
] |
[
"src/Matcher/matcher.py"
] |
[
"# NanoSciTracker - 2020\n# Author: Luis G. Leon Vega <luis@luisleon.me>\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# This project was sponsored by CNR-IOM\n\n\"\"\"\nDevelopment notes:\n- The position should be the most relevant and it must be as close\n as possible\n- The weights and threshold are hyperparameters\n- The position is matched here since it's a global parameter\n- The rest of features are local level parameters, they should be analysed\n within the trackers\n- The analysis is from new to all out-of-scene\n\n- The matcher will return the: not matched values in new and out and the\n new deployed trackers which matched\n\"\"\"\n\nimport copy\nimport numpy as np\n\n\nclass Matcher:\n def __init__(self, weights=None, th=None, max_dead_time=None):\n # Defaulting\n if weights is None:\n weights = {\n \"position\": -0.5,\n \"velocity\": -0.2,\n \"angle\": 0.1,\n \"histogram\": 0.3,\n \"mosse\": -0.5,\n }\n if th is None:\n th = 0.45\n if max_dead_time is None:\n max_dead_time = 100\n # Features to analyse\n self.ce_position = weights.get(\"position\", 0.0) != 0.0\n self.ce_velocity = weights.get(\"velocity\", 0.0) != 0.0\n self.ce_angle = weights.get(\"angle\", 0.0) != 0.0\n self.ce_hog = weights.get(\"hog\", 0.0) != 0.0\n self.ce_histogram = weights.get(\"histogram\", 0.0) != 0.0\n self.ce_mosse = weights.get(\"mosse\", 0.0) != 0.0\n\n # Weights\n self.w_position = weights.get(\"position\", 0.0)\n self.w_velocity = weights.get(\"velocity\", 0.0)\n self.w_angle = weights.get(\"angle\", 0.0)\n self.w_hog = weights.get(\"hog\", 0.0)\n self.w_histogram = weights.get(\"histogram\", 0.0)\n self.w_mosse = weights.get(\"mosse\", 0.0)\n\n # Probability Threshold\n self.threshold = th\n self.max_dead_time = max_dead_time\n\n def _compare_histogram(self, lhs, rhs):\n \"\"\"\n Computes the histogram probability lhs respect to rhs\n Params:\n - lhs, rhs: trackers\n Returns:\n - normalised probability (the closer, the higher)\n \"\"\"\n if not self.ce_histogram:\n return np.array([0.0])\n\n histo1 = lhs.histogram\n histo2 = rhs.histogram\n\n # Perform comparison\n return histo2.compare(histo1)\n\n def _compare_mosse(self, lhs, rhs):\n \"\"\"\n Computes the mosse probability lhs respect to rhs\n Params:\n - lhs, rhs: trackers\n Returns:\n - normalised probability (the closer, the higher)\n \"\"\"\n if not self.ce_mosse:\n return np.array([0.0])\n\n mosse1 = lhs.mosse\n mosse2 = rhs.mosse\n\n # Perform comparison\n return mosse2.compare(mosse1)\n\n def _compare_hog(self, lhs, rhs):\n \"\"\"\n Computes the hog probability lhs respect to rhs\n Params:\n - lhs, rhs: trackers\n Returns:\n - normalised probability (the closer, the higher)\n \"\"\"\n if not self.ce_hog:\n return np.array([0.0])\n\n hog1 = lhs.hog\n hog2 = rhs.hog\n\n # Perform comparison\n return hog2.compare(hog1)\n\n def _compare_velocity(self, lhs, rhs):\n \"\"\"\n Computes the velocity probability lhs respect to rhs\n Params:\n - lhs, rhs: trackers\n Returns:\n - normalised probability (the closer, the higher)\n \"\"\"\n if not self.ce_velocity and not self.ce_angle:\n return np.array([0.0, 0.0])\n\n vel1 = lhs.velocity\n vel2 = rhs.velocity\n\n # Set up the comparer\n vel2.compare_speed = self.ce_velocity\n vel2.compare_direction = self.ce_angle\n\n # Perform comparison\n features = vel2.compare(vel1)\n return features\n\n def _compare_position(self, lhs, rhs):\n \"\"\"\n Computes the position probability\n Params:\n - lhs, rhs: trackers\n Returns:\n - normalised probability (the closer, the higher)\n \"\"\"\n if not self.ce_position:\n return np.array([0.0])\n\n if lhs.roi_offset is None:\n lroi = (0, 0)\n else:\n lroi = lhs.roi_offset\n if rhs.roi_offset is None:\n rroi = (0, 0)\n else:\n rroi = rhs.roi_offset\n\n lpos = [lhs.position[0] + lroi[0], lhs.position[1] + lroi[1]]\n rpos = [rhs.position[0] + rroi[0], rhs.position[1] + rroi[1]]\n\n X = np.array(lpos)\n Y = np.array(rpos)\n # Normalise respect to the maximum distance\n normaliser = np.linalg.norm([1200, 1400])\n X = X / normaliser\n Y = Y / normaliser\n # Compute the distance\n distance = np.linalg.norm(X - Y)\n\n return np.array([distance])\n\n def filter(self, lhs, rhs):\n \"\"\"\n Cleans the lhs based on the replicates on rhs\n \"\"\"\n for elem in lhs:\n if elem in rhs:\n lhs.remove(elem)\n\n return lhs\n\n def pre_clean(self, cur_v, new_v, out_v, dead_v):\n cur_v = self.filter(cur_v, out_v)\n new_v = self.filter(new_v, out_v)\n new_v = self.filter(new_v, cur_v)\n cur_v = self.filter(cur_v, dead_v)\n return cur_v, new_v, out_v, dead_v\n\n def post_clean(self, cur_v, new_v, out_v, last_idx, frame_cnt):\n for tracker in out_v:\n try:\n cur_v.remove(tracker)\n except:\n # The scene doesn't delete the out-of-scene immediately\n continue\n\n for out_ in out_v:\n out_.dead_time += 1\n if out_.dead_time == self.max_dead_time:\n out_v.remove(out_)\n\n new_to_continue = []\n\n for cur_ in cur_v:\n # Check if it is already timed-out\n if cur_.timeout == 0:\n cur_v.remove(cur_)\n\n for new_ in new_v:\n # Check if it is already timed-out\n if new_.timeout == 0:\n continue\n\n # Skipping until having the right number of samples\n if new_.samples < new_.sample_bins:\n new_to_continue.append(new_)\n continue\n\n # Labeling\n if new_.label is None:\n last_idx += 1\n new_.label = {\"id\": last_idx, \"time\": frame_cnt}\n # Adding to the current list\n if not new_ in cur_v:\n cur_v.append(new_)\n\n new_v = list([])\n return last_idx, cur_v, new_to_continue, out_v\n\n def match(self, cur_v, new_v, out_v):\n \"\"\"\n Matcher\n Params:\n - the vectors\n Returns:\n - new_v: not matched\n - out_v: not matched\n - cur_v: updated list\n \"\"\"\n out_local = list(set(out_v))\n new_local = copy.copy(new_v)\n cur_local = copy.copy(cur_v)\n\n for new_ in new_v:\n n_old = len(out_local)\n if n_old == 0:\n break\n probabilities = np.zeros((n_old,), dtype=np.float32)\n cnt = 0\n\n if new_.samples < new_.sample_bins:\n continue\n\n # Find the probabilities of all the trackers\n for out_ in out_local:\n weights = np.zeros((6,), dtype=np.float32)\n # Compare position\n weights[0] = self.w_position * self._compare_position(new_, out_)[0]\n # Compare speed and direction\n velocity = self._compare_velocity(new_, out_)\n weights[1] = self.w_velocity * velocity[0]\n weights[2] = self.w_angle * velocity[1]\n # Compare hog\n weights[3] = self.w_hog * self._compare_hog(new_, out_)[0]\n # Compare histo\n weights[4] = self.w_histogram * self._compare_histogram(new_, out_)[0]\n # Compare mosse\n weights[5] = self.w_mosse * self._compare_mosse(new_, out_)[0]\n # Probability Superposition\n probabilities[cnt] = weights.sum()\n cnt += 1\n\n # Find the maximum (argmax)\n max_idx = np.argmax(probabilities)\n max_val = probabilities[max_idx]\n\n if max_val >= self.threshold:\n out_tracker = out_local[max_idx]\n out_tracker.timeout = 0\n if not out_tracker.label is None:\n # Accept\n new_tracker = new_\n new_tracker.label = out_tracker.label\n cur_local.append(new_tracker)\n # Remove from the lists\n new_local.remove(new_tracker)\n out_local.remove(out_tracker)\n\n return cur_local, new_local, out_local\n"
] |
[
[
"numpy.argmax",
"numpy.array",
"numpy.zeros",
"numpy.linalg.norm"
]
] |
chrwm/OSEMF_Comparison
|
[
"a44ad3ba69234e2c01588815254f00c6c5970b5e"
] |
[
"oemof/T8784O.py"
] |
[
"# -*- coding: utf-8 -*-\n\n\"\"\"\nGeneral description\n-------------------\n\nA basic example to show how to model a simple energy system with oemof.solph.\n\nThe following energy system is modeled:\n\n input/output bgas bel\n | | | |\n | | | |\n wind(FixedSource) |------------------>| |\n | | | |\n pv(FixedSource) |------------------>| |\n | | | |\n rgas(Commodity) |--------->| | |\n | | | |\n demand(Sink) |<------------------| |\n | | | |\n | | | |\n pp_gas(Transformer) |<---------| | |\n |------------------>| |\n | | | |\n storage(Storage) |<------------------| |\n |------------------>| |\n\n\nData\n----\nbasic_example.csv\n\n\nInstallation requirements\n-------------------------\n\nThis example requires the version v0.3.x of oemof. Install by:\n\n pip install 'oemof>=0.3,<0.4'\n\nOptional:\n\n pip install matplotlib\n\n\"\"\"\n\n__copyright__ = \"oemof developer group\"\n__license__ = \"GPLv3\"\n\n# ****************************************************************************\n# ********** PART 1 - Define and optimise the energy system ******************\n# ****************************************************************************\n\n###############################################################################\n# imports\n###############################################################################\n\n# Default logger of oemof\nfrom oemof.tools import logger\nfrom oemof.tools import helpers\n\nimport oemof.solph as solph\nimport oemof.outputlib as outputlib\n\nimport logging\nimport os\nimport pandas as pd\nimport pprint as pp\n\ntry:\n import matplotlib.pyplot as plt\nexcept ImportError:\n plt = None\n\n\nsolver = 'glpk' # 'glpk', 'gurobi',....\ndebug = True # Set number_of_timesteps to 3 to get a readable lp-file.\nnumber_of_time_steps = 8784\nsolver_verbose = True # show/hide solver output\n\n# initiate the logger (see the API docs for more information)\nlogger.define_logging(logfile='oemof_example.log',\n screen_level=logging.INFO,\n file_level=logging.DEBUG)\n\nlogging.info('Initialize the energy system')\ndate_time_index = pd.date_range('1/1/2016', periods=number_of_time_steps,\n freq='H')\n\nenergysystem = solph.EnergySystem(timeindex=date_time_index)\n\n# Read data file\nfilename = os.path.join(os.path.dirname(__file__), 'T8784.csv')\ndata = pd.read_csv(filename)\n\n##########################################################################\n# Create oemof object\n##########################################################################\n\nlogging.info('Create oemof objects')\n\n# The bus objects were assigned to variables which makes it easier to connect\n# components to these buses (see below).\n\n## create (commodity (fuels + electricity in OSeMOSYS) busses Brandenburg & Berlin\n# Brandenburg\nBBNaturalGas = solph.Bus(label=\"BBNaturalGas\")\nBBHardCoal = solph.Bus(label=\"BBHardCoal\")\nBBLignite = solph.Bus(label=\"BBLignite\")\nBBOil = solph.Bus(label=\"BBOil\")\nBBBiomass = solph.Bus(label=\"BBBiomass\")\nBBEL_SEC = solph.Bus(label=\"BBEL_SEC\")\nBBEL_FIN = solph.Bus(label=\"BBEL_FIN\")\n# Berlin\nBENaturalGas = solph.Bus(label=\"BENaturalGas\")\nBEHardCoal = solph.Bus(label=\"BEHardCoal\")\nBELignite = solph.Bus(label=\"BELignite\")\nBEOil = solph.Bus(label=\"BEOil\")\nBEBiomass = solph.Bus(label=\"BEBiomass\")\nBEEL_SEC = solph.Bus(label=\"BEEL_SEC\")\nBEEL_FIN = solph.Bus(label=\"BEEL_FIN\")\n\n## adding the buses to the energy system\n#Brandenburg\nenergysystem.add(BBNaturalGas, BBHardCoal, BBLignite, BBOil, BBBiomass, BBEL_SEC, BBEL_FIN)\n#Berlin\nenergysystem.add(BENaturalGas, BEHardCoal, BELignite, BEOil, BEBiomass, BEEL_SEC, BEEL_FIN)\n\n## create sources (fuel import technologies in OSeMOSYS) to represent the fuel input (annual limit)\n#Brandenburg\nenergysystem.add(solph.Source(label='rBBGAS_IMPORT', outputs={BBNaturalGas: solph.Flow()}))\nenergysystem.add(solph.Source(label='rBBHCO_IMPORT', outputs={BBHardCoal: solph.Flow()}))\nenergysystem.add(solph.Source(label='rBBLIG_IMPORT', outputs={BBLignite: solph.Flow()}))\nenergysystem.add(solph.Source(label='rBBOIL_IMPORT', outputs={BBOil: solph.Flow()}))\nenergysystem.add(solph.Source(label='rBBBIO_IMPORT', outputs={BBBiomass: solph.Flow()}))\n#Berlin\nenergysystem.add(solph.Source(label='rBEGAS_IMPORT', outputs={BENaturalGas: solph.Flow()}))\nenergysystem.add(solph.Source(label='rBEHCO_IMPORT', outputs={BEHardCoal: solph.Flow()}))\nenergysystem.add(solph.Source(label='rBELIG_IMPORT', outputs={BELignite: solph.Flow()}))\nenergysystem.add(solph.Source(label='rBEOIL_IMPORT', outputs={BEOil: solph.Flow()}))\nenergysystem.add(solph.Source(label='rBEBIO_IMPORT', outputs={BEBiomass: solph.Flow()}))\n\n## create fixed sources to represent the renewable volatiles wind, pv, run-of-river\n#Brandenburg\nenergysystem.add(solph.Source(label='BBWIND_P', outputs={BBEL_SEC: solph.Flow(\n actual_value=data['BBWIND_P'], nominal_value=6358.14, fixed=True)}))\nenergysystem.add(solph.Source(label='BBSOLPV_P', outputs={BBEL_SEC: solph.Flow(\n actual_value=data['BBSOLPV_P'], nominal_value=3205.76, fixed=True)}))\nenergysystem.add(solph.Source(label='BBRORHYD_P', outputs={BBEL_SEC: solph.Flow(\n actual_value=data['BBRORHYD_P'], nominal_value=4.86, fixed=True)}))\n#Berlin\nenergysystem.add(solph.Source(label='BEWIND_P', outputs={BEEL_SEC: solph.Flow(\n actual_value=data['BEWIND_P'], nominal_value=12.38, fixed=True)}))\nenergysystem.add(solph.Source(label='BESOLPV_P', outputs={BEEL_SEC: solph.Flow(\n actual_value=data['BESOLPV_P'], nominal_value=86.95, fixed=True)}))\n\n## create excess component for the electricity bus to allow overproduction\n#Brandenburg\nenergysystem.add(solph.Sink(label='excess_BBEL_FIN', inputs={BBEL_FIN: solph.Flow()}))\n#Berlin\nenergysystem.add(solph.Sink(label='excess_BEEL_FIN', inputs={BEEL_FIN: solph.Flow()}))\n\n## create simple sink object representing the electrical demand\n#Brandenburg\nenergysystem.add(solph.Sink(label='demand_BBEL_FIN', inputs={BBEL_FIN: solph.Flow(\n actual_value=data['demand_BBEL_FIN'], fixed=True, nominal_value=1)}))\n#Berlin\nenergysystem.add(solph.Sink(label='demand_BEEL_FIN', inputs={BEEL_FIN: solph.Flow(\n actual_value=data['demand_BEEL_FIN'], fixed=True, nominal_value=1)}))\n\n\n## create simple transformer object representing a power plants\n#Brandenburg\nenergysystem.add(solph.Transformer(\n label=\"BBNGA_P\",\n inputs={BBNaturalGas: solph.Flow()},\n outputs={BBEL_SEC: solph.Flow(nominal_value=733.3, variable_costs=19.89)},\n conversion_factors={BBEL_SEC: 0.581395349}))\n\nenergysystem.add(solph.Transformer(\n label=\"BBHCO_P\",\n inputs={BBHardCoal: solph.Flow()},\n outputs={BBEL_SEC: solph.Flow(nominal_value=0, variable_costs=11.24)},\n conversion_factors={BBEL_SEC: 0.460829493}))\n\nenergysystem.add(solph.Transformer(\n label=\"BBLIG_P\",\n inputs={BBLignite: solph.Flow()},\n outputs={BBEL_SEC: solph.Flow(nominal_value=4409, variable_costs=4.72)},\n conversion_factors={BBEL_SEC: 0.429184549}))\n\nenergysystem.add(solph.Transformer(\n label=\"BBOIL_P\",\n inputs={BBOil: solph.Flow()},\n outputs={BBEL_SEC: solph.Flow(nominal_value=333.5, variable_costs=25.17)},\n conversion_factors={BBEL_SEC: 0.383141762}))\n\nenergysystem.add(solph.Transformer(\n label=\"BBBIO_P\",\n inputs={BBBiomass: solph.Flow()},\n outputs={BBEL_SEC: solph.Flow(nominal_value=439.8, variable_costs=30.18)},\n conversion_factors={BBEL_SEC: 0.4}))\n#Berlin\nenergysystem.add(solph.Transformer(\n label=\"BENGA_P\",\n inputs={BENaturalGas: solph.Flow()},\n outputs={BEEL_SEC: solph.Flow(nominal_value=1040, variable_costs=19.89)},\n conversion_factors={BEEL_SEC: 0.581395349}))\n\nenergysystem.add(solph.Transformer(\n label=\"BEHCO_P\",\n inputs={BEHardCoal: solph.Flow()},\n outputs={BEEL_SEC: solph.Flow(nominal_value=777, variable_costs=11.24)},\n conversion_factors={BEEL_SEC: 0.460829493}))\n\nenergysystem.add(solph.Transformer(\n label=\"BELIG_P\",\n inputs={BELignite: solph.Flow()},\n outputs={BEEL_SEC: solph.Flow(nominal_value=0, variable_costs=4.72)},\n conversion_factors={BEEL_SEC: 0.429184549}))\n\nenergysystem.add(solph.Transformer(\n label=\"BEOIL_P\",\n inputs={BEOil: solph.Flow()},\n outputs={BEEL_SEC: solph.Flow(nominal_value=327, variable_costs=25.17)},\n conversion_factors={BEEL_SEC: 0.383141762}))\n\nenergysystem.add(solph.Transformer(\n label=\"BEBIO_P\",\n inputs={BEBiomass: solph.Flow()},\n outputs={BEEL_SEC: solph.Flow(nominal_value=45.19, variable_costs=30.18)},\n conversion_factors={BEEL_SEC: 0.4}))\n\n## create transmission & trade lines\n#Brandenburg\nenergysystem.add(solph.Transformer(\n label=\"BBTRANS\",\n inputs={BBEL_SEC: solph.Flow()},\n outputs={BBEL_FIN: solph.Flow(variable_costs=0)},\n conversion_factors={BBEL_FIN: 0.9}))\n# trade !TO! Brandenburg\nenergysystem.add(solph.Transformer(\n label=\"BBINT\",\n inputs={BEEL_SEC: solph.Flow()},\n outputs={BBEL_SEC: solph.Flow(nominal_value=3000, variable_costs=2)},\n conversion_factors={BBEL_SEC: 1}))\n#Berlin\nenergysystem.add(solph.Transformer(\n label=\"BETRANS\",\n inputs={BEEL_SEC: solph.Flow()},\n outputs={BEEL_FIN: solph.Flow(variable_costs=0)},\n conversion_factors={BEEL_FIN: 0.9}))\n# trade !TO! Berlin\nenergysystem.add(solph.Transformer(\n label=\"BEINT\",\n inputs={BBEL_SEC: solph.Flow()},\n outputs={BEEL_SEC: solph.Flow(nominal_value=3000, variable_costs=1)},\n conversion_factors={BEEL_SEC: 1}))\n\n## create Backstop (source) to cover demand\n#Brandenburg\nenergysystem.add(solph.Transformer(\n label=\"BBBACKSTOP_FIN\",\n outputs={BBEL_FIN: solph.Flow(nominal_value=999999999, variable_costs=1000000000)},\n conversion_factors={BBEL_FIN: 1}))\n#Berlin\nenergysystem.add(solph.Transformer(\n label=\"BEBACKSTOP_FIN\",\n outputs={BEEL_FIN: solph.Flow(nominal_value=999999999, variable_costs=1000000000)},\n conversion_factors={BEEL_FIN: 1}))\n\n\n##########################################################################\n# Optimise the energy system and plot the results\n##########################################################################\n\nlogging.info('Optimise the energy system')\n\n# initialise the operational model\nmodel = solph.Model(energysystem)\n\n# This is for debugging only. It is not(!) necessary to solve the problem and\n# should be set to False to save time and disc space in normal use. For\n# debugging the timesteps should be set to 3, to increase the readability of\n# the lp-file.\nif debug:\n filename = os.path.join(\n helpers.extend_basic_path('lp_files'), r'C:\\Users\\Winfried\\Oemof\\results\\lp\\T8784O.lp')\n logging.info('Store lp-file in {0}.'.format(filename))\n model.write(filename, io_options={'symbolic_solver_labels': True})\n\n# if tee_switch is true solver messages will be displayed\nlogging.info('Solve the optimization problem')\nmodel.solve(solver=solver, solve_kwargs={'tee': solver_verbose})\n\nlogging.info('Store the energy system with the results.')\n\n# The processing module of the outputlib can be used to extract the results\n# from the model transfer them into a homogeneous structured dictionary.\n\n# add results to the energy system to make it possible to store them.\nenergysystem.results['main'] = outputlib.processing.results(model)\nenergysystem.results['meta'] = outputlib.processing.meta_results(model)\n\n# The default path is the '.oemof' folder in your $HOME directory.\n# The default filename is 'es_dump.oemof'.\n# You can omit the attributes (as None is the default value) for testing cases.\n# You should use unique names/folders for valuable results to avoid\n# overwriting.\n\n# store energy system with results\nenergysystem.dump(dpath=None, filename=None)\n\n# ****************************************************************************\n# ********** PART 2 - Processing the results *********************************\n# ****************************************************************************\n\nlogging.info('**** The script can be divided into two parts here.')\nlogging.info('Restore the energy system and the results.')\nenergysystem = solph.EnergySystem()\nenergysystem.restore(dpath=None, filename=None)\n\n# define an alias for shorter calls below (optional)\nresults = energysystem.results['main']\n\n\n# get all variables of a specific component/bus\ncustom_storage = outputlib.views.node(results, 'storage')\nelectricity_bus = outputlib.views.node(results, 'electricity')\nwind_component = outputlib.views.node(results, 'wind')\npv = outputlib.views.node(results, 'pv')\nppgas = outputlib.views.node(results, 'pp_gas')\n\n# plot the time series (sequences) of a specific component/bus\n# if plt is not None:\n# fig, ax = plt.subplots(figsize=(10, 5))\n# electricity_bus['sequences'].plot(ax=ax, kind='line',\n# drawstyle='steps-post')\n# plt.legend(loc='upper center', prop={'size': 8}, bbox_to_anchor=(0.5, 1.3),\n# ncol=2)\n# fig.subplots_adjust(top=0.8)\n# #plt.show()\n\n\n# print the solver results\nprint('********* Meta results *********')\npp.pprint(energysystem.results['meta'])\nprint('')\n\ndict_meta = energysystem.results['meta']\n\nf = open(r\"C:\\Users\\Winfried\\Oemof\\results\\meta\\meta_T8784O.txt\",\"w\")\nf.write( str(dict_meta) )\nf.close()\n\n# ####################################################################################################\n# string_results = outputlib.processing.convert_keys_to_strings(results)\n# print(string_results.keys())\n\n# make the dict \"electricity_bus\" to dataframe \"df_electricity_bus\" and print to csv\nnode_BBEL_SEC = outputlib.views.node(results, 'BBEL_SEC')\ndf_node_BBEL_SEC = node_BBEL_SEC['sequences']\n\nnode_BBEL_FIN = outputlib.views.node(results, 'BBEL_FIN')\ndf_node_BBEL_FIN = node_BBEL_FIN['sequences']\n\nnode_BEEL_SEC = outputlib.views.node(results, 'BEEL_SEC')\ndf_node_BEEL_SEC = node_BEEL_SEC['sequences']\n\nnode_BEEL_FIN = outputlib.views.node(results, 'BEEL_FIN')\ndf_node_BEEL_FIN = node_BEEL_FIN['sequences']\n\npd.concat([\n pd.concat([df_node_BBEL_SEC, df_node_BBEL_FIN,df_node_BEEL_SEC, df_node_BEEL_FIN], axis=1)]).to_csv(r'C:\\Users\\Winfried\\Oemof\\results\\T8784O_EL.csv')\n\n\n\n"
] |
[
[
"pandas.concat",
"pandas.read_csv",
"pandas.date_range"
]
] |
pofenghsieh/LPRNet_Pytorch
|
[
"b1a8c5f0a171962bb7d8b72f9a7c0bfe5faa9f61"
] |
[
"train_LPRNet.py"
] |
[
"# -*- coding: utf-8 -*-\n# /usr/bin/env/python3\n\n'''\nPytorch implementation for LPRNet.\nAuthor: aiboy.wei@outlook.com .\n'''\n\nfrom data.load_data import CHARS, CHARS_DICT, LPRDataLoader\nfrom model.LPRNet import build_lprnet\n# import torch.backends.cudnn as cudnn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom torch.utils.data import *\nfrom torch import optim\nimport torch.nn as nn\nimport numpy as np\nimport argparse\nimport torch\nimport time\nimport os\n\ndef sparse_tuple_for_ctc(T_length, lengths):\n input_lengths = []\n target_lengths = []\n\n for ch in lengths:\n input_lengths.append(T_length)\n target_lengths.append(ch)\n\n return tuple(input_lengths), tuple(target_lengths)\n\ndef adjust_learning_rate(optimizer, cur_epoch, base_lr, lr_schedule):\n \"\"\"\n Sets the learning rate\n \"\"\"\n lr = 0\n for i, e in enumerate(lr_schedule):\n if cur_epoch < e:\n lr = base_lr * (0.1 ** i)\n break\n if lr == 0:\n lr = base_lr\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n return lr\n\ndef get_parser():\n parser = argparse.ArgumentParser(description='parameters to train net')\n parser.add_argument('--max_epoch', default=15, help='epoch to train the network')\n parser.add_argument('--img_size', default=[94, 24], help='the image size')\n parser.add_argument('--train_img_dirs', default=\"~/workspace/trainMixLPR\", help='the train images path')\n parser.add_argument('--test_img_dirs', default=\"~/workspace/testMixLPR\", help='the test images path')\n parser.add_argument('--dropout_rate', default=0.5, help='dropout rate.')\n parser.add_argument('--learning_rate', default=0.1, help='base value of learning rate.')\n parser.add_argument('--lpr_max_len', default=8, help='license plate number max length.')\n parser.add_argument('--train_batch_size', default=128, help='training batch size.')\n parser.add_argument('--test_batch_size', default=120, help='testing batch size.')\n parser.add_argument('--phase_train', default=True, type=bool, help='train or test phase flag.')\n parser.add_argument('--num_workers', default=8, type=int, help='Number of workers used in dataloading')\n parser.add_argument('--cuda', default=True, type=bool, help='Use cuda to train model')\n parser.add_argument('--resume_epoch', default=0, type=int, help='resume iter for retraining')\n parser.add_argument('--save_interval', default=2000, type=int, help='interval for save model state dict')\n parser.add_argument('--test_interval', default=2000, type=int, help='interval for evaluate')\n parser.add_argument('--momentum', default=0.9, type=float, help='momentum')\n parser.add_argument('--weight_decay', default=2e-5, type=float, help='Weight decay for SGD')\n parser.add_argument('--lr_schedule', default=[4, 8, 12, 14, 16], help='schedule for learning rate.')\n parser.add_argument('--save_folder', default='./weights/', help='Location to save checkpoint models')\n # parser.add_argument('--pretrained_model', default='./weights/Final_LPRNet_model.pth', help='pretrained base model')\n parser.add_argument('--pretrained_model', default='', help='pretrained base model')\n\n args = parser.parse_args()\n\n return args\n\ndef collate_fn(batch):\n imgs = []\n labels = []\n lengths = []\n for _, sample in enumerate(batch):\n img, label, length = sample\n imgs.append(torch.from_numpy(img))\n labels.extend(label)\n lengths.append(length)\n labels = np.asarray(labels).flatten().astype(np.int)\n\n return (torch.stack(imgs, 0), torch.from_numpy(labels), lengths)\n\ndef train():\n args = get_parser()\n\n T_length = 18 # args.lpr_max_len\n epoch = 0 + args.resume_epoch\n loss_val = 0\n\n if not os.path.exists(args.save_folder):\n os.mkdir(args.save_folder)\n\n lprnet = build_lprnet(lpr_max_len=args.lpr_max_len, phase=args.phase_train, class_num=len(CHARS), dropout_rate=args.dropout_rate)\n device = torch.device(\"cuda:0\" if args.cuda else \"cpu\")\n lprnet.to(device)\n print(\"Successful to build network!\")\n\n # load pretrained model\n if args.pretrained_model:\n lprnet.load_state_dict(torch.load(args.pretrained_model))\n print(\"load pretrained model successful!\")\n else:\n def xavier(param):\n nn.init.xavier_uniform(param)\n\n def weights_init(m):\n for key in m.state_dict():\n if key.split('.')[-1] == 'weight':\n if 'conv' in key:\n nn.init.kaiming_normal_(m.state_dict()[key], mode='fan_out')\n if 'bn' in key:\n m.state_dict()[key][...] = xavier(1)\n elif key.split('.')[-1] == 'bias':\n m.state_dict()[key][...] = 0.01\n\n lprnet.backbone.apply(weights_init)\n lprnet.container.apply(weights_init)\n print(\"initial net weights successful!\")\n\n # define optimizer\n # optimizer = optim.SGD(lprnet.parameters(), lr=args.learning_rate,\n # momentum=args.momentum, weight_decay=args.weight_decay)\n optimizer = optim.RMSprop(lprnet.parameters(), lr=args.learning_rate, alpha = 0.9, eps=1e-08,\n momentum=args.momentum, weight_decay=args.weight_decay)\n train_img_dirs = os.path.expanduser(args.train_img_dirs)\n test_img_dirs = os.path.expanduser(args.test_img_dirs)\n train_dataset = LPRDataLoader(train_img_dirs.split(','), args.img_size, args.lpr_max_len)\n test_dataset = LPRDataLoader(test_img_dirs.split(','), args.img_size, args.lpr_max_len)\n\n epoch_size = len(train_dataset) // args.train_batch_size\n max_iter = args.max_epoch * epoch_size\n\n ctc_loss = nn.CTCLoss(blank=len(CHARS)-1, reduction='mean') # reduction: 'none' | 'mean' | 'sum'\n\n if args.resume_epoch > 0:\n start_iter = args.resume_epoch * epoch_size\n else:\n start_iter = 0\n\n for iteration in range(start_iter, max_iter):\n if iteration % epoch_size == 0:\n # create batch iterator\n batch_iterator = iter(DataLoader(train_dataset, args.train_batch_size, shuffle=True, num_workers=args.num_workers, collate_fn=collate_fn))\n loss_val = 0\n epoch += 1\n\n if iteration !=0 and iteration % args.save_interval == 0:\n torch.save(lprnet.state_dict(), args.save_folder + 'LPRNet_' + '_iteration_' + repr(iteration) + '.pth')\n\n if (iteration + 1) % args.test_interval == 0:\n Greedy_Decode_Eval(lprnet, test_dataset, args)\n # lprnet.train() # should be switch to train mode\n\n start_time = time.time()\n # load train data\n images, labels, lengths = next(batch_iterator)\n # labels = np.array([el.numpy() for el in labels]).T\n # print(labels)\n # get ctc parameters\n input_lengths, target_lengths = sparse_tuple_for_ctc(T_length, lengths)\n # update lr\n lr = adjust_learning_rate(optimizer, epoch, args.learning_rate, args.lr_schedule)\n\n if args.cuda:\n images = Variable(images, requires_grad=False).cuda()\n labels = Variable(labels, requires_grad=False).cuda()\n else:\n images = Variable(images, requires_grad=False)\n labels = Variable(labels, requires_grad=False)\n\n # forward\n logits = lprnet(images)\n log_probs = logits.permute(2, 0, 1) # for ctc loss: T x N x C\n # print(labels.shape)\n log_probs = log_probs.log_softmax(2).requires_grad_()\n # log_probs = log_probs.detach().requires_grad_()\n # print(log_probs.shape)\n # backprop\n optimizer.zero_grad()\n loss = ctc_loss(log_probs, labels, input_lengths=input_lengths, target_lengths=target_lengths)\n if loss.item() == np.inf:\n continue\n loss.backward()\n optimizer.step()\n loss_val += loss.item()\n end_time = time.time()\n if iteration % 20 == 0:\n print('Epoch:' + repr(epoch) + ' || epochiter: ' + repr(iteration % epoch_size) + '/' + repr(epoch_size)\n + '|| Totel iter ' + repr(iteration) + ' || Loss: %.4f||' % (loss.item()) +\n 'Batch time: %.4f sec. ||' % (end_time - start_time) + 'LR: %.8f' % (lr))\n # final test\n print(\"Final test Accuracy:\")\n Greedy_Decode_Eval(lprnet, test_dataset, args)\n\n # save final parameters\n torch.save(lprnet.state_dict(), args.save_folder + 'Final_LPRNet_model.pth')\n\ndef Greedy_Decode_Eval(Net, datasets, args):\n # TestNet = Net.eval()\n epoch_size = len(datasets) // args.test_batch_size\n batch_iterator = iter(DataLoader(datasets, args.test_batch_size, shuffle=True, num_workers=args.num_workers, collate_fn=collate_fn))\n\n Tp = 0\n Tn_1 = 0\n Tn_2 = 0\n t1 = time.time()\n for i in range(epoch_size):\n # load train data\n images, labels, lengths = next(batch_iterator)\n start = 0\n targets = []\n for length in lengths:\n label = labels[start:start+length]\n targets.append(label)\n start += length\n targets = np.array([el.numpy() for el in targets])\n\n if args.cuda:\n images = Variable(images.cuda())\n else:\n images = Variable(images)\n\n # forward\n prebs = Net(images)\n # greedy decode\n prebs = prebs.cpu().detach().numpy()\n preb_labels = list()\n for i in range(prebs.shape[0]):\n preb = prebs[i, :, :]\n preb_label = list()\n for j in range(preb.shape[1]):\n preb_label.append(np.argmax(preb[:, j], axis=0))\n no_repeat_blank_label = list()\n pre_c = preb_label[0]\n for c in preb_label: # dropout repeate label and blank label\n if (pre_c == c) or (c == len(CHARS) - 1):\n if c == len(CHARS) - 1:\n pre_c = c\n continue\n no_repeat_blank_label.append(c)\n pre_c = c\n preb_labels.append(no_repeat_blank_label)\n for i, label in enumerate(preb_labels):\n if len(label) != len(targets[i]):\n Tn_1 += 1\n continue\n if (np.asarray(targets[i]) == np.asarray(label)).all():\n Tp += 1\n else:\n Tn_2 += 1\n\n Acc = Tp * 1.0 / (Tp + Tn_1 + Tn_2)\n print(\"[Info] Test Accuracy: {} [{}:{}:{}:{}]\".format(Acc, Tp, Tn_1, Tn_2, (Tp+Tn_1+Tn_2)))\n t2 = time.time()\n print(\"[Info] Test Speed: {}s 1/{}]\".format((t2 - t1) / len(datasets), len(datasets)))\n\n\nif __name__ == \"__main__\":\n train()\n"
] |
[
[
"torch.load",
"numpy.asarray",
"torch.from_numpy",
"torch.autograd.Variable",
"numpy.argmax",
"torch.device",
"torch.nn.init.xavier_uniform",
"torch.stack"
]
] |
bsl546/energym
|
[
"0133ca7a19d21352a427e1913755e1ebf6fd8bb6"
] |
[
"tests/test_env/test_modelica_FMU.py"
] |
[
"import numpy as np\nimport pandas as pd\nimport platform\nimport time\n\nimport matplotlib.pyplot as plt\n\nimport energym\n\n# ============================================================================\n# Constants\n# ============================================================================\nop_sys = platform.system().lower()\n\nT0 = 273.15 # [K] Zero degree Celsius in Kelvin\ncp = 4180 # [J/(kg K)] Water specific heat capacity\n\n\n# ============================================================================\n# Plot Functions\n# ============================================================================\n\n\ndef set_plot_labels(ax):\n ax[0, 0].set_ylabel(\"I [W/m2]\")\n ax[1, 0].set_ylabel(\"P [kW]\")\n ax[2, 0].set_ylabel(\"T [°C]\")\n ax[0, 1].set_ylabel(\"-\")\n ax[1, 1].set_ylabel(\"mf [kg/s]\")\n ax[2, 1].set_ylabel(\"-\")\n\n\ndef plot_sh_rad(record, model_name):\n row, col = 3, 2\n fig, ax = plt.subplots(row, col, sharex=True, num=model_name)\n\n record[\"rad_Q\"] = (\n (record[\"temSup.T\"] - record[\"temRet.T\"]) * record[\"rad.m_flow\"] * cp\n )\n (\n record[\n [\n \"weaBus.HDifHor\",\n \"weaBus.HDirNor\",\n \"weaBus.HGloHor\",\n \"weaBus.HHorIR\",\n \"sunRad.y\",\n ]\n ]\n ).plot(ax=ax[0, 0])\n (\n record[\n [\n \"preHea.Q_flow\",\n \"sunHea.Q_flow\",\n \"heaPum.QEva_flow\",\n \"heaPum.QCon_flow\",\n \"heaPum.P\",\n \"rad.Q_flow\",\n \"rad_Q\",\n ]\n ].abs()\n * 1e-3\n ).plot(ax=ax[1, 0])\n (\n record[\n [\n \"heaPum.TEvaAct\",\n \"heaPum.TConAct\",\n \"temRet.T\",\n \"temSup.T\",\n \"temRoo.T\",\n \"TOut.T\",\n ]\n ]\n - T0\n ).plot(ax=ax[2, 0])\n record[[\"heaPum.COP\", \"heaPum.COPCar\"]].plot(ax=ax[0, 1])\n record[[\"rad.m_flow\"]].plot(ax=ax[1, 1])\n record[[\"u\"]].plot(ax=ax[2, 1])\n set_plot_labels(ax)\n # plt.show()\n\n\ndef plot_sh_rsla(record, model_name):\n row, col = 3, 2\n fig, ax = plt.subplots(row, col, sharex=True, num=model_name)\n\n record[\"rad_Q\"] = (\n (record[\"temSup.T\"] - record[\"temRet.T\"]) * record[\"sla.m_flow\"] * cp\n )\n (\n record[\n [\n \"weaBus.HDifHor\",\n \"weaBus.HDirNor\",\n \"weaBus.HGloHor\",\n \"weaBus.HHorIR\",\n \"sunRad.y\",\n ]\n ]\n ).plot(ax=ax[0, 0])\n (\n record[\n [\n \"preHea.Q_flow\",\n \"sunHea.Q_flow\",\n \"heaPum.QEva_flow\",\n \"heaPum.QCon_flow\",\n \"heaPum.P\",\n \"sla.QTot\",\n ]\n ].abs()\n * 1e-3\n ).plot(ax=ax[1, 0])\n (\n record[\n [\n \"heaPum.TEvaAct\",\n \"heaPum.TConAct\",\n \"temRet.T\",\n \"temSup.T\",\n \"sla.heatPortEmb[1].T\",\n \"temRoo.T\",\n \"TOut.T\",\n ]\n ]\n - T0\n ).plot(ax=ax[2, 0])\n record[[\"heaPum.COP\", \"heaPum.COPCar\"]].plot(ax=ax[0, 1])\n record[[\"sla.m_flow\"]].plot(ax=ax[1, 1])\n record[[\"u\"]].plot(ax=ax[2, 1])\n set_plot_labels(ax)\n # plt.show()\n\n\ndef plot_sh_slab(record, model_name):\n row, col = 3, 2\n fig, ax = plt.subplots(row, col, sharex=True, num=model_name)\n\n record[\"slab_Q\"] = (\n (record[\"temSup.T\"] - record[\"temRet.T\"]) * record[\"sla.m_flow\"] * cp\n )\n (\n record[\n [\n \"weaBus.HDifHor\",\n \"weaBus.HDirNor\",\n \"weaBus.HGloHor\",\n \"weaBus.HHorIR\",\n \"sunRad.y\",\n ]\n ]\n ).plot(ax=ax[0, 0])\n (\n record[\n [\n \"preHea.Q_flow\",\n \"sunHea.Q_flow\",\n \"heaPum.QEva_flow\",\n \"heaPum.QCon_flow\",\n \"heaPum.P\",\n \"sla.surf_a.Q_flow\",\n \"sla.surf_b.Q_flow\",\n \"slab_Q\",\n ]\n ].abs()\n * 1e-3\n ).plot(ax=ax[1, 0])\n (\n record[\n [\n \"heaPum.TEvaAct\",\n \"heaPum.TConAct\",\n \"temRet.T\",\n \"temSup.T\",\n \"sla.surf_a.T\",\n \"sla.surf_b.T\",\n \"temRoo.T\",\n \"TOut.T\",\n ]\n ]\n - T0\n ).plot(ax=ax[2, 0])\n record[[\"heaPum.COP\", \"heaPum.COPCar\"]].plot(ax=ax[0, 1])\n record[[\"sla.m_flow\"]].plot(ax=ax[1, 1])\n record[[\"u\"]].plot(ax=ax[2, 1])\n set_plot_labels(ax)\n # plt.show()\n\n\ndef plot_tank_sh_rsla(record, model_name):\n row, col = 3, 1\n fig, ax = plt.subplots(row, col, sharex=True, num=model_name)\n\n (record[[\"heaPum.P\", \"heaPum.QCon_flow\", \"sla.QTot\"]].abs() * 1e-3).plot(ax=ax[0])\n (record[[\"tanSH.heaPorSid.T\", \"sla.heatPortEmb[1].T\",\n \"temRoo.T\", \"TOut.T\"]] - T0).plot(ax=ax[1])\n record[[\"uHP\", \"uRSla\"]].plot(ax=ax[row - 1])\n ax[0].set_ylabel(\"P [kW]\")\n ax[1].set_ylabel(\"T [°C]\")\n ax[2].set_ylabel(\"inputs\")\n # plt.show()\n\n\ndef select_plot_model(model_name: str):\n if \"SimpleHouseRad\" in model_name:\n func = plot_sh_rad\n elif \"SimpleHouseRSla\" in model_name or \"SwissHouseRSlaW2W\" in model_name or \"SwissHouseRSlaA2W\" in model_name:\n func = plot_sh_rsla\n elif \"SimpleHouseSlab\" in model_name:\n func = plot_sh_slab\n elif \"SwissHouseRSlaTank\" in model_name:\n func = plot_tank_sh_rsla\n else:\n print(\"no plot function available\")\n func = None\n return func\n\n\n# ============================================================================\n# Model and control\n# ============================================================================\n\n\ndef model_param(env, model_name):\n \"\"\"Model parameters configuration\"\"\"\n param_fmu = {\n # \"P_nominal\": 1000,\n \"COP_nominal\": 3,\n # \"therm_cond_G\": 100,\n # \"heat_capa_C\": 40e6,\n # \"TCon_nominal\": T0 + 30,\n # \"room_vol_V\": 750,\n }\n # get_param = env.get_variable_data([\"P_nominal\"])\n # param_fmu[\"P_nominal\"] = get_param[\"P_nominal\"]*0.5\n\n param_read = [\n \"P_nominal\", \"COP_nominal\",\n \"therm_cond_G\", \"heat_capa_C\",\n ]\n\n if \"SimpleHouseRad\" in model_name:\n param_fmu = dict(**param_fmu, **{\n # \"TRadSup_nominal\": T0 + 40,\n # \"TRadRet_nominal\": T0 + 35,\n })\n param_read.extend([\n \"Q_flow_nominal\",\n \"mHeaPum_flow_nominal\",\n ])\n elif \"SimpleHouseRSla\" in model_name or \"SwissHouseRSlaW2W\" in model_name or \"SwissHouseRSlaA2W\" in model_name:\n param_fmu = dict(**param_fmu, **{\n # \"slab_surf\": 200,\n })\n param_read.extend([\n \"Q_flow_nominal\",\n \"mHeaPum_flow_nominal\",\n \"slab_surf\",\n ])\n elif \"SimpleHouseSlab\" in model_name:\n param_fmu = dict(**param_fmu, **{\n # \"slab_surf\": 200,\n # \"slab_G_Abo\": 1e3, #10e3,\n # \"slab_G_Bel\": 1e3, #120,\n })\n param_read.extend([\n \"Q_flow_nominal\",\n \"mHeaPum_flow_nominal\",\n \"slab_G_Abo\", \"slab_G_Bel\",\n \"slab_surf\",\n ])\n else:\n # param_fmu = {}\n # param_read = []\n pass\n\n print(\"old param:\", env.get_variable_data(param_fmu))\n env.set_model_variables(list(param_fmu.keys()), param_fmu.values())\n print(\"new param:\", env.get_variable_data(param_fmu))\n print(\"read param:\", env.get_variable_data(param_read))\n\n\ndef control_param(model_name):\n \"\"\"Feedback controller parameters\"\"\"\n if \"Tank\" in model_name:\n ctrl = {\n \"inputs\": [\"uHP\", \"uRSla\"],\n \"sensor\": [\"tanSH.heaPorSid.T\", \"temRoo.T\"],\n \"ref\": [T0 + 40, T0 + 21],\n \"kp\": [0.1, 0.04],\n \"bound\": [[0, 1], [0, 1]]\n }\n elif \"TankDhw\" in model_name:\n ctrl = {\n \"inputs\": [\"uHP\", \"uRSla\"],\n \"sensor\": [\"tanSH.heaPorSid.T\", \"temRoo.T\"],\n \"ref\": [T0 + 40, T0 + 21],\n \"kp\": [0.1, 0.04],\n \"bound\": [[0, 1], [0, 1]]\n }\n else:\n ctrl = {\n \"inputs\": [\"u\"],\n \"sensor\": [\"temRoo.T\"],\n \"ref\": [T0 + 20],\n \"kp\": [0.5],\n \"bound\": [[0, 1]]\n }\n return ctrl\n\n\ndef controller(meas, ref, kp, bnd):\n uval = kp * (ref - meas)\n uval = np.clip(uval, bnd[0], bnd[1])\n return uval\n\n\ndef run_model(model_name: str):\n env = energym.make(model_name)\n print(model_name)\n # Init data record\n N = round((env.stop_time - env.start_time) / env.step_size)\n outputs = env.get_outputs_names()\n record = pd.DataFrame(\n np.zeros((N, len(outputs) + 1)),\n index=np.arange(N) * env.step_size,\n columns=[\"u\"] + outputs,\n )\n\n model_param(env, model_name)\n ctrl = control_param(model_name)\n\n # Get states\n out = env.get_variable_data(outputs)\n\n # Run feedback loop\n tic = time.time()\n for dt in record.index:\n # Get control law\n uval = [[controller(\n out[ctrl[\"sensor\"][n]], ctrl[\"ref\"][n], ctrl[\"kp\"][n], ctrl[\"bound\"][n]\n )] for n in range(len(ctrl[\"inputs\"]))]\n\n # DoStep\n out = env.step(dict(zip(ctrl[\"inputs\"], uval)))\n\n # Save into DataFrame\n record.loc[dt, ctrl[\"inputs\"]] = [val[0] for val in uval]\n record.loc[dt, outputs] = [out[key] for key in outputs]\n\n toc = time.time()\n print(\"Elapsed time: %.2f s\" % (toc - tic))\n\n return record, env\n\n\ndef test_models():\n # List of models to be tested\n # to_test = [\"SimpleHouseRad-v0\", \"SimpleHouseSlab-v0\", \"SimpleHouseRSla-v0\"]\n # to_test = [\"SimpleHouseRSla-v0\", \"SwissHouseRSlaW2W-v0\", \"SwissHouseRSlaA2W-v0\"]\n to_test = [\"SimpleHouseRSla-v0\", \"SwissHouseRSlaW2W-v0\", \"SwissHouseRSlaA2W-v0\", \"SwissHouseRSlaTank-v0\"]\n # to_test = [\"SwissHouseRSlaTank-v0\", \"SwissHouseRSlaTankDhw-v0\"]\n records, envs = {}, {}\n\n for model_name in to_test:\n record, env = run_model(model_name)\n assert record.to_numpy().sum() != 0\n records[model_name] = record\n envs[model_name] = env\n # plot\n plot_fun = select_plot_model(model_name)\n plot_fun(record, model_name)\n\n return records, envs\n\n\n# ============================================================================\n# Main\n# ============================================================================\nif __name__ == \"__main__\":\n plt.close(\"all\")\n records, envs = test_models()\n"
] |
[
[
"numpy.arange",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.close",
"numpy.clip"
]
] |
kuechenrole/tidal_melting
|
[
"b71eec6aa502e1eb0570e9fc4a9d0170aa4dc24b"
] |
[
"src/preprocessing/grid/smooth_grid.py"
] |
[
"\n# coding: utf-8\n\n# In[1]:\n\n\nimport os\nimport sys\nimport bathy_smoother\nimport xarray as xr\nsrc_dir = os.environ.get('srcdir')\nsys.path.append(src_dir)\nfrom features.log_progress import log_progress\nfrom features.mask_roms_uvp import uvp_masks\nimport numpy as np\n\n\n# In[ ]:\n\n\ngrd_path = os.path.join(os.environ.get(\"intdir\"),'waom1_grd_patched.nc')\nprint('loading grid: ',grd_path)\ngrd = xr.open_dataset(grd_path)\n\n#mask ostock for smoothing eta_min, eta_max, xi_min, xi_max\n#vostock = [2000,2750,3750,4750]\nvostock = [1100,1250,2000,2300]\n\nout_path = os.path.join(os.environ.get('prodir'),'waom1_grd.nc')\n\nrx0=0.3\nnb_smooth=50\n\n# In[4]:\n\n\ndef smoothing_PlusMinus_rx0(MSK, Hobs, rx0max, AreaMatrix,rounds):\n \"\"\"\n This program use the Mellor-Ezer-Oey method (Mellor et al., 1994).\n The bathymetry is optimized for a given rx0 factor by doing a sequence\n of increase/decrease at adjacent cells.\n\n Usage:\n RetBathy, HmodifVal, ValueFct = smoothing_PlusMinus_rx0(MSK, Hobs, rx0max, AreaMatrix)\n\n ---MSK(eta_rho,xi_rho) is the mask of the grid\n 1 for sea\n 0 for land\n ---Hobs(eta_rho,xi_rho) is the raw depth of the grid\n ---rx0max is the target rx0 roughness factor\n ---AreaMatrix(eta_rho,xi_rho) is the matrix of areas at\n rho-points.\n \"\"\"\n\n eta_rho, xi_rho = Hobs.shape\n\n ListNeigh = np.array([[1, 0],\n [0, 1],\n [-1, 0],\n [0, -1]])\n\n RetBathy = Hobs.copy()\n\n HmodifVal = 0\n TheMultiplier = (1 - rx0max) / (1 + rx0max)\n tol = 0.000001\n ValueFct = 0\n\n #while(True):\n for round in log_progress(range(rounds),name='steps'):\n eta=[]\n xi=[]\n IsFinished = 1\n for iEta in range(eta_rho):\n for iXi in range(xi_rho):\n if (MSK[iEta, iXi] == 1):\n Area = AreaMatrix[iEta, iXi]\n for ineigh in range(4):\n iEtaN = iEta + ListNeigh[ineigh,0]\n iXiN = iXi + ListNeigh[ineigh,1]\n if (iEtaN <= eta_rho-1 and iEtaN >= 0 and iXiN <= xi_rho-1 and iXiN >= 0 and MSK[iEtaN,iXiN] == 1):\n AreaN = AreaMatrix[iEtaN,iXiN]\n LowerBound = RetBathy[iEtaN,iXiN] * TheMultiplier\n if ((RetBathy[iEta,iXi] - LowerBound) < -tol):\n IsFinished = 0\n h = (TheMultiplier * RetBathy[iEtaN,iXiN] - RetBathy[iEta,iXi]) / (AreaN + TheMultiplier * Area)\n RetBathy[iEta,iXi] = RetBathy[iEta,iXi] + AreaN * h\n RetBathy[iEtaN,iXiN] = RetBathy[iEtaN,iXiN] - Area * h\n HmodifVal = HmodifVal + abs(h)\n ValueFct = ValueFct + abs(h) * (Area + AreaN)\n eta.append(iEta)\n xi.append(iXi)\n \n #H = AreaMatrix * Hobs * MSK\n #TheBathymetry1 = H.sum()\n #H = AreaMatrix * RetBathy * MSK\n #TheBathymetry2 = H.sum()\n #DeltaBathymetry = TheBathymetry1 - TheBathymetry2\n #print('DeltaBathymetry = ', DeltaBathymetry) \n if (IsFinished == 1):\n break\n H = AreaMatrix * Hobs * MSK\n TheBathymetry1 = H.sum()\n H = AreaMatrix * RetBathy * MSK\n TheBathymetry2 = H.sum()\n DeltaBathymetry = TheBathymetry1 - TheBathymetry2\n print('DeltaBathymetry = ', DeltaBathymetry)\n\n return RetBathy, HmodifVal, ValueFct,eta,xi\n\n# In[82]:\n\nprint('calculate Roughness')\nRoughMat_old = bathy_smoother.bathy_tools.RoughnessMatrix(grd.h.values,grd.mask_rho.values)\nprint('Max Roughness value is: ', RoughMat_old.max())\n\n\n# In[83]:\n\n\nArea = 1/(grd.pm.values*grd.pn.values)\nmask = grd.mask_rho.values\nmask[vostock[0]:vostock[1],vostock[2]:vostock[3]] = 0\n\n\n# In[84]:\n\nprint('smooth to rx0 <=',rx0,' with max iterations: ',nb_smooth)\nRetBathy, HmodifVal, ValueFct,eta,xi = smoothing_PlusMinus_rx0(mask,grd.h.values,rx0,Area,nb_smooth)\n\n\n# In[ ]:\n\n\nRoughMat = bathy_smoother.bathy_tools.RoughnessMatrix(RetBathy,grd.mask_rho.values)\nprint('Max Roughness value is: ', RoughMat.max())\n\n# In[ ]:\n\n\nbed = RetBathy.copy()\nice = grd.zice.values.copy()\n#set bed minimum depth to 10 cm\nbed[bed<0.1]= 0.1\n#set ice draft at these places to zero \nice[bed<0.1] = 0.0\n\n#set water column thickness to a small positive value (ROMS don't like when bed = ice draft)\nwct = (bed+ice).copy()\nice[wct<=0] = -bed[wct<=0] + 0.1\n\ngrd.h.values = bed\ngrd.zice.values = ice\n\n\nmask = np.ones_like(bed) \nmask[(wct<20.0)]=0\nmask[grd.mask_rho==0]=0\n\numask,vmask,pmask = uvp_masks(mask)\n\ngrd.mask_rho.values = mask\ngrd.mask_u.values = umask\ngrd.mask_v.values = vmask\ngrd.mask_psi.values = pmask\n\n# In[ ]:\n\n\nprint(\"write smoothed bathy to \",out_path)\ngrd.to_netcdf(out_path)\n\n"
] |
[
[
"numpy.array",
"numpy.ones_like"
]
] |
Michaliv/IML.HUJI
|
[
"ff1bd564cc0575dde6da581c810e847c9cd20f27"
] |
[
"exercises/house_price_prediction.py"
] |
[
"import math\n\nfrom IMLearn.utils import split_train_test\nfrom IMLearn.learners.regressors import LinearRegression\n\nfrom typing import NoReturn\nimport numpy as np\nimport pandas as pd\nimport plotly.graph_objects as go\nimport plotly.express as px\nimport plotly.io as pio\npio.templates.default = \"simple_white\"\n\n\ndef load_data(filename: str):\n \"\"\"\n Load house prices dataset and preprocess data.\n Parameters\n ----------\n filename: str\n Path to house prices dataset\n\n Returns\n -------\n Design matrix and response vector (prices) - either as a single\n DataFrame or a Tuple[DataFrame, Series]\n \"\"\"\n houseDataFrame = pd.read_csv(filename) # read data set\n\n remove_invalid_values(houseDataFrame) # remove invalid data\n\n # replace each none value with the mean of this feature:\n for feature in houseDataFrame:\n meanOfFeature = houseDataFrame[feature].mean()\n houseDataFrame[feature].replace(np.nan, meanOfFeature, inplace=True)\n\n # add more features:\n add_recently_renewed_feature(houseDataFrame)\n add_number_of_people_feature(houseDataFrame)\n\n # generate dummy data for zipcode\n houseDataFrame = pd.get_dummies(houseDataFrame, prefix='zipcode',\n columns=['zipcode'])\n\n # add intercept\n houseDataFrame.insert(0, 'intercept', 1, True)\n\n return houseDataFrame.drop(\"price\", 1), houseDataFrame.price\n\ndef remove_invalid_values(houseDataFrame):\n \"\"\"\n removes the invalid values from the data frame\n \"\"\"\n # remove id, date, lat, long (entire feature)\n houseDataFrame.drop([\"id\", \"long\", \"date\", \"lat\"], axis=1, inplace=True)\n\n # remove prices that have to be really positive: (larger than 0)\n removeNegOrZero = ['price', 'sqft_living', 'sqft_living15', 'floors',\n 'sqft_above', 'yr_built']\n for feature in removeNegOrZero:\n houseDataFrame.drop(houseDataFrame[houseDataFrame[feature] <= 0].index,\n inplace=True)\n\n # remove prices that have to be non-negative: (could be 0)\n removeNeg = ['bathrooms', 'bedrooms', 'sqft_lot', 'sqft_lot15']\n for feature in removeNeg:\n houseDataFrame.drop(houseDataFrame[houseDataFrame[feature] < 0].index,\n inplace=True)\n\n # remove invalid values\n houseDataFrame.drop(houseDataFrame[houseDataFrame[\"bedrooms\"] >= 15].index,\n inplace=True)\n houseDataFrame.drop(houseDataFrame[houseDataFrame[\"sqft_living\"] >=\n 12000].index,\n inplace=True)\n houseDataFrame.drop(houseDataFrame[houseDataFrame[\"sqft_lot\"] >=\n 1300000].index,\n inplace=True)\n houseDataFrame.drop(houseDataFrame[houseDataFrame[\"sqft_lot15\"] >=\n 500000].index,\n inplace=True)\n\ndef add_recently_renewed_feature(houseDataFrame):\n \"\"\"\n adds to the data set a binary feature of recently renewed-\n if the house was built in the last 10 years or renewed in the last 10 years\n the index will have 1, else- 0\n \"\"\"\n conditions = [(houseDataFrame['yr_built'] > 2005) |\n (houseDataFrame['yr_renovated'] > 2005),\n (houseDataFrame['yr_built'] <= 2005) &\n (houseDataFrame['yr_renovated'] <= 2005)]\n values = [1, 0]\n\n houseDataFrame['recently_renewed'] = np.select(conditions, values)\n\ndef add_number_of_people_feature(houseDataFrame):\n \"\"\"\n adds to the data set a feature of number of people who can live in the\n house- we assume that num of bedrooms = num of people who can live in the\n house, but- if the sqft of the house is bigger than the average, the\n house can accomadte more- so we add to the original number the dis\n between the actual sqft of house and the average sqft (meaning the value\n of how bigger the house is than usual), divided by the squareFitPerPerson.\n If the house is equal in size to normal/smaller than average, we don't\n change the value\n \"\"\"\n # calculate the mean value of sqft above and the mean value of bedrooms:\n meanOfSqftAbove = math.ceil(houseDataFrame['sqft_above'].mean())\n meanOfNumBedrooms = houseDataFrame['bedrooms'].mean()\n\n # calculate the sf per person:\n squareFitPerPerson = meanOfSqftAbove // meanOfNumBedrooms\n\n conditions = [(houseDataFrame['sqft_above'] > meanOfSqftAbove),\n (houseDataFrame['sqft_above'] <= meanOfSqftAbove)]\n\n calc = np.ceil((1 / squareFitPerPerson) * (houseDataFrame['sqft_above'] -\n meanOfSqftAbove))\n values = [houseDataFrame['bedrooms'] + calc, houseDataFrame['bedrooms']]\n\n houseDataFrame['num_of_people'] = np.select(conditions, values)\n\n\ndef feature_evaluation(X: pd.DataFrame, y: pd.Series, output_path: str = \".\") -> NoReturn:\n \"\"\"\n Create scatter plot between each feature and the response.\n - Plot title specifies feature name\n - Plot title specifies Pearson Correlation between feature and response\n - Plot saved under given folder with file name including feature name\n Parameters\n ----------\n X : DataFrame of shape (n_samples, n_features)\n Design matrix of regression problem\n\n y : array-like of shape (n_samples, )\n Response vector to evaluate against\n\n output_path: str (default \".\")\n Path to folder in which plots are saved\n \"\"\"\n X = X.iloc[:, 1:] # disclude \"intercept\" feature\n zipcodes = [col for col in X if \"zipcode\" in col]\n X = X.drop(zipcodes, axis=1)\n for feature in X:\n # cov returns a matrix which the diagonal is var of x and ver of y,\n # and the cov is the non diagonals- so we take [0][1] index:\n cov = np.cov(X[feature], y)[0][1]\n stdX = np.std(X[feature])\n stdY = np.std(y)\n\n pearCorr = cov / (stdX * stdY)\n\n # plot graph:\n df = pd.DataFrame({\"Feature Values\": X[feature], \"Response Values\": y})\n fig = px.scatter(df, x= \"Feature Values\", y=\"Response Values\",\n trendline=\"ols\", trendline_color_override='darkblue')\n\n fig.update_layout(\n title=f\"Feature: {feature} <br>Pearson Correlation: {pearCorr}\",\n xaxis_title=\"Feature Values\",\n yaxis_title=\"Response Values\"\n )\n\n fig.write_image(output_path + feature + \".png\")\n\n\nif __name__ == '__main__':\n np.random.seed(0)\n # Question 1 - Load and preprocessing of housing prices dataset\n X, y = load_data('house_prices.csv')\n\n # Question 2 - Feature evaluation with respect to response\n feature_evaluation(X, y)\n #\n # # Question 3 - Split samples into training- and testing sets.\n trainX, trainY, testX, testY = split_train_test(X,y)\n\n # Question 4 - Fit model over increasing percentages of the overall training data\n # For every percentage p in 10%, 11%, ..., 100%, repeat the following 10 times:\n # 1) Sample p% of the overall training data\n # 2) Fit linear model (including intercept) over sampled set\n # 3) Test fitted model over test set\n # 4) Store average and variance of loss over test set\n # Then plot average loss as function of training size with error ribbon of size (mean-2*std, mean+2*std)\n lin = LinearRegression(True) # include intercept in lin regression\n trainX.insert(0, 'response', np.array(trainY), True)\n meanLossOfAllSamples = []\n stdLossOfAllSamples = []\n percentages = np.arange(10,101)\n for p in range(10,101):\n lossMseOf10Samples = []\n numOfSamples = (p * trainX.shape[0]) // 100\n for i in range(10):\n sampleSizedP = trainX.sample(n = numOfSamples)\n sampleX, sampleY = sampleSizedP.drop('response', 1), sampleSizedP.response\n lin.fit(sampleX, sampleY)\n lossMseOf10Samples.append(lin.loss(testX, testY))\n lossMseOf10Samples = np.array(lossMseOf10Samples) # create nparray\n meanLossOfAllSamples.append(np.mean(lossMseOf10Samples)) # add to array\n stdLossOfAllSamples.append(np.std(lossMseOf10Samples)) # array of std\n\n # plot the graph\n fig = go.Figure()\n fig.add_trace(go.Scatter(x=percentages, y=meanLossOfAllSamples,\n mode=\"markers+lines\", name=\"Mean Loss\", line=dict(dash=\"dash\"),\n marker=dict(color=\"green\", opacity=.7)))\n fig.add_trace(go.Scatter(x=percentages, y= np.array(meanLossOfAllSamples) -\n np.array(stdLossOfAllSamples)*2,\n fill=None, mode=\"lines\", line=dict(color=\"lightgrey\"),\n showlegend=False))\n fig.add_trace(go.Scatter(x=percentages, y= np.array(meanLossOfAllSamples) +\n np.array(stdLossOfAllSamples)*2,\n fill='tonexty', mode=\"lines\",\n line=dict(color=\"lightgrey\"),\n showlegend=False))\n\n fig.update_layout(\n title=\"Mean Loss as a function of p- percentage of train set\",\n xaxis_title=\"Percentage of Train Set\",\n yaxis_title=\"Mean Loss\"\n )\n\n\n fig.show()\n\n\n\n\n\n"
] |
[
[
"pandas.read_csv",
"numpy.random.seed",
"numpy.arange",
"pandas.DataFrame",
"numpy.ceil",
"numpy.std",
"numpy.cov",
"numpy.mean",
"numpy.select",
"numpy.array",
"pandas.get_dummies"
]
] |
FightingZhen/FCN
|
[
"ff8de5c0ae2c1ccc0d4e933d8396693a65fc290b"
] |
[
"FCN_practical_resize.py"
] |
[
"import FCN as FCN4\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport TensorflowUtils as utils\r\nimport os\r\nimport argparse\r\nimport h5py as h5\r\n\r\nparser = argparse.ArgumentParser()\r\n\r\nparser.add_argument('--MODEL_NAME')\r\nparser.add_argument('--GPU')\r\nparser.add_argument('--threshold', type=float, default=0.5)\r\nparser.add_argument('--WEIGHT_INIT', default=\"Xavier\") # Truncated_Normal or Xavier\r\n\r\nargs = parser.parse_args()\r\n\r\nMODEL_URL = 'http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat'\r\n\r\nos.environ[\"CUDA_DIVICE_ORDER\"] = \"PCI_BUS_ID\"\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = args.GPU\r\n\r\nsess = tf.InteractiveSession()\r\n\r\nimage_list = utils.generate_image_mask_list_practical()\r\n\r\nweight_init = args.WEIGHT_INIT\r\nmodel_name = args.MODEL_NAME\r\nlogs_dir = './' + model_name + \"/logs/\"\r\nmodel_dir = \"./Model/\"\r\nsaved_dir = './' + model_name + \"/saved_model/\"\r\nthreshold = args.threshold\r\ntest_saved_dir = './' + model_name + \"/test_practical/\" + str(threshold) + '/'\r\n\r\npre_threshold_resize_dir = test_saved_dir + 'h5_pre_threshold_resize/'\r\n\r\ntest_batch_size = 1\r\ntest_batch_num = 85\r\n\r\nNUM_OF_CLASSESS = 2\r\nIMAGE_HEIGHT = 800\r\nIMAGE_WIDTH = 800\r\nRESIZED_IMAGE_HEIGHT = 1944\r\nRESIZED_IMAGE_WIDTH = 2592\r\n\r\n# print(sess.run(image_list))\r\n\r\nprint(\"WEIGHT_INIT:\" + weight_init)\r\nprint(\"MODEL_NAME:\" + model_name)\r\nprint(\"LOGS_DIR:\" + logs_dir)\r\nprint(\"MODEL_DIR:\" + model_dir)\r\nprint(\"SAVED_DIR:\" + saved_dir)\r\nprint(\"TEST_SAVED_DIR:\" + test_saved_dir)\r\nprint(\"TEST_BATCH_SIZE:\" + str(test_batch_size))\r\nprint(\"TEST_BATCH_NUM:\" + str(test_batch_num))\r\nprint(\"MAX_OF_CLASS:\" + str(NUM_OF_CLASSESS))\r\nprint(\"IMAGE_SIZE:\" + str(IMAGE_WIDTH) + '*' + str(IMAGE_HEIGHT))\r\nprint(\"GPU:\" + args.GPU)\r\nprint(\"Threshold:\" + str(threshold))\r\n\r\nfilename_queue = tf.train.slice_input_producer([image_list], shuffle=False)\r\n\r\nimage_content = tf.read_file(filename_queue[0])\r\n\r\nimg = tf.image.decode_png(image_content, channels=3)\r\nimg = tf.cast(img, tf.float32)\r\nimg = tf.reshape(img, [IMAGE_HEIGHT, IMAGE_WIDTH, 3])\r\n\r\nprint(\"Data sets processe finished !\")\r\n\r\ndef main(argv=None):\r\n batch_size = test_batch_size\r\n keep_probability = tf.placeholder(tf.float32, name=\"keep_probabilty\")\r\n image_batch, img_name = tf.train.batch([img, filename_queue[0]], batch_size)\r\n\r\n coord = tf.train.Coordinator()\r\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\r\n\r\n logits = FCN4.inference(image_batch, keep_probability)\r\n\r\n pred_annotation, pred_annotation_resized = utils.argmax_pre_threshold_resize(logits)\r\n pred_annotation = tf.reshape(pred_annotation, [batch_size, IMAGE_HEIGHT, IMAGE_WIDTH, 1])\r\n pred_annotation_resized = tf.reshape(pred_annotation_resized, [batch_size, RESIZED_IMAGE_HEIGHT, RESIZED_IMAGE_WIDTH, 1])\r\n\r\n print(\"Setting up Saver...\")\r\n saver = tf.train.Saver()\r\n\r\n ckpt = tf.train.get_checkpoint_state(saved_dir)\r\n if ckpt and ckpt.model_checkpoint_path:\r\n saver.restore(sess, ckpt.model_checkpoint_path)\r\n print(\"Model restored...\")\r\n\r\n if not os.path.isdir(test_saved_dir):\r\n os.makedirs(test_saved_dir)\r\n\r\n for counter in range(test_batch_num):\r\n pred, pred_resized, image_test, image_name = sess.run([pred_annotation, pred_annotation_resized, image_batch, img_name],\r\n feed_dict={keep_probability: 1.0})\r\n\r\n image_name = image_name[0].decode()\r\n image_name = image_name.split('/')[-1].strip('.png')\r\n\r\n pred = np.squeeze(pred, axis=3)\r\n pred_resized = np.squeeze(pred_resized, axis=3)\r\n\r\n image_test = np.reshape(image_test, [IMAGE_HEIGHT, IMAGE_WIDTH, 3])\r\n pred = np.reshape(pred, [IMAGE_HEIGHT, IMAGE_WIDTH])\r\n pred_resized = np.reshape(pred_resized, [RESIZED_IMAGE_HEIGHT, RESIZED_IMAGE_WIDTH])\r\n\r\n if not os.path.isdir(pre_threshold_resize_dir):\r\n os.makedirs(pre_threshold_resize_dir)\r\n f = h5.File(pre_threshold_resize_dir + image_name + '.h5', 'w')\r\n f['data'] = pred\r\n f['data_resized'] = pred_resized\r\n f.close()\r\n\r\n pred = utils.apply_threshold(pred, threshold)\r\n pred_resized = utils.apply_threshold(pred_resized, threshold)\r\n\r\n pred = sess.run(pred)\r\n pred_resized = sess.run(pred_resized)\r\n\r\n utils.save_image(image_test, test_saved_dir + 'image/',\r\n name=image_name + \"_image\")\r\n utils.save_image(pred, test_saved_dir + 'pred/',\r\n name=image_name + \"_pred\", category=True)\r\n utils.save_image(pred_resized, test_saved_dir + 'pred_resized/',\r\n name=image_name + \"_pred_resized\", category=True)\r\n print(\"Saved no. %s image: %s\" % (counter, image_name + '.png'))\r\n\r\n coord.request_stop()\r\n coord.join(threads)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n tf.app.run()\r\n"
] |
[
[
"tensorflow.train.get_checkpoint_state",
"tensorflow.InteractiveSession",
"tensorflow.read_file",
"numpy.reshape",
"tensorflow.train.start_queue_runners",
"tensorflow.image.decode_png",
"tensorflow.cast",
"tensorflow.reshape",
"tensorflow.placeholder",
"tensorflow.train.Coordinator",
"numpy.squeeze",
"tensorflow.train.slice_input_producer",
"tensorflow.train.Saver",
"tensorflow.train.batch",
"tensorflow.app.run"
]
] |
manojsharma221/Project-SCARA
|
[
"6757dd5b9668d62f4fd5aeb01c71dba9f91b84a5"
] |
[
"SCARA Vision/pyimagesearch/colorlabeler.py"
] |
[
"from scipy.spatial import distance as dist\nfrom collections import OrderedDict\nimport numpy as np\nimport cv2\n\nclass ColorLabeler:\n\tdef __init__(self):\n\t\t# initialize the colors dictionary, containing the color\n\t\t# name as the key and the RGB tuple as the value\n\t\tcolors = OrderedDict({\n\t\t\t\"red\":(255,0,0),\n\t\t\t\"green\":(0,255,0),\n\t\t\t\"blue\":(0,0,255)})\n\t\t# allocate memory for the L*a*b* image, then initialize\n\t\t# the color names list\n\t\tself.lab = np.zeros((len(colors), 1, 3), dtype=\"uint8\")\n\t\tself.colorNames = []\n\t\t\n\t\t# loop over the colors dictionary\n\t\tfor (i, (name, rgb)) in enumerate(colors.items()):\n\t\t\t# update the L*a*b* array and the color names list\n\t\t\tself.lab[i] = rgb\n\t\t\tself.colorNames.append(name)\n\t\t# convert the L*a*b* array from the RGB color space\n\t\t# to L*a*b*\n\t\tself.lab = cv2.cvtColor(self.lab, cv2.COLOR_RGB2LAB)\n\t\t\n\tdef label(self, image, c):\n\t\t# construct a mask for the contour, then compute the\n\t\t# average L*a*b* value for the masked region\n\t\tmask = np.zeros(image.shape[:2], dtype=\"uint8\")\n\t\tcv2.drawContours(mask, [c], -1, 255, -1)\n\t\tmask = cv2.erode(mask, None, iterations=2)\n\t\tmean = cv2.mean(image, mask=mask)[:3]\n\t\t# initialize the minimum distance found thus far\n\t\tminDist = (np.inf, None)\n\t\t# loop over the known L*a*b* color values\n\t\tfor (i, row) in enumerate(self.lab):\n\t\t\t# compute the distance between the current L*a*b*\n\t\t\t# color value and the mean of the image\n\t\t\td = dist.euclidean(row[0], mean)\n\t\t\t# if the distance is smaller than the current distance,\n\t\t\t# then update the bookkeeping variable\n\t\t\tif d < minDist[0]:\n\t\t\t\tminDist = (d, i)\n\t\t# return the name of the color with the smallest distance\n\t\treturn self.colorNames[minDist[1]]"
] |
[
[
"numpy.zeros",
"scipy.spatial.distance.euclidean"
]
] |
ssaunderss/fire-detection
|
[
"2a1b5d0d1c709585f181896601461b06b12a41a9"
] |
[
"main.py"
] |
[
"'''\nProject: Fire-Detection\nFile Name: main.py\nGroup Members: Austin Saunders, Sergiu Iliev, Peng Zeng, Yuan Li\nCapabilities: Visualise all the fires in target region of the word using data from historical NASA satellites and\nmark the most impactful fires.\nMIT License, Copyright (c) 2020, Sergiu Iliev, Austin Saunders, Peng Zeng, Yuan Li\n\nImport Notes\nThis file imports\n - process_data.py so we can load and transform VIIRS/MODIS satellite data\n - Risk_Calculation.py so we can generate historical risk scores for cleaned lat/long coords\n - Websource.py so we can scrape historical fire/Australian city name information\n - visualisation.py so we can visualise our end product\n - pandas so we can read a previously generated csv\n'''\nfrom visualisation import generate_map\nimport subprocess\nimport process_data as pro\nimport Risk_Calculation as rc\nimport Websource as ws\nimport pandas as pd\n\n# first we need the user to decide if they will be processing all new data or be using our data\nuser_input = False\nanswer = \"y\"\nprint(\"By default we use pre-cleaned data to demonstrate the capabilities of our code,\")\nprint(\"if you would like to use newer data, you will have to process the data on your\")\nprint(\"own. This process takes a significant amount of time ~2 hours, so we recommend\")\nprint(\"using our pre-processed data.\\n\\n\")\nwhile user_input == False:\n try:\n answer = input(\"Would you like to use default data? (y/n): \")\n except:\n print(\"Wrong format\")\n user_input = False\n if answer != \"y\" and answer != \"n\":\n print(\"You have to enter either \\\"y\\\" or \\\"n\\\", please try again\")\n else:\n user_input = True\n\n# if the user wants to use new data, this will call the process_data file and reprocess all data and\n# return new data to display\nif answer == \"n\":\n pro.transform_data()\n #refreshes the risk calculation so the map will also have up to date data\n rc.calc_risk()\n\n#Before visualizing, need to grab the riskcalculation.csv\nresults = pd.read_csv(\"data/riskcalculation.csv\")\n\n# Call the Visualise function\n# Generating the map takes around 2 minutes\ngenerate_map(results)\nws.historical_map()"
] |
[
[
"pandas.read_csv"
]
] |
orestis-z/Mask_RCNN
|
[
"d590e0f5085f8cbe895a6698e284426fd0116aa4"
] |
[
"instance_segmentation/NYU-Depth_V2/generate_np_data.py"
] |
[
"\"\"\"\nscript to convert matlab file containing dataset to python readable format \n\"\"\"\nimport os, sys\nimport h5py\nimport numpy as np\n\n\ndataset_dir = '/external_datasets/NYU-Depth_V2'\nfile = 'nyu_depth_v2_labeled.mat'\nfile_path = os.path.join(dataset_dir, file)\n\nincludes = [\"images\", \"depths\", \"instances\", \"labels\"]\nsubsets = [\"training\", \"validation\"]\nn_img = 1449.0\nthresh = 0.8\n\nfor subset in subsets:\n for key, value in h5py.File(file_path).items():\n if key in includes:\n directory = os.path.join('data', subset, key)\n if not os.path.exists(directory):\n os.makedirs(directory)\n print(\"Converting {} to .npy\".format(key))\n for idx, img in enumerate(value):\n if (subset == \"training\" and (idx + 1) / n_img <= thresh) or (subset == \"validation\" and (idx + 1) / n_img > thresh):\n np.save(os.path.join(directory, \"{}.npy\".format(idx)), np.array(img))\n\nfor key, value in h5py.File(file_path).items():\n if key == \"names\":\n names = value\n elif key == \"namesToIds\": \n namesToIds = value\n\nprint(\"Done\")\n"
] |
[
[
"numpy.array"
]
] |
DavidMachineLearning/CartPole_RL
|
[
"a15ceeffa7b7b9ef3d67b386fa16535454e3e2ca"
] |
[
"TFDQN.py"
] |
[
"from collections import deque\nimport tensorflow as tf\nfrom time import sleep\nimport numpy as np\nimport random\nimport gym\n\n\ndef fully_connected(name, input_tensor, num_units, activation=tf.nn.relu):\n \"\"\"Returns a fully connected layer\"\"\"\n # initialize weights\n w = tf.compat.v1.get_variable(f\"W_{name}\", shape=[input_tensor.get_shape()[1], num_units],\n initializer=tf.compat.v1.initializers.he_uniform(),\n dtype=tf.float32, trainable=True)\n # initialize bias\n b = tf.compat.v1.get_variable(f\"B_{name}\", shape=[num_units],\n initializer=tf.constant_initializer(0.0),\n dtype=tf.float32,\n trainable=True)\n # output\n out = tf.matmul(input_tensor, w) + b\n # add activation\n if activation:\n out = activation(out, name=f\"activation_{name}\")\n # change name\n out = tf.compat.v1.identity(out, name=name)\n\n return out\n\n\nclass DQNAgent:\n \"\"\"Class providing DQN algorithm based on tensorflow\"\"\"\n def __init__(self, state_size, action_size, name, gamma=1.0, epsilon_start=1.0, epsilon_decay=0.0002,\n epsilon_min=0.01, memorysize=100000, learning_rate=0.0001, n_Hlayers=2, n_nodes=64):\n self.state_size = state_size\n self.action_size = action_size\n self.memory = deque(maxlen=memorysize)\n self.gamma = gamma\n self.epsilon = epsilon_start\n self.epsilon_max = epsilon_start\n self.epsilon_min = epsilon_min\n self.epsilon_decay = epsilon_decay\n self.learning_rate = learning_rate\n self.step = 0\n self._build_model(name, n_Hlayers, n_nodes)\n \n def _build_model(self, name, hidden_layers, nodes):\n \"\"\"Build the neural network structure\"\"\"\n with tf.variable_scope(name):\n self.inputs_ = tf.placeholder(tf.float32, [None, self.state_size], name='inputs')\n self.actions_ = tf.placeholder(tf.int32, [None], name='actions')\n one_hot_actions = tf.one_hot(self.actions_, self.action_size)\n self.targetQs_ = tf.placeholder(tf.float32, [None], name='target')\n self.layers = list()\n self.layers.append(fully_connected(\"hidden1\", self.inputs_, nodes))\n for layer in range(hidden_layers):\n self.layers.append(fully_connected(f\"hidden{layer+2}\", self.layers[layer], nodes))\n self.output = fully_connected(\"output\", self.layers[-1], self.action_size, activation=None)\n self.Q = tf.reduce_sum(tf.multiply(self.output, one_hot_actions), axis=1)\n self.loss = tf.reduce_mean(tf.square(self.targetQs_ - self.Q))\n self.opt = tf.train.AdamOptimizer(self.learning_rate).minimize(self.loss)\n\n def _take_action(self, state):\n \"\"\"Return the action that gives the biggest reward\"\"\"\n feed = {self.inputs_: state.reshape((1, *state.shape))}\n Qs = sess.run(self.output, feed_dict=feed)\n return np.argmax(Qs)\n\n def _sample(self, batch_size):\n \"\"\"Gets a random batch from the memory\"\"\"\n idx = np.random.choice(np.arange(len(self.memory)), \n size=batch_size, \n replace=False)\n return [self.memory[i] for i in idx]\n\n def remember(self, experience):\n \"\"\"experience = (state, action, reward, next_state)\"\"\"\n self.memory.append(experience)\n \n def action(self, state, mode='train'):\n \"\"\"Return an action based on the current state, if mode is test the agent choose\n the best action that gives the biggest reward.\n If mode is train, then it can choose also a random action with epsilon probability\"\"\"\n self.step += 1\n # reduce gradually epsilon to its minimum value\n self.epsilon = self.epsilon_min + (\n self.epsilon_max - self.epsilon_min)*np.exp(-self.epsilon_decay*self.step)\n if np.random.rand() > self.epsilon or mode.lower() == \"test\":\n return self._take_action(state)\n else:\n return random.randrange(self.action_size)\n \n def replay(self, batch_size):\n \"\"\"Train the agent with a random batch of the collected data\"\"\"\n batch = self._sample(batch_size)\n states = np.array([each[0] for each in batch])\n actions = np.array([each[1] for each in batch])\n rewards = np.array([each[2] for each in batch])\n next_states = np.array([each[3] for each in batch])\n target_Qs = sess.run(self.output, feed_dict={self.inputs_: next_states})\n episode_ends = (next_states == np.zeros(states[0].shape)).all(axis=1)\n target_Qs[episode_ends] = (0, 0)\n \n targets = rewards + self.gamma * np.max(target_Qs, axis=1)\n\n loss, _ = sess.run([self.loss, self.opt], feed_dict={self.inputs_: states,\n self.targetQs_: targets,\n self.actions_: actions})\n return loss\n\n\ndef collect_experience(env_, agent_, size):\n \"\"\"Save data in agent's memory, preparing it for training\"\"\"\n env_.reset()\n state, reward, done, _ = env_.step(env_.action_space.sample())\n for data in range(size):\n action = env_.action_space.sample()\n next_state, reward, done, _ = env_.step(action)\n # penalize reward based on the position of the cart\n reward = max(0, reward * (1 - abs(next_state[0]/2.4)))\n if done:\n next_state = np.zeros(state.shape)\n # save experience in agent's memory\n agent_.remember((state, action, reward, next_state))\n env_.reset()\n state, reward, done, _ = env_.step(env.action_space.sample())\n else:\n # save experience in agent's memory\n agent_.remember((state, action, reward, next_state))\n state = next_state\n\n \nif __name__ == \"__main__\":\n # initialize gym environment and the agent\n env = gym.make('CartPole-v1')\n tf.reset_default_graph()\n agent = DQNAgent(4, 2, \"main\")\n train_episodes = 700\n batch_size = 32\n \n # populate memory\n collect_experience(env, agent, batch_size)\n \n # Iterate the game\n rewards_list = list()\n saver = tf.train.Saver()\n max_steps = 500\n with tf.Session() as sess:\n # Initialize variables\n sess.run(tf.compat.v1.global_variables_initializer())\n step = 0\n state = env.reset()\n for ep in range(1, train_episodes):\n total_reward = 0\n t = 0\n while t < max_steps:\n step += 1\n \n # Take action, get new state and reward\n action = agent.action(state)\n next_state, reward, done, _ = env.step(action)\n\n # penalize reward based on the position of the cart\n reward = max(0, reward * (1 - abs(next_state[0]/2.4)))\n\n # collect total reward\n total_reward += reward\n \n if done:\n # the episode ends so no next state\n next_state = np.zeros(state.shape)\n t = max_steps\n \n print('Episode: {}'.format(ep),\n 'Total reward: {}'.format(total_reward),\n 'Explore P: {:.4f}'.format(agent.epsilon))\n\n # Add reward to list\n rewards_list.append(total_reward)\n \n # Add experience to memory\n agent.remember((state, action, reward, next_state))\n \n # Start new episode\n env.reset()\n \n # Take one random step to get the pole and cart moving\n state, reward, done, _ = env.step(env.action_space.sample())\n\n else:\n # Add experience to memory\n agent.remember((state, action, reward, next_state))\n state = next_state\n t += 1\n\n # train using batch\n loss = agent.replay(batch_size)\n \n # if the agent gets 10 rewards bigger than 470 consecutively, stop the training\n # 499 is never going to be reached because of the penalized reward\n if len(rewards_list) > 10:\n stop_training = False\n for reward in rewards_list[-10:]:\n if reward < 470:\n break\n else:\n stop_training = True\n if stop_training:\n break\n \n # save the model\n saver.save(sess, \"checkpoints/cartpole.ckpt\")\n \n # whatch a trained agent for 5 episodes\n for episode in range(1, 6):\n state = env.reset()\n while True:\n action = agent.action(state, mode=\"test\")\n state, reward, done, _ = env.step(action)\n env.render()\n sleep(0.05)\n if done:\n env.close()\n break\n"
] |
[
[
"numpy.max",
"tensorflow.train.AdamOptimizer",
"numpy.exp",
"tensorflow.compat.v1.identity",
"tensorflow.compat.v1.initializers.he_uniform",
"tensorflow.reset_default_graph",
"numpy.argmax",
"tensorflow.Session",
"tensorflow.square",
"tensorflow.train.Saver",
"numpy.zeros",
"tensorflow.matmul",
"tensorflow.placeholder",
"tensorflow.one_hot",
"numpy.random.rand",
"numpy.array",
"tensorflow.multiply",
"tensorflow.compat.v1.global_variables_initializer",
"tensorflow.constant_initializer",
"tensorflow.variable_scope"
]
] |
mukundsood1996/Rahat-Dashboard
|
[
"906e659e7481643051603753284ed0131895b7c8"
] |
[
"app.py"
] |
[
"from flask import Flask, render_template, request, url_for, flash, session, jsonify\nfrom flask_googlemaps import GoogleMaps\nfrom flask_googlemaps import Map, icons\nfrom flask import Flask\n\nfrom sklearn.cluster import KMeans\n\nimport numpy as np\nimport rahat_sql as r_data\n\n\nvics = []\nhelps = []\n\napp = Flask(__name__, template_folder=\"pages\")\n\n# # you can set key as config\n# app.config['GOOGLEMAPS_KEY'] = \"AIzaSyA-LeuHfPV55l0eTntXdhCCWuGQ_CWmtGE\"\n\n# # Initialize the extension\n# GoogleMaps(app)\n\n# you can also pass the key here if you prefer\nGoogleMaps(app, key=\"AIzaSyA-LeuHfPV55l0eTntXdhCCWuGQ_CWmtGE\")\n\n# GoogleMaps(app)\n\n\n@app.route(\"/\")\ndef mapview():\n\n global vics\n global helps\n vics = []\n helps = []\n\n # creating a map in the view\n victims = r_data.show_all_victims()\n shelters = r_data.show_all_shelters()\n helpers = r_data.show_all_help()\n\n markers = []\n\n for victim in victims:\n icon = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png'\n lat = float(victim[2])\n lng = float(victim[3])\n infobox = 'Victim'\n marker = {'icon':icon, 'lat':lat, 'lng':lng, 'infobox':infobox}\n markers.append(marker)\n vics.append(list(victim))\n\n for shelter in shelters:\n icon = 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'\n lat = float(shelter[1])\n lng = float(shelter[2])\n infobox = 'Shelter'\n marker = {'icon':icon, 'lat':lat, 'lng':lng, 'infobox':infobox}\n markers.append(marker)\n print(\"Entered Green Dash\")\n\n for helper in helpers:\n icon = 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'\n lat = float(helper[2])\n lng = float(helper[3])\n infobox = 'Helper'\n marker = {'icon':icon, 'lat':lat, 'lng':lng, 'infobox':infobox}\n markers.append(marker)\n helps.append(list(helper))\n print(\"Entered Blue Dash\")\n\n mymap = Map(\n identifier=\"map-element\",\n lat=12.9716,\n lng=77.5946,\n markers=markers,\n style=(\n \"height:25%;\"\n \"width:100%;\"\n \"top:0;\"\n \"left:0;\"\n ),\n zoom=12.5\n )\n\n return render_template('index.html', mymap=mymap)\n\n@app.route('/addVictim', methods = ['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n print('POST Request detected', request)\n print(request.data)\n response = app.response_class(response=\"Doing POST right!\", status=200, mimetype=\"application/json\")\n return response\n elif request.method == 'GET':\n print('GET Request detected', request)\n response = app.response_class(response=\"Doing GET right!\", status=200, mimetype=\"application/json\")\n return response\n\t\t\n\n@app.route('/getTweet', methods = ['GET', 'POST'])\ndef get_tweets():\n\n temp = request.args.get('index', 0)\n data = r_data.show_all_tweets()\n tweets = []\n\n for tweet in data:\n tweets.append(list(tweet))\n\n return(jsonify(tweets))\n\n@app.route('/getVictims', methods = ['GET', 'POST'])\ndef get_victims():\n\n temp = request.args.get('index', 0)\n \n return(jsonify(vics))\n\n@app.route('/getHelpers', methods = ['GET', 'POST'])\ndef get_helpers():\n\n temp = request.args.get('index', 0)\n \n return(jsonify(helps))\n\n\n@app.route('/naksha', methods = ['GET', 'POST'])\ndef get_map():\n\n # creating a map in the view\n victims = r_data.show_all_victims()\n shelters = r_data.show_all_shelters()\n helpers = r_data.show_all_help()\n\n lat_lngs = []\n\n markers = []\n\n for victim in victims:\n icon = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png'\n lat = float(victim[2])\n lng = float(victim[3])\n infobox = 'Victim'\n marker = {'icon':icon, 'lat':lat, 'lng':lng, 'infobox':infobox}\n markers.append(marker)\n lat_lngs.append((lat,lng))\n\n # for shelter in shelters:\n # icon = 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'\n # lat = float(shelter[1])\n # lng = float(shelter[2])\n # infobox = 'Shelter'\n # marker = {'icon':icon, 'lat':lat, 'lng':lng, 'infobox':infobox}\n # markers.append(marker)\n # print(\"Entered Green\")\n\n # for helper in helpers:\n # icon = 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'\n # lat = float(helper[2])\n # lng = float(helper[3])\n # infobox = 'Helper'\n # marker = {'icon':icon, 'lat':lat, 'lng':lng, 'infobox':infobox}\n # markers.append(marker)\n # print(\"Entered Help\")\n\n lat_lngs = np.array(lat_lngs)\n estimator = KMeans(n_clusters=3, random_state=0).fit(lat_lngs)\n kmeans = estimator.fit_predict(lat_lngs)\n target = [0, 1, 2]\n\n # Finding the clusters\n clusters_centroids=dict()\n clusters_radii= dict()\n \n for cluster in list(set(target)):\n clusters_centroids[cluster] = list(zip(estimator.cluster_centers_[:, 0],estimator.cluster_centers_[:,1]))[cluster]\n clusters_radii[cluster] = max([i[0]-clusters_centroids[cluster][0]+i[1]-clusters_centroids[cluster][1] for i in zip(lat_lngs[kmeans == cluster, 0],lat_lngs[kmeans == cluster, 1])])\n\n print(\"\\n\\n\\n\")\n print(clusters_centroids)\n print(clusters_radii)\n \n\n big_map = Map(\n identifier=\"map-element\",\n lat=12.9716,\n lng=77.5946,\n markers=markers,\n style=(\n \"height:750px;\"\n \"width:100%;\"\n \"top:0;\"\n \"left:0;\"\n ),\n zoom=13,\n circles=[{'stroke_color':'yellow', 'stroke_opacity':.8, 'fill_color':'yellow', 'fill_opacity':.3, 'center':{'lat':clusters_centroids[0][0], 'lng':clusters_centroids[0][1]}, 'radius':clusters_radii[0]*100000 + 100}, \n {'stroke_color':'red', 'stroke_opacity':.8, 'fill_color':'red', 'fill_opacity':.3, 'center':{'lat':clusters_centroids[1][0], 'lng':clusters_centroids[1][1]}, 'radius':clusters_radii[1]*100000 + 650},\n {'stroke_color':'green', 'stroke_opacity':.8, 'fill_color':'green', 'fill_opacity':.3, 'center':{'lat':clusters_centroids[2][0], 'lng':clusters_centroids[2][1]}, 'radius':clusters_radii[2]*100000 + 20}]\n )\n\n\n\n return render_template('naksha.html', big_map=big_map)\n\n\n@app.route('/pehchan', methods = ['GET', 'POST'])\ndef get_face():\n\n return render_template('pehchan.html')\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)"
] |
[
[
"numpy.array",
"sklearn.cluster.KMeans"
]
] |
YeYuanS/Object-Detection
|
[
"ea618670fe991a8f400553b3af8d4367779a9229"
] |
[
"train_phone_finder.py"
] |
[
"from sklearn.model_selection import train_test_split\r\nfrom sklearn.utils import shuffle\r\nimport sys\r\nimport glob\r\nimport cv2\r\nimport random\r\nimport numpy as np\r\nimport os\r\nimport matplotlib.pyplot as plt\r\n# Keras modules\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\nfrom keras.layers import Dropout\r\nfrom keras.layers import Flatten\r\nfrom keras.layers.convolutional import Conv2D\r\nfrom keras.layers.convolutional import MaxPooling2D\r\nfrom keras import optimizers\r\nfrom keras.callbacks import EarlyStopping\r\nfrom keras.utils import np_utils\r\nfrom keras.models import load_model\r\nimport tensorflow as tf\r\nfrom keras import backend as K\r\nK.set_image_dim_ordering('th')\r\n# Get the prediction function to find accuracy\r\nfrom find_phone import predict_phone_position\r\n\r\nhalf_crop_size = 22\r\ncrop_size = 44\r\n\r\ndef crop_images(img, pos, num_sample_phones=50, num_sampe_background=50):\r\n height, width = img.shape\r\n phone_images = []\r\n background_images = []\r\n pos_pixel = np.array((int(pos[0] * width), int(pos[1] * height)))\r\n # left boundary of box\r\n box_lb = pos_pixel[0] - half_crop_size\r\n # right boundary of box\r\n box_rb = pos_pixel[0] + half_crop_size\r\n # upper boundary of box\r\n box_ub = pos_pixel[1] - half_crop_size\r\n # bottom boundary of box\r\n box_bb = pos_pixel[1] + half_crop_size\r\n # crop the phone from the image\r\n phone_crop = img[box_ub:box_bb, box_lb:box_rb]\r\n # randomly rotate 90 degree of cropped phone\r\n for i in range(num_sample_phones):\r\n random.seed(i)\r\n pi = random.random()\r\n if pi > 0.75:\r\n t = random.choice([1, 2, 3, 4])\r\n phone_images.append(np.rot90(phone_crop, t))\r\n else:\r\n phone_images.append(phone_crop)\r\n\r\n # randomly crop background images\r\n for i in range(num_sampe_background):\r\n # coordinate of the left up corner of cropped background\r\n random.seed(i)\r\n start_x = box_lb - 60 if (box_lb > 60) else 0\r\n start_y = box_ub - 60 if (box_ub > 60) else 0\r\n b_x = random.randint(start_x, width - crop_size)\r\n b_y = random.randint(start_y, height - crop_size)\r\n # in case there would be overlap between the background crop and phone crop\r\n while b_x in range(start_x, box_rb) and b_y in range(start_y, box_bb):\r\n b_x = random.randint(0, width - crop_size)\r\n b_y = random.randint(0, height - crop_size)\r\n back_crop = img[b_y: b_y + crop_size, b_x: b_x + crop_size]\r\n background_images.append(back_crop)\r\n\r\n return phone_images, background_images\r\n\r\n\r\ndef prepare_data(image_dir, label_dir):\r\n # read in label and stored into list\r\n f = open(label_dir)\r\n iter_f = iter(f)\r\n list_f = []\r\n for line in iter_f:\r\n line = line.strip('\\n')\r\n list_f.append(line.split(\" \"))\r\n # convert list to dict\r\n dict_f = {x[0]: np.array([round(float(x[1]), 4), round(float(x[2]), 4)]) for x in list_f}\r\n\r\n data_phone = []\r\n data_background = []\r\n for filename in os.listdir(image_dir):\r\n if filename != \"labels.txt\":\r\n image = cv2.imread(image_dir + '/' + filename)\r\n #print(filename)\r\n image_G = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\r\n phone_images, background_images = crop_images(image_G, dict_f[filename])\r\n data_phone.extend(phone_images)\r\n data_background.extend(background_images)\r\n data_phone = np.array(data_phone)\r\n data_background = np.array(data_background)\r\n data = np.vstack((data_phone, data_background))\r\n label = np.hstack((np.ones(len(data_phone)), np.zeros(len(data_background))))\r\n\r\n data, label = shuffle(data, label, random_state=42)\r\n\r\n train_data, test_data, train_label, test_label = train_test_split(data, label, test_size=0.2, random_state=42)\r\n\r\n # Reshape data to match input format of CNN\r\n train_data = train_data.reshape(train_data.shape[0], 1, crop_size, crop_size).astype('float32')\r\n test_data = test_data.reshape(test_data.shape[0], 1, crop_size, crop_size).astype('float32')\r\n # normalize input data\r\n train_data = train_data / 255.0\r\n test_data = test_data / 255.0\r\n\r\n return train_data, test_data, train_label, test_label\r\n\r\n\r\ndef create_model(X_train, X_test, y_train, y_test):\r\n # to get reproducible results\r\n np.random.seed(0)\r\n tf.set_random_seed(0)\r\n\r\n # create model\r\n model = Sequential()\r\n model.add(Conv2D(16, (3, 3), input_shape=(1, 44, 44), activation='relu'))\r\n model.add(MaxPooling2D(pool_size=(2, 2)))\r\n model.add(Conv2D(8, (3, 3), activation='relu'))\r\n model.add(MaxPooling2D(pool_size=(2, 2)))\r\n model.add(Dropout(0.2))\r\n model.add(Flatten())\r\n model.add(Dense(128, activation='relu'))\r\n model.add(Dense(1, activation='sigmoid'))\r\n\r\n # Compile model\r\n sgd = optimizers.SGD(lr=0.1, decay=1e-2)\r\n model.compile(loss='binary_crossentropy', optimizer=sgd, metrics=['accuracy'])\r\n # Earlystopping\r\n earlystop = EarlyStopping(monitor='val_loss', min_delta=0.001, patience=5, verbose=0, mode='auto')\r\n callbacks_list = [earlystop]\r\n # Fit the model\r\n history = model.fit(X_train, y_train, validation_data=(X_test, y_test), callbacks=callbacks_list, epochs=50,\r\n batch_size=128)\r\n # save model in HDF5 format\r\n model.save(\"model.h5\")\r\n return model\r\n\r\n\r\ndef accuracy(image_dir, label_dir):\r\n f = open(label_dir)\r\n iter_f = iter(f)\r\n list_f = []\r\n for line in iter_f:\r\n line = line.strip('\\n')\r\n list_f.append(line.split(\" \"))\r\n # convert list to dict\r\n dict_f = {x[0]: np.array([round(float(x[1]), 4), round(float(x[2]), 4)]) for x in list_f}\r\n\r\n model = load_model('model.h5')\r\n accuracy = 0\r\n total = 0\r\n for filename in os.listdir(image_dir):\r\n total = total + 1\r\n image = image_dir + '/' + filename\r\n pos = predict_phone_position(image, model)\r\n res = np.sqrt(np.sum(np.power(pos - dict_f[filename], 2)))\r\n if res <= 0.05:\r\n accuracy = accuracy + 1\r\n else:\r\n print(filename, \" \", pos, \" \", dict_f[filename])\r\n accuracy = accuracy / total\r\n print(accuracy)\r\n return accuracy\r\n\r\ndef main():\r\n path = sys.argv[1]\r\n print(path)\r\n train_data, test_data, train_label, test_label= prepare_data(path, os.path.join(path, 'labels.txt'))\r\n #accuracy(path, os.path.join(path, 'labels.txt'))\r\n model = create_model(train_data, test_data, train_label, test_label)\r\n print(\"model trained\")\r\n\r\nif __name__ == \"__main__\":\r\n main()"
] |
[
[
"numpy.rot90",
"numpy.random.seed",
"numpy.power",
"sklearn.utils.shuffle",
"sklearn.model_selection.train_test_split",
"tensorflow.set_random_seed",
"numpy.array",
"numpy.vstack"
]
] |
bcgazen/zarr-python
|
[
"6a5903aecf2c33f7c127a55a532e02a2c5006523"
] |
[
"zarr/tests/test_core.py"
] |
[
"import atexit\nimport os\nimport pickle\nimport shutil\nimport unittest\nfrom itertools import zip_longest\nfrom tempfile import mkdtemp, mktemp\n\nimport numpy as np\nimport pytest\nfrom numcodecs import (BZ2, JSON, LZ4, Blosc, Categorize, Delta,\n FixedScaleOffset, GZip, MsgPack, Pickle, VLenArray,\n VLenBytes, VLenUTF8, Zlib)\nfrom numcodecs.compat import ensure_bytes, ensure_ndarray\nfrom numcodecs.tests.common import greetings\nfrom numpy.testing import assert_array_almost_equal, assert_array_equal\n\nfrom zarr.core import Array\nfrom zarr.meta import json_loads\nfrom zarr.n5 import N5Store, n5_keywords\nfrom zarr.storage import (\n ABSStore,\n DBMStore,\n DirectoryStore,\n LMDBStore,\n LRUStoreCache,\n NestedDirectoryStore,\n SQLiteStore,\n FSStore,\n atexit_rmglob,\n atexit_rmtree,\n init_array,\n init_group,\n)\nfrom zarr.util import buffer_size\nfrom zarr.tests.util import skip_test_env_var, have_fsspec\n\n# noinspection PyMethodMayBeStatic\n\n\nclass TestArray(unittest.TestCase):\n\n def test_array_init(self):\n\n # normal initialization\n store = dict()\n init_array(store, shape=100, chunks=10, dtype='<f8')\n a = Array(store)\n assert isinstance(a, Array)\n assert (100,) == a.shape\n assert (10,) == a.chunks\n assert '' == a.path\n assert a.name is None\n assert a.basename is None\n assert store is a.store\n assert \"8fecb7a17ea1493d9c1430d04437b4f5b0b34985\" == a.hexdigest()\n\n # initialize at path\n store = dict()\n init_array(store, shape=100, chunks=10, path='foo/bar', dtype='<f8')\n a = Array(store, path='foo/bar')\n assert isinstance(a, Array)\n assert (100,) == a.shape\n assert (10,) == a.chunks\n assert 'foo/bar' == a.path\n assert '/foo/bar' == a.name\n assert 'bar' == a.basename\n assert store is a.store\n assert \"8fecb7a17ea1493d9c1430d04437b4f5b0b34985\" == a.hexdigest()\n\n # store not initialized\n store = dict()\n with pytest.raises(ValueError):\n Array(store)\n\n # group is in the way\n store = dict()\n init_group(store, path='baz')\n with pytest.raises(ValueError):\n Array(store, path='baz')\n\n def create_array(self, read_only=False, **kwargs):\n store = dict()\n kwargs.setdefault('compressor', Zlib(level=1))\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n def test_store_has_text_keys(self):\n # Initialize array\n np.random.seed(42)\n z = self.create_array(shape=(1050,), chunks=100, dtype='f8', compressor=[])\n z[:] = np.random.random(z.shape)\n\n expected_type = str\n\n for k in z.chunk_store.keys():\n if not isinstance(k, expected_type): # pragma: no cover\n pytest.fail(\"Non-text key: %s\" % repr(k))\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_store_has_binary_values(self):\n # Initialize array\n np.random.seed(42)\n z = self.create_array(shape=(1050,), chunks=100, dtype='f8', compressor=[])\n z[:] = np.random.random(z.shape)\n\n for v in z.chunk_store.values():\n try:\n ensure_ndarray(v)\n except TypeError: # pragma: no cover\n pytest.fail(\"Non-bytes-like value: %s\" % repr(v))\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_store_has_bytes_values(self):\n # Test that many stores do hold bytes values.\n # Though this is not a strict requirement.\n # Should be disabled by any stores that fail this as needed.\n\n # Initialize array\n np.random.seed(42)\n z = self.create_array(shape=(1050,), chunks=100, dtype='f8', compressor=[])\n z[:] = np.random.random(z.shape)\n\n # Check in-memory array only contains `bytes`\n assert all([isinstance(v, bytes) for v in z.chunk_store.values()])\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_nbytes_stored(self):\n\n # dict as store\n z = self.create_array(shape=1000, chunks=100)\n expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values())\n assert expect_nbytes_stored == z.nbytes_stored\n z[:] = 42\n expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values())\n assert expect_nbytes_stored == z.nbytes_stored\n\n # mess with store\n try:\n z.store[z._key_prefix + 'foo'] = list(range(10))\n assert -1 == z.nbytes_stored\n except TypeError:\n pass\n\n # noinspection PyStatementEffect\n def test_array_1d(self):\n a = np.arange(1050)\n z = self.create_array(shape=a.shape, chunks=100, dtype=a.dtype)\n\n # check properties\n assert len(a) == len(z)\n assert a.ndim == z.ndim\n assert a.shape == z.shape\n assert a.dtype == z.dtype\n assert (100,) == z.chunks\n assert a.nbytes == z.nbytes\n assert 11 == z.nchunks\n assert 0 == z.nchunks_initialized\n assert (11,) == z.cdata_shape\n\n # check empty\n b = z[:]\n assert isinstance(b, np.ndarray)\n assert a.shape == b.shape\n assert a.dtype == b.dtype\n\n # check attributes\n z.attrs['foo'] = 'bar'\n assert 'bar' == z.attrs['foo']\n\n # set data\n z[:] = a\n\n # check properties\n assert a.nbytes == z.nbytes\n assert 11 == z.nchunks\n assert 11 == z.nchunks_initialized\n\n # check slicing\n assert_array_equal(a, np.array(z))\n assert_array_equal(a, z[:])\n assert_array_equal(a, z[...])\n # noinspection PyTypeChecker\n assert_array_equal(a, z[slice(None)])\n assert_array_equal(a[:10], z[:10])\n assert_array_equal(a[10:20], z[10:20])\n assert_array_equal(a[-10:], z[-10:])\n assert_array_equal(a[:10, ...], z[:10, ...])\n assert_array_equal(a[10:20, ...], z[10:20, ...])\n assert_array_equal(a[-10:, ...], z[-10:, ...])\n assert_array_equal(a[..., :10], z[..., :10])\n assert_array_equal(a[..., 10:20], z[..., 10:20])\n assert_array_equal(a[..., -10:], z[..., -10:])\n # ...across chunk boundaries...\n assert_array_equal(a[:110], z[:110])\n assert_array_equal(a[190:310], z[190:310])\n assert_array_equal(a[-110:], z[-110:])\n # single item\n assert a[0] == z[0]\n assert a[-1] == z[-1]\n # unusual integer items\n assert a[42] == z[np.int64(42)]\n assert a[42] == z[np.int32(42)]\n assert a[42] == z[np.uint64(42)]\n assert a[42] == z[np.uint32(42)]\n # too many indices\n with pytest.raises(IndexError):\n z[:, :]\n with pytest.raises(IndexError):\n z[0, :]\n with pytest.raises(IndexError):\n z[:, 0]\n with pytest.raises(IndexError):\n z[0, 0]\n # only single ellipsis allowed\n with pytest.raises(IndexError):\n z[..., ...]\n\n # check partial assignment\n b = np.arange(1e5, 2e5)\n z[190:310] = b[190:310]\n assert_array_equal(a[:190], z[:190])\n assert_array_equal(b[190:310], z[190:310])\n assert_array_equal(a[310:], z[310:])\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_array_1d_fill_value(self):\n for fill_value in -1, 0, 1, 10:\n\n a = np.arange(1050)\n f = np.empty_like(a)\n f.fill(fill_value)\n z = self.create_array(shape=a.shape, chunks=100, dtype=a.dtype,\n fill_value=fill_value)\n z[190:310] = a[190:310]\n\n assert_array_equal(f[:190], z[:190])\n assert_array_equal(a[190:310], z[190:310])\n assert_array_equal(f[310:], z[310:])\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_array_1d_set_scalar(self):\n # test setting the contents of an array with a scalar value\n\n # setup\n a = np.zeros(100)\n z = self.create_array(shape=a.shape, chunks=10, dtype=a.dtype)\n z[:] = a\n assert_array_equal(a, z[:])\n\n for value in -1, 0, 1, 10:\n a[15:35] = value\n z[15:35] = value\n assert_array_equal(a, z[:])\n a[:] = value\n z[:] = value\n assert_array_equal(a, z[:])\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_array_1d_selections(self):\n # light test here, full tests in test_indexing\n\n # setup\n a = np.arange(1050)\n z = self.create_array(shape=a.shape, chunks=100, dtype=a.dtype)\n z[:] = a\n\n # get\n assert_array_equal(a[50:150], z.get_orthogonal_selection(slice(50, 150)))\n assert_array_equal(a[50:150], z.oindex[50: 150])\n ix = [99, 100, 101]\n bix = np.zeros_like(a, dtype=bool)\n bix[ix] = True\n assert_array_equal(a[ix], z.get_orthogonal_selection(ix))\n assert_array_equal(a[ix], z.oindex[ix])\n assert_array_equal(a[ix], z.get_coordinate_selection(ix))\n assert_array_equal(a[ix], z.vindex[ix])\n assert_array_equal(a[bix], z.get_mask_selection(bix))\n assert_array_equal(a[bix], z.oindex[bix])\n assert_array_equal(a[bix], z.vindex[bix])\n\n # set\n z.set_orthogonal_selection(slice(50, 150), 1)\n assert_array_equal(1, z[50:150])\n z.oindex[50:150] = 2\n assert_array_equal(2, z[50:150])\n z.set_orthogonal_selection(ix, 3)\n assert_array_equal(3, z.get_coordinate_selection(ix))\n z.oindex[ix] = 4\n assert_array_equal(4, z.oindex[ix])\n z.set_coordinate_selection(ix, 5)\n assert_array_equal(5, z.get_coordinate_selection(ix))\n z.vindex[ix] = 6\n assert_array_equal(6, z.vindex[ix])\n z.set_mask_selection(bix, 7)\n assert_array_equal(7, z.get_mask_selection(bix))\n z.vindex[bix] = 8\n assert_array_equal(8, z.vindex[bix])\n z.oindex[bix] = 9\n assert_array_equal(9, z.oindex[bix])\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # noinspection PyStatementEffect\n def test_array_2d(self):\n a = np.arange(10000).reshape((1000, 10))\n z = self.create_array(shape=a.shape, chunks=(100, 2), dtype=a.dtype)\n\n # check properties\n assert len(a) == len(z)\n assert a.ndim == z.ndim\n assert a.shape == z.shape\n assert a.dtype == z.dtype\n assert (100, 2) == z.chunks\n assert 0 == z.nchunks_initialized\n assert (10, 5) == z.cdata_shape\n\n # set data\n z[:] = a\n\n # check properties\n assert a.nbytes == z.nbytes\n assert 50 == z.nchunks_initialized\n\n # check array-like\n assert_array_equal(a, np.array(z))\n\n # check slicing\n\n # total slice\n assert_array_equal(a, z[:])\n assert_array_equal(a, z[...])\n # noinspection PyTypeChecker\n assert_array_equal(a, z[slice(None)])\n\n # slice first dimension\n assert_array_equal(a[:10], z[:10])\n assert_array_equal(a[10:20], z[10:20])\n assert_array_equal(a[-10:], z[-10:])\n assert_array_equal(a[:10, :], z[:10, :])\n assert_array_equal(a[10:20, :], z[10:20, :])\n assert_array_equal(a[-10:, :], z[-10:, :])\n assert_array_equal(a[:10, ...], z[:10, ...])\n assert_array_equal(a[10:20, ...], z[10:20, ...])\n assert_array_equal(a[-10:, ...], z[-10:, ...])\n assert_array_equal(a[:10, :, ...], z[:10, :, ...])\n assert_array_equal(a[10:20, :, ...], z[10:20, :, ...])\n assert_array_equal(a[-10:, :, ...], z[-10:, :, ...])\n\n # slice second dimension\n assert_array_equal(a[:, :2], z[:, :2])\n assert_array_equal(a[:, 2:4], z[:, 2:4])\n assert_array_equal(a[:, -2:], z[:, -2:])\n assert_array_equal(a[..., :2], z[..., :2])\n assert_array_equal(a[..., 2:4], z[..., 2:4])\n assert_array_equal(a[..., -2:], z[..., -2:])\n assert_array_equal(a[:, ..., :2], z[:, ..., :2])\n assert_array_equal(a[:, ..., 2:4], z[:, ..., 2:4])\n assert_array_equal(a[:, ..., -2:], z[:, ..., -2:])\n\n # slice both dimensions\n assert_array_equal(a[:10, :2], z[:10, :2])\n assert_array_equal(a[10:20, 2:4], z[10:20, 2:4])\n assert_array_equal(a[-10:, -2:], z[-10:, -2:])\n\n # slicing across chunk boundaries\n assert_array_equal(a[:110], z[:110])\n assert_array_equal(a[190:310], z[190:310])\n assert_array_equal(a[-110:], z[-110:])\n assert_array_equal(a[:110, :], z[:110, :])\n assert_array_equal(a[190:310, :], z[190:310, :])\n assert_array_equal(a[-110:, :], z[-110:, :])\n assert_array_equal(a[:, :3], z[:, :3])\n assert_array_equal(a[:, 3:7], z[:, 3:7])\n assert_array_equal(a[:, -3:], z[:, -3:])\n assert_array_equal(a[:110, :3], z[:110, :3])\n assert_array_equal(a[190:310, 3:7], z[190:310, 3:7])\n assert_array_equal(a[-110:, -3:], z[-110:, -3:])\n\n # single row/col/item\n assert_array_equal(a[0], z[0])\n assert_array_equal(a[-1], z[-1])\n assert_array_equal(a[:, 0], z[:, 0])\n assert_array_equal(a[:, -1], z[:, -1])\n assert a[0, 0] == z[0, 0]\n assert a[-1, -1] == z[-1, -1]\n\n # too many indices\n with pytest.raises(IndexError):\n z[:, :, :]\n with pytest.raises(IndexError):\n z[0, :, :]\n with pytest.raises(IndexError):\n z[:, 0, :]\n with pytest.raises(IndexError):\n z[:, :, 0]\n with pytest.raises(IndexError):\n z[0, 0, 0]\n # only single ellipsis allowed\n with pytest.raises(IndexError):\n z[..., ...]\n\n # check partial assignment\n b = np.arange(10000, 20000).reshape((1000, 10))\n z[190:310, 3:7] = b[190:310, 3:7]\n assert_array_equal(a[:190], z[:190])\n assert_array_equal(a[:, :3], z[:, :3])\n assert_array_equal(b[190:310, 3:7], z[190:310, 3:7])\n assert_array_equal(a[310:], z[310:])\n assert_array_equal(a[:, 7:], z[:, 7:])\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_array_2d_edge_case(self):\n # this fails with filters - chunks extend beyond edge of array, messes with delta\n # filter if no fill value?\n shape = 1000, 10\n chunks = 300, 30\n dtype = 'i8'\n z = self.create_array(shape=shape, dtype=dtype, chunks=chunks)\n z[:] = 0\n expect = np.zeros(shape, dtype=dtype)\n actual = z[:]\n assert_array_equal(expect, actual)\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_array_2d_partial(self):\n z = self.create_array(shape=(1000, 10), chunks=(100, 2), dtype='i4',\n fill_value=0)\n\n # check partial assignment, single row\n c = np.arange(z.shape[1])\n z[0, :] = c\n with pytest.raises(ValueError):\n # N.B., NumPy allows this, but we'll be strict for now\n z[2:3] = c\n with pytest.raises(ValueError):\n # N.B., NumPy allows this, but we'll be strict for now\n z[-1:] = c\n z[2:3] = c[None, :]\n z[-1:] = c[None, :]\n assert_array_equal(c, z[0, :])\n assert_array_equal(c, z[2, :])\n assert_array_equal(c, z[-1, :])\n\n # check partial assignment, single column\n d = np.arange(z.shape[0])\n z[:, 0] = d\n with pytest.raises(ValueError):\n z[:, 2:3] = d\n with pytest.raises(ValueError):\n z[:, -1:] = d\n z[:, 2:3] = d[:, None]\n z[:, -1:] = d[:, None]\n assert_array_equal(d, z[:, 0])\n assert_array_equal(d, z[:, 2])\n assert_array_equal(d, z[:, -1])\n\n # check single item assignment\n z[0, 0] = -1\n z[2, 2] = -1\n z[-1, -1] = -1\n assert -1 == z[0, 0]\n assert -1 == z[2, 2]\n assert -1 == z[-1, -1]\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_array_order(self):\n\n # 1D\n a = np.arange(1050)\n for order in 'C', 'F':\n z = self.create_array(shape=a.shape, chunks=100, dtype=a.dtype,\n order=order)\n assert order == z.order\n if order == 'F':\n assert z[:].flags.f_contiguous\n else:\n assert z[:].flags.c_contiguous\n z[:] = a\n assert_array_equal(a, z[:])\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # 2D\n a = np.arange(10000).reshape((100, 100))\n for order in 'C', 'F':\n z = self.create_array(shape=a.shape, chunks=(10, 10),\n dtype=a.dtype, order=order)\n assert order == z.order\n if order == 'F':\n assert z[:].flags.f_contiguous\n else:\n assert z[:].flags.c_contiguous\n z[:] = a\n actual = z[:]\n assert_array_equal(a, actual)\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_setitem_data_not_shared(self):\n # check that data don't end up being shared with another array\n # https://github.com/alimanfoo/zarr/issues/79\n z = self.create_array(shape=20, chunks=10, dtype='i4')\n a = np.arange(20, dtype='i4')\n z[:] = a\n assert_array_equal(z[:], np.arange(20, dtype='i4'))\n a[:] = 0\n assert_array_equal(z[:], np.arange(20, dtype='i4'))\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def expected(self):\n return [\n \"063b02ff8d9d3bab6da932ad5828b506ef0a6578\",\n \"f97b84dc9ffac807415f750100108764e837bb82\",\n \"c7190ad2bea1e9d2e73eaa2d3ca9187be1ead261\",\n \"14470724dca6c1837edddedc490571b6a7f270bc\",\n \"2a1046dd99b914459b3e86be9dde05027a07d209\",\n ]\n\n def test_hexdigest(self):\n found = []\n\n # Check basic 1-D array\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n found.append(z.hexdigest())\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # Check basic 1-D array with different type\n z = self.create_array(shape=(1050,), chunks=100, dtype='<f4')\n found.append(z.hexdigest())\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # Check basic 2-D array\n z = self.create_array(shape=(20, 35,), chunks=10, dtype='<i4')\n found.append(z.hexdigest())\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # Check basic 1-D array with some data\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z[200:400] = np.arange(200, 400, dtype='i4')\n found.append(z.hexdigest())\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # Check basic 1-D array with attributes\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z.attrs['foo'] = 'bar'\n found.append(z.hexdigest())\n if hasattr(z.store, 'close'):\n z.store.close()\n\n self.expected() == found\n\n def test_resize_1d(self):\n\n z = self.create_array(shape=105, chunks=10, dtype='i4',\n fill_value=0)\n a = np.arange(105, dtype='i4')\n z[:] = a\n assert (105,) == z.shape\n assert (105,) == z[:].shape\n assert np.dtype('i4') == z.dtype\n assert np.dtype('i4') == z[:].dtype\n assert (10,) == z.chunks\n assert_array_equal(a, z[:])\n\n z.resize(205)\n assert (205,) == z.shape\n assert (205,) == z[:].shape\n assert np.dtype('i4') == z.dtype\n assert np.dtype('i4') == z[:].dtype\n assert (10,) == z.chunks\n assert_array_equal(a, z[:105])\n assert_array_equal(np.zeros(100, dtype='i4'), z[105:])\n\n z.resize(55)\n assert (55,) == z.shape\n assert (55,) == z[:].shape\n assert np.dtype('i4') == z.dtype\n assert np.dtype('i4') == z[:].dtype\n assert (10,) == z.chunks\n assert_array_equal(a[:55], z[:])\n\n # via shape setter\n z.shape = (105,)\n assert (105,) == z.shape\n assert (105,) == z[:].shape\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_resize_2d(self):\n\n z = self.create_array(shape=(105, 105), chunks=(10, 10), dtype='i4',\n fill_value=0)\n a = np.arange(105*105, dtype='i4').reshape((105, 105))\n z[:] = a\n assert (105, 105) == z.shape\n assert (105, 105) == z[:].shape\n assert np.dtype('i4') == z.dtype\n assert np.dtype('i4') == z[:].dtype\n assert (10, 10) == z.chunks\n assert_array_equal(a, z[:])\n\n z.resize((205, 205))\n assert (205, 205) == z.shape\n assert (205, 205) == z[:].shape\n assert np.dtype('i4') == z.dtype\n assert np.dtype('i4') == z[:].dtype\n assert (10, 10) == z.chunks\n assert_array_equal(a, z[:105, :105])\n assert_array_equal(np.zeros((100, 205), dtype='i4'), z[105:, :])\n assert_array_equal(np.zeros((205, 100), dtype='i4'), z[:, 105:])\n\n z.resize((55, 55))\n assert (55, 55) == z.shape\n assert (55, 55) == z[:].shape\n assert np.dtype('i4') == z.dtype\n assert np.dtype('i4') == z[:].dtype\n assert (10, 10) == z.chunks\n assert_array_equal(a[:55, :55], z[:])\n\n z.resize((55, 1))\n assert (55, 1) == z.shape\n assert (55, 1) == z[:].shape\n assert np.dtype('i4') == z.dtype\n assert np.dtype('i4') == z[:].dtype\n assert (10, 10) == z.chunks\n assert_array_equal(a[:55, :1], z[:])\n\n # via shape setter\n z.shape = (105, 105)\n assert (105, 105) == z.shape\n assert (105, 105) == z[:].shape\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_append_1d(self):\n\n a = np.arange(105)\n z = self.create_array(shape=a.shape, chunks=10, dtype=a.dtype)\n z[:] = a\n assert a.shape == z.shape\n assert a.dtype == z.dtype\n assert (10,) == z.chunks\n assert_array_equal(a, z[:])\n\n b = np.arange(105, 205)\n e = np.append(a, b)\n z.append(b)\n assert e.shape == z.shape\n assert e.dtype == z.dtype\n assert (10,) == z.chunks\n assert_array_equal(e, z[:])\n\n # check append handles array-like\n c = [1, 2, 3]\n f = np.append(e, c)\n z.append(c)\n assert f.shape == z.shape\n assert f.dtype == z.dtype\n assert (10,) == z.chunks\n assert_array_equal(f, z[:])\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_append_2d(self):\n\n a = np.arange(105*105, dtype='i4').reshape((105, 105))\n z = self.create_array(shape=a.shape, chunks=(10, 10), dtype=a.dtype)\n z[:] = a\n assert a.shape == z.shape\n assert a.dtype == z.dtype\n assert (10, 10) == z.chunks\n actual = z[:]\n assert_array_equal(a, actual)\n\n b = np.arange(105*105, 2*105*105, dtype='i4').reshape((105, 105))\n e = np.append(a, b, axis=0)\n z.append(b)\n assert e.shape == z.shape\n assert e.dtype == z.dtype\n assert (10, 10) == z.chunks\n actual = z[:]\n assert_array_equal(e, actual)\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_append_2d_axis(self):\n\n a = np.arange(105*105, dtype='i4').reshape((105, 105))\n z = self.create_array(shape=a.shape, chunks=(10, 10), dtype=a.dtype)\n z[:] = a\n assert a.shape == z.shape\n assert a.dtype == z.dtype\n assert (10, 10) == z.chunks\n assert_array_equal(a, z[:])\n\n b = np.arange(105*105, 2*105*105, dtype='i4').reshape((105, 105))\n e = np.append(a, b, axis=1)\n z.append(b, axis=1)\n assert e.shape == z.shape\n assert e.dtype == z.dtype\n assert (10, 10) == z.chunks\n assert_array_equal(e, z[:])\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_append_bad_shape(self):\n a = np.arange(100)\n z = self.create_array(shape=a.shape, chunks=10, dtype=a.dtype)\n z[:] = a\n b = a.reshape(10, 10)\n with pytest.raises(ValueError):\n z.append(b)\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_read_only(self):\n\n z = self.create_array(shape=1000, chunks=100)\n assert not z.read_only\n if hasattr(z.store, 'close'):\n z.store.close()\n\n z = self.create_array(shape=1000, chunks=100, read_only=True)\n assert z.read_only\n with pytest.raises(PermissionError):\n z[:] = 42\n with pytest.raises(PermissionError):\n z.resize(2000)\n with pytest.raises(PermissionError):\n z.append(np.arange(1000))\n with pytest.raises(PermissionError):\n z.set_basic_selection(Ellipsis, 42)\n with pytest.raises(PermissionError):\n z.set_orthogonal_selection([0, 1, 2], 42)\n with pytest.raises(PermissionError):\n z.oindex[[0, 1, 2]] = 42\n with pytest.raises(PermissionError):\n z.set_coordinate_selection([0, 1, 2], 42)\n with pytest.raises(PermissionError):\n z.vindex[[0, 1, 2]] = 42\n with pytest.raises(PermissionError):\n z.set_mask_selection(np.ones(z.shape, dtype=bool), 42)\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_pickle(self):\n\n # setup array\n z = self.create_array(shape=1000, chunks=100, dtype=int, cache_metadata=False,\n cache_attrs=False)\n shape = z.shape\n chunks = z.chunks\n dtype = z.dtype\n compressor_config = None\n if z.compressor:\n compressor_config = z.compressor.get_config()\n fill_value = z.fill_value\n cache_metadata = z._cache_metadata\n attrs_cache = z.attrs.cache\n a = np.random.randint(0, 1000, 1000)\n z[:] = a\n\n # round trip through pickle\n dump = pickle.dumps(z)\n # some stores cannot be opened twice at the same time, need to close\n # store before can round-trip through pickle\n if hasattr(z.store, 'close'):\n z.store.close()\n z2 = pickle.loads(dump)\n\n # verify\n assert shape == z2.shape\n assert chunks == z2.chunks\n assert dtype == z2.dtype\n if z2.compressor:\n assert compressor_config == z2.compressor.get_config()\n assert fill_value == z2.fill_value\n assert cache_metadata == z2._cache_metadata\n assert attrs_cache == z2.attrs.cache\n assert_array_equal(a, z2[:])\n\n if hasattr(z2.store, 'close'):\n z2.store.close()\n\n def test_np_ufuncs(self):\n z = self.create_array(shape=(100, 100), chunks=(10, 10))\n a = np.arange(10000).reshape(100, 100)\n z[:] = a\n\n assert np.sum(a) == np.sum(z)\n assert_array_equal(np.sum(a, axis=0), np.sum(z, axis=0))\n assert np.mean(a) == np.mean(z)\n assert_array_equal(np.mean(a, axis=1), np.mean(z, axis=1))\n condition = np.random.randint(0, 2, size=100, dtype=bool)\n assert_array_equal(np.compress(condition, a, axis=0),\n np.compress(condition, z, axis=0))\n indices = np.random.choice(100, size=50, replace=True)\n assert_array_equal(np.take(a, indices, axis=1),\n np.take(z, indices, axis=1))\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # use zarr array as indices or condition\n zc = self.create_array(shape=condition.shape, dtype=condition.dtype,\n chunks=10, filters=None)\n zc[:] = condition\n assert_array_equal(np.compress(condition, a, axis=0),\n np.compress(zc, a, axis=0))\n if hasattr(zc.store, 'close'):\n zc.store.close()\n\n zi = self.create_array(shape=indices.shape, dtype=indices.dtype,\n chunks=10, filters=None)\n zi[:] = indices\n # this triggers __array__() call with dtype argument\n assert_array_equal(np.take(a, indices, axis=1),\n np.take(a, zi, axis=1))\n if hasattr(zi.store, 'close'):\n zi.store.close()\n\n # noinspection PyStatementEffect\n def test_0len_dim_1d(self):\n # Test behaviour for 1D array with zero-length dimension.\n\n z = self.create_array(shape=0, fill_value=0)\n a = np.zeros(0)\n assert a.ndim == z.ndim\n assert a.shape == z.shape\n assert a.dtype == z.dtype\n assert a.size == z.size\n assert 0 == z.nchunks\n\n # cannot make a good decision when auto-chunking if a dimension has zero length,\n # fall back to 1 for now\n assert (1,) == z.chunks\n\n # check __getitem__\n assert isinstance(z[:], np.ndarray)\n assert_array_equal(a, np.array(z))\n assert_array_equal(a, z[:])\n assert_array_equal(a, z[...])\n assert_array_equal(a[0:0], z[0:0])\n with pytest.raises(IndexError):\n z[0]\n\n # check __setitem__\n # these should succeed but do nothing\n z[:] = 42\n z[...] = 42\n # this should error\n with pytest.raises(IndexError):\n z[0] = 42\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # noinspection PyStatementEffect\n def test_0len_dim_2d(self):\n # Test behavioud for 2D array with a zero-length dimension.\n\n z = self.create_array(shape=(10, 0), fill_value=0)\n a = np.zeros((10, 0))\n assert a.ndim == z.ndim\n assert a.shape == z.shape\n assert a.dtype == z.dtype\n assert a.size == z.size\n assert 0 == z.nchunks\n\n # cannot make a good decision when auto-chunking if a dimension has zero length,\n # fall back to 1 for now\n assert (10, 1) == z.chunks\n\n # check __getitem__\n assert isinstance(z[:], np.ndarray)\n assert_array_equal(a, np.array(z))\n assert_array_equal(a, z[:])\n assert_array_equal(a, z[...])\n assert_array_equal(a[0], z[0])\n assert_array_equal(a[0, 0:0], z[0, 0:0])\n assert_array_equal(a[0, :], z[0, :])\n assert_array_equal(a[0, 0:0], z[0, 0:0])\n with pytest.raises(IndexError):\n z[:, 0]\n\n # check __setitem__\n # these should succeed but do nothing\n z[:] = 42\n z[...] = 42\n z[0, :] = 42\n # this should error\n with pytest.raises(IndexError):\n z[:, 0] = 42\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # noinspection PyStatementEffect\n def test_array_0d(self):\n # test behaviour for array with 0 dimensions\n\n # setup\n a = np.zeros(())\n z = self.create_array(shape=(), dtype=a.dtype, fill_value=0)\n\n # check properties\n assert a.ndim == z.ndim\n assert a.shape == z.shape\n assert a.size == z.size\n assert a.dtype == z.dtype\n assert a.nbytes == z.nbytes\n with pytest.raises(TypeError):\n len(z)\n assert () == z.chunks\n assert 1 == z.nchunks\n assert (1,) == z.cdata_shape\n # compressor always None - no point in compressing a single value\n assert z.compressor is None\n\n # check __getitem__\n b = z[...]\n assert isinstance(b, np.ndarray)\n assert a.shape == b.shape\n assert a.dtype == b.dtype\n assert_array_equal(a, np.array(z))\n assert_array_equal(a, z[...])\n assert a[()] == z[()]\n with pytest.raises(IndexError):\n z[0]\n with pytest.raises(IndexError):\n z[:]\n\n # check __setitem__\n z[...] = 42\n assert 42 == z[()]\n z[()] = 43\n assert 43 == z[()]\n with pytest.raises(IndexError):\n z[0] = 42\n with pytest.raises(IndexError):\n z[:] = 42\n with pytest.raises(ValueError):\n z[...] = np.array([1, 2, 3])\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_nchunks_initialized(self):\n\n z = self.create_array(shape=100, chunks=10)\n assert 0 == z.nchunks_initialized\n # manually put something into the store to confuse matters\n z.store['foo'] = b'bar'\n assert 0 == z.nchunks_initialized\n z[:] = 42\n assert 10 == z.nchunks_initialized\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_array_dtype_shape(self):\n\n dt = \"(2, 2)f4\"\n # setup some data\n d = np.array([((0, 1),\n (1, 2)),\n ((1, 2),\n (2, 3)),\n ((2, 3),\n (3, 4))],\n dtype=dt)\n\n for a in (d, d[:0]):\n for fill_value in None, 0:\n z = self.create_array(shape=a.shape[:-2], chunks=2, dtype=dt, fill_value=fill_value)\n assert len(a) == len(z)\n if fill_value is not None:\n assert fill_value == z.fill_value\n z[...] = a\n assert_array_equal(a, z[...])\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def check_structured_array(self, d, fill_values):\n for a in (d, d[:0]):\n for fill_value in fill_values:\n z = self.create_array(shape=a.shape, chunks=2, dtype=a.dtype, fill_value=fill_value)\n assert len(a) == len(z)\n assert a.shape == z.shape\n assert a.dtype == z.dtype\n\n # check use of fill value before array is initialised with data\n if fill_value is not None:\n if fill_value == b'':\n # numpy 1.14 compatibility\n np_fill_value = np.array(fill_value, dtype=a.dtype.str).view(a.dtype)[()]\n else:\n np_fill_value = np.array(fill_value, dtype=a.dtype)[()]\n assert np_fill_value == z.fill_value\n if len(a):\n assert np_fill_value == z[0]\n assert np_fill_value == z[-1]\n empty = np.empty_like(a)\n empty[:] = np_fill_value\n assert empty[0] == z[0]\n assert_array_equal(empty[0:2], z[0:2])\n assert_array_equal(empty, z[...])\n for f in a.dtype.names:\n assert_array_equal(empty[f], z[f])\n\n # store data in array\n z[...] = a\n\n # check stored data\n if len(a):\n assert a[0] == z[0]\n assert a[-1] == z[-1]\n assert_array_equal(a[0:2], z[0:2])\n assert_array_equal(a, z[...])\n for f in a.dtype.names:\n assert_array_equal(a[f], z[f])\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_structured_array(self):\n d = np.array([(b'aaa', 1, 4.2),\n (b'bbb', 2, 8.4),\n (b'ccc', 3, 12.6)],\n dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])\n fill_values = None, b'', (b'zzz', 42, 16.8)\n self.check_structured_array(d, fill_values)\n\n def test_structured_array_subshapes(self):\n d = np.array([(0, ((0, 1, 2), (1, 2, 3)), b'aaa'),\n (1, ((1, 2, 3), (2, 3, 4)), b'bbb'),\n (2, ((2, 3, 4), (3, 4, 5)), b'ccc')],\n dtype=[('foo', 'i8'), ('bar', '(2, 3)f4'), ('baz', 'S3')])\n fill_values = None, b'', (0, ((0, 0, 0), (1, 1, 1)), b'zzz')\n self.check_structured_array(d, fill_values)\n\n def test_structured_array_nested(self):\n d = np.array([(0, (0, ((0, 1), (1, 2), (2, 3)), 0), b'aaa'),\n (1, (1, ((1, 2), (2, 3), (3, 4)), 1), b'bbb'),\n (2, (2, ((2, 3), (3, 4), (4, 5)), 2), b'ccc')],\n dtype=[('foo', 'i8'), ('bar', [('foo', 'i4'), ('bar', '(3, 2)f4'),\n ('baz', 'u1')]), ('baz', 'S3')])\n fill_values = None, b'', (0, (0, ((0, 0), (1, 1), (2, 2)), 0), b'zzz')\n self.check_structured_array(d, fill_values)\n\n def test_dtypes(self):\n\n # integers\n for dtype in 'u1', 'u2', 'u4', 'u8', 'i1', 'i2', 'i4', 'i8':\n z = self.create_array(shape=10, chunks=3, dtype=dtype)\n assert z.dtype == np.dtype(dtype)\n a = np.arange(z.shape[0], dtype=dtype)\n z[:] = a\n assert_array_equal(a, z[:])\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # floats\n for dtype in 'f2', 'f4', 'f8':\n z = self.create_array(shape=10, chunks=3, dtype=dtype)\n assert z.dtype == np.dtype(dtype)\n a = np.linspace(0, 1, z.shape[0], dtype=dtype)\n z[:] = a\n assert_array_almost_equal(a, z[:])\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # complex\n for dtype in 'c8', 'c16':\n z = self.create_array(shape=10, chunks=3, dtype=dtype)\n assert z.dtype == np.dtype(dtype)\n a = np.linspace(0, 1, z.shape[0], dtype=dtype)\n a -= 1j * a\n z[:] = a\n assert_array_almost_equal(a, z[:])\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # datetime, timedelta\n for base_type in 'Mm':\n for resolution in 'D', 'us', 'ns':\n dtype = '{}8[{}]'.format(base_type, resolution)\n z = self.create_array(shape=100, dtype=dtype, fill_value=0)\n assert z.dtype == np.dtype(dtype)\n a = np.random.randint(np.iinfo('i8').min, np.iinfo('i8').max,\n size=z.shape[0],\n dtype='i8').view(dtype)\n z[:] = a\n assert_array_equal(a, z[:])\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # check that datetime generic units are not allowed\n with pytest.raises(ValueError):\n self.create_array(shape=100, dtype='M8')\n with pytest.raises(ValueError):\n self.create_array(shape=100, dtype='m8')\n\n def test_object_arrays(self):\n\n # an object_codec is required for object arrays\n with pytest.raises(ValueError):\n self.create_array(shape=10, chunks=3, dtype=object)\n\n # an object_codec is required for object arrays, but allow to be provided via\n # filters to maintain API backwards compatibility\n with pytest.warns(FutureWarning):\n z = self.create_array(shape=10, chunks=3, dtype=object, filters=[MsgPack()])\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # create an object array using msgpack\n z = self.create_array(shape=10, chunks=3, dtype=object, object_codec=MsgPack())\n z[0] = 'foo'\n assert z[0] == 'foo'\n z[1] = b'bar'\n assert z[1] == b'bar'\n z[2] = 1\n assert z[2] == 1\n z[3] = [2, 4, 6, 'baz']\n assert z[3] == [2, 4, 6, 'baz']\n z[4] = {'a': 'b', 'c': 'd'}\n assert z[4] == {'a': 'b', 'c': 'd'}\n a = z[:]\n assert a.dtype == object\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # create an object array using pickle\n z = self.create_array(shape=10, chunks=3, dtype=object, object_codec=Pickle())\n z[0] = 'foo'\n assert z[0] == 'foo'\n z[1] = b'bar'\n assert z[1] == b'bar'\n z[2] = 1\n assert z[2] == 1\n z[3] = [2, 4, 6, 'baz']\n assert z[3] == [2, 4, 6, 'baz']\n z[4] = {'a': 'b', 'c': 'd'}\n assert z[4] == {'a': 'b', 'c': 'd'}\n a = z[:]\n assert a.dtype == object\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # create an object array using JSON\n z = self.create_array(shape=10, chunks=3, dtype=object, object_codec=JSON())\n z[0] = 'foo'\n assert z[0] == 'foo'\n # z[1] = b'bar'\n # assert z[1] == b'bar' # not supported for JSON\n z[2] = 1\n assert z[2] == 1\n z[3] = [2, 4, 6, 'baz']\n assert z[3] == [2, 4, 6, 'baz']\n z[4] = {'a': 'b', 'c': 'd'}\n assert z[4] == {'a': 'b', 'c': 'd'}\n a = z[:]\n assert a.dtype == object\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_object_arrays_vlen_text(self):\n\n data = np.array(greetings * 1000, dtype=object)\n\n z = self.create_array(shape=data.shape, dtype=object, object_codec=VLenUTF8())\n z[0] = 'foo'\n assert z[0] == 'foo'\n z[1] = 'bar'\n assert z[1] == 'bar'\n z[2] = 'baz'\n assert z[2] == 'baz'\n z[:] = data\n a = z[:]\n assert a.dtype == object\n assert_array_equal(data, a)\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # convenience API\n z = self.create_array(shape=data.shape, dtype=str)\n assert z.dtype == object\n assert isinstance(z.filters[0], VLenUTF8)\n z[:] = data\n assert_array_equal(data, z[:])\n if hasattr(z.store, 'close'):\n z.store.close()\n\n z = self.create_array(shape=data.shape, dtype=object, object_codec=MsgPack())\n z[:] = data\n assert_array_equal(data, z[:])\n if hasattr(z.store, 'close'):\n z.store.close()\n\n z = self.create_array(shape=data.shape, dtype=object, object_codec=JSON())\n z[:] = data\n assert_array_equal(data, z[:])\n if hasattr(z.store, 'close'):\n z.store.close()\n\n z = self.create_array(shape=data.shape, dtype=object, object_codec=Pickle())\n z[:] = data\n assert_array_equal(data, z[:])\n if hasattr(z.store, 'close'):\n z.store.close()\n\n z = self.create_array(shape=data.shape, dtype=object,\n object_codec=Categorize(greetings, dtype=object))\n z[:] = data\n assert_array_equal(data, z[:])\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_object_arrays_vlen_bytes(self):\n\n greetings_bytes = [g.encode('utf8') for g in greetings]\n data = np.array(greetings_bytes * 1000, dtype=object)\n\n z = self.create_array(shape=data.shape, dtype=object, object_codec=VLenBytes())\n z[0] = b'foo'\n assert z[0] == b'foo'\n z[1] = b'bar'\n assert z[1] == b'bar'\n z[2] = b'baz'\n assert z[2] == b'baz'\n z[:] = data\n a = z[:]\n assert a.dtype == object\n assert_array_equal(data, a)\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # convenience API\n z = self.create_array(shape=data.shape, dtype=bytes)\n assert z.dtype == object\n assert isinstance(z.filters[0], VLenBytes)\n z[:] = data\n assert_array_equal(data, z[:])\n if hasattr(z.store, 'close'):\n z.store.close()\n\n z = self.create_array(shape=data.shape, dtype=object, object_codec=Pickle())\n z[:] = data\n assert_array_equal(data, z[:])\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_object_arrays_vlen_array(self):\n\n data = np.array([np.array([1, 3, 7]),\n np.array([5]),\n np.array([2, 8, 12])] * 1000, dtype=object)\n\n def compare_arrays(expected, actual, item_dtype):\n assert isinstance(actual, np.ndarray)\n assert actual.dtype == object\n assert actual.shape == expected.shape\n for ev, av in zip(expected.flat, actual.flat):\n assert isinstance(av, np.ndarray)\n assert_array_equal(ev, av)\n assert av.dtype == item_dtype\n\n codecs = VLenArray(int), VLenArray('<u4')\n for codec in codecs:\n z = self.create_array(shape=data.shape, dtype=object, object_codec=codec)\n z[0] = np.array([4, 7])\n assert_array_equal(np.array([4, 7]), z[0])\n z[:] = data\n a = z[:]\n assert a.dtype == object\n compare_arrays(data, a, codec.dtype)\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # convenience API\n for item_type in 'int', '<u4':\n z = self.create_array(shape=data.shape, dtype='array:{}'.format(item_type))\n assert z.dtype == object\n assert isinstance(z.filters[0], VLenArray)\n assert z.filters[0].dtype == np.dtype(item_type)\n z[:] = data\n compare_arrays(data, z[:], np.dtype(item_type))\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_object_arrays_danger(self):\n\n # do something dangerous - manually force an object array with no object codec\n z = self.create_array(shape=5, chunks=2, dtype=object, fill_value=0,\n object_codec=MsgPack())\n z._filters = None # wipe filters\n with pytest.raises(RuntimeError):\n z[0] = 'foo'\n with pytest.raises(RuntimeError):\n z[:] = 42\n if hasattr(z.store, 'close'):\n z.store.close()\n\n # do something else dangerous\n data = greetings * 10\n for compressor in Zlib(1), Blosc():\n z = self.create_array(shape=len(data), chunks=30, dtype=object,\n object_codec=Categorize(greetings,\n dtype=object),\n compressor=compressor)\n z[:] = data\n v = z.view(filters=[])\n with pytest.raises(RuntimeError):\n # noinspection PyStatementEffect\n v[:]\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_object_codec_warnings(self):\n\n with pytest.warns(UserWarning):\n # provide object_codec, but not object dtype\n z = self.create_array(shape=10, chunks=5, dtype='i4', object_codec=JSON())\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_iteration_exceptions(self):\n # zero d array\n a = np.array(1, dtype=int)\n z = self.create_array(shape=a.shape, dtype=int)\n z[...] = a\n with pytest.raises(TypeError):\n # noinspection PyStatementEffect\n list(a)\n with pytest.raises(TypeError):\n # noinspection PyStatementEffect\n list(z)\n\n # input argument error handling\n a = np.array((10, 10), dtype=int)\n z = self.create_array(shape=a.shape, dtype=int)\n z[...] = a\n\n params = (\n (-1, 0),\n (0, -1),\n (0.5, 1),\n (0, 0.5)\n )\n\n for start, end in params:\n with pytest.raises(ValueError):\n # noinspection PyStatementEffect\n list(z.islice(start, end))\n\n # check behavior for start > end\n assert [] == list(z.islice(6, 5))\n\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_iter(self):\n params = (\n ((1,), (1,)),\n ((2,), (1,)),\n ((1,), (2,)),\n ((3,), (3,)),\n ((1000,), (100,)),\n ((100,), (1000,)),\n ((1, 100), (1, 1)),\n ((1, 0), (1, 1)),\n ((0, 1), (1, 1)),\n ((0, 1), (2, 1)),\n ((100, 1), (3, 1)),\n ((100, 100), (10, 10)),\n ((10, 10, 10), (3, 3, 3)),\n )\n for shape, chunks in params:\n z = self.create_array(shape=shape, chunks=chunks, dtype=int)\n a = np.arange(np.product(shape)).reshape(shape)\n z[:] = a\n for expect, actual in zip_longest(a, z):\n assert_array_equal(expect, actual)\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_islice(self):\n params = (\n ((1,), (1,), 0, 1),\n ((2,), (1,), 0, 1),\n ((1,), (2,), 0, 1),\n ((3,), (3,), 1, 2),\n ((1000,), (100,), 150, 1050),\n ((100,), (1000,), 25, 75),\n ((1, 100), (1, 1), 0, 1),\n ((100, 1), (3, 1), 56, 100),\n ((100, 100), (10, 10), 13, 99),\n ((10, 10, 10), (3, 3, 3), 2, 4),\n )\n for shape, chunks, start, end in params:\n z = self.create_array(shape=shape, chunks=chunks, dtype=int)\n a = np.arange(np.product(shape)).reshape(shape)\n z[:] = a\n end_array = min(end, a.shape[0])\n for expect, actual in zip_longest(a[start:end_array],\n z.islice(start, end)):\n assert_array_equal(expect, actual)\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_compressors(self):\n compressors = [\n None, BZ2(), Blosc(), LZ4(), Zlib(), GZip()\n ]\n if LZMA:\n compressors.append(LZMA())\n for compressor in compressors:\n a = self.create_array(shape=1000, chunks=100, compressor=compressor)\n a[0:100] = 1\n assert np.all(a[0:100] == 1)\n a[:] = 1\n assert np.all(a[:] == 1)\n if hasattr(a.store, 'close'):\n a.store.close()\n\n def test_endian(self):\n dtype = np.dtype('float32')\n a1 = self.create_array(shape=1000, chunks=100, dtype=dtype.newbyteorder('<'))\n a1[:] = 1\n x1 = a1[:]\n a2 = self.create_array(shape=1000, chunks=100, dtype=dtype.newbyteorder('>'))\n a2[:] = 1\n x2 = a2[:]\n assert_array_equal(x1, x2)\n if hasattr(a1.store, 'close'):\n a1.store.close()\n if hasattr(a2.store, 'close'):\n a2.store.close()\n\n def test_attributes(self):\n a = self.create_array(shape=10, chunks=10, dtype='i8')\n a.attrs['foo'] = 'bar'\n assert a.attrs.key in a.store\n attrs = json_loads(a.store[a.attrs.key])\n assert 'foo' in attrs and attrs['foo'] == 'bar'\n\n a.attrs['bar'] = 'foo'\n assert a.attrs.key in a.store\n attrs = json_loads(a.store[a.attrs.key])\n assert 'foo' in attrs and attrs['foo'] == 'bar'\n assert 'bar' in attrs and attrs['bar'] == 'foo'\n if hasattr(a.store, 'close'):\n a.store.close()\n\n\nclass TestArrayWithPath(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n store = dict()\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n init_array(store, path='foo/bar', **kwargs)\n return Array(store, path='foo/bar', read_only=read_only,\n cache_metadata=cache_metadata, cache_attrs=cache_attrs)\n\n def test_hexdigest(self):\n # Check basic 1-D array\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n assert 'f710da18d45d38d4aaf2afd7fb822fdd73d02957' == z.hexdigest()\n\n # Check basic 1-D array with different type\n z = self.create_array(shape=(1050,), chunks=100, dtype='<f4')\n assert '1437428e69754b1e1a38bd7fc9e43669577620db' == z.hexdigest()\n\n # Check basic 2-D array\n z = self.create_array(shape=(20, 35,), chunks=10, dtype='<i4')\n assert '6c530b6b9d73e108cc5ee7b6be3d552cc994bdbe' == z.hexdigest()\n\n # Check basic 1-D array with some data\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z[200:400] = np.arange(200, 400, dtype='i4')\n assert '4c0a76fb1222498e09dcd92f7f9221d6cea8b40e' == z.hexdigest()\n\n # Check basic 1-D array with attributes\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z.attrs['foo'] = 'bar'\n assert '05b0663ffe1785f38d3a459dec17e57a18f254af' == z.hexdigest()\n\n def test_nbytes_stored(self):\n\n # dict as store\n z = self.create_array(shape=1000, chunks=100)\n expect_nbytes_stored = sum(buffer_size(v)\n for k, v in z.store.items()\n if k.startswith('foo/bar/'))\n assert expect_nbytes_stored == z.nbytes_stored\n z[:] = 42\n expect_nbytes_stored = sum(buffer_size(v)\n for k, v in z.store.items()\n if k.startswith('foo/bar/'))\n assert expect_nbytes_stored == z.nbytes_stored\n\n # mess with store\n z.store[z._key_prefix + 'foo'] = list(range(10))\n assert -1 == z.nbytes_stored\n\n\nclass TestArrayWithChunkStore(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n store = dict()\n # separate chunk store\n chunk_store = dict()\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n init_array(store, chunk_store=chunk_store, **kwargs)\n return Array(store, read_only=read_only, chunk_store=chunk_store,\n cache_metadata=cache_metadata, cache_attrs=cache_attrs)\n\n def test_hexdigest(self):\n # Check basic 1-D array\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n assert 'f710da18d45d38d4aaf2afd7fb822fdd73d02957' == z.hexdigest()\n\n # Check basic 1-D array with different type\n z = self.create_array(shape=(1050,), chunks=100, dtype='<f4')\n assert '1437428e69754b1e1a38bd7fc9e43669577620db' == z.hexdigest()\n\n # Check basic 2-D array\n z = self.create_array(shape=(20, 35,), chunks=10, dtype='<i4')\n assert '6c530b6b9d73e108cc5ee7b6be3d552cc994bdbe' == z.hexdigest()\n\n # Check basic 1-D array with some data\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z[200:400] = np.arange(200, 400, dtype='i4')\n assert '4c0a76fb1222498e09dcd92f7f9221d6cea8b40e' == z.hexdigest()\n\n # Check basic 1-D array with attributes\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z.attrs['foo'] = 'bar'\n assert '05b0663ffe1785f38d3a459dec17e57a18f254af' == z.hexdigest()\n\n def test_nbytes_stored(self):\n\n z = self.create_array(shape=1000, chunks=100)\n expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values())\n expect_nbytes_stored += sum(buffer_size(v)\n for v in z.chunk_store.values())\n assert expect_nbytes_stored == z.nbytes_stored\n z[:] = 42\n expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values())\n expect_nbytes_stored += sum(buffer_size(v)\n for v in z.chunk_store.values())\n assert expect_nbytes_stored == z.nbytes_stored\n\n # mess with store\n z.chunk_store[z._key_prefix + 'foo'] = list(range(10))\n assert -1 == z.nbytes_stored\n\n\nclass TestArrayWithDirectoryStore(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n store = DirectoryStore(path)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n def test_nbytes_stored(self):\n\n # dict as store\n z = self.create_array(shape=1000, chunks=100)\n expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values())\n assert expect_nbytes_stored == z.nbytes_stored\n z[:] = 42\n expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values())\n assert expect_nbytes_stored == z.nbytes_stored\n\n\n@skip_test_env_var(\"ZARR_TEST_ABS\")\nclass TestArrayWithABSStore(TestArray):\n\n @staticmethod\n def absstore():\n asb = pytest.importorskip(\"azure.storage.blob\")\n blob_client = asb.BlockBlobService(is_emulated=True)\n blob_client.delete_container('test')\n blob_client.create_container('test')\n store = ABSStore(container='test', account_name='foo', account_key='bar',\n blob_service_kwargs={'is_emulated': True})\n store.rmdir()\n return store\n\n def create_array(self, read_only=False, **kwargs):\n store = self.absstore()\n kwargs.setdefault('compressor', Zlib(1))\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n @pytest.mark.xfail\n def test_nbytes_stored(self):\n return super().test_nbytes_stored()\n\n\nclass TestArrayWithNestedDirectoryStore(TestArrayWithDirectoryStore):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n store = NestedDirectoryStore(path)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n def expected(self):\n return [\n \"d174aa384e660eb51c6061fc8d20850c1159141f\",\n \"125f00eea40032f16016b292f6767aa3928c00a7\",\n \"1b52ead0ed889a781ebd4db077a29e35d513c1f3\",\n \"719a88b34e362ff65df30e8f8810c1146ab72bc1\",\n \"6e0abf30daf45de51593c227fb907759ca725551\",\n ]\n\n\nclass TestArrayWithN5Store(TestArrayWithDirectoryStore):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n store = N5Store(path)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n def test_array_0d(self):\n # test behaviour for array with 0 dimensions\n\n # setup\n a = np.zeros(())\n z = self.create_array(shape=(), dtype=a.dtype, fill_value=0)\n\n # check properties\n assert a.ndim == z.ndim\n assert a.shape == z.shape\n assert a.size == z.size\n assert a.dtype == z.dtype\n assert a.nbytes == z.nbytes\n with pytest.raises(TypeError):\n len(z)\n assert () == z.chunks\n assert 1 == z.nchunks\n assert (1,) == z.cdata_shape\n # compressor always None - no point in compressing a single value\n assert z.compressor.compressor_config is None\n\n # check __getitem__\n b = z[...]\n assert isinstance(b, np.ndarray)\n assert a.shape == b.shape\n assert a.dtype == b.dtype\n assert_array_equal(a, np.array(z))\n assert_array_equal(a, z[...])\n assert a[()] == z[()]\n with pytest.raises(IndexError):\n z[0]\n with pytest.raises(IndexError):\n z[:]\n\n # check __setitem__\n z[...] = 42\n assert 42 == z[()]\n z[()] = 43\n assert 43 == z[()]\n with pytest.raises(IndexError):\n z[0] = 42\n with pytest.raises(IndexError):\n z[:] = 42\n with pytest.raises(ValueError):\n z[...] = np.array([1, 2, 3])\n\n def test_array_1d_fill_value(self):\n nvalues = 1050\n dtype = np.int32\n for fill_value in 0, None:\n a = np.arange(nvalues, dtype=dtype)\n f = np.empty_like(a)\n f.fill(fill_value or 0)\n z = self.create_array(shape=a.shape, chunks=100, dtype=a.dtype,\n fill_value=fill_value)\n z[190:310] = a[190:310]\n\n assert_array_equal(f[:190], z[:190])\n assert_array_equal(a[190:310], z[190:310])\n assert_array_equal(f[310:], z[310:])\n\n with pytest.raises(ValueError):\n z = self.create_array(shape=(nvalues,), chunks=100, dtype=dtype,\n fill_value=1)\n\n def test_array_order(self):\n\n # N5 only supports 'C' at the moment\n with pytest.raises(ValueError):\n self.create_array(shape=(10, 11), chunks=(10, 11), dtype='i8',\n order='F')\n\n # 1D\n a = np.arange(1050)\n z = self.create_array(shape=a.shape, chunks=100, dtype=a.dtype,\n order='C')\n assert z.order == 'C'\n assert z[:].flags.c_contiguous\n z[:] = a\n assert_array_equal(a, z[:])\n\n # 2D\n a = np.arange(10000).reshape((100, 100))\n z = self.create_array(shape=a.shape, chunks=(10, 10),\n dtype=a.dtype, order='C')\n\n assert z.order == 'C'\n assert z[:].flags.c_contiguous\n z[:] = a\n actual = z[:]\n assert_array_equal(a, actual)\n\n def test_structured_array(self):\n d = np.array([(b'aaa', 1, 4.2),\n (b'bbb', 2, 8.4),\n (b'ccc', 3, 12.6)],\n dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])\n fill_values = None, b'', (b'zzz', 42, 16.8)\n with pytest.raises(TypeError):\n self.check_structured_array(d, fill_values)\n\n def test_structured_array_subshapes(self):\n d = np.array([(0, ((0, 1, 2), (1, 2, 3)), b'aaa'),\n (1, ((1, 2, 3), (2, 3, 4)), b'bbb'),\n (2, ((2, 3, 4), (3, 4, 5)), b'ccc')],\n dtype=[('foo', 'i8'), ('bar', '(2, 3)f4'), ('baz', 'S3')])\n fill_values = None, b'', (0, ((0, 0, 0), (1, 1, 1)), b'zzz')\n with pytest.raises(TypeError):\n self.check_structured_array(d, fill_values)\n\n def test_structured_array_nested(self):\n d = np.array([(0, (0, ((0, 1), (1, 2), (2, 3)), 0), b'aaa'),\n (1, (1, ((1, 2), (2, 3), (3, 4)), 1), b'bbb'),\n (2, (2, ((2, 3), (3, 4), (4, 5)), 2), b'ccc')],\n dtype=[('foo', 'i8'), ('bar', [('foo', 'i4'), ('bar', '(3, 2)f4'),\n ('baz', 'u1')]), ('baz', 'S3')])\n fill_values = None, b'', (0, (0, ((0, 0), (1, 1), (2, 2)), 0), b'zzz')\n with pytest.raises(TypeError):\n self.check_structured_array(d, fill_values)\n\n def test_dtypes(self):\n\n # integers\n for dtype in 'u1', 'u2', 'u4', 'u8', 'i1', 'i2', 'i4', 'i8':\n z = self.create_array(shape=10, chunks=3, dtype=dtype)\n assert z.dtype == np.dtype(dtype)\n a = np.arange(z.shape[0], dtype=dtype)\n z[:] = a\n assert_array_equal(a, z[:])\n\n # floats\n for dtype in 'f2', 'f4', 'f8':\n z = self.create_array(shape=10, chunks=3, dtype=dtype)\n assert z.dtype == np.dtype(dtype)\n a = np.linspace(0, 1, z.shape[0], dtype=dtype)\n z[:] = a\n assert_array_almost_equal(a, z[:])\n\n # check that datetime generic units are not allowed\n with pytest.raises(ValueError):\n self.create_array(shape=100, dtype='M8')\n with pytest.raises(ValueError):\n self.create_array(shape=100, dtype='m8')\n\n def test_object_arrays(self):\n\n # an object_codec is required for object arrays\n with pytest.raises(ValueError):\n self.create_array(shape=10, chunks=3, dtype=object)\n\n # an object_codec is required for object arrays, but allow to be provided via\n # filters to maintain API backwards compatibility\n with pytest.raises(ValueError):\n with pytest.warns(FutureWarning):\n self.create_array(shape=10, chunks=3, dtype=object, filters=[MsgPack()])\n\n # create an object array using an object codec\n with pytest.raises(ValueError):\n self.create_array(shape=10, chunks=3, dtype=object, object_codec=MsgPack())\n\n def test_object_arrays_vlen_text(self):\n\n data = np.array(greetings * 1000, dtype=object)\n\n with pytest.raises(ValueError):\n self.create_array(shape=data.shape, dtype=object, object_codec=VLenUTF8())\n\n # convenience API\n with pytest.raises(ValueError):\n self.create_array(shape=data.shape, dtype=str)\n\n def test_object_arrays_vlen_bytes(self):\n\n greetings_bytes = [g.encode('utf8') for g in greetings]\n data = np.array(greetings_bytes * 1000, dtype=object)\n\n with pytest.raises(ValueError):\n self.create_array(shape=data.shape, dtype=object, object_codec=VLenBytes())\n\n # convenience API\n with pytest.raises(ValueError):\n self.create_array(shape=data.shape, dtype=bytes)\n\n def test_object_arrays_vlen_array(self):\n\n data = np.array([np.array([1, 3, 7]),\n np.array([5]),\n np.array([2, 8, 12])] * 1000, dtype=object)\n\n codecs = VLenArray(int), VLenArray('<u4')\n for codec in codecs:\n with pytest.raises(ValueError):\n self.create_array(shape=data.shape, dtype=object, object_codec=codec)\n\n # convenience API\n for item_type in 'int', '<u4':\n with pytest.raises(ValueError):\n self.create_array(shape=data.shape, dtype='array:{}'.format(item_type))\n\n def test_object_arrays_danger(self):\n # Cannot hacking out object codec as N5 doesn't allow object codecs\n pass\n\n def test_attrs_n5_keywords(self):\n z = self.create_array(shape=(1050,), chunks=100, dtype='i4')\n for k in n5_keywords:\n with pytest.raises(ValueError):\n z.attrs[k] = \"\"\n\n def test_compressors(self):\n compressors = [\n None, BZ2(), Zlib(), GZip()\n ]\n if LZMA:\n compressors.append(LZMA())\n compressors.append(LZMA(preset=1))\n compressors.append(LZMA(preset=6))\n for compressor in compressors:\n a1 = self.create_array(shape=1000, chunks=100, compressor=compressor)\n a1[0:100] = 1\n assert np.all(a1[0:100] == 1)\n a1[:] = 1\n assert np.all(a1[:] == 1)\n\n compressors_warn = [\n Blosc()\n ]\n if LZMA:\n compressors_warn.append(LZMA(2)) # Try lzma.FORMAT_ALONE, which N5 doesn't support.\n for compressor in compressors_warn:\n with pytest.warns(RuntimeWarning):\n a2 = self.create_array(shape=1000, chunks=100, compressor=compressor)\n a2[0:100] = 1\n assert np.all(a2[0:100] == 1)\n a2[:] = 1\n assert np.all(a2[:] == 1)\n\n def expected(self):\n return [\n 'c6b83adfad999fbd865057531d749d87cf138f58',\n 'a3d6d187536ecc3a9dd6897df55d258e2f52f9c5',\n 'ec2e008525ae09616dbc1d2408cbdb42532005c8',\n 'b63f031031dcd5248785616edcb2d6fe68203c28',\n '0cfc673215a8292a87f3c505e2402ce75243c601',\n ]\n\n def test_hexdigest(self):\n found = []\n # Check basic 1-D array\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n found.append(z.hexdigest())\n\n # Check basic 1-D array with different type\n z = self.create_array(shape=(1050,), chunks=100, dtype='<f4')\n found.append(z.hexdigest())\n\n # Check basic 2-D array\n z = self.create_array(shape=(20, 35,), chunks=10, dtype='<i4')\n found.append(z.hexdigest())\n\n # Check basic 1-D array with some data\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z[200:400] = np.arange(200, 400, dtype='i4')\n found.append(z.hexdigest())\n\n # Check basic 1-D array with attributes\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z.attrs['foo'] = 'bar'\n found.append(z.hexdigest())\n\n assert self.expected() == found\n\n\nclass TestArrayWithDBMStore(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n path = mktemp(suffix='.anydbm')\n atexit.register(atexit_rmglob, path + '*')\n store = DBMStore(path, flag='n')\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_attrs=cache_attrs,\n cache_metadata=cache_metadata)\n\n def test_nbytes_stored(self):\n pass # not implemented\n\n\nclass TestArrayWithDBMStoreBerkeleyDB(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n bsddb3 = pytest.importorskip(\"bsddb3\")\n path = mktemp(suffix='.dbm')\n atexit.register(os.remove, path)\n store = DBMStore(path, flag='n', open=bsddb3.btopen)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n def test_nbytes_stored(self):\n pass # not implemented\n\n\nclass TestArrayWithLMDBStore(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n pytest.importorskip(\"lmdb\")\n path = mktemp(suffix='.lmdb')\n atexit.register(atexit_rmtree, path)\n store = LMDBStore(path, buffers=True)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n def test_store_has_bytes_values(self):\n pass # returns values as memoryviews/buffers instead of bytes\n\n def test_nbytes_stored(self):\n pass # not implemented\n\n\nclass TestArrayWithLMDBStoreNoBuffers(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n pytest.importorskip(\"lmdb\")\n path = mktemp(suffix='.lmdb')\n atexit.register(atexit_rmtree, path)\n store = LMDBStore(path, buffers=False)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n def test_nbytes_stored(self):\n pass # not implemented\n\n\nclass TestArrayWithSQLiteStore(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n pytest.importorskip(\"sqlite3\")\n path = mktemp(suffix='.db')\n atexit.register(atexit_rmtree, path)\n store = SQLiteStore(path)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n def test_nbytes_stored(self):\n pass # not implemented\n\n\nclass TestArrayWithNoCompressor(TestArray):\n\n def create_array(self, read_only=False, **kwargs):\n store = dict()\n kwargs.setdefault('compressor', None)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n def test_hexdigest(self):\n # Check basic 1-D array\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n assert 'd3da3d485de4a5fcc6d91f9dfc6a7cba9720c561' == z.hexdigest()\n\n # Check basic 1-D array with different type\n z = self.create_array(shape=(1050,), chunks=100, dtype='<f4')\n assert '443b8dee512e42946cb63ff01d28e9bee8105a5f' == z.hexdigest()\n\n # Check basic 2-D array\n z = self.create_array(shape=(20, 35,), chunks=10, dtype='<i4')\n assert 'b75eb90f68aa8ee1e29f2c542e851d3945066c54' == z.hexdigest()\n\n # Check basic 1-D array with some data\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z[200:400] = np.arange(200, 400, dtype='i4')\n assert '42b6ae0d50ec361628736ab7e68fe5fefca22136' == z.hexdigest()\n\n # Check basic 1-D array with attributes\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z.attrs['foo'] = 'bar'\n assert 'a0535f31c130f5e5ac66ba0713d1c1ceaebd089b' == z.hexdigest()\n\n\nclass TestArrayWithBZ2Compressor(TestArray):\n\n def create_array(self, read_only=False, **kwargs):\n store = dict()\n compressor = BZ2(level=1)\n kwargs.setdefault('compressor', compressor)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n def test_hexdigest(self):\n # Check basic 1-D array\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n assert '33141032439fb1df5e24ad9891a7d845b6c668c8' == z.hexdigest()\n\n # Check basic 1-D array with different type\n z = self.create_array(shape=(1050,), chunks=100, dtype='<f4')\n assert '44d719da065c88a412d609a5500ff41e07b331d6' == z.hexdigest()\n\n # Check basic 2-D array\n z = self.create_array(shape=(20, 35,), chunks=10, dtype='<i4')\n assert '37c7c46e5730bba37da5e518c9d75f0d774c5098' == z.hexdigest()\n\n # Check basic 1-D array with some data\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z[200:400] = np.arange(200, 400, dtype='i4')\n assert '1e1bcaac63e4ef3c4a68f11672537131c627f168' == z.hexdigest()\n\n # Check basic 1-D array with attributes\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z.attrs['foo'] = 'bar'\n assert '86d7b9bf22dccbeaa22f340f38be506b55e76ff2' == z.hexdigest()\n\n\nclass TestArrayWithBloscCompressor(TestArray):\n\n def create_array(self, read_only=False, **kwargs):\n store = dict()\n compressor = Blosc(cname='zstd', clevel=1, shuffle=1)\n kwargs.setdefault('compressor', compressor)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n def test_hexdigest(self):\n # Check basic 1-D array\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n assert '7ff2ae8511eac915fad311647c168ccfe943e788' == z.hexdigest()\n\n # Check basic 1-D array with different type\n z = self.create_array(shape=(1050,), chunks=100, dtype='<f4')\n assert '962705c861863495e9ccb7be7735907aa15e85b5' == z.hexdigest()\n\n # Check basic 2-D array\n z = self.create_array(shape=(20, 35,), chunks=10, dtype='<i4')\n assert '74ed339cfe84d544ac023d085ea0cd6a63f56c4b' == z.hexdigest()\n\n # Check basic 1-D array with some data\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z[200:400] = np.arange(200, 400, dtype='i4')\n assert '90e30bdab745a9641cd0eb605356f531bc8ec1c3' == z.hexdigest()\n\n # Check basic 1-D array with attributes\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z.attrs['foo'] = 'bar'\n assert '95d40c391f167db8b1290e3c39d9bf741edacdf6' == z.hexdigest()\n\n\ntry:\n from numcodecs import LZMA\nexcept ImportError: # pragma: no cover\n LZMA = None\n\n\n@unittest.skipIf(LZMA is None, 'LZMA codec not available')\nclass TestArrayWithLZMACompressor(TestArray):\n\n def create_array(self, read_only=False, **kwargs):\n store = dict()\n compressor = LZMA(preset=1)\n kwargs.setdefault('compressor', compressor)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n def test_hexdigest(self):\n # Check basic 1-D array\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n assert '93ecaa530a1162a9d48a3c1dcee4586ccfc59bae' == z.hexdigest()\n\n # Check basic 1-D array with different type\n z = self.create_array(shape=(1050,), chunks=100, dtype='<f4')\n assert '04a9755a0cd638683531b7816c7fa4fbb6f577f2' == z.hexdigest()\n\n # Check basic 2-D array\n z = self.create_array(shape=(20, 35,), chunks=10, dtype='<i4')\n assert '9de97b5c49b38e68583ed701d7e8f4c94b6a8406' == z.hexdigest()\n\n # Check basic 1-D array with some data\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z[200:400] = np.arange(200, 400, dtype='i4')\n assert 'cde499f3dc945b4e97197ff8e3cf8188a1262c35' == z.hexdigest()\n\n # Check basic 1-D array with attributes\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z.attrs['foo'] = 'bar'\n assert 'e2cf3afbf66ad0e28a2b6b68b1b07817c69aaee2' == z.hexdigest()\n\n\nclass TestArrayWithFilters(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n store = dict()\n dtype = kwargs.get('dtype', None)\n filters = [\n Delta(dtype=dtype),\n FixedScaleOffset(dtype=dtype, scale=1, offset=0),\n ]\n kwargs.setdefault('filters', filters)\n compressor = Zlib(1)\n kwargs.setdefault('compressor', compressor)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_attrs=cache_attrs,\n cache_metadata=cache_metadata)\n\n def test_hexdigest(self):\n # Check basic 1-D array\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n assert 'b80367c5599d47110d42bd8886240c2f46620dba' == z.hexdigest()\n\n # Check basic 1-D array with different type\n z = self.create_array(shape=(1050,), chunks=100, dtype='<f4')\n assert '95a7b2471225e73199c9716d21e8d3dd6e5f6f2a' == z.hexdigest()\n\n # Check basic 2-D array\n z = self.create_array(shape=(20, 35,), chunks=10, dtype='<i4')\n assert '7300f1eb130cff5891630038fd99c28ef23d3a01' == z.hexdigest()\n\n # Check basic 1-D array with some data\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z[200:400] = np.arange(200, 400, dtype='i4')\n assert 'c649ad229bc5720258b934ea958570c2f354c2eb' == z.hexdigest()\n\n # Check basic 1-D array with attributes\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z.attrs['foo'] = 'bar'\n assert '62fc9236d78af18a5ec26c12eea1d33bce52501e' == z.hexdigest()\n\n def test_astype_no_filters(self):\n shape = (100,)\n dtype = np.dtype(np.int8)\n astype = np.dtype(np.float32)\n\n store = dict()\n init_array(store, shape=shape, chunks=10, dtype=dtype)\n\n data = np.arange(np.prod(shape), dtype=dtype).reshape(shape)\n\n z1 = Array(store)\n z1[...] = data\n z2 = z1.astype(astype)\n\n expected = data.astype(astype)\n assert_array_equal(expected, z2)\n assert z2.read_only\n\n def test_astype(self):\n shape = (100,)\n chunks = (10,)\n\n dtype = np.dtype(np.int8)\n astype = np.dtype(np.float32)\n\n data = np.arange(np.prod(shape), dtype=dtype).reshape(shape)\n\n z1 = self.create_array(shape=shape, chunks=chunks, dtype=dtype)\n z1[...] = data\n z2 = z1.astype(astype)\n\n expected = data.astype(astype)\n assert_array_equal(expected, z2)\n\n def test_array_dtype_shape(self):\n # skip this one, cannot do delta on unstructured array\n pass\n\n def test_structured_array(self):\n # skip this one, cannot do delta on structured array\n pass\n\n def test_structured_array_subshapes(self):\n # skip this one, cannot do delta on structured array\n pass\n\n def test_structured_array_nested(self):\n # skip this one, cannot do delta on structured array\n pass\n\n def test_dtypes(self):\n # skip this one, delta messes up floats\n pass\n\n def test_object_arrays(self):\n # skip this one, cannot use delta with objects\n pass\n\n def test_object_arrays_vlen_text(self):\n # skip this one, cannot use delta with objects\n pass\n\n def test_object_arrays_vlen_bytes(self):\n # skip this one, cannot use delta with objects\n pass\n\n def test_object_arrays_vlen_array(self):\n # skip this one, cannot use delta with objects\n pass\n\n def test_object_arrays_danger(self):\n # skip this one, cannot use delta with objects\n pass\n\n\n# custom store, does not support getsize()\nclass CustomMapping(object):\n\n def __init__(self):\n self.inner = dict()\n\n def keys(self):\n return self.inner.keys()\n\n def values(self):\n return self.inner.values()\n\n def get(self, item, default=None):\n try:\n return self.inner[item]\n except KeyError:\n return default\n\n def __getitem__(self, item):\n return self.inner[item]\n\n def __setitem__(self, item, value):\n self.inner[item] = ensure_bytes(value)\n\n def __delitem__(self, key):\n del self.inner[key]\n\n def __contains__(self, item):\n return item in self.inner\n\n\nclass TestArrayWithCustomMapping(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n store = CustomMapping()\n kwargs.setdefault('compressor', Zlib(1))\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n def test_nbytes_stored(self):\n z = self.create_array(shape=1000, chunks=100)\n assert -1 == z.nbytes_stored\n z[:] = 42\n assert -1 == z.nbytes_stored\n\n\nclass TestArrayNoCache(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n store = dict()\n kwargs.setdefault('compressor', Zlib(level=1))\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n def test_cache_metadata(self):\n a1 = self.create_array(shape=100, chunks=10, dtype='i1', cache_metadata=False)\n a2 = Array(a1.store, cache_metadata=True)\n assert a1.shape == a2.shape\n assert a1.size == a2.size\n assert a1.nbytes == a2.nbytes\n assert a1.nchunks == a2.nchunks\n\n # a1 is not caching so *will* see updates made via other objects\n a2.resize(200)\n assert (200,) == a2.shape\n assert 200 == a2.size\n assert 200 == a2.nbytes\n assert 20 == a2.nchunks\n assert a1.shape == a2.shape\n assert a1.size == a2.size\n assert a1.nbytes == a2.nbytes\n assert a1.nchunks == a2.nchunks\n\n a2.append(np.zeros(100))\n assert (300,) == a2.shape\n assert 300 == a2.size\n assert 300 == a2.nbytes\n assert 30 == a2.nchunks\n assert a1.shape == a2.shape\n assert a1.size == a2.size\n assert a1.nbytes == a2.nbytes\n assert a1.nchunks == a2.nchunks\n\n # a2 is caching so *will not* see updates made via other objects\n a1.resize(400)\n assert (400,) == a1.shape\n assert 400 == a1.size\n assert 400 == a1.nbytes\n assert 40 == a1.nchunks\n assert (300,) == a2.shape\n assert 300 == a2.size\n assert 300 == a2.nbytes\n assert 30 == a2.nchunks\n\n def test_cache_attrs(self):\n a1 = self.create_array(shape=100, chunks=10, dtype='i1', cache_attrs=False)\n a2 = Array(a1.store, cache_attrs=True)\n assert a1.attrs.asdict() == a2.attrs.asdict()\n\n # a1 is not caching so *will* see updates made via other objects\n a2.attrs['foo'] = 'xxx'\n a2.attrs['bar'] = 42\n assert a1.attrs.asdict() == a2.attrs.asdict()\n\n # a2 is caching so *will not* see updates made via other objects\n a1.attrs['foo'] = 'yyy'\n assert 'yyy' == a1.attrs['foo']\n assert 'xxx' == a2.attrs['foo']\n\n def test_object_arrays_danger(self):\n # skip this one as it only works if metadata are cached\n pass\n\n\nclass TestArrayWithStoreCache(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n store = LRUStoreCache(dict(), max_size=None)\n kwargs.setdefault('compressor', Zlib(level=1))\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n def test_store_has_bytes_values(self):\n # skip as the cache has no control over how the store provides values\n pass\n\n\n@pytest.mark.skipif(have_fsspec is False, reason=\"needs fsspec\")\nclass TestArrayWithFSStore(TestArray):\n @staticmethod\n def create_array(read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n key_separator = kwargs.pop('key_separator', \".\")\n store = FSStore(path, key_separator=key_separator, auto_mkdir=True)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n kwargs.setdefault('compressor', Blosc())\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n def expected(self):\n return [\n \"ab753fc81df0878589535ca9bad2816ba88d91bc\",\n \"c16261446f9436b1e9f962e57ce3e8f6074abe8a\",\n \"c2ef3b2fb2bc9dcace99cd6dad1a7b66cc1ea058\",\n \"6e52f95ac15b164a8e96843a230fcee0e610729b\",\n \"091fa99bc60706095c9ce30b56ce2503e0223f56\",\n ]\n\n def test_hexdigest(self):\n found = []\n\n # Check basic 1-D array\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n found.append(z.hexdigest())\n\n # Check basic 1-D array with different type\n z = self.create_array(shape=(1050,), chunks=100, dtype='<f4')\n found.append(z.hexdigest())\n\n # Check basic 2-D array\n z = self.create_array(shape=(20, 35,), chunks=10, dtype='<i4')\n found.append(z.hexdigest())\n\n # Check basic 1-D array with some data\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z[200:400] = np.arange(200, 400, dtype='i4')\n found.append(z.hexdigest())\n\n # Check basic 1-D array with attributes\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z.attrs['foo'] = 'bar'\n found.append(z.hexdigest())\n\n assert self.expected() == found\n\n\n@pytest.mark.skipif(have_fsspec is False, reason=\"needs fsspec\")\nclass TestArrayWithFSStorePartialRead(TestArray):\n @staticmethod\n def create_array(read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n store = FSStore(path)\n cache_metadata = kwargs.pop(\"cache_metadata\", True)\n cache_attrs = kwargs.pop(\"cache_attrs\", True)\n kwargs.setdefault(\"compressor\", Blosc())\n init_array(store, **kwargs)\n return Array(\n store,\n read_only=read_only,\n cache_metadata=cache_metadata,\n cache_attrs=cache_attrs,\n partial_decompress=True,\n )\n\n def test_hexdigest(self):\n # Check basic 1-D array\n z = self.create_array(shape=(1050,), chunks=100, dtype=\"<i4\")\n assert \"f710da18d45d38d4aaf2afd7fb822fdd73d02957\" == z.hexdigest()\n\n # Check basic 1-D array with different type\n z = self.create_array(shape=(1050,), chunks=100, dtype=\"<f4\")\n assert \"1437428e69754b1e1a38bd7fc9e43669577620db\" == z.hexdigest()\n\n # Check basic 2-D array\n z = self.create_array(\n shape=(\n 20,\n 35,\n ),\n chunks=10,\n dtype=\"<i4\",\n )\n assert \"6c530b6b9d73e108cc5ee7b6be3d552cc994bdbe\" == z.hexdigest()\n\n # Check basic 1-D array with some data\n z = self.create_array(shape=(1050,), chunks=100, dtype=\"<i4\")\n z[200:400] = np.arange(200, 400, dtype=\"i4\")\n assert \"4c0a76fb1222498e09dcd92f7f9221d6cea8b40e\" == z.hexdigest()\n\n # Check basic 1-D array with attributes\n z = self.create_array(shape=(1050,), chunks=100, dtype=\"<i4\")\n z.attrs[\"foo\"] = \"bar\"\n assert \"05b0663ffe1785f38d3a459dec17e57a18f254af\" == z.hexdigest()\n\n def test_non_cont(self):\n z = self.create_array(shape=(500, 500, 500), chunks=(50, 50, 50), dtype=\"<i4\")\n z[:, :, :] = 1\n # actually go through the partial read by accessing a single item\n assert z[0, :, 0].any()\n\n def test_read_nitems_less_than_blocksize_from_multiple_chunks(self):\n '''Tests to make sure decompression doesn't fail when `nitems` is\n less than a compressed block size, but covers multiple blocks\n '''\n z = self.create_array(shape=1000000, chunks=100_000)\n z[40_000:80_000] = 1\n b = Array(z.store, read_only=True, partial_decompress=True)\n assert (b[40_000:80_000] == 1).all()\n\n def test_read_from_all_blocks(self):\n '''Tests to make sure `PartialReadBuffer.read_part` doesn't fail when\n stop isn't in the `start_points` array\n '''\n z = self.create_array(shape=1000000, chunks=100_000)\n z[2:99_000] = 1\n b = Array(z.store, read_only=True, partial_decompress=True)\n assert (b[2:99_000] == 1).all()\n\n\n@pytest.mark.skipif(have_fsspec is False, reason=\"needs fsspec\")\nclass TestArrayWithFSStoreNested(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n key_separator = kwargs.pop('key_separator', \"/\")\n store = FSStore(path, key_separator=key_separator, auto_mkdir=True)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n kwargs.setdefault('compressor', Blosc())\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs)\n\n def expected(self):\n return [\n \"94884f29b41b9beb8fc99ad7bf9c0cbf0f2ab3c9\",\n \"077aa3bd77b8d354f8f6c15dce5ae4f545788a72\",\n \"22be95d83c097460adb339d80b2d7fe19c513c16\",\n \"85131cec526fa46938fd2c4a6083a58ee11037ea\",\n \"c3167010c162c6198cb2bf3c1da2c46b047c69a1\",\n ]\n\n def test_hexdigest(self):\n found = []\n\n # Check basic 1-D array\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n found.append(z.hexdigest())\n\n # Check basic 1-D array with different type\n z = self.create_array(shape=(1050,), chunks=100, dtype='<f4')\n found.append(z.hexdigest())\n\n # Check basic 2-D array\n z = self.create_array(shape=(20, 35,), chunks=10, dtype='<i4')\n found.append(z.hexdigest())\n\n # Check basic 1-D array with some data\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z[200:400] = np.arange(200, 400, dtype='i4')\n found.append(z.hexdigest())\n\n # Check basic 1-D array with attributes\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z.attrs['foo'] = 'bar'\n found.append(z.hexdigest())\n\n assert self.expected() == found\n\n\n@pytest.mark.skipif(have_fsspec is False, reason=\"needs fsspec\")\nclass TestArrayWithFSStoreNestedPartialRead(TestArray):\n @staticmethod\n def create_array(read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n key_separator = kwargs.pop('key_separator', \"/\")\n store = FSStore(path, key_separator=key_separator, auto_mkdir=True)\n cache_metadata = kwargs.pop(\"cache_metadata\", True)\n cache_attrs = kwargs.pop(\"cache_attrs\", True)\n kwargs.setdefault(\"compressor\", Blosc())\n init_array(store, **kwargs)\n return Array(\n store,\n read_only=read_only,\n cache_metadata=cache_metadata,\n cache_attrs=cache_attrs,\n partial_decompress=True,\n )\n\n def expected(self):\n return [\n \"94884f29b41b9beb8fc99ad7bf9c0cbf0f2ab3c9\",\n \"077aa3bd77b8d354f8f6c15dce5ae4f545788a72\",\n \"22be95d83c097460adb339d80b2d7fe19c513c16\",\n \"85131cec526fa46938fd2c4a6083a58ee11037ea\",\n \"c3167010c162c6198cb2bf3c1da2c46b047c69a1\",\n ]\n\n def test_hexdigest(self):\n found = []\n\n # Check basic 1-D array\n z = self.create_array(shape=(1050,), chunks=100, dtype=\"<i4\")\n found.append(z.hexdigest())\n\n # Check basic 1-D array with different type\n z = self.create_array(shape=(1050,), chunks=100, dtype=\"<f4\")\n found.append(z.hexdigest())\n\n # Check basic 2-D array\n z = self.create_array(\n shape=(\n 20,\n 35,\n ),\n chunks=10,\n dtype=\"<i4\",\n )\n found.append(z.hexdigest())\n\n # Check basic 1-D array with some data\n z = self.create_array(shape=(1050,), chunks=100, dtype=\"<i4\")\n z[200:400] = np.arange(200, 400, dtype=\"i4\")\n found.append(z.hexdigest())\n\n # Check basic 1-D array with attributes\n z = self.create_array(shape=(1050,), chunks=100, dtype=\"<i4\")\n z.attrs[\"foo\"] = \"bar\"\n found.append(z.hexdigest())\n\n assert self.expected() == found\n\n def test_non_cont(self):\n z = self.create_array(shape=(500, 500, 500), chunks=(50, 50, 50), dtype=\"<i4\")\n z[:, :, :] = 1\n # actually go through the partial read by accessing a single item\n assert z[0, :, 0].any()\n\n def test_read_nitems_less_than_blocksize_from_multiple_chunks(self):\n '''Tests to make sure decompression doesn't fail when `nitems` is\n less than a compressed block size, but covers multiple blocks\n '''\n z = self.create_array(shape=1000000, chunks=100_000)\n z[40_000:80_000] = 1\n b = Array(z.store, read_only=True, partial_decompress=True)\n assert (b[40_000:80_000] == 1).all()\n\n def test_read_from_all_blocks(self):\n '''Tests to make sure `PartialReadBuffer.read_part` doesn't fail when\n stop isn't in the `start_points` array\n '''\n z = self.create_array(shape=1000000, chunks=100_000)\n z[2:99_000] = 1\n b = Array(z.store, read_only=True, partial_decompress=True)\n assert (b[2:99_000] == 1).all()\n"
] |
[
[
"numpy.product",
"numpy.take",
"numpy.linspace",
"numpy.dtype",
"numpy.all",
"numpy.zeros_like",
"numpy.mean",
"numpy.iinfo",
"numpy.random.randint",
"numpy.uint32",
"numpy.arange",
"numpy.empty_like",
"numpy.zeros",
"numpy.testing.assert_array_almost_equal",
"numpy.random.choice",
"numpy.int64",
"numpy.append",
"numpy.array",
"numpy.sum",
"numpy.random.random",
"numpy.random.seed",
"numpy.int32",
"numpy.compress",
"numpy.ones",
"numpy.testing.assert_array_equal",
"numpy.uint64",
"numpy.prod"
]
] |
LucasGMeneses/OpenGL_labs
|
[
"ddf753c29cc2fcb07cd0ad04b16f03958b8e452f"
] |
[
"OpenGL3/python/cube.py"
] |
[
"import sys\nimport numpy as np\nimport math \n\nimport pyrr \nfrom OpenGL.GL import *\nfrom OpenGL.GL import shaders\nfrom OpenGL.GLUT import *\n\nvao = None\nvbo = None\nshaderProgram = None\nuMat = None # variavel uniforme\nmodel = None # matriz de transformação\n\n# le os arquivos do shaders\ndef readShaderFile(filename):\n\twith open('shader/' + filename, 'r') as myfile:\n\t\treturn myfile.read()\n\ndef init():\n\tglobal shaderProgram\n\tglobal vao\n\tglobal vbo\n\tglobal model\n\tglobal uMat\n\t\n\t\n\n\n\tglClearColor(0, 0, 0, 0)\n\t\n\tvertex_code = readShaderFile('cube.vp')\n\tfragment_code = readShaderFile('cube.fp')\n\n\t# compile shaders and program\n\tvertexShader = shaders.compileShader(vertex_code, GL_VERTEX_SHADER)\n\tfragmentShader = shaders.compileShader(fragment_code, GL_FRAGMENT_SHADER)\n\tshaderProgram = shaders.compileProgram(vertexShader, fragmentShader)\n\t\n\t# Create and bind the Vertex Array Object\n\tvao = GLuint(0)\n\tglGenVertexArrays(1, vao)\n\tglBindVertexArray(vao)\n\n\t# Create and bind the Vertex Buffer Object (CUBE 3D)\n\tvertices = np.array(\n\t\t[[-1.0,-1.0,-1.0],\n\t\t[-1.0,-1.0, 1.0],\n\t\t[-1.0, 1.0, 1.0],\n\t\t[1.0, 1.0,-1.0],\n\t\t[-1.0,-1.0,-1.0],\n\t\t[-1.0, 1.0,-1.0],\n\t\t[1.0,-1.0, 1.0],\n\t\t[-1.0,-1.0,-1.0],\n\t\t[1.0,-1.0,-1.0],\n\t\t[1.0, 1.0,-1.0],\n\t\t[1.0,-1.0,-1.0],\n\t\t[-1.0,-1.0,-1.0],\n\t\t[-1.0,-1.0,-1.0],\n\t\t[-1.0, 1.0, 1.0],\n\t\t[-1.0, 1.0,-1.0],\n\t\t[1.0,-1.0, 1.0],\n\t\t[-1.0,-1.0, 1.0],\n\t\t[-1.0,-1.0,-1.0],\n\t\t[-1.0, 1.0, 1.0],\n\t\t[-1.0,-1.0, 1.0],\n\t\t[1.0,-1.0, 1.0],\n\t\t[1.0, 1.0, 1.0],\n\t\t[1.0,-1.0,-1.0],\n\t\t[1.0, 1.0,-1.0],\n\t\t[1.0,-1.0,-1.0],\n\t\t[1.0, 1.0, 1.0],\n\t\t[1.0,-1.0, 1.0],\n\t\t[1.0, 1.0, 1.0],\n\t\t[1.0, 1.0,-1.0],\n\t\t[-1.0, 1.0,-1.0],\n\t\t[1.0, 1.0, 1.0],\n\t\t[-1.0, 1.0,-1.0],\n\t\t[-1.0, 1.0, 1.0],\n\t\t[1.0, 1.0, 1.0],\n\t\t[-1.0, 1.0, 1.0],\n\t\t[1.0,-1.0, 1.0]], dtype='f')\n\t\n\tvbo = glGenBuffers(1)\n\tglBindBuffer(GL_ARRAY_BUFFER, vbo)\n\tglBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW)\n\tglVertexAttribPointer(0, 3, GL_FLOAT, False, 3 * sizeof(GLfloat), ctypes.c_void_p(0)) # first 0 is the location in shader\n\t#glVertexAttribPointer(1, 3, GL_FLOAT, False, 6 * sizeof(GLfloat), ctypes.c_void_p(3*sizeof(GLfloat))) # first 0 is the location in shader\n\t#glVertexAttribPointer(0, 3, GL_FLOAT, False, 0, None) # first 0 is the location in shader\n\t#glBindAttribLocation(shaderProgram, 0, 'vertexPosition') # name of attribute in shader\n\tglEnableVertexAttribArray(0) # 0=location do atributo, tem que ativar todos os atributos inicialmente sao desabilitados por padrao\n\tglEnableVertexAttribArray(1) # 0=location do atributo, tem que ativar todos os atributos inicialmente sao desabilitados por padrao\n\t# cria a matriz de transformação\n\tmodel = pyrr.matrix44.create_identity()\n\tscale = pyrr.matrix44.create_from_scale([0.5,0.5,0.5],dtype='f')\n\tmodel = pyrr.matrix44.multiply(model,scale)\n\n\trotY = pyrr.matrix44.create_from_y_rotation(math.radians(45))\n\trotx = pyrr.matrix44.create_from_x_rotation(math.radians(45))\n\trotT = pyrr.matrix44.multiply(rotY,rotx)\n\n\tmodel = pyrr.matrix44.multiply(model,rotT)\n\t# atribui uma variavel uniforme para matriz de transformacao\n\tuMat = glGetUniformLocation(shaderProgram, \"model\")\n\n\t# Note that this is allowed, the call to glVertexAttribPointer registered VBO\n\t# as the currently bound vertex buffer object so afterwards we can safely unbind\n\tglBindBuffer(GL_ARRAY_BUFFER, 0)\n\t# Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs)\n\tglBindVertexArray(0)\n\ndef display():\n\tglobal shaderProgram\n\tglobal vao\n\t\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\t\n\t# load everthing back\n\tglUseProgram(shaderProgram)\n\tglBindVertexArray(vao)\n\tglBindBuffer(GL_ARRAY_BUFFER, vbo)\n\tglUniformMatrix4fv(uMat, 1, GL_FALSE, model)\n\t#glDrawArrays( mode , first, count)\n\t#glDrawArrays(GL_LINES, 0, 36)\n\tglDrawArrays(GL_TRIANGLE_STRIP, 0, 100)\n\n\t#clean things up\n\tglBindBuffer(GL_ARRAY_BUFFER, 0)\n\tglBindVertexArray(0)\n\tglUseProgram(0)\n\t\n\tglutSwapBuffers() # necessario para windows!\n\ndef reshape(width, height):\n\tglViewport(0, 0, width, height)\n\n\n\nif __name__ == '__main__':\n\tglutInit(sys.argv)\n\tglutInitContextVersion(3, 0)\n\tglutInitContextProfile(GLUT_CORE_PROFILE);\n\tglutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)\n\t\n\tglutInitWindowSize(640, 640);\n\tglutCreateWindow(b'cube 3D!')\n\t\n\tglutReshapeFunc(reshape)\n\tglutDisplayFunc(display)\n\n\tinit()\n\t\n\tglutMainLoop()\n"
] |
[
[
"numpy.array"
]
] |
OmranAlrawahi/OmranAlrawahi.github.io
|
[
"ade2bf1bff416425d051eeabbdf4c21f4fc1867c"
] |
[
"FinalModel.py"
] |
[
"\r\n#This Code is created by Omran ALRawahi, Student No. 201285265, Dec/2018\r\n\r\n# When running in Spyder set graphics prefrences to inline.\r\n\r\n\r\n\"\"\"\r\nThis model is agent based model(ABM) run from GUI (graphical user interface)\r\nwhen you run the model it is expected that window will be appeared in your screen has only one menu bar.\r\nthe menu bar has model option on the top left of the screen and it has the \"Run model\" option. \r\n\r\nThis model is creating an agents in an environment,\r\nThe agents move, eat and share the resources in the environment and sharing the resources with each other under conditions.\r\n\"\"\"\r\n\r\n\r\n\"\"\"\r\nImport operator\r\nimport operator which will be used in the model and it is better to import them all on the top of the model\r\n\"\"\"\r\nimport random\r\nimport matplotlib.pyplot\r\nimport agentframework\r\nimport csv\r\nimport matplotlib.animation\r\nimport matplotlib\r\nimport tkinter\r\nmatplotlib.use('TkAgg')\r\nimport matplotlib.backends.backend_tkagg\r\nimport requests\r\nimport bs4\r\n\r\n\r\n\r\n\"\"\"\r\nStep 1: Initiate parameters\r\n\r\nparameters can be changed to examin the hanges in the model \r\nall parameters normaly located on the top of the module to simplify changing any of them.\r\n\"\"\"\r\nprint (\"Step 1: Initiate parameters\")\r\nnum_of_agents = 50\r\nnum_of_iterations = 10\r\nneighbourhood = 20\r\nagents = []\r\nenvironment = []\r\n\r\n\r\n\r\n\"\"\"\r\nStep 2: Get data from the web\r\n\"\"\"\r\nprint (\"Step 2: Get data from the web\")\r\nr = requests.get('http://www.geog.leeds.ac.uk/courses/computing/practicals/python/agent-framework/part9/data.html')\r\ncontent = r.text\r\nsoup = bs4.BeautifulSoup(content, 'html.parser')\r\ntd_ys = soup.find_all(attrs={\"class\" : \"y\"})\r\ntd_xs = soup.find_all(attrs={\"class\" : \"x\"})\r\n\r\n\"\"\"\r\nprint to test\r\n#print(td_ys)\r\n#print(td_xs)\r\n\"\"\" \r\n\r\n\r\n\"\"\"\r\nStep 3: Read the csv file and create a 2D List\r\n\r\ncsv file stored in the model repository contains integers will be used as an environment\r\nThe file will be used to inetiate the spatial environment where the agents will act\r\n\"\"\"\r\nprint (\"Step 3: Read the csv file and create a 2D List\")\r\nfig = matplotlib.pyplot.figure(figsize=(7, 7))\r\nax = fig.add_axes([0, 0, 1, 1])\r\nf = open('in.txt', newline='') \r\nreader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)\r\n\r\n\"\"\"\r\nStep 4: Append the csv value to the environment to inetiate the spatial environment where the agents will act\r\n\"\"\"\r\nprint (\"Step 4: Append the csv value to the environment to inetiate the spatial environment where the agents will act\")\r\nfor row in reader:\t# A list of rows\r\n rowlist = []\r\n environment.append(rowlist)\r\n for value in row:\t# A list of value\r\n #print(value) # Floats\r\n rowlist.append(value)\r\n \r\n\"\"\"\r\nStep 5: Initiatethe agents.\r\n\r\ndefining the agent based on predefined x and y list from the web from step 2\r\nAs the web file has 100 row the number of the agents cant be more than 100 \r\nagents location can be random using random operator \r\n\"\"\"\r\nprint (\"Step 5: Initiatethe agents.\")\r\nfor i in range(num_of_agents):\r\n y = int(td_ys[i].text)# defining y (this can be picked randomly using random operator)\r\n x = int(td_xs[i].text)# defining x (this can be picked randomly using random operator)\r\n agents.append(agentframework.Agent(environment, agents, x, y))\r\n\r\n \r\ncarry_on = True\r\n\r\n\"\"\"\t \r\n Step 6: Update the frame and make the agents animate.\r\n\"\"\" \r\nprint (\" Step 6: Update the frame and make the agents animate.\")\r\ndef update(frame_number):\r\n fig.clear()\r\n \"\"\"\r\n Clear the figure\r\n \"\"\"\r\n global carry_on\r\n matplotlib.pyplot.xlim(0, 99)\r\n matplotlib.pyplot.ylim(0, 99)\r\n matplotlib.pyplot.imshow(environment)\r\n \r\n '''to stop the agents based on condition''' \r\n if random.random() < 0.05:\r\n carry_on = False\r\n print(\"stopping condition\")\r\n\r\n \r\n ''' Move the agents and make them interact with the environment and with each other'''\r\n\r\n for i in range(num_of_agents):\r\n agents[i].move()\r\n agents[i].eat()\r\n agents[i].share_with_neighbours(neighbourhood)\r\n for i in range(num_of_agents):\r\n matplotlib.pyplot.scatter(agents[i].x,agents[i].y)\r\n\r\n\r\n \r\n\"\"\"\r\nfunction make the agent keep animating till it reach 100 move or met the stoping condition \r\n\"\"\"\r\n\r\ndef gen_function(b = [0]):\r\n a = 0\r\n global carry_on #Not actually needed as we're not assigning, but clearer\r\n while (a < 100) & (carry_on == True) :\r\n yield a\t\t\t# Returns control and waits next call.\r\n a = a + 1\r\n\r\n\r\n\r\n\r\ndef distance_between(agents_row_a, agents_row_b):\r\n return (((agents_row_a.x - agents_row_b.x)**2) + ((agents_row_a.y - agents_row_b.y)**2))**0.5 \r\n\r\n\r\n# to calculate the distance between agents.\r\nfor agents_row_a in agents:\r\n for agents_row_b in agents:\r\n distance = distance_between(agents_row_a, agents_row_b)\r\n#print (distance) to test teh distence calculation\r\n\r\n\"\"\"\r\nStep 7: Display the plot\r\n\"\"\"\r\nprint (\"Step 7: Display the plot\")\r\ndef run(): \r\n animation = matplotlib.animation.FuncAnimation(fig, update, interval=1, repeat=False, frames=gen_function)\r\n canvas.show()\r\n\r\n\"\"\"\r\nStep 8: Initiat GUI and its properties\r\n\"\"\"\r\nprint (\"Step 8: Initiat GUI and its properties\")\r\nroot = tkinter.Tk() \r\nroot.wm_title(\"Model!!\")\r\ncanvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(fig, master=root)\r\ncanvas._tkcanvas.pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)\r\nmenu_bar = tkinter.Menu(root)\r\nroot.config(menu=menu_bar) # to create menubar \r\nmodel_menu = tkinter.Menu(menu_bar)\r\nmenu_bar.add_cascade(label=\"Model\", menu=model_menu) # to create model menu in the menu bar\r\nmodel_menu.add_command(label=\"Run model\", command=run) #to creat Run Model function under model menu in the menu bar\r\n\r\ntkinter.mainloop()\r\n\r\n\r\n\"\"\"\r\nThis model can be improved by \r\n1. Enhance the agent behaviur like make the agent share the resource not only by distance condition but by the need or amount of stor if other agents \r\n2. set your own parameters and change the coditions to suit your purpos \r\n\"\"\""
] |
[
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.ylim",
"matplotlib.use",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.xlim",
"matplotlib.animation.FuncAnimation",
"matplotlib.backends.backend_tkagg.FigureCanvasTkAgg"
]
] |
suapapa/khaiii
|
[
"52603b9fb0aca4be4cd1b87d0f7663d069e94f91"
] |
[
"rsc/lib/vocabulary.py"
] |
[
"# -*- coding: utf-8 -*-\n\n\n\"\"\"\nvocabulary library\n__author__ = 'Jamie (jamie.lim@kakaocorp.com)'\n__copyright__ = 'Copyright (C) 2018-, Kakao Corp. All rights reserved.'\n\"\"\"\n\n\n###########\n# imports #\n###########\nimport re\nimport codecs\nfrom collections import defaultdict\nimport copy\nimport logging\nimport os\nimport torch\nfrom torch import nn\nimport numpy as np\nfrom tqdm import tqdm\n\n\n#########\n# types #\n#########\nclass Vocabulary(object):\n \"\"\"\n vocabulary class\n \"\"\"\n def __init__(self, path, cutoff=1, special=None, padding=''):\n \"\"\"\n Args:\n path: file path\n cutoff: cutoff frequency\n special: special entries located at the first\n padding: add padding special char at the end\n \"\"\"\n self.dic = {} # {entry: number} dictionary\n self.rev = copy.deepcopy(special) if special else [] # reverse dictionary\n for num, entry in enumerate(self.rev):\n self.dic[entry] = num\n self._load(path, cutoff)\n self.padding = padding\n if padding:\n if padding in self.dic:\n raise ValueError('padding special character already in vocab: {}'.format(padding))\n padding_idx = len(self.dic)\n self.dic[padding] = padding_idx\n self.rev.append(padding)\n assert len(self.dic) == len(self.rev)\n\n def __getitem__(self, key):\n \"\"\"\n Args:\n key: key\n Returns:\n word number for string key, word for int key\n \"\"\"\n if isinstance(key, int):\n return self.rev[key]\n try:\n return self.dic[key]\n except KeyError:\n return 0 # unknown word number\n\n def __len__(self):\n return len(self.dic)\n\n def get_embedding(self, dim, padding_idx=None):\n \"\"\"\n embedding을 리턴합니다.\n Args:\n dim: embedding dimension\n padding_idx: padding index\n \"\"\"\n if padding_idx:\n return nn.Embedding(len(self), dim, padding_idx=padding_idx)\n return nn.Embedding(len(self), dim)\n\n def padding_idx(self):\n \"\"\"\n 맨 마지막에 추가한 패딩의 인덱스를 리턴한다.\n Returns:\n 패딩 인덱스\n \"\"\"\n if not self.padding:\n raise RuntimeError('vocabulary has no padding')\n return self.dic[self.padding]\n\n def _load(self, path, cutoff=1):\n \"\"\"\n load vocabulary from file\n Args:\n path: file path\n cutoff: cutoff frequency\n \"\"\"\n append_num = 0\n cutoff_num = 0\n for line in codecs.open(path, 'r', encoding='UTF-8'):\n line = line.rstrip('\\r\\n')\n if not line:\n continue\n try:\n entry, freq = line.split('\\t')\n if int(freq) <= cutoff:\n cutoff_num += 1\n continue\n except ValueError:\n entry = line\n if entry in self.dic:\n cutoff_num += 1\n continue\n self.dic[entry] = len(self.dic)\n self.rev.append(entry)\n append_num += 1\n logging.info('%s: %d entries, %d cutoff', os.path.basename(path), append_num, cutoff_num)\n\n\nclass PreTrainedVocabulary(Vocabulary):\n \"\"\"\n pre-train된 word2vec를 사용하는 경우, vector에 있는 어휘로\n 사전을 구성하도록 합니다.\n \"\"\"\n def __init__(self, path): #pylint: disable=super-init-not-called\n \"\"\"\n Args:\n path: file path\n \"\"\"\n # simple : 사과/N , none : 사과\n # 읽어들인 glove의 키 타입을 보고 판단해놓는다.\n self.glove_key_type = None\n self.dic, self.vectors = self._load_glove(path)\n self.rev = {val:key for key, val in self.dic.items()}\n assert len(self.dic) == len(self.rev)\n logging.info('%s: %d entries, %d dim - not trainable',\n os.path.basename(path), len(self.dic), self.vectors.size(1))\n\n def get_embedding(self, dim, padding_idx=None):\n \"\"\"\n pre-training된 벡터가 세팅된 embedding을 리턴합니다.\n \"\"\"\n assert dim == self.vectors.size(1)\n embed = super().get_embedding(dim, padding_idx)\n embed.weight = nn.Parameter(self.vectors, requires_grad=False)\n return embed\n\n def _load_glove(self, path):\n \"\"\"\n pre-trained GloVe (텍스트 포맷) 워드 벡터를 읽어들인다.\n Args:\n path: 워드 벡터 경로\n \"\"\"\n unk = None\n vecs = []\n for line in tqdm(codecs.open(path, 'r', encoding='UTF-8')):\n cols = line.split(' ')\n word = cols[0]\n vec = np.array([float(_) for _ in cols[1:]])\n if vec.size == 0: # format error\n continue\n if word == '<unk>':\n unk = vec\n continue\n vecs.append((word, vec))\n if self.glove_key_type is None:\n if re.search('/[A-Z]$', word) is None:\n self.glove_key_type = 'none'\n else:\n self.glove_key_type = 'simple'\n if unk is None:\n unk = [0] * len(vecs[0][1])\n padding = [0] * len(vecs[0][1])\n vecs.sort(key=lambda x: x[0])\n vecs.insert(0, ('<unk>', unk))\n vecs.insert(1, ('<p>', padding))\n vocab = defaultdict(int)\n vocab.update({word: idx for idx, (word, _) in enumerate(vecs)})\n return vocab, torch.Tensor([vec for _, vec in vecs])\n"
] |
[
[
"torch.nn.Parameter",
"torch.Tensor"
]
] |
mmarrkv/spotcheck_ds
|
[
"db824e5561ac96efe776b12a5531da2612f74faa"
] |
[
"kpca_for_ad_memorydumps.py"
] |
[
"'''\nFeature scaling: attribute ratio where each row adds up to 1; Rending each row execution sample length insensitive\n'''\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.decomposition import KernelPCA\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import mean_squared_error\nimport matplotlib.pyplot as plt\nimport argparse\nimport os\nimport sys\nimport pickle\n\n'''\nprint(\"place quick tests here\")\nsys.exit(0)\n'''\n\n#Datase load + scale\n\ndef normalize(x, rowsum, histogram_dim):\n\n if rowsum > 0:\n return x/rowsum\n else:\n return 1/histogram_dim #Handles all-0 vector case\n\ndef rowratio(row): #histogram scaling to row ratio is insensitive \"overall\" to execution time + HANDLES probs with all-0 vectors\n histogram_dim = row.shape[0] \n return row.apply(normalize, args=(row.sum(),histogram_dim))\n\n#Datase load + scale\ndef get_dataset(file_path):\n\n df = pd.read_csv(file_path)\n\n selectcols = df.loc[:, 'apk_AccessibilityManager':'apk_WindowManager']\n selectcols = selectcols.astype(np.float64)\n histogram_dim = selectcols.shape[1]\n selectcols=selectcols.apply(rowratio, axis=1)\n labels = df.loc[:, 'apk_id':'apk_is_mal']\n return selectcols, labels\n\n#Grid Search cross-validation scorer\ndef my_scorer(estimator, X, y=None):\n X_reduced = estimator.transform(X)\n X_preimage = estimator.inverse_transform(X_reduced)\n return -1 * mean_squared_error(X, X_preimage)\n\n\n#latent visualization\ndef vis_latent(data, labels,\n model_name=\"kpca_for_ad_hprof\"):\n\n y_true = labels['apk_is_mal']\n filename = os.path.join(model_name, \"kpca_mean_hprof.png\")\n\n plt.figure(figsize=(12, 10))\n plt.scatter(data[:, 0], data[:, 1], c=y_true)\n plt.colorbar(ticks=[0, 1])\n plt.xlabel(\"z[0]\")\n plt.ylabel(\"z[1]\")\n plt.savefig(filename)\n\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser._action_groups.pop()\n required = parser.add_argument_group('required arguments')\n optional = parser.add_argument_group('optional arguments')\n help_ = \"Load trained principal components\"\n optional.add_argument(\"-w\", \"--weights\", help=help_)\n help_ = \"Path to train+val/test csv\"\n required.add_argument('-f', '--fpath', help=help_, required=True)\n args = parser.parse_args()\n\n\n if args.weights:\n\n print(\"Using trained model..\")\n rbf_pca = pickle.load(open(args.weights, 'rb'))\n\n df, labels = get_dataset(args.fpath)\n print(df.head())\n\n X = df.to_numpy()\n\n\n X_reduced = rbf_pca.transform(X)\n vis_latent(X_reduced,labels)\n X_preimage = rbf_pca.inverse_transform(X_reduced)\n\n\n norows = X.shape[0]\n reconerr_scores = np.zeros([norows])\n for i in range(0,norows):\n mse=mean_squared_error(X[i], X_preimage[i])\n reconerr_scores[i]=mse\n #print(\"mse \"+str(i)+\" \"+str(mse))\n \n print(reconerr_scores)\n labels['ReconErr_Scores'] = reconerr_scores\n labels.to_csv ('kpca_for_ad_hprof/kpca_for_ad_hprof_scores.csv', index = False, header=True)\n\n\n else:\n\n print('Training mode...')\n os.makedirs('kpca_for_ad_hprof', exist_ok=True)\n\n df, labels = get_dataset(args.fpath)\n print(df.head())\n X = df.to_numpy()\n print(X[:2][:])\n\n param_grid = [{\"gamma\": np.linspace(0.03, 0.05, 10), \"kernel\": [\"rbf\"] }]\n rbf_pca = KernelPCA(n_components = 2, kernel=\"rbf\", fit_inverse_transform=True)\n grid_search = GridSearchCV(rbf_pca, param_grid, cv=3, scoring=my_scorer)\n grid_search.fit(X)\n\n X_reduced = grid_search.transform(X)\n print(X_reduced[:2][:])\n\n X_preimage = grid_search.inverse_transform(X_reduced)\n print(X_preimage[:2][:])\n\n filename = \"kpca_for_ad_hprof/kpca_for_ad_hprof.mdl\"\n pickle.dump(grid_search, open(filename, 'wb'))\n\n\n\n\n\n"
] |
[
[
"sklearn.model_selection.GridSearchCV",
"pandas.read_csv",
"matplotlib.pyplot.scatter",
"numpy.linspace",
"matplotlib.pyplot.savefig",
"sklearn.metrics.mean_squared_error",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"sklearn.decomposition.KernelPCA",
"numpy.zeros",
"matplotlib.pyplot.figure"
]
] |
mathemaphysics/pylearn2
|
[
"477bf562c387ad9af9a78e876b635afb0d98b3b7"
] |
[
"pylearn2/utils/tests/test_mnist_ubyte.py"
] |
[
"import struct\nimport tempfile\n\nimport numpy\nimport six\n\nfrom pylearn2.utils.mnist_ubyte import read_mnist_images, read_mnist_labels\nfrom pylearn2.utils.mnist_ubyte import MNIST_LABEL_MAGIC, MNIST_IMAGE_MAGIC\n\n\ndef test_read_labels():\n with tempfile.TemporaryFile() as f:\n data = struct.pack('>iiBBBB', MNIST_LABEL_MAGIC, 4, 9, 4, 3, 1)\n f.write(data)\n f.seek(0)\n arr = read_mnist_labels(f)\n assert arr.shape == (4,)\n assert arr.dtype == numpy.dtype('uint8')\n assert arr[0] == 9\n assert arr[1] == 4\n assert arr[2] == 3\n assert arr[3] == 1\n\n\ndef test_read_images():\n header = struct.pack('>iiii', MNIST_IMAGE_MAGIC, 4, 3, 2)\n data = six.b('\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00'\n '\\t\\x00\\x00\\x00\\x00\\x00\\x00\\xff.\\x00\\x00\\x00\\x00\\x00')\n with tempfile.TemporaryFile() as f:\n buf = header + data\n f.write(buf)\n f.seek(0)\n arr = read_mnist_images(f)\n assert arr.dtype == numpy.dtype('uint8')\n assert arr[0, 1, 1] == 4\n assert arr[1, 2, 0] == 9\n assert arr[2, 2, 1] == 255\n assert arr[3, 0, 0] == 46\n assert (arr == 0).sum() == 20\n f.seek(0)\n arr = read_mnist_images(f, dtype='float32')\n assert arr.dtype == numpy.dtype('float32')\n assert arr[0, 1, 1] == numpy.float32(4 / 255.)\n assert arr[1, 2, 0] == numpy.float32(9 / 255.)\n assert arr[2, 2, 1] == 1.0\n assert arr[3, 0, 0] == numpy.float32(46 / 255.)\n assert (arr == 0).sum() == 20\n f.seek(0)\n arr = read_mnist_images(f, dtype='bool')\n assert arr.dtype == numpy.dtype('bool')\n assert arr[2, 2, 1]\n assert (arr == 0).sum() == 23\n"
] |
[
[
"numpy.float32",
"numpy.dtype"
]
] |
dmwyatt/bookcut
|
[
"4db9c1f31005e35ccaa3216ebe87be82e319b96f"
] |
[
"bookcut/search.py"
] |
[
"from bookcut.mirror_checker import main as mirror_checker\nfrom bookcut.downloader import pathfinder\nfrom bs4 import BeautifulSoup as Soup\nimport mechanize\nimport pandas as pd\nimport os\nimport requests\nfrom tqdm import tqdm\n\n\ndef search_downloader(file, href):\n response = requests.get(href, stream=True)\n total_size = int(response.headers.get('content-length'))\n inMb = total_size / 1000000\n inMb = round(inMb, 2)\n filename = file\n print(\"\\nDownloading...\\n\", \"Total file size:\", inMb, 'MB')\n\n path = pathfinder()\n\n filename = os.path.join(path, filename)\n # progress bar\n buffer_size = 1024\n progress = tqdm(response.iter_content(buffer_size), f\"{file}\",\n total=total_size, unit=\"B\", unit_scale=True,\n unit_divisor=1024)\n with open(filename, \"wb\") as f:\n for data in progress:\n # write data read to the file\n f.write(data)\n # update the progress bar manually\n progress.update(len(data))\n print(\"================================\\nFile saved as:\", filename)\n\n\ndef link_finder(link,mirror_used):\n page = requests.get(link)\n soup = Soup(page.content, 'html.parser')\n searcher = [a['href'] for a in soup.find_all(href=True) if a.text]\n filename = soup.find('input')['value']\n if searcher[0].startswith('http') is False:\n searcher[0] = mirror_used + searcher[0]\n results = [filename, searcher[0]]\n return results\n\n\ndef search(term):\n # This function is used when searching to LibGen with the command\n # bookcut search -t \"keyword\"\n\n url = mirror_checker()\n if url is not None:\n br = mechanize.Browser()\n br.set_handle_robots(False) # ignore robots\n br.set_handle_refresh(False) #\n br.addheaders = [('User-agent', 'Firefox')]\n\n br.open(url)\n br.select_form('libgen')\n input_form = term\n br.form['req'] = input_form\n ac = br.submit()\n html_from_page = ac\n soup = Soup(html_from_page, 'html.parser')\n table = soup.find_all('table')[2]\n\n table_data = []\n mirrors = []\n extensions = []\n\n for i in table:\n j = 0\n try:\n td = i.find_all('td')\n for tr in td:\n # scrape mirror links\n if j == 9:\n temp = tr.find('a', href=True)\n mirrors.append(temp['href'])\n j = j + 1\n row = [tr.text for tr in td]\n table_data.append(row)\n extensions.append(row[8])\n\n except:\n pass\n\n # Clean result page\n for j in table_data:\n j.pop(0)\n del j[8:15]\n headers = ['Author(s)', 'Title', 'Publisher', 'Year', 'Pages',\n 'Language', 'Size', 'Extension']\n\n try:\n tabular = pd.DataFrame(table_data)\n tabular.index += 1\n tabular.columns = headers\n print(tabular)\n choices = []\n temp = len(mirrors) + 1\n for i in range(1, temp):\n choices.append(str(i))\n choices.append('C')\n choices.append('c')\n while True:\n tell_me = str(input('\\n\\nPlease enter a number from 1 to {number}'\n ' to download a book or press \"C\" to abort'\n ' search: '.format(number=len(extensions))))\n if tell_me in choices:\n if tell_me == 'C' or tell_me == 'c':\n print(\"Aborted!\")\n return None\n else:\n c = int(tell_me) - 1\n results = [mirrors[c], extensions[c]]\n return results\n except ValueError:\n print('\\nNo results found or bad Internet connection.')\n print('Please,try again.')\n return None\n else:\n print('\\nNo results found or bad Internet connection.')\n print('Please,try again.')\n\n\ndef single_search():\n def search(term):\n # This function is used when searching to LibGen with the command\n # bookcut search -t \"keyword\"\n\n url = mirror_checker()\n if url is not None:\n br = mechanize.Browser()\n br.set_handle_robots(False) # ignore robots\n br.set_handle_refresh(False) #\n br.addheaders = [('User-agent', 'Firefox')]\n\n br.open(url)\n br.select_form('libgen')\n input_form = term\n br.form['req'] = input_form\n ac = br.submit()\n html_from_page = ac\n soup = Soup(html_from_page, 'html.parser')\n table = soup.find_all('table')[2]\n\n table_data = []\n mirrors = []\n extensions = []\n\n for i in table:\n j = 0\n try:\n td = i.find_all('td')\n for tr in td:\n # scrape mirror links\n if j == 9:\n temp = tr.find('a', href=True)\n mirrors.append(temp['href'])\n j = j + 1\n row = [tr.text for tr in td]\n table_data.append(row)\n extensions.append(row[8])\n\n except:\n pass\n\n # Clean result page\n for j in table_data:\n j.pop(0)\n del j[8:15]\n headers = ['Author(s)', 'Title', 'Publisher', 'Year', 'Pages',\n 'Language', 'Size', 'Extension']\n\n try:\n tabular = pd.DataFrame(table_data)\n tabular.index += 1\n tabular.columns = headers\n print(tabular)\n choices = []\n temp = len(mirrors) + 1\n for i in range(1, temp):\n choices.append(str(i))\n choices.append('C')\n choices.append('c')\n while True:\n tell_me = str(input('\\n\\nPlease enter a number from 1 to {number}'\n ' to download a book or press \"C\" to abort'\n ' search: '.format(number=len(extensions))))\n if tell_me in choices:\n if tell_me == 'C' or tell_me == 'c':\n print(\"Aborted!\")\n return None\n else:\n c = int(tell_me) - 1\n print(mirrors[c], \" \", extensions[c])\n results = [mirrors[c], extensions[c]]\n return results\n except ValueError:\n print('\\nNo results found or bad Internet connection.')\n print('Please,try again.')\n return None\n else:\n print('\\nNo results found or bad Internet connection.')\n print('Please,try again.')\n\n\nif __name__ == '__main__':\n search(input('Term: '))\n"
] |
[
[
"pandas.DataFrame"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.