repo_name
stringlengths 6
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence | possible_versions
list |
---|---|---|---|---|---|
PVoodoo/RLDQTrading | [
"caac2965bfb62c026af531b0dd5a74c1f3ee4c6a"
] | [
"agent/PVAgent.py"
] | [
"# mainly keras model to RLDQ model, some important settings here so far\n# Programming [email protected]\n# v1.0.0.1 20190305\n# 1.0.0.3 20190308 model changed \n# v1.0.1.0 20190310 Start of \n##############################\n# own ad: For NinjaTrader related stuff: check https://pvoodoo.com or blog: https://pvoodoo.blogspot.com/?view=flipcard\n##############################\n\nimport keras\nfrom keras.models import Sequential\nfrom keras.models import load_model, Model\nfrom keras.layers import Dense, LSTM, Flatten, Input, concatenate\nfrom keras.optimizers import Adam\n\nimport numpy as np\nimport random\nfrom collections import deque\nimport constant\n\nDebug=True # or constant.Debug\n\n\nclass PVAgent:\n def __init__(self, time_steps, feature_count, is_eval=False, model_name=\"\"):\n self.time_steps = time_steps # period \n self.feature_count = feature_count\n self.action_size = 3 # no_action, buy, sell, 1 is actually based to constant.py now, it is active GO FLAT > exit trade, maybe 4 actions needed [No action, Long, Short, Exit]\n self.memory = deque(maxlen=256) # according some new study, no need to be high at stock data .. but try 128,256,512 (DayTrading -> short is okay) \n self.inventory = []\n self.model_name = model_name\n self.is_eval = is_eval\n\n # next ones are actually quite important parameters here, try with different settings!, general guidance is available from the web\n self.gamma = 0.80 #\n self.epsilon = 1.0\n self.epsilon_min = 0.01\n self.epsilon_decay = 0.995\n self.learning_rate = 0.001 # actually a learning rate to Adam optimizer, this might be even smaller as some ..\n\n self.model = load_model(\"models/\" + model_name + \".h5\") if is_eval else self._model()\n\n \n # just a simple model first, add dropouts or batch normalization and experiment some dif shapes and sizes and activations (tanh?, but set scaler ?)\n def _model(self):\n \n \n feature_input = Input(shape=(self.time_steps, self.feature_count), name=\"Market_inputs\") # 3D shape here.., actually market features, suitable directly to recurrent neural networks\n \n lstm = LSTM(32, return_sequences=True, activation=\"relu\")(feature_input)\n flattened_features = LSTM(16, return_sequences=False, activation=\"relu\")(lstm) # or without that but you need to set return sequences false at previous then to get flattened shape\n \n # flattened_price=lstm\n #flattened_price = Flatten()(feature_input) # 3D shape is/was meant to LSTMm, CONV, recurrent models, keep time_steps short otherwise, even 1 if reasonable feature match, try those recurrent ones too!!\n \n state_input = Input(shape=(constant.PositionStateWidth,), name=\"Position_inputs\") # 2D [Flat no more => Long,Short,Current_PnL] anyway to merge this , position features\n \n state = Dense(8, activation=\"relu\")(state_input)\n #state_input = Input() what if this is not connected ?, lets try\n \n \n merged = concatenate([flattened_features, state], axis=1) # the most simplest merged model now \n \n #merged = Dense(units=64, activation=\"relu\")(merged)\n merged = Dense(units=16, activation=\"relu\")(merged)\n \n preds = Dense(self.action_size, activation=\"softmax\", name=\"Actions\")(merged) # activation linear, softmax could be used as well?\n \n model = Model(inputs=[feature_input, state_input], outputs=preds)\n #model = Model(inputs=feature_input, outputs=preds)\n \n model.compile(optimizer=Adam(lr=self.learning_rate), loss=\"mse\")\n \n # if Debug:\n # print(\"Model:\")\n # print(model.layers[0].input.shape.as_list())\n # print(model)\n \n return model\n \n # next is/was identical, just for info , not used any more and don't even fit to input any more, if you prefer that way of building, but additional input will be added so previous one is easier to handle\n # model = Sequential()\n # model.add(Dense(units=64, input_shape=(self.feature_count,), activation=\"relu\"))\n # model.add(Dense(units=8, activation=\"relu\"))\n # model.add(Dense(self.action_size, activation=\"linear\")) # or use softmax \n # model.compile(loss=\"mse\", optimizer=Adam())\n\n # return model\n\n def act(self, state):\n if not self.is_eval and np.random.rand() <= self.epsilon:\n return random.randrange(self.action_size)\n #return np.argmax(np.random.multinomial(1, [0.6, 0.2, 0.2])) # see the distribution, so NO action is preferred to speed up training, maybe [0.8, 0.1, 0.1] could be used as well\n # here could be some restrictions too , new model, index 0 is active -> sell to exit, back to normal distribution\n \n options = self.model.predict(state) # modified with 0\n return np.argmax(options[0])\n #return options # or should it be options[0] to be same format\n\n def expReplay(self, batch_size):\n mini_batch = []\n l = len(self.memory)\n for i in range(l - batch_size + 1, l):\n mini_batch.append(self.memory.popleft())\n\n states0, states1, targets = [],[], []\n for state, action, reward, next_state, done in mini_batch:\n target = reward\n if not done:\n #if Debug:\n # print(\"expRep: shapes: \", next_state[0].shape, next_state[1].shape)\n target = reward + self.gamma * np.amax(self.model.predict(next_state)[0]) ## simple kartpole model next_state[0] to forget second input\n \n\n target_f = self.model.predict(state) #Modif with 0\n target_f[0][action] = target\n\n states0.append(state[0]) # modified state, only first , market_state\n states1.append(state[1]) # position_state, added as a list \n targets.append(target_f)\n\n self.model.fit([np.vstack(states0), np.vstack(states1)], [np.vstack(targets)], epochs=1, verbose=0)\n\n if self.epsilon > self.epsilon_min:\n self.epsilon *= self.epsilon_decay\n\n##############################\n# own ad: For NinjaTrader related stuff: check https://pvoodoo.com or blog: https://pvoodoo.blogspot.com/?view=flipcard\n##############################\n"
] | [
[
"numpy.argmax",
"numpy.random.rand",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
david-ryan-alviola/utilities | [
"e14d384cdf5fb849c9e0d4a50960db0c099d382d"
] | [
"evaluation/evaluate_utils.py"
] | [
"import pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom statsmodels.formula.api import ols\nfrom sklearn.metrics import mean_squared_error, classification_report, accuracy_score\nfrom math import sqrt\n\ndef _compare_sum_squared_errors(model_sse2, baseline_sse2):\n delta = model_sse2 - baseline_sse2\n \n if (model_sse2 < baseline_sse2):\n print(f\"The MODEL performs better than the baseline with an SSE value of {model_sse2} and delta of {delta}\")\n return True\n else:\n print(f\"The BASELINE performs better than the model with an SSE value of {baseline_sse2} and delta of {delta}\")\n return False\n\ndef plot_residuals(y, yhat):\n sns.scatterplot(x=y, y=yhat - y)\n plt.title(\"Residuals\")\n plt.ylabel(\"yhat - y\")\n plt.show()\n \ndef plot_residuals_against_x(x, y, yhat, df):\n sns.scatterplot(x=x, y=(yhat - y), data=df)\n plt.title(\"Residuals\")\n plt.ylabel(\"yhat - y\")\n plt.show()\n \ndef regression_errors(y, yhat):\n sse2 = mean_squared_error(y, yhat) * len(y)\n ess = sum((yhat - y.mean()) ** 2)\n tss = ess + sse2\n mse = mean_squared_error(y, yhat)\n rmse = sqrt(mse)\n \n return sse2, ess, tss, mse, rmse\n\ndef baseline_mean_errors(y):\n index = []\n \n for i in range(1, len(y) + 1):\n index.append(i)\n \n y_mean = pd.Series(y.mean(), index=index)\n\n sse2_baseline = mean_squared_error(y, y_mean) * len(y)\n mse_baseline = mean_squared_error(y, y_mean)\n rmse_baseline = sqrt(mse_baseline)\n \n return sse2_baseline, mse_baseline, rmse_baseline\n\ndef better_than_baseline(y, yhat):\n sse2, ess, tss, mse, rmse = regression_errors(y, yhat)\n sse2_baseline, mse_baseline, rmse_baseline = baseline_mean_errors(y)\n \n model_errors = {'sse' : sse2, 'ess' : ess, 'tss' : tss, 'mse' : mse, 'rmse' : rmse}\n baseline_errors = {'sse' : sse2_baseline, 'mse' : mse_baseline, 'rmse' : rmse_baseline}\n\n _print_comparison(model_errors, baseline_errors)\n \n return _compare_sum_squared_errors(sse2, sse2_baseline)\n\ndef model_signficance(ols_model):\n r2 = ols_model.rsquared\n p_value = ols_model.f_pvalue\n alpha = .05\n\n print(f\"variance: {r2}, p: {p_value}, a: {alpha}, signficant: {p_value < alpha}\")\n return r2, p_value, p_value < alpha\n\ndef _print_comparison(model_errors, baseline_errors):\n print(\"----------------------------------------------\")\n print(pd.DataFrame(index=model_errors.keys(), columns=[\"model\"], data=model_errors.values()))\n print(\"----------------------------------------------\")\n print(pd.DataFrame(index=baseline_errors.keys(), columns=[\"baseline\"], data=baseline_errors.values()))\n print(\"----------------------------------------------\")\n\ndef print_model_evaluation(sample_df, prediction_key):\n print('Accuracy: {:.2%}'.format(accuracy_score(sample_df.actual, sample_df[prediction_key])))\n print('---')\n print('Confusion Matrix')\n print(pd.crosstab(sample_df[prediction_key], sample_df.actual))\n print('---')\n print(classification_report(sample_df.actual, sample_df[prediction_key]))\n"
] | [
[
"pandas.crosstab",
"matplotlib.pyplot.title",
"sklearn.metrics.accuracy_score",
"sklearn.metrics.mean_squared_error",
"matplotlib.pyplot.show",
"sklearn.metrics.classification_report",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
NathanHowell/kornia | [
"777e2e03ba61f2a69ad686a01de72a1829f780fd"
] | [
"test/filters/test_median.py"
] | [
"from typing import Tuple\n\nimport pytest\n\nimport kornia\nimport kornia.testing as utils # test utils\n\nimport torch\nfrom torch.testing import assert_allclose\nfrom torch.autograd import gradcheck\n\n\nclass TestMedianBlur:\n def test_shape(self, device, dtype):\n inp = torch.zeros(1, 3, 4, 4, device=device, dtype=dtype)\n assert kornia.filters.median_blur(inp, (3, 3)).shape == (1, 3, 4, 4)\n\n def test_shape_batch(self, device, dtype):\n inp = torch.zeros(2, 6, 4, 4, device=device, dtype=dtype)\n assert kornia.filters.median_blur(inp, (3, 3)).shape == (2, 6, 4, 4)\n\n def test_kernel_3x3(self, device, dtype):\n inp = torch.tensor([[\n [0., 0., 0., 0., 0.],\n [0., 3., 7., 5., 0.],\n [0., 3., 1., 1., 0.],\n [0., 6., 9., 2., 0.],\n [0., 0., 0., 0., 0.]\n ], [\n [36., 7.0, 25., 0., 0.],\n [3.0, 14., 1.0, 0., 0.],\n [65., 59., 2.0, 0., 0.],\n [0.0, 0.0, 0.0, 0., 0.],\n [0.0, 0.0, 0.0, 0., 0.]\n ]], device=device, dtype=dtype).repeat(2, 1, 1, 1)\n\n kernel_size = (3, 3)\n actual = kornia.filters.median_blur(inp, kernel_size)\n assert_allclose(actual[0, 0, 2, 2], torch.tensor(3.).to(actual))\n assert_allclose(actual[0, 1, 1, 1], torch.tensor(14.).to(actual))\n\n def test_noncontiguous(self, device, dtype):\n batch_size = 3\n inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)\n\n kernel_size = (3, 3)\n actual = kornia.filters.median_blur(inp, kernel_size)\n expected = actual\n assert_allclose(actual, actual)\n\n def test_gradcheck(self, device, dtype):\n batch_size, channels, height, width = 1, 2, 5, 4\n img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)\n img = utils.tensor_to_gradcheck_var(img) # to var\n assert gradcheck(kornia.filters.median_blur, (img, (5, 3),),\n raise_exception=True)\n\n def test_jit(self, device, dtype):\n kernel_size = (3, 5)\n img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)\n op = kornia.filters.median_blur\n op_script = torch.jit.script(op)\n actual = op_script(img, kernel_size)\n expected = op(img, kernel_size)\n assert_allclose(actual, expected)\n\n def test_module(self, device, dtype):\n kernel_size = (3, 5)\n img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)\n op = kornia.filters.median_blur\n op_module = kornia.filters.MedianBlur((3, 5))\n actual = op_module(img)\n expected = op(img, kernel_size)\n assert_allclose(actual, expected)\n"
] | [
[
"torch.jit.script",
"torch.testing.assert_allclose",
"torch.zeros",
"torch.tensor",
"torch.rand",
"torch.autograd.gradcheck"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
saswatpp/lightning-flash | [
"d0e6ee65419e140ea7894f1c03a5955919d66310"
] | [
"tests/image/classification/test_model.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 os\nimport re\nfrom unittest import mock\n\nimport pytest\nimport torch\n\nfrom flash import Trainer\nfrom flash.core.classification import Probabilities\nfrom flash.core.data.data_source import DefaultDataKeys\nfrom flash.core.utilities.imports import _IMAGE_AVAILABLE\nfrom flash.image import ImageClassifier\nfrom flash.image.classification.data import ImageClassificationPreprocess\nfrom tests.helpers.utils import _IMAGE_TESTING, _SERVE_TESTING\n\n# ======== Mock functions ========\n\n\nclass DummyDataset(torch.utils.data.Dataset):\n\n def __getitem__(self, index):\n return {\n DefaultDataKeys.INPUT: torch.rand(3, 224, 224),\n DefaultDataKeys.TARGET: torch.randint(10, size=(1, )).item(),\n }\n\n def __len__(self) -> int:\n return 100\n\n\nclass DummyMultiLabelDataset(torch.utils.data.Dataset):\n\n def __init__(self, num_classes: int):\n self.num_classes = num_classes\n\n def __getitem__(self, index):\n return {\n DefaultDataKeys.INPUT: torch.rand(3, 224, 224),\n DefaultDataKeys.TARGET: torch.randint(0, 2, (self.num_classes, )),\n }\n\n def __len__(self) -> int:\n return 100\n\n\n# ==============================\n\n\[email protected](not _IMAGE_TESTING, reason=\"image libraries aren't installed.\")\[email protected](\n \"backbone\",\n [\n \"resnet18\",\n # \"resnet34\",\n # \"resnet50\",\n # \"resnet101\",\n # \"resnet152\",\n ],\n)\ndef test_init_train(tmpdir, backbone):\n model = ImageClassifier(10, backbone=backbone)\n train_dl = torch.utils.data.DataLoader(DummyDataset())\n trainer = Trainer(default_root_dir=tmpdir, fast_dev_run=True)\n trainer.finetune(model, train_dl, strategy=\"freeze_unfreeze\")\n\n\[email protected](not _IMAGE_TESTING, reason=\"image libraries aren't installed.\")\ndef test_non_existent_backbone():\n with pytest.raises(KeyError):\n ImageClassifier(2, \"i am never going to implement this lol\")\n\n\[email protected](not _IMAGE_TESTING, reason=\"image libraries aren't installed.\")\ndef test_freeze():\n model = ImageClassifier(2)\n model.freeze()\n for p in model.backbone.parameters():\n assert p.requires_grad is False\n\n\[email protected](not _IMAGE_TESTING, reason=\"image libraries aren't installed.\")\ndef test_unfreeze():\n model = ImageClassifier(2)\n model.unfreeze()\n for p in model.backbone.parameters():\n assert p.requires_grad is True\n\n\[email protected](not _IMAGE_TESTING, reason=\"image libraries aren't installed.\")\ndef test_multilabel(tmpdir):\n\n num_classes = 4\n ds = DummyMultiLabelDataset(num_classes)\n model = ImageClassifier(num_classes, multi_label=True, serializer=Probabilities(multi_label=True))\n train_dl = torch.utils.data.DataLoader(ds, batch_size=2)\n trainer = Trainer(default_root_dir=tmpdir, fast_dev_run=True)\n trainer.finetune(model, train_dl, strategy=\"freeze_unfreeze\")\n image, label = ds[0][DefaultDataKeys.INPUT], ds[0][DefaultDataKeys.TARGET]\n predictions = model.predict([{DefaultDataKeys.INPUT: image}])\n assert (torch.tensor(predictions) > 1).sum() == 0\n assert (torch.tensor(predictions) < 0).sum() == 0\n assert len(predictions[0]) == num_classes == len(label)\n assert len(torch.unique(label)) <= 2\n\n\[email protected](not _IMAGE_TESTING, reason=\"image libraries aren't installed.\")\[email protected](\"jitter, args\", [(torch.jit.script, ()), (torch.jit.trace, (torch.rand(1, 3, 32, 32), ))])\ndef test_jit(tmpdir, jitter, args):\n path = os.path.join(tmpdir, \"test.pt\")\n\n model = ImageClassifier(2)\n model.eval()\n\n model = jitter(model, *args)\n\n torch.jit.save(model, path)\n model = torch.jit.load(path)\n\n out = model(torch.rand(1, 3, 32, 32))\n assert isinstance(out, torch.Tensor)\n assert out.shape == torch.Size([1, 2])\n\n\[email protected](not _SERVE_TESTING, reason=\"serve libraries aren't installed.\")\[email protected](\"flash._IS_TESTING\", True)\ndef test_serve():\n model = ImageClassifier(2)\n # TODO: Currently only servable once a preprocess has been attached\n model._preprocess = ImageClassificationPreprocess()\n model.eval()\n model.serve()\n\n\[email protected](_IMAGE_AVAILABLE, reason=\"image libraries are installed.\")\ndef test_load_from_checkpoint_dependency_error():\n with pytest.raises(ModuleNotFoundError, match=re.escape(\"'lightning-flash[image]'\")):\n ImageClassifier.load_from_checkpoint(\"not_a_real_checkpoint.pt\")\n"
] | [
[
"torch.jit.save",
"torch.jit.load",
"torch.Size",
"torch.randint",
"torch.utils.data.DataLoader",
"torch.tensor",
"torch.unique",
"torch.rand"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ZhenyuZhangUSTC/deit | [
"ce09a7241e663cd1cc3455ea727637fc6a85e7f7"
] | [
"pruning_utils.py"
] | [
"import copy \nimport torch\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.utils.prune as prune\nfrom layers import Conv2d, Linear\n\n__all__ = ['masked_parameters', 'SynFlow', 'Mag', 'check_sparsity', 'check_sparsity_dict', \n 'prune_model_identity', 'prune_model_custom', 'extract_mask', 'prune_conv_linear']\n\ndef masks(module):\n r\"\"\"Returns an iterator over modules masks, yielding the mask.\n \"\"\"\n for name, buf in module.named_buffers():\n if \"mask\" in name:\n yield buf\n\ndef masked_parameters(model):\n r\"\"\"Returns an iterator over models prunable parameters, yielding both the\n mask and parameter tensors.\n \"\"\"\n for module in model.modules():\n if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear):\n for mask, param in zip(masks(module), module.parameters(recurse=False)):\n if param is not module.bias:\n yield mask, param\n\nclass Pruner:\n def __init__(self, masked_parameters):\n self.masked_parameters = list(masked_parameters)\n self.scores = {}\n\n def score(self, model, loss, dataloader, device):\n raise NotImplementedError\n\n def _global_mask(self, sparsity):\n r\"\"\"Updates masks of model with scores by sparsity level globally.\n \"\"\"\n # # Set score for masked parameters to -inf \n # for mask, param in self.masked_parameters:\n # score = self.scores[id(param)]\n # score[mask == 0.0] = -np.inf\n\n # Threshold scores\n global_scores = torch.cat([torch.flatten(v) for v in self.scores.values()])\n k = int((1.0 - sparsity) * global_scores.numel())\n if not k < 1:\n threshold, _ = torch.kthvalue(global_scores, k)\n for mask, param in self.masked_parameters:\n score = self.scores[id(param)] \n zero = torch.tensor([0.]).to(mask.device)\n one = torch.tensor([1.]).to(mask.device)\n mask.copy_(torch.where(score <= threshold, zero, one))\n \n def _local_mask(self, sparsity):\n r\"\"\"Updates masks of model with scores by sparsity level parameter-wise.\n \"\"\"\n for mask, param in self.masked_parameters:\n score = self.scores[id(param)]\n k = int((1.0 - sparsity) * score.numel())\n if not k < 1:\n threshold, _ = torch.kthvalue(torch.flatten(score), k)\n zero = torch.tensor([0.]).to(mask.device)\n one = torch.tensor([1.]).to(mask.device)\n mask.copy_(torch.where(score <= threshold, zero, one))\n\n def mask(self, sparsity, scope):\n r\"\"\"Updates masks of model with scores by sparsity according to scope.\n \"\"\"\n if scope == 'global':\n self._global_mask(sparsity)\n if scope == 'local':\n self._local_mask(sparsity)\n\n @torch.no_grad()\n def apply_mask(self):\n r\"\"\"Applies mask to prunable parameters.\n \"\"\"\n for mask, param in self.masked_parameters:\n param.mul_(mask)\n\n def alpha_mask(self, alpha):\n r\"\"\"Set all masks to alpha in model.\n \"\"\"\n for mask, _ in self.masked_parameters:\n mask.fill_(alpha)\n\n # Based on https://github.com/facebookresearch/open_lth/blob/master/utils/tensor_utils.py#L43\n def shuffle(self):\n for mask, param in self.masked_parameters:\n shape = mask.shape\n perm = torch.randperm(mask.nelement())\n mask = mask.reshape(-1)[perm].reshape(shape)\n\n def invert(self):\n for v in self.scores.values():\n v.div_(v**2)\n\n def stats(self):\n r\"\"\"Returns remaining and total number of prunable parameters.\n \"\"\"\n remaining_params, total_params = 0, 0 \n for mask, _ in self.masked_parameters:\n remaining_params += mask.detach().cpu().numpy().sum()\n total_params += mask.numel()\n return remaining_params, total_params\n\nclass SynFlow(Pruner):\n def __init__(self, masked_parameters):\n super(SynFlow, self).__init__(masked_parameters)\n\n def score(self, model, loss, dataloader, device):\n\n @torch.no_grad()\n def linearize(model):\n # model.double()\n signs = {}\n for name, param in model.state_dict().items():\n signs[name] = torch.sign(param)\n param.abs_()\n return signs\n\n @torch.no_grad()\n def nonlinearize(model, signs):\n # model.float()\n for name, param in model.state_dict().items():\n param.mul_(signs[name])\n \n signs = linearize(model)\n\n (data, _) = next(iter(dataloader))\n input_dim = list(data[0,:].shape)\n input = torch.ones([1] + input_dim).to(device)#, dtype=torch.float64).to(device)\n output = model(input)\n torch.sum(output).backward()\n \n for _, p in self.masked_parameters:\n self.scores[id(p)] = torch.clone(p.grad * p).detach().abs_()\n p.grad.data.zero_()\n\n nonlinearize(model, signs)\n\nclass Mag(Pruner):\n def __init__(self, masked_parameters):\n super(Mag, self).__init__(masked_parameters)\n \n def score(self, model, loss, dataloader, device):\n for _, p in self.masked_parameters:\n self.scores[id(p)] = torch.clone(p.data).detach().abs_()\n\ndef check_sparsity(model):\n\n sum_list = 0\n zero_sum = 0\n\n for name,m in model.named_modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n sum_list = sum_list+float(m.weight.nelement())\n zero_sum = zero_sum+float(torch.sum(m.weight == 0)) \n\n print('* remain weight = ', 100*(1-zero_sum/sum_list),'%')\n \n return 100*(1-zero_sum/sum_list)\n\ndef check_sparsity_dict(model_dict):\n\n sum_list = 0\n zero_sum = 0\n\n for key in model_dict.keys():\n if 'mask' in key:\n sum_list = sum_list+float(model_dict[key].nelement())\n zero_sum = zero_sum+float(torch.sum(model_dict[key] == 0)) \n\n print('* remain weight = ', 100*(1-zero_sum/sum_list),'%')\n \n return 100*(1-zero_sum/sum_list)\n\ndef prune_model_identity(model):\n\n print('start pruning with identity mask')\n for name,m in model.named_modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n print('identity pruning layer {}'.format(name))\n prune.Identity.apply(m, 'weight')\n\ndef prune_model_custom(model, mask_dict):\n\n print('start pruning with custom mask')\n for name,m in model.named_modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n print('custom pruning layer {}'.format(name))\n prune.CustomFromMask.apply(m, 'weight', mask=mask_dict[name+'.weight_mask'])\n\ndef extract_mask(model_dict):\n\n new_dict = {}\n\n for key in model_dict.keys():\n if 'mask' in key:\n new_dict[key] = copy.deepcopy(model_dict[key])\n\n return new_dict\n\ndef prune_conv_linear(model):\n\n for name, module in reversed(model._modules.items()):\n\n if len(list(module.children())) > 0:\n model._modules[name] = prune_conv_linear(model=module)\n\n if isinstance(module, nn.Linear):\n bias=True\n if module.bias == None:\n bias=False\n layer_new = Linear(module.in_features, module.out_features, bias)\n model._modules[name] = layer_new\n\n if isinstance(module, nn.Conv2d):\n layer_new = Conv2d(module.in_channels, module.out_channels, module.kernel_size, module.stride)\n model._modules[name] = layer_new\n\n return model\n\n\n"
] | [
[
"torch.ones",
"torch.sign",
"torch.kthvalue",
"torch.clone",
"torch.sum",
"torch.nn.utils.prune.Identity.apply",
"torch.tensor",
"torch.no_grad",
"torch.where",
"torch.flatten",
"torch.nn.utils.prune.CustomFromMask.apply"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jrrwll/demopy | [
"f8ef302b85801ed63fbdda1627b97a153f28bc5c"
] | [
"demopy/numpy/get-start.py"
] | [
"#!/usr/bin/env python3\n\nimport numpy as np\n\n# 1D Array\na = np.array([0, 1, 2, 3, 4])\nb = np.array((0, 1, 2, 3, 4))\nc = np.arange(5)\nd = np.linspace(0, 2 * np.pi, 5)\n\nprint(a) # >>>[0 1 2 3 4]\nprint(b) # >>>[0 1 2 3 4]\nprint(c) # >>>[0 1 2 3 4]\nprint(d) # >>>[ 0. 1.57079633 3.14159265 4.71238898 6.28318531]\nprint(a[3]) # >>>3\n\n# MD Array,\na = np.array([[11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n [26, 27, 28, 29, 30],\n [31, 32, 33, 34, 35]])\n\nprint(a[2, 4]) # >>>25\n\n# MD slicing\nprint(a[0, 1:4]) # >>>[12 13 14]\nprint(a[1:4, 0]) # >>>[16 21 26]\nprint(a[::2, ::2]) # >>>[[11 13 15]\n# [21 23 25]\n# [31 33 35]]\nprint(a[:, 1]) # >>>[12 17 22 27 32]\n\n# Array properties\na = np.array([[11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n [26, 27, 28, 29, 30],\n [31, 32, 33, 34, 35]])\n\nprint(type(a)) # >>><class 'numpy.ndarray'>\nprint(a.dtype) # >>>int64\nprint(a.size) # >>>25\nprint(a.shape) # >>>(5, 5)\nprint(a.itemsize) # >>>8\nprint(a.ndim) # >>>2\nprint(a.nbytes) # >>>200\n\n# Basic Operators\na = np.arange(25)\na = a.reshape((5, 5))\n\nb = np.array([10, 62, 1, 14, 2, 56, 79, 2, 1, 45,\n 4, 92, 5, 55, 63, 43, 35, 6, 53, 24,\n 56, 3, 56, 44, 78])\nb = b.reshape((5, 5))\n\nprint(a + b)\nprint(a - b)\nprint(a * b)\nprint(a / b)\nprint(a ** 2)\nprint(a < b)\nprint(a > b)\nprint(a.dot(b))\n\n# dot, sum, min, max, cumsum\na = np.arange(10)\n\nprint(a.sum()) # >>>45\nprint(a.min()) # >>>0\nprint(a.max()) # >>>9\nprint(a.cumsum()) # >>>[ 0 1 3 6 10 15 21 28 36 45]\n\n# Fancy indexing\na = np.arange(0, 100, 10)\nindices = [1, 5, -1]\nb = a[indices]\nprint(a) # >>>[ 0 10 20 30 40 50 60 70 80 90]\nprint(b) # >>>[10 50 90]\n\n# Incomplete Indexing\na = np.arange(0, 100, 10)\nb = a[:5]\nc = a[a >= 50]\nprint(b) # >>>[ 0 10 20 30 40]\nprint(c) # >>>[50 60 70 80 90]\n\n# Where\na = np.arange(0, 100, 10)\nb = np.where(a < 50)\nc = np.where(a >= 50)[0]\nprint(b) # >>>(array([0, 1, 2, 3, 4]),)\nprint(c) # >>>[5 6 7 8 9]\n"
] | [
[
"numpy.arange",
"numpy.array",
"numpy.where",
"numpy.linspace"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dineshbabusv/SeqGenSQL | [
"e42d63b10097bc92105485d21ec913c3d150d128"
] | [
"data/dataset2.py"
] | [
"import argparse\nimport glob\nimport os\nimport json\nimport time\nimport logging\nimport random\nimport re\nimport copy\nfrom itertools import chain\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nimport tqdm\nimport pickle\n\nimport multiprocessing as mtp\nfrom transformers import (\n AdamW,\n T5ForConditionalGeneration,\n T5Tokenizer,\n get_linear_schedule_with_warmup\n)\n\ninputs = []\ntargets = []\ngate_masks = []\ngenerated_data_flag = []\ndata = []\n\ninput_string_list = []\nsql_statement_list = []\ngate_mask_list = []\n\n\n######################################################################\n## WikiSql Dataset\n######################################################################\nclass WikiSqlDataset(Dataset):\n def __init__(self, tokenizer, data_dir, dataset_type, \n include_data_type = True, include_sample_data = 0, \n data_augmentation = [], generated_data = [], generated_data_dropout = True,\n max_input_len=512, max_output_len = 200,include_question = False):\n self.dataset_type = dataset_type\n self.data_file = os.path.join(data_dir, dataset_type+'.jsonl')\n self.table_file = os.path.join(data_dir, dataset_type+'.tables.jsonl')\n self.generated_data = generated_data\n\n self.max_input_len = max_input_len\n self.max_output_len = max_output_len\n self.data_augmentation = data_augmentation \n self.tokenizer = tokenizer\n self.tokenizer.sep_token = '<sep>'\n self.generated_data_dropout = generated_data_dropout\n self.include_question = include_question\n\n self.inputs = []\n self.targets = []\n self.generated_data_flag=[]\n\n # raw data\n self.data = []\n self.tables = {}\n\n # feature engineering\n self.include_data_type = include_data_type\n self.include_sample_data = include_sample_data\n\n # process data\n self.input_string = []\n self.target_string = []\n\n # gated layer\n self.gate_masks = []\n\n self.cond_ops = ['=', '>', '<', 'OP']\n self.agg_ops = ['', 'MAX', 'MIN', 'COUNT', 'SUM', 'AVG']\n\n self.input_str = []\n #self._build()\n \n def __len__(self):\n return len(self.data)\n\n def _get_encode_length(self, text):\n return len(self.tokenizer.encode(text))\n\n def _build_input_output(self, raw_data):\n question, sql, table_id = raw_data['question'],raw_data['sql'], raw_data['table_id']\n columns, columns_types = self.tables[raw_data['table_id']]['header'], self.tables[raw_data['table_id']]['types']\n\n # input = question + table id + (column names, column types)\n input = question + self.tokenizer.sep_token + table_id\n question_pos = len(self.tokenizer.encode(question))\n\n # mask for gated layer\n gate_mask = [1] * self._get_encode_length(input) # consider questions\n\n # Get sample data\n if self.include_sample_data > 0:\n selected_num_rows = min(self.include_sample_data, len(self.tables[table_id]['rows']))\n #rng = np.random.default_rng()\n #row_indexes = np.sort(rng.choice(selected_num_rows + 1, size=self.include_sample_data , replace = False))\n selected_rows = self.tables[table_id]['rows'][:selected_num_rows]\n \n #add columns names + [SEP] + column data type + [SEP]\n for (ci, (c, ct)) in enumerate(zip(columns, columns_types)) :\n input += self.tokenizer.sep_token + c \n gate_mask += [1] * self._get_encode_length(self.tokenizer.sep_token + c) # consider column headers\n if self.include_data_type:\n input += self.tokenizer.sep_token + ct\n gate_mask += [0] * self._get_encode_length(self.tokenizer.sep_token + ct) # do not use data types\n if self.include_sample_data > 0 :\n for r in selected_rows:\n input += self.tokenizer.sep_token + str(r[ci])\n gate_mask += [0] * self._get_encode_length(self.tokenizer.sep_token + str(r[ci])) # do not use data types\n\n input += self.tokenizer.eos_token\n input = input.lower()\n \n # generate label - sql statement\n sql_statement = 'SELECT ' + self.agg_ops[sql['agg']] \n if sql['agg'] > 0:\n sql_statement += '([' + columns[sql['sel']] + ']) FROM [' + table_id +\"] \"\n else:\n sql_statement += ' [' + columns[sql['sel']] + '] FROM [' + table_id +\"] \"\n\n if len(sql['conds']) > 0:\n sql_statement += 'WHERE '\n \n for c in sql['conds']:\n sql_statement += '[' + columns[c[0]] + '] ' + self.cond_ops[c[1]]\n if isinstance(c[2], (int, float)):\n sql_statement += \" \" + str(c[2])\n else:\n sql_statement += \" '\" + c[2] + \"'\"\n sql_statement += \" AND \"\n sql_statement = sql_statement[:-4]\n \n sql_statement += self.tokenizer.eos_token\n sql_statement = sql_statement.lower()\n\n # pad gate_mask\n if len(gate_mask) < self.max_input_len:\n gate_mask += [0] * (self.max_input_len - len(gate_mask))\n elif len(gate_mask) > self.max_input_len:\n gate_mask = gate_mask[:self.max_input_len]\n\n gate_mask = torch.Tensor(gate_mask)\n return input, sql_statement , gate_mask , question_pos \n\n\n # This is a data augmentation method: to replace select column using randomly selected column\n def _replace_select_col(self, data):\n question = data['question'].lower()\n table_id = data['table_id']\n headers = self.tables[table_id]['header']\n sel_col = data['sql']['sel']\n sel_name = headers[sel_col].lower()\n\n new_col = np.random.randint(len(headers))\n new_colname = headers[new_col].lower()\n \n new_data = data.copy()\n new_data['question'] = question.replace(sel_name, new_colname)\n \n if question.find(sel_name) > -1:\n new_data['sql']['sel'] = new_col\n input, sql_statement , gate_mask, question_pos = self._build_input_output(new_data)\n return input, sql_statement, gate_mask, question_pos \n\n # this is augmentation method 2: replace where value with any value from database\n def _replace_where_val(self, data):\n \n question = data['question'].lower()\n table_id = data['table_id']\n headers = self.tables[table_id]['header']\n\n new_data = copy.deepcopy(data)\n #1: Randomly pick one condition\n condition_len = len(data['sql']['conds'])\n if condition_len > 0:\n cond_idx = np.random.randint(condition_len, size = 1)[0]\n cond_where = data['sql']['conds'][cond_idx]\n where_col = cond_where[0]\n\n # construct real sql to get all available values\n new_row_idx = np.random.randint(len(self.tables[data['table_id']]['rows']))\n new_where_value = self.tables[data['table_id']]['rows'][new_row_idx][where_col]\n\n # Now replace old value\n old_where_value = data['sql']['conds'][cond_idx][2]\n \n # replace\n new_data['question'] = question.replace(str(old_where_value).lower(), str(new_where_value).lower())\n new_data['sql']['conds'][cond_idx][2] = new_where_value\n \n # Generate tokens\n input, sql_statement, gate_mask, question_pos = self._build_input_output(new_data)\n return input, sql_statement, gate_mask, question_pos \n\n def __getitem__(self, index):\n # Augmenting train set only\n if self.dataset_type != 'train' or self.data_augmentation == []:\n input_string = self.input_string[index]\n target_string = self.target_string[index]\n\n source_ids = self.inputs[index][\"input_ids\"].squeeze()\n target_ids = self.targets[index][\"input_ids\"].squeeze()\n\n src_mask = self.inputs[index][\"attention_mask\"].squeeze() # might need to squeeze\n target_mask = self.targets[index][\"attention_mask\"].squeeze() # might need to squeeze\n\n gate_mask = self.gate_masks[index].squeeze()\n\n # Input token drop out\n if self.dataset_type == 'train' and self.generated_data_flag[index] > 0 and self.generated_data_dropout:\n #drop out 1 token\n pos = np.random.randint(self.generated_data_flag[index])\n source_ids[pos] = self.tokenizer.pad_token_id\n else:\n # generate input and output\n aug = np.random.choice(self.data_augmentation)\n if aug == 'select_column':\n input_string, target_string, gate_mask, question_pos = self._replace_select_col(self.data[index]) \n elif aug == 'where_value' :\n input_string, target_string, gate_mask, question_pos = self._replace_where_val(self.data[index]) \n \n self.input_string.append(input_string)\n self.target_string.append(target_string)\n self.gate_masks.append(gate_mask)\n # tokenize inputs\n tokenized_inputs = self.tokenizer.batch_encode_plus(\n [input_string], max_length=self.max_input_len, pad_to_max_length=True, return_tensors=\"pt\"\n )\n # tokenize targets\n tokenized_targets = self.tokenizer.batch_encode_plus(\n [target_string], max_length=self.max_output_len, pad_to_max_length=True, return_tensors=\"pt\"\n )\n \n source_ids = tokenized_inputs[\"input_ids\"].squeeze()\n target_ids = tokenized_targets[\"input_ids\"].squeeze()\n\n src_mask = tokenized_inputs[\"attention_mask\"].squeeze() # might need to squeeze\n target_mask = tokenized_targets[\"attention_mask\"].squeeze() # might need to squeeze\n\n if self.include_question :\n return {\"source_ids\": source_ids, \"target_ids\": target_ids, \n \"question\": self.data[index]['question'],\n \"source_mask\": src_mask, \"target_mask\": target_mask, 'gate_mask': gate_mask}\n else:\n return {\"source_ids\": source_ids, \"target_ids\": target_ids, \n #\"input_string\": input_string, \"target_string\": target_string, \n \"source_mask\": src_mask, \"target_mask\": target_mask, 'gate_mask': gate_mask}\n\n\n def clean_step1(self, line):\n sql = json.loads(line.strip())\n data.append(sql) \n\n\n def _multi_build_input_output(self, sql):\n input_string, sql_statement,gate_mask, _ = self._build_input_output(sql)\n input_string_list.append(input_string)\n sql_statement_list.append(sql_statement)\n gate_mask_list.append(gate_mask)\n\n\n def _async_multi_build_input_output(self, sql):\n input_string, sql_statement,gate_mask, _ = self._build_input_output(sql)\n return [input_string, sql_statement, gate_mask]\n\n\n def clean_step2(self, dat):\n p = mtp.Pool(mtp.cpu_count())\n temp_list = []\n for el in dat:\n temp_list.append(p.apply_async(self._async_multi_build_input_output, (el,)))\n return temp_list\n #input_string_list.append(input_string)\n #sql_statement_list.append(sql_statement)\n #gate_mask_list.append(gate_mask)\n\n def _build2(self): \n # load all data from file\n p = mtp.Pool(mtp.cpu_count())\n\n with open(self.table_file, 'r') as f:\n all_lines = f.readlines()\n for idx, line in enumerate(all_lines):\n t1 = json.loads(line.strip())\n self.tables[t1['id']] = t1\n \n with open(self.data_file) as f:\n print(\"Loading {} ...\".format(self.data_file), end=\"\") \n all_lines = f.readlines()\n for idx, line in enumerate(all_lines): \n self.clean_step1(line)\n self.data = data\n \n #input_data = self.data[:10]\n res = []\n for k in range(500//2, 5000//2, 1):\n print(f\"processing the batch n° {str(k)}\")\n for idx,sql in tqdm.tqdm(enumerate(self.data[k*2:(k+1)*2])):\n res.append(self.clean_step2([sql]))\n\n p.close()\n p.join()\n result = res\n print(len(result))\n \n\n self.input_str += [el[0].get() for el in result]\n with open(f'my_dumped_file_{str(k)}','wb') as f:\n pickle.dump(self.input_str, f)\n #print(input_str)\n\n\n\n\n #print(input_str)\n #print(sql_str)\n #print(gate_str)\n\n #for idx, line in tqdm.tqdm(enumerate(f)):\n # p.apply_async(self.clean_step1, args = (line ))\n # p.close()\n # p.join()\n\n\n \n# for idx, line in tqdm.tqdm(enumerate(f)):\n# sql = json.loads(line.strip())\n# self.data.append(sql) \n\n# if self.dataset_type != 'train' or self.data_augmentation == []:\n# # generate input and output\n# input_string, sql_statement,gate_mask, _ = self._build_input_output(sql) \n\n# self.input_string.append(input_string)\n# self.target_string.append(sql_statement)\n# # tokenize inputs\n# tokenized_inputs = self.tokenizer.batch_encode_plus(\n# [input_string], max_length=self.max_input_len, pad_to_max_length=True, return_tensors=\"pt\"\n# )\n # tokenize targets\n# tokenized_targets = self.tokenizer.batch_encode_plus(\n# [sql_statement], max_length=self.max_output_len, pad_to_max_length=True, return_tensors=\"pt\"\n# )\n\n# self.inputs.append(tokenized_inputs)\n# self.targets.append(tokenized_targets)\n# self.gate_masks.append(gate_mask)\n# self.generated_data_flag.append(0) # not generated data\n# print(\"Done!\") \n \n\n\n\n\n\n\n\n\n\n \n def _build(self): \n # load all data from file\n with open(self.table_file) as f:\n for idx, line in enumerate(f):\n t1 = json.loads(line.strip())\n self.tables[t1['id']] = t1\n \n with open(self.data_file) as f:\n print(\"Loading {} ...\".format(self.data_file), end=\"\") \n for idx, line in tqdm.tqdm(enumerate(f)):\n sql = json.loads(line.strip())\n self.data.append(sql) \n\n if self.dataset_type != 'train' or self.data_augmentation == []:\n # generate input and output\n input_string, sql_statement,gate_mask, _ = self._build_input_output(sql) \n\n self.input_string.append(input_string)\n self.target_string.append(sql_statement)\n # tokenize inputs\n tokenized_inputs = self.tokenizer.batch_encode_plus(\n [input_string], max_length=self.max_input_len, pad_to_max_length=True, return_tensors=\"pt\"\n )\n # tokenize targets\n tokenized_targets = self.tokenizer.batch_encode_plus(\n [sql_statement], max_length=self.max_output_len, pad_to_max_length=True, return_tensors=\"pt\"\n )\n\n self.inputs.append(tokenized_inputs)\n self.targets.append(tokenized_targets)\n self.gate_masks.append(gate_mask)\n self.generated_data_flag.append(0) # not generated data\n print(\"Done!\") \n \n if self.dataset_type == 'train':\n\n for gen_file in tqdm.tqdm(self.generated_data):\n print(\"Loading {} ...\".format(gen_file), end=\"\")\n with open(gen_file) as f:\n for idx, line in enumerate(f):\n sql = json.loads(line.strip())\n self.data.append(sql) \n\n if self.data_augmentation == []:\n # generate input and output\n input_string, sql_statement, gate_mask,question_pos = self._build_input_output(sql) \n\n self.input_string.append(input_string)\n self.target_string.append(sql_statement)\n # tokenize inputs\n tokenized_inputs = self.tokenizer.batch_encode_plus(\n [input_string], max_length=self.max_input_len, pad_to_max_length=True, return_tensors=\"pt\"\n )\n # tokenize targets\n tokenized_targets = self.tokenizer.batch_encode_plus(\n [sql_statement], max_length=self.max_output_len, pad_to_max_length=True, return_tensors=\"pt\"\n )\n\n self.inputs.append(tokenized_inputs)\n self.targets.append(tokenized_targets)\n self.gate_masks.append(gate_mask)\n self.generated_data_flag.append(question_pos) # generated data\n print(\"Done!\")\n\n\n\nif __name__ =='__main__':\n\n tokenizer = T5Tokenizer.from_pretrained(\"t5-base\")\n data_dir = \"data\"\n dataset_type= 'train'\n include_data_type = True\n include_sample_data = 3\n data_augmentation = []\n generated_data = []\n max_input_len= 512\n max_output_len= 200\n\n train_wiki_dataset = WikiSqlDataset(tokenizer=tokenizer, \n data_dir=data_dir, \n dataset_type=dataset_type, \n include_data_type = True, \n include_sample_data = 3, \n data_augmentation = [],\n generated_data = [],\n max_input_len=512, \n max_output_len=200)\n\n print(train_wiki_dataset.data)\n train_wiki_dataset._build2()\n print(len(train_wiki_dataset.data))"
] | [
[
"numpy.random.randint",
"torch.Tensor",
"numpy.random.choice"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
pandeyab/create_your_own_image_classifier | [
"2829d1d77be5162316b68b92f54f3f6bf31f594b"
] | [
"predict.py"
] | [
"#!/usr/bin/env python3\n# \n# author: Abhishek Pandey\n# date: 09-08-2020 \n# description: Use a trained network to predict the class for an input image.Prints the most likely classes.\n#\n# Use argparse Expected Call with <> indicating expected user input:\n# python predict.py </path/to/image> <checkpoint>\n# --top_k <return top K most likely classes> \n# --category_names <path to a JSON file that maps the class values to other category names>\n# --gpu \n# Example command:\n# python predict.py flowers/test/17/image_03864.jpg checkpoint.pth --category_names cat_to_name.json --top_k 5 --gpu True\n##\n#main imports\nimport argparse\nimport sys\nimport os\nimport json\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n#from time import time, sleep\nimport time\nfrom collections import OrderedDict\n\n\n#import torch\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\nfrom torch import optim\nfrom torch.autograd import Variable\nfrom torchvision import datasets, transforms, models\n\nfrom PIL import Image\n\n\n\n# Main program function defined below\ndef main():\n # start time\n startTime = time.time()\n \n # Creates & retrieves Command Line Arugments\n args = getArguments()\n \n # Set device to cuda if gpu flag is set\n if args.gpu==True:\n device = 'cuda'\n else:\n device = 'cpu'\n \n # If given, read the mapping of categories to class names\n cat_to_name = {}\n if args.category_names:\n with open(args.category_names, 'r') as f:\n cat_to_name = json.load(f)\n \n # Load checkpoint and get the model\n model = load_checkpoint(args.checkpoint, args.gpu)\n print(model)\n \n # setting actual class labels convrter on probabilities\n model.idx_to_class = dict([[v,k] for k, v in model.class_to_idx.items()])\n \n # Predict probabilities and classes\n probs, clas = predict(args.img_path, model, args.top_k, args.gpu)\n print(probs)\n print(clas)\n # Convert categories into real names\n if cat_to_name:\n clas = [cat_to_name[str(cat)] for cat in clas]\n\n # Print results\n print('\\nThe top {} most likely classes are:'.format(args.top_k))\n max_name_len = len(max(clas, key=len))\n row_format =\"{:<\" + str(max_name_len + 2) + \"}{:<.4f}\"\n for prob, name in zip(probs, clas):\n print(row_format.format(name, prob))\n \n # verall runtime in seconds & prints it in hh:mm:ss format\n total_time = time.time() - startTime\n print(\"Total Elapsed Runtime: {:.0f}m {:.0f}s\".format(total_time//60, total_time % 60))\n\n \n\n #argument parser function\ndef getArguments():\n \"\"\"\n Retrieves and parses the command line arguments created. This function returns these arguments as an\n ArgumentParser object. \n Parameters:\n None - \n Returns:\n parse_args() - CLI data structure \n \"\"\"\n parser = argparse.ArgumentParser()\n\n # Manditory arguments\n parser.add_argument('img_path', type=str, help='path to input image')\n parser.add_argument('checkpoint', type=str, help='path to a saved checkpoint')\n \n #option arguments\n parser.add_argument('--top_k', type=int, default=3, dest='top_k', help='return top K most likely classes')\n parser.add_argument('--category_names', type=str, dest='category_names', help='path to a JSON file that maps the class values to other category names')\n parser.add_argument('--gpu', type=bool, default=False, dest='gpu', const=True, nargs='?', help='options to include cpu or cuda')\n\n # return parsed argument collection\n return parser.parse_args()\n\n\n\n#Checkpoint loading function\ndef load_checkpoint(filepath, gpu):\n ''' \n loads a model, classifier, state_dict and class_to_idx from a torch save\n '''\n if gpu==True:\n checkpoint = torch.load(filepath)\n else:\n checkpoint = torch.load(filepath, map_location=lambda storage, loc: storage)\n model = checkpoint['model']\n model.classifier = checkpoint['classifier']\n model.load_state_dict(checkpoint['state_dict'])\n model.class_to_idx = checkpoint['class_to_idx']\n optimizer = checkpoint['optimizer']\n \n return model\n\n\n \n#defining prediction function\ndef predict(image_path, model, topk, gpu): \n ''' Predict the class (or classes) of an image using a trained deep learning model.\n '''\n # DONE: Implement the code to predict the class from an image file\n image = Image.open(image_path).convert('RGB')\n image = process_image(image_path)\n image = torch.from_numpy(image).unsqueeze_(0).float()\n if gpu==True and torch.cuda.is_available():\n toCuda = torch.device(\"cuda:0\")\n model = model.to(toCuda)\n image = image.to(toCuda)\n else:\n toCuda = torch.device(\"cpu\")\n model.cpu()\n image.cpu()\n\n model.eval()\n \n # Calculate class probabilities \n with torch.no_grad():\n outputs = model.forward(image)\n \n # Get topk probabilities and classes\n probs, class_idxs = outputs.topk(topk)\n \n probs, class_idxs = probs.to('cpu'), class_idxs.to('cpu')\n probs = probs.exp().data.numpy()[0]\n class_idxs = class_idxs.data.numpy()[0]\n #print(class_idxs)\n \n # Convert from indices to the actual class labels\n try:\n ## Convert from indices to the actual class labels\n classes = np.array([model.idx_to_class[idx] for idx in class_idxs])\n \n except KeyError:\n print(\"The key does not exist!\")\n \n return probs, classes\n\n\n\n# image processing function\ndef process_image(image_path):\n ''' Scales, crops, and normalizes a PIL image for a PyTorch model,\n returns an Numpy array\n '''\n # TODO: Process a PIL image for use in a PyTorch model\n \n image = Image.open(image_path)\n \n if image.size[0] > image.size[1]:\n image.thumbnail((4500,256)) \n else:\n image.thumbnail((256,4500))\n \n left_margin = (image.width -224)/2\n bottom_margin = (image.height -224)/2\n right_margin = left_margin + 224\n top_margin = bottom_margin + 224\n \n image = image.crop((left_margin,bottom_margin,right_margin,top_margin))\n \n image_new = np.array(image)/225\n mean = np.array([0.485,0.456,0.406])\n std = np.array([0.229,0.224,0.225])\n image_new = (image_new - mean)/std\n \n image_new = image_new.transpose((2,0,1))\n \n return image_new\n \n \n\n#main function call\nif __name__ == \"__main__\":\n\n main()"
] | [
[
"torch.load",
"torch.from_numpy",
"torch.no_grad",
"torch.cuda.is_available",
"torch.device",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
fayalalebrun/pyquante2 | [
"e0a4a8ba038b3c702a620f069999798f2259c1c6"
] | [
"pyquante2/ints/integrals.py"
] | [
"\"\"\"\nGeneral module for integral generation and access.\n\"\"\"\ntry:\n from pyquante2.ctwo import ERI_hgp as ERI\nexcept:\n print(\"Couldn't find cython int routine\")\n from pyquante2.ints.hgp import ERI_hgp as ERI\n\ntry:\n from pyquante2.cone import S,T,V\nexcept:\n print(\"Couldn't find cython int routine\")\n from pyquante2.ints.one import S,T,V\n\nfrom pyquante2.utils import pairs\nfrom itertools import product\nimport numpy as np\n\n# This is the old part of the code. It has now been replaced with the one\n# below it, which takes 8x as much space, but is significantly faster.\n# It's also more elegant code.\nclass twoe_integrals_compressed(object):\n \"\"\"\n >>> from pyquante2.geo.samples import h\n >>> from pyquante2.basis.basisset import basisset\n >>> bfs = basisset(h,'sto3g')\n >>> twoe_integrals_compressed(bfs)\n array([ 0.77460594])\n \"\"\"\n def __init__(self,bfs):\n nbf = self.nbf = len(bfs)\n self.totlen = nbf*(nbf+1)*(nbf*nbf+nbf+2)//8\n self._2e_ints = np.empty(self.totlen,'d')\n \n for i,j,k,l in iiterator(nbf):\n self._2e_ints[iindex(i,j,k,l)] = ERI(bfs[i],bfs[j],bfs[k],bfs[l])\n return\n def __getitem__(self,pos): return self._2e_ints[iindex(*pos)]\n def __repr__(self): return repr(self._2e_ints)\n\n def fetch_2jk(self,i,j):\n nbf = self.nbf\n temp = np.empty(nbf**2,'d')\n kl = 0\n for k,l in product(range(nbf),repeat=2):\n temp[kl] = 2*self[i,j,k,l]-self[i,k,j,l]\n kl += 1\n return temp\n\n def fetch_j(self,i,j):\n nbf = self.nbf\n temp = np.empty(nbf**2,'d')\n kl = 0\n for k,l in product(range(nbf),repeat=2):\n temp[kl] = self[i,j,k,l]\n kl += 1\n return temp\n\n def fetch_k(self,i,j):\n nbf = self.nbf\n temp = np.empty(nbf**2,'d')\n kl = 0\n for k,l in product(range(nbf),repeat=2):\n temp[kl] = self[i,k,j,l]\n kl += 1\n return temp\n\n def make_operator(self,D,fetcher):\n nbf = self.nbf\n D1 = np.reshape(D,(nbf*nbf,))\n G = np.empty((nbf,nbf),'d')\n for i,j in pairs(range(nbf)):\n temp = fetcher(i,j) # replace temp with fetcher()\n G[i,j] = G[j,i] = np.dot(D1,temp)\n return G\n\n def get_2jk(self,D): return self.make_operator(D,self.fetch_2jk)\n def get_j(self,D): return self.make_operator(D,self.fetch_j)\n def get_k(self,D): return self.make_operator(D,self.fetch_k)\n\nclass twoe_integrals(object):\n \"\"\"\n >>> from pyquante2.geo.samples import h\n >>> from pyquante2.basis.basisset import basisset\n >>> bfs = basisset(h,'sto3g')\n >>> twoe_integrals(bfs)\n array([ 0.77460594])\n \"\"\"\n def __init__(self,bfs):\n nbf = self.nbf = len(bfs)\n self._2e_ints = np.empty((nbf,nbf,nbf,nbf),'d')\n ints = self._2e_ints\n \n for i,j,k,l in iiterator(nbf):\n ints[i,j,k,l] = ints[j,i,k,l] = ints[i,j,l,k] = ints[j,i,l,k] = \\\n ints[k,l,i,j] = ints[l,k,i,j] = ints[k,l,j,i] = \\\n ints[l,k,j,i] = ERI(bfs[i],bfs[j],bfs[k],bfs[l])\n return\n def __getitem__(self,*args): return self._2e_ints.__getitem__(*args)\n def __repr__(self): return repr(self._2e_ints.ravel())\n\n def transform(self,c): return np.einsum('aI,bJ,cK,dL,abcd->IJKL',c,c,c,c,self._2e_ints)\n def transform_mp2(self,c,nocc):\n return np.einsum('aI,bJ,cK,dL,abcd->IJKL',c[:,:nocc],c,c[:,:nocc],c,self._2e_ints)\n\n\n # This turns out to be slower:\n #def get_j(self,D): return np.einsum('ij,ijkl->kl',D,self._2e_ints)\n def get_j(self,D): return np.einsum('kl,ijkl->ij',D,self._2e_ints)\n def get_k(self,D): return np.einsum('ij,ikjl->kl',D,self._2e_ints)\n def get_2jk(self,D): return 2*self.get_j(D)-self.get_k(D)\n \nclass onee_integrals(object):\n \"\"\"\n >>> from pyquante2.geo.samples import h\n >>> from pyquante2.basis.basisset import basisset\n >>> bfs = basisset(h,'sto3g')\n >>> i1 = onee_integrals(bfs,h)\n >>> i1.S\n array([[ 1.]])\n >>> i1.T\n array([[ 0.76003188]])\n >>> i1.V\n array([[-1.22661373]])\n \"\"\"\n def __init__(self,bfs,geo):\n nbf = self.nbf = len(bfs)\n self.S = np.empty((nbf,nbf),'d')\n self.T = np.empty((nbf,nbf),'d')\n self.V = np.empty((nbf,nbf),'d')\n for i,j in pairs(range(nbf)):\n ibf,jbf = bfs[i],bfs[j]\n self.S[i,j] = self.S[j,i] = S(ibf,jbf)\n self.T[i,j] = self.T[j,i] = T(ibf,jbf)\n self.V[i,j] = self.V[j,i] = sum(at.Z*V(ibf,jbf,at.r) for at in geo)\n return\n \n\ndef iiterator(nbf):\n \"\"\"\n Iterator over n**4 integral indices\n >>> list(iiterator(2))\n [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 1), (0, 1, 0, 1), (0, 1, 1, 1), (1, 1, 1, 1)]\n \"\"\"\n for i,j in pairs(range(nbf)):\n ij = i*(i+1)/2+j\n for k,l in pairs(range(nbf)):\n kl = k*(k+1)/2+l\n if ij <= kl:\n yield i,j,k,l\n return\n\ndef iindex(i,j,k,l):\n \"\"\"\n Indexing into the integral array\n >>> iindex(0,0,0,0)\n 0\n >>> iindex(1,0,0,0)\n 1\n >>> iindex(0,1,0,0)\n 1\n >>> iindex(0,0,1,0)\n 1\n >>> iindex(0,0,0,1)\n 1\n >>> iindex(1,0,1,0)\n 2\n >>> iindex(0,1,0,1)\n 2\n >>> iindex(1,1,0,0)\n 3\n >>> iindex(0,0,1,1)\n 3\n \"\"\"\n if i<j: i,j = j,i\n if k<l: k,l = l,k\n ij = (i*(i+1))//2+j\n kl = (k*(k+1))//2+l\n if ij < kl: ij,kl = kl,ij\n return (ij*(ij+1))//2+kl\n \n\nif __name__ == '__main__':\n import doctest; doctest.testmod()\n"
] | [
[
"numpy.reshape",
"numpy.dot",
"numpy.einsum",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Michael0711/quantopian | [
"0848a8a4862fd8bbe7ba64654e6bc731b4b622b7"
] | [
"tests/calendars/test_trading_calendar.py"
] | [
"#\n# Copyright 2016 Quantopian, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom datetime import time\nfrom os.path import (\n abspath,\n dirname,\n join,\n)\nfrom unittest import TestCase\n\nimport numpy as np\nimport pandas as pd\nfrom nose_parameterized import parameterized\nfrom pandas import read_csv\nfrom pandas.tslib import Timedelta\nfrom pandas.util.testing import assert_index_equal\nfrom pytz import timezone\nfrom toolz import concat\n\nfrom zipline.errors import (\n CalendarNameCollision,\n InvalidCalendarName,\n)\n\nfrom zipline.utils.calendars import(\n register_calendar,\n deregister_calendar,\n get_calendar,\n)\nfrom zipline.utils.calendars.calendar_utils import (\n _default_calendar_aliases,\n _default_calendar_factories,\n register_calendar_type,\n\n)\nfrom zipline.utils.calendars.trading_calendar import days_at_time, \\\n TradingCalendar\n\n\nclass FakeCalendar(TradingCalendar):\n @property\n def name(self):\n return \"DMY\"\n\n @property\n def tz(self):\n return \"Asia/Ulaanbaatar\"\n\n @property\n def open_time(self):\n return time(11, 13)\n\n @property\n def close_time(self):\n return time(11, 49)\n\n\nclass CalendarRegistrationTestCase(TestCase):\n def setUp(self):\n self.dummy_cal_type = FakeCalendar\n\n def tearDown(self):\n deregister_calendar('DMY')\n\n def test_register_calendar(self):\n # Build a fake calendar\n dummy_cal = self.dummy_cal_type()\n\n # Try to register and retrieve the calendar\n register_calendar('DMY', dummy_cal)\n retr_cal = get_calendar('DMY')\n self.assertEqual(dummy_cal, retr_cal)\n\n # Try to register again, expecting a name collision\n with self.assertRaises(CalendarNameCollision):\n register_calendar('DMY', dummy_cal)\n\n # Deregister the calendar and ensure that it is removed\n deregister_calendar('DMY')\n with self.assertRaises(InvalidCalendarName):\n get_calendar('DMY')\n\n def test_register_calendar_type(self):\n register_calendar_type(\"DMY\", self.dummy_cal_type)\n retr_cal = get_calendar(\"DMY\")\n self.assertEqual(self.dummy_cal_type, type(retr_cal))\n\n def test_both_places_are_checked(self):\n dummy_cal = self.dummy_cal_type()\n\n # if instance is registered, can't register type with same name\n register_calendar('DMY', dummy_cal)\n with self.assertRaises(CalendarNameCollision):\n register_calendar_type('DMY', type(dummy_cal))\n\n deregister_calendar('DMY')\n\n # if type is registered, can't register instance with same name\n register_calendar_type('DMY', type(dummy_cal))\n\n with self.assertRaises(CalendarNameCollision):\n register_calendar('DMY', dummy_cal)\n\n def test_force_registration(self):\n register_calendar(\"DMY\", self.dummy_cal_type())\n first_dummy = get_calendar(\"DMY\")\n\n # force-register a new instance\n register_calendar(\"DMY\", self.dummy_cal_type(), force=True)\n\n second_dummy = get_calendar(\"DMY\")\n\n self.assertNotEqual(first_dummy, second_dummy)\n\n\nclass DefaultsTestCase(TestCase):\n def test_default_calendars(self):\n for name in concat([_default_calendar_factories,\n _default_calendar_aliases]):\n self.assertIsNotNone(get_calendar(name),\n \"get_calendar(%r) returned None\" % name)\n\n\nclass DaysAtTimeTestCase(TestCase):\n @parameterized.expand([\n # NYSE standard day\n (\n '2016-07-19', 0, time(9, 31), timezone('US/Eastern'),\n '2016-07-19 9:31',\n ),\n # CME standard day\n (\n '2016-07-19', -1, time(17, 1), timezone('America/Chicago'),\n '2016-07-18 17:01',\n ),\n # CME day after DST start\n (\n '2004-04-05', -1, time(17, 1), timezone('America/Chicago'),\n '2004-04-04 17:01'\n ),\n # ICE day after DST start\n (\n '1990-04-02', -1, time(19, 1), timezone('America/Chicago'),\n '1990-04-01 19:01',\n ),\n ])\n def test_days_at_time(self, day, day_offset, time_offset, tz, expected):\n days = pd.DatetimeIndex([pd.Timestamp(day, tz=tz)])\n result = days_at_time(days, time_offset, tz, day_offset)[0]\n expected = pd.Timestamp(expected, tz=tz).tz_convert('UTC')\n self.assertEqual(result, expected)\n\n\nclass ExchangeCalendarTestBase(object):\n\n # Override in subclasses.\n answer_key_filename = None\n calendar_class = None\n\n GAPS_BETWEEN_SESSIONS = True\n\n MAX_SESSION_HOURS = 0\n\n @staticmethod\n def load_answer_key(filename):\n \"\"\"\n Load a CSV from tests/resources/calendars/{filename}.csv\n \"\"\"\n fullpath = join(\n dirname(abspath(__file__)),\n '../resources',\n 'calendars',\n filename + '.csv',\n )\n\n return read_csv(\n fullpath,\n index_col=0,\n # NOTE: Merely passing parse_dates=True doesn't cause pandas to set\n # the dtype correctly, and passing all reasonable inputs to the\n # dtype kwarg cause read_csv to barf.\n parse_dates=[0, 1, 2],\n date_parser=lambda x: pd.Timestamp(x, tz='UTC')\n )\n\n @classmethod\n def setupClass(cls):\n cls.answers = cls.load_answer_key(cls.answer_key_filename)\n\n cls.start_date = cls.answers.index[0]\n cls.end_date = cls.answers.index[-1]\n cls.calendar = cls.calendar_class(cls.start_date, cls.end_date)\n\n cls.one_minute = pd.Timedelta(minutes=1)\n cls.one_hour = pd.Timedelta(hours=1)\n\n def test_sanity_check_session_lengths(self):\n # make sure that no session is longer than self.MAX_SESSION_HOURS hours\n for session in self.calendar.all_sessions:\n o, c = self.calendar.open_and_close_for_session(session)\n delta = c - o\n self.assertTrue((delta.seconds / 3600) <= self.MAX_SESSION_HOURS)\n\n def test_calculated_against_csv(self):\n assert_index_equal(self.calendar.schedule.index, self.answers.index)\n\n def test_is_open_on_minute(self):\n one_minute = pd.Timedelta(minutes=1)\n\n for market_minute in self.answers.market_open:\n market_minute_utc = market_minute\n # The exchange should be classified as open on its first minute\n self.assertTrue(self.calendar.is_open_on_minute(market_minute_utc))\n\n if self.GAPS_BETWEEN_SESSIONS:\n # Decrement minute by one, to minute where the market was not\n # open\n pre_market = market_minute_utc - one_minute\n self.assertFalse(self.calendar.is_open_on_minute(pre_market))\n\n for market_minute in self.answers.market_close:\n close_minute_utc = market_minute\n # should be open on its last minute\n self.assertTrue(self.calendar.is_open_on_minute(close_minute_utc))\n\n if self.GAPS_BETWEEN_SESSIONS:\n # increment minute by one minute, should be closed\n post_market = close_minute_utc + one_minute\n self.assertFalse(self.calendar.is_open_on_minute(post_market))\n\n def _verify_minute(self, calendar, minute,\n next_open_answer, prev_open_answer,\n next_close_answer, prev_close_answer):\n self.assertEqual(\n calendar.next_open(minute),\n next_open_answer\n )\n\n self.assertEqual(\n self.calendar.previous_open(minute),\n prev_open_answer\n )\n\n self.assertEqual(\n self.calendar.next_close(minute),\n next_close_answer\n )\n\n self.assertEqual(\n self.calendar.previous_close(minute),\n prev_close_answer\n )\n\n def test_next_prev_open_close(self):\n # for each session, check:\n # - the minute before the open (if gaps exist between sessions)\n # - the first minute of the session\n # - the second minute of the session\n # - the minute before the close\n # - the last minute of the session\n # - the first minute after the close (if gaps exist between sessions)\n answers_to_use = self.answers[1:-2]\n\n for idx, info in enumerate(answers_to_use.iterrows()):\n open_minute = info[1].iloc[0]\n close_minute = info[1].iloc[1]\n\n minute_before_open = open_minute - self.one_minute\n\n # answers_to_use starts at the second element of self.answers,\n # so self.answers.iloc[idx] is one element before, and\n # self.answers.iloc[idx + 2] is one element after the current\n # element\n previous_open = self.answers.iloc[idx].market_open\n next_open = self.answers.iloc[idx + 2].market_open\n previous_close = self.answers.iloc[idx].market_close\n next_close = self.answers.iloc[idx + 2].market_close\n\n # minute before open\n if self.GAPS_BETWEEN_SESSIONS:\n self._verify_minute(\n self.calendar, minute_before_open, open_minute,\n previous_open, close_minute, previous_close\n )\n\n # open minute\n self._verify_minute(\n self.calendar, open_minute, next_open, previous_open,\n close_minute, previous_close\n )\n\n # second minute of session\n self._verify_minute(\n self.calendar, open_minute + self.one_minute, next_open,\n open_minute, close_minute, previous_close\n )\n\n # minute before the close\n self._verify_minute(\n self.calendar, close_minute - self.one_minute, next_open,\n open_minute, close_minute, previous_close\n )\n\n # the close\n self._verify_minute(\n self.calendar, close_minute, next_open, open_minute,\n next_close, previous_close\n )\n\n # minute after the close\n if self.GAPS_BETWEEN_SESSIONS:\n self._verify_minute(\n self.calendar, close_minute + self.one_minute, next_open,\n open_minute, next_close, close_minute\n )\n\n def test_next_prev_minute(self):\n all_minutes = self.calendar.all_minutes\n\n # test 20,000 minutes because it takes too long to do the rest.\n for idx, minute in enumerate(all_minutes[1:20000]):\n self.assertEqual(\n all_minutes[idx + 2],\n self.calendar.next_minute(minute)\n )\n\n self.assertEqual(\n all_minutes[idx],\n self.calendar.previous_minute(minute)\n )\n\n # test a couple of non-market minutes\n if self.GAPS_BETWEEN_SESSIONS:\n for open_minute in self.answers.market_open[1:]:\n hour_before_open = open_minute - self.one_hour\n self.assertEqual(\n open_minute,\n self.calendar.next_minute(hour_before_open)\n )\n\n for close_minute in self.answers.market_close[1:]:\n hour_after_close = close_minute + self.one_hour\n self.assertEqual(\n close_minute,\n self.calendar.previous_minute(hour_after_close)\n )\n\n def test_minute_to_session_label(self):\n for idx, info in enumerate(self.answers[1:-2].iterrows()):\n session_label = info[1].name\n open_minute = info[1].iloc[0]\n close_minute = info[1].iloc[1]\n hour_into_session = open_minute + self.one_hour\n\n minute_before_session = open_minute - self.one_minute\n minute_after_session = close_minute + self.one_minute\n\n next_session_label = self.answers.iloc[idx + 2].name\n previous_session_label = self.answers.iloc[idx].name\n\n # verify that minutes inside a session resolve correctly\n minutes_that_resolve_to_this_session = [\n self.calendar.minute_to_session_label(open_minute),\n self.calendar.minute_to_session_label(open_minute,\n direction=\"next\"),\n self.calendar.minute_to_session_label(open_minute,\n direction=\"previous\"),\n self.calendar.minute_to_session_label(open_minute,\n direction=\"none\"),\n self.calendar.minute_to_session_label(hour_into_session),\n self.calendar.minute_to_session_label(hour_into_session,\n direction=\"next\"),\n self.calendar.minute_to_session_label(hour_into_session,\n direction=\"previous\"),\n self.calendar.minute_to_session_label(hour_into_session,\n direction=\"none\"),\n self.calendar.minute_to_session_label(close_minute),\n self.calendar.minute_to_session_label(close_minute,\n direction=\"next\"),\n self.calendar.minute_to_session_label(close_minute,\n direction=\"previous\"),\n self.calendar.minute_to_session_label(close_minute,\n direction=\"none\"),\n session_label\n ]\n\n if self.GAPS_BETWEEN_SESSIONS:\n minutes_that_resolve_to_this_session.append(\n self.calendar.minute_to_session_label(\n minute_before_session\n )\n )\n minutes_that_resolve_to_this_session.append(\n self.calendar.minute_to_session_label(\n minute_before_session,\n direction=\"next\"\n )\n )\n\n minutes_that_resolve_to_this_session.append(\n self.calendar.minute_to_session_label(\n minute_after_session,\n direction=\"previous\"\n )\n )\n\n self.assertTrue(all(x == minutes_that_resolve_to_this_session[0]\n for x in minutes_that_resolve_to_this_session))\n\n minutes_that_resolve_to_next_session = [\n self.calendar.minute_to_session_label(minute_after_session),\n self.calendar.minute_to_session_label(minute_after_session,\n direction=\"next\"),\n next_session_label\n ]\n\n self.assertTrue(all(x == minutes_that_resolve_to_next_session[0]\n for x in minutes_that_resolve_to_next_session))\n\n self.assertEqual(\n self.calendar.minute_to_session_label(minute_before_session,\n direction=\"previous\"),\n previous_session_label\n )\n\n # make sure that exceptions are raised at the right time\n with self.assertRaises(ValueError):\n self.calendar.minute_to_session_label(open_minute, \"asdf\")\n\n if self.GAPS_BETWEEN_SESSIONS:\n with self.assertRaises(ValueError):\n self.calendar.minute_to_session_label(\n minute_before_session,\n direction=\"none\"\n )\n\n @parameterized.expand([\n (1, 0),\n (2, 0),\n (2, 1),\n ])\n def test_minute_index_to_session_labels(self, interval, offset):\n minutes = self.calendar.minutes_for_sessions_in_range('2011-01-04',\n '2011-04-04')\n minutes = minutes[range(offset, len(minutes), interval)]\n\n np.testing.assert_array_equal(\n np.array(minutes.map(self.calendar.minute_to_session_label),\n dtype='datetime64[ns]'),\n self.calendar.minute_index_to_session_labels(minutes)\n )\n\n def test_next_prev_session(self):\n session_labels = self.answers.index[1:-2]\n max_idx = len(session_labels) - 1\n\n # the very first session\n first_session_label = self.answers.index[0]\n with self.assertRaises(ValueError):\n self.calendar.previous_session_label(first_session_label)\n\n # all the sessions in the middle\n for idx, session_label in enumerate(session_labels):\n if idx < max_idx:\n self.assertEqual(\n self.calendar.next_session_label(session_label),\n session_labels[idx + 1]\n )\n\n if idx > 0:\n self.assertEqual(\n self.calendar.previous_session_label(session_label),\n session_labels[idx - 1]\n )\n\n # the very last session\n last_session_label = self.answers.index[-1]\n with self.assertRaises(ValueError):\n self.calendar.next_session_label(last_session_label)\n\n @staticmethod\n def _find_full_session(calendar):\n for session_label in calendar.schedule.index:\n if session_label not in calendar.early_closes:\n return session_label\n\n return None\n\n def test_minutes_for_period(self):\n # full session\n # find a session that isn't an early close. start from the first\n # session, should be quick.\n full_session_label = self._find_full_session(self.calendar)\n if full_session_label is None:\n raise ValueError(\"Cannot find a full session to test!\")\n\n minutes = self.calendar.minutes_for_session(full_session_label)\n _open, _close = self.calendar.open_and_close_for_session(\n full_session_label\n )\n\n np.testing.assert_array_equal(\n minutes,\n pd.date_range(start=_open, end=_close, freq=\"min\")\n )\n\n # early close period\n early_close_session_label = self.calendar.early_closes[0]\n minutes_for_early_close = \\\n self.calendar.minutes_for_session(early_close_session_label)\n _open, _close = self.calendar.open_and_close_for_session(\n early_close_session_label\n )\n\n np.testing.assert_array_equal(\n minutes_for_early_close,\n pd.date_range(start=_open, end=_close, freq=\"min\")\n )\n\n def test_sessions_in_range(self):\n # pick two sessions\n session_count = len(self.calendar.schedule.index)\n\n first_idx = session_count / 3\n second_idx = 2 * first_idx\n\n first_session_label = self.calendar.schedule.index[first_idx]\n second_session_label = self.calendar.schedule.index[second_idx]\n\n answer_key = \\\n self.calendar.schedule.index[first_idx:second_idx + 1]\n\n np.testing.assert_array_equal(\n answer_key,\n self.calendar.sessions_in_range(first_session_label,\n second_session_label)\n )\n\n def _get_session_block(self):\n # find and return a (full session, early close session, full session)\n # block\n\n shortened_session = self.calendar.early_closes[0]\n shortened_session_idx = \\\n self.calendar.schedule.index.get_loc(shortened_session)\n\n session_before = self.calendar.schedule.index[\n shortened_session_idx - 1\n ]\n session_after = self.calendar.schedule.index[shortened_session_idx + 1]\n\n return [session_before, shortened_session, session_after]\n\n def test_minutes_in_range(self):\n sessions = self._get_session_block()\n\n first_open, first_close = self.calendar.open_and_close_for_session(\n sessions[0]\n )\n minute_before_first_open = first_open - self.one_minute\n\n middle_open, middle_close = \\\n self.calendar.open_and_close_for_session(sessions[1])\n\n last_open, last_close = self.calendar.open_and_close_for_session(\n sessions[-1]\n )\n minute_after_last_close = last_close + self.one_minute\n\n # get all the minutes between first_open and last_close\n minutes1 = self.calendar.minutes_in_range(\n first_open,\n last_close\n )\n minutes2 = self.calendar.minutes_in_range(\n minute_before_first_open,\n minute_after_last_close\n )\n\n if self.GAPS_BETWEEN_SESSIONS:\n np.testing.assert_array_equal(minutes1, minutes2)\n else:\n # if no gaps, then minutes2 should have 2 extra minutes\n np.testing.assert_array_equal(minutes1, minutes2[1:-1])\n\n # manually construct the minutes\n all_minutes = np.concatenate([\n pd.date_range(\n start=first_open,\n end=first_close,\n freq=\"min\"\n ),\n pd.date_range(\n start=middle_open,\n end=middle_close,\n freq=\"min\"\n ),\n pd.date_range(\n start=last_open,\n end=last_close,\n freq=\"min\"\n )\n ])\n\n np.testing.assert_array_equal(all_minutes, minutes1)\n\n def test_minutes_for_sessions_in_range(self):\n sessions = self._get_session_block()\n\n minutes = self.calendar.minutes_for_sessions_in_range(\n sessions[0],\n sessions[-1]\n )\n\n # do it manually\n session0_minutes = self.calendar.minutes_for_session(sessions[0])\n session1_minutes = self.calendar.minutes_for_session(sessions[1])\n session2_minutes = self.calendar.minutes_for_session(sessions[2])\n\n concatenated_minutes = np.concatenate([\n session0_minutes.values,\n session1_minutes.values,\n session2_minutes.values\n ])\n\n np.testing.assert_array_equal(\n concatenated_minutes,\n minutes.values\n )\n\n def test_sessions_window(self):\n sessions = self._get_session_block()\n\n np.testing.assert_array_equal(\n self.calendar.sessions_window(sessions[0], len(sessions) - 1),\n self.calendar.sessions_in_range(sessions[0], sessions[-1])\n )\n\n np.testing.assert_array_equal(\n self.calendar.sessions_window(\n sessions[-1],\n -1 * (len(sessions) - 1)),\n self.calendar.sessions_in_range(sessions[0], sessions[-1])\n )\n\n def test_session_distance(self):\n sessions = self._get_session_block()\n\n self.assertEqual(2, self.calendar.session_distance(sessions[0],\n sessions[-1]))\n\n def test_open_and_close_for_session(self):\n for index, row in self.answers.iterrows():\n session_label = row.name\n open_answer = row.iloc[0]\n close_answer = row.iloc[1]\n\n found_open, found_close = \\\n self.calendar.open_and_close_for_session(session_label)\n\n self.assertEqual(open_answer, found_open)\n self.assertEqual(close_answer, found_close)\n\n def test_daylight_savings(self):\n # 2004 daylight savings switches:\n # Sunday 2004-04-04 and Sunday 2004-10-31\n\n # make sure there's no weirdness around calculating the next day's\n # session's open time.\n\n for date in [\"2004-04-05\", \"2004-11-01\"]:\n next_day = pd.Timestamp(date, tz='UTC')\n open_date = next_day + Timedelta(days=self.calendar.open_offset)\n\n the_open = self.calendar.schedule.loc[next_day].market_open\n\n localized_open = the_open.tz_localize(\"UTC\").tz_convert(\n self.calendar.tz\n )\n\n self.assertEqual(\n (open_date.year, open_date.month, open_date.day),\n (localized_open.year, localized_open.month, localized_open.day)\n )\n\n self.assertEqual(\n self.calendar.open_time.hour,\n localized_open.hour\n )\n\n self.assertEqual(\n self.calendar.open_time.minute,\n localized_open.minute\n )\n"
] | [
[
"pandas.tslib.Timedelta",
"pandas.Timedelta",
"numpy.testing.assert_array_equal",
"numpy.concatenate",
"pandas.util.testing.assert_index_equal",
"pandas.date_range",
"pandas.Timestamp"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
JackChuBoy/ML-Exercises | [
"39c48c07bb3831d8625bbe37da828e032dd62327",
"39c48c07bb3831d8625bbe37da828e032dd62327"
] | [
"Deep Learning/diff_gradient.py",
"Deep Learning/gradient_demo.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 4 21:11:42 2021\n\n@author: user\n\"\"\"\nimport numpy as np\nfrom matplotlib import pyplot as plt\n# from mpl_toolkits.mplot3d import Axes3D\n\n# # 函數微分 中央分差\ndef num_diff(f, x):\n h = 1e-4 # 0.0001\n return (f(x + h) - f(x - h)) / (2 * h)\n\n# 函數1\ndef function_1(x):\n return x ** 2 + x\n\n# 函數2 --> 偏微分\ndef function_2(x):\n if x.ndim == 1:\n return np.sum(x**2)\n else:\n return np.sum(x**2, axis=1)\n \ndef function_z(x0, x1):\n return x0**2 + x1**2\n \ndef _numerical_gradient_no_batch(f, x):\n h = 1e-4 # 0.0001\n grad = np.zeros_like(x)\n \n for idx in range(x.size):\n tmp_val = x[idx]\n x[idx] = float(tmp_val) + h\n fxh1 = f(x) # f(x+h)\n \n x[idx] = tmp_val - h \n fxh2 = f(x) # f(x-h)\n grad[idx] = (fxh1 - fxh2) / (2*h)\n \n x[idx] = tmp_val # 値を元に戻す\n \n return grad\n\n\ndef numerical_gradient(f, X):\n if X.ndim == 1:\n return _numerical_gradient_no_batch(f, X)\n else:\n grad = np.zeros_like(X)\n \n for idx, x in enumerate(X):\n grad[idx] = _numerical_gradient_no_batch(f, x)\n \n return grad\n\n\n# 微分切線方程式: y = f(a) + d(x − a) = f(a) - d * a + d * x\n# 這部分回傳一個function讓我們可以得到函數再把x帶入.\ndef tangent_fun(f, a):\n d = num_diff(f, a)\n #print(d)\n y = f(a) - d * a\n return lambda x: d * x + y\n\ndef draw_tangent_line():\n x = np.arange(0.0, 20, 00.1)\n y = function_1(x)\n\n tan_fun = tangent_fun(function_1, 5)\n y2 = tan_fun(x)\n\n plt.plot(x, y2, label = \"tangent line\")\n plt.plot(x, y, label = \"line\")\n plt.xlabel(\"$x$\")\n plt.ylabel(\"$f (x)$\")\n plt.legend()\n plt.show()\n\ndef draw_gradient():\n x0 = np.arange(-2.0, 2.5, 0.25)\n x1 = np.arange(-2.0, 2.5, 0.25)\n \n #將x和y擴展當相同大小.再轉一維\n X, Y = np.meshgrid(x0, x1)\n \n X = X.flatten()\n Y = Y.flatten()\n \n #求梯度\n grad = numerical_gradient(function_2, np.array([X, Y]).T).T\n \n print('-------- X ----------------')\n print(X)\n print('-------- Y ----------------')\n print(Y)\n print('-------- Gradient ----------------')\n print(grad)\n \n #畫出quiver方向圖, xlim指定顯示大小, label標籤顯示, grid顯示網格\n plt.quiver(X, Y, -grad[0], -grad[1], angles=\"xy\", color=\"#666666\")\n plt.xlim([-2, 2])\n plt.ylim([-2, 2])\n plt.xlabel('x0')\n plt.ylabel('x1')\n plt.grid()\n plt.draw()\n plt.show()\n \ndef draw_mutivar_3d():\n x0 = np.arange(-2.0, 2.5, 0.25)\n x1 = np.arange(-2.0, 2.5, 0.25)\n \n X, Y = np.meshgrid(x0, x1)\n \n X = X.flatten()\n Y = Y.flatten()\n Z = function_2(np.array([X, Y]).T).T\n \n # plt.figure(figsize = (9.6, 7.2))\n ax = plt.axes(projection='3d')\n surf = ax.plot_trisurf(X, Y, Z, cmap='RdGy')\n \n plt.colorbar(surf, shrink=0.5, aspect=5)\n ax.set_xlabel('$x0$')\n ax.set_ylabel('$x1$')\n ax.set_zlabel('$y = x_0^2 * x_1^2$', )\n # ax.set_xlim(-2.5, 2.7)\n # ax.set_ylim(-2.5, 2.7)\n \n plt.show()\n \ndef draw_mutivar_3ds():\n x0 = np.arange(-2.0, 2.5, 0.1)\n x1 = np.arange(-2.0, 2.5, 0.1)\n \n X, Y = np.meshgrid(x0, x1)\n Z = function_z(X, Y)\n \n ax = plt.axes(projection='3d')\n surf = ax.plot_surface(X, Y, Z, cmap='RdGy')\n \n plt.colorbar(surf, shrink=0.5, aspect=5)\n ax.set_xlabel('$x0$')\n ax.set_ylabel('$x1$')\n ax.set_zlabel('$y = x_0^2 * x_1^2$', )\n \n plt.show()\n\n\nif __name__ == '__main__':\n \n plt.rcParams['figure.figsize'] = (9.6, 7.2)\n # draw_tangent_line()\n # draw_gradient()\n draw_mutivar_3d()\n draw_mutivar_3ds()\n \n \n ",
"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib import patches\nfrom diff_gradient import numerical_gradient\n\ndef gradient_descent(f, init_x, lr=0.01, step_num=100):\n x = init_x\n x_history = []\n\n for i in range(step_num):\n x_history.append( x.copy() )\n\n grad = numerical_gradient(f, x)\n x -= lr * grad\n\n return x, np.array(x_history)\n\n\ndef function_2(x):\n return x[0]**2 + x[1]**2\n\nif __name__ == '__main__':\n \n init_x = np.array([-3.0, 4.0]) \n\n lr = 0.1\n step_num = 20\n x, x_history = gradient_descent(function_2, init_x, lr=lr, step_num=step_num)\n \n figure, axes = plt.subplots()\n plt.axvline(x=0, ls='--', c='blue')\n plt.axhline(y=0, ls='--', c='blue')\n \n for r in range(6):\n draw_c = plt.Circle(xy=(0,0), radius=r*0.8, ls='dashed', fill=False)\n axes.add_patch(draw_c)\n \n \n plt.plot(x_history[:,0], x_history[:,1], 'o')\n \n plt.xlim(-3.5, 3.5)\n plt.ylim(-4.5, 4.5)\n plt.xlabel(\"X0\")\n plt.ylabel(\"X1\")\n plt.show()\n\n"
] | [
[
"matplotlib.pyplot.legend",
"numpy.meshgrid",
"numpy.arange",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.axes",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.colorbar",
"numpy.zeros_like",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.quiver",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.sum",
"matplotlib.pyplot.ylabel"
],
[
"matplotlib.pyplot.axhline",
"matplotlib.pyplot.axvline",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.Circle",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
eryuehouniao/mmdetection | [
"e80df144aeb2000116f1a8deb98fa4916b1fe5c3"
] | [
"tools/get_dense.py"
] | [
"import json\nimport pandas\nimport numpy as np\nimport os\nfrom PIL import Image\n\n\n\ndef get_dense(defces):\n\n # get the dense iamge id-------------------------------------------------------------------------------------------\n num_img = 2795\n per_num_defces = np.zeros(num_img)\n anns = defces[\"annotations\"]\n for ann in anns:\n img_id = ann[\"image_id\"]\n per_num_defces[img_id]+=1\n\n dense_imgs = list(np.where(per_num_defces>100)) # index of dense image\n print(dense_imgs)\n\n # get dense images name------------------------------------------------------------------------/mmdetection/configs/cascade_rcnn_r101_fpn_1x.py\n dense_imgs_name = []\n images = defces[\"images\"]\n for dense_img in dense_imgs[0]:\n image = images[dense_img]\n dense_imgs_name.append(image[\"file_name\"])\n print(dense_imgs_name)\n\n return dense_imgs, dense_imgs\n\ndef remake_sparse_json(defces,dense_imgs):\n # remake and save sparse json file--------------------------------------------------------------------\"/mmdetection/configs/hrnet/cascade_rcnn_hrnetv2p_w32_20e.py\"\n anns_sparse = []\n json_sparse_path = \"/mmdetection/data1/gzx/train_round2/train_coco_sparse.json\"\n anns = defces[\"annotations\"]\n for ann in anns:\n img_id = ann[\"image_id\"]\n if img_id not in dense_imgs[0]:\n anns_sparse.append(ann)\n defces[\"annotations\"] = anns_sparse\n with open(json_sparse_path, 'w') as fp:\n json.dump(defces, fp)\n\ndef remake_dense_json(defces,dense_imgs):\n # remake and save dense json file,(comment the front module before use this one)----------------------------------------------------------------------\n anns_dense = []\n json_dense_path = \"/mmdetection/data1/gzx/train_round2/train_coco_dense.json\"\n anns = defces[\"annotations\"]\n for ann in anns:\n img_id = ann[\"image_id\"]\n if img_id in dense_imgs[0]:\n anns_dense.append(ann)\n defces[\"annotations\"] = anns_dense\n with open(json_dense_path, 'w') as fp:\n json.dump(defces, fp)\n\ndef copy_remove_dense_image():\n #copy and remove dense images------------------------------------------------------------------------------------------------------------------------------\n # root_path = \"/mmdetection/data1/gzx/train_round2/train_viz/\"\n # copy_path = \"/mmdetection/data1/gzx/train_round2/dense_image/\"\n # for dense_img_name in dense_imgs_name:\n # img_path = os.path.join(root_path, dense_img_name)\n # img = Image.open(img_path)\n # img.save(copy_path+dense_img_name)\n # os.remove(img_path)\n pass\n\n\ndef analysis_result():\n # aim to compare the defect info between inference and ground truth-----------------------------------------------------------------------------------------\n inference_json_path = '/mmdetection/result.json'\n ground_json_path = \"/data1/gzx/train_round2/val_coco_final.json\"\n with open(inference_json_path, 'r') as fp:\n inference_json = json.load(fp)\n with open(ground_json_path,'r') as fp:\n ground_json = json.load(fp)\n\n inference_info = np.zeros(16)\n ground_info = np.zeros(16)\n for defect in inference_json:\n cla = defect[\"category\"]\n inference_info[cla] = inference_info[cla]+1\n for defect in ground_json:\n cla = defect[\"category\"]\n ground_info[cla] += 1\n return inference_info, ground_info\n\ndef delete_1():\n ground_json_path = \"/data1/gzx/train_round2/train_coco_sparse.json\"\n delete_1_json_path = \"/data1/gzx/train_round2/train_coco_sparse_delete_1.json\"\n with open(ground_json_path,'r') as fp:\n ground_json = json.load(fp)\n annos = ground_json[\"annotations\"]\n annos_new = []\n for anno in annos:\n if anno[\"category_id\"]!=1.0:\n annos_new.append(anno)\n ground_json[\"annotatons\"] = annos_new\n with open(delete_1_json_path, 'w') as fp:\n json.dump(ground_json, fp)\n\ndef save_1():\n ground_json_path = \"/data1/gzx/train_round2/train_coco_sparse.json\"\n save_1_json_path = \"/data1/gzx/train_round2/train_coco_sparse_save_1.json\"\n with open(ground_json_path, 'r') as fp:\n ground_json = json.load(fp)\n annos = ground_json[\"annotations\"]\n annos_new = []\n for anno in annos:\n if anno[\"category_id\"] == 1.0:\n annos_new.append(anno)\n ground_json[\"annotatons\"] = annos_new\n with open(save_1_json_path, 'w') as fp:\n json.dump(ground_json, fp)\n\n\nif __name__=='__main__':\n # json_path = \"/mmdetection/data1/gzx/train_round2/train_coco.json\"\n # with open(json_path, 'r') as fp:\n # defces = json.load(fp)\n\n # get the inference and ground info--------------------------------------------------------------------------------------------------------\n # inference_info, ground_info = analysis_result()\n # print(inference_info, '\\n', ground_info)\n\n # delet 1 class-----------------------------------------------------------------------------------------\n delete_1()\n save_1()"
] | [
[
"numpy.zeros",
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
vishwa-pr/python-sentiment-analysis | [
"eb69e0d28b27a809bbd273341bb0de2f532c5798"
] | [
"sentiment_analyzer.py"
] | [
"import pandas as pd\r\nimport json\r\nimport nltk\r\nnltk.download('vader_lexicon')\r\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\r\nfrom textblob import TextBlob\r\nimport flair\r\n\r\n\r\n#flair model will be downloaded first time . After download change to downloaded path\r\nflair_sentiment = flair.models.TextClassifier.load('en-sentiment')\r\n\r\n\r\n#text list\r\ntext_list = [\"It was a great movie.I enjoyed it a lot\",\r\n \"The movie was horrible.0 stars from me\",\r\n \"It's a good day to watch a movie\"]\r\n\r\n\r\nnltk_list=[]\r\ntb_list=[]\r\nflair_list=[]\r\nround_off_val =4\r\n\r\nfor text in text_list:\r\n\r\n #nltk sentiment\r\n sid = SentimentIntensityAnalyzer()\r\n nltk_dict = sid.polarity_scores(text)\r\n print(sid.polarity_scores(text))\r\n del nltk_dict['compound']\r\n max_senti_score = max(nltk_dict, key=nltk_dict.get)\r\n if max_senti_score == \"pos\":\r\n nltk_list.append(\"positive (\"+str(round(nltk_dict[max_senti_score],round_off_val))+\")\")\r\n elif max_senti_score == \"neu\":\r\n nltk_list.append(\"neutral (\"+str(round(nltk_dict[max_senti_score],round_off_val))+\")\")\r\n elif max_senti_score == \"neg\":\r\n nltk_list.append(\"negative (\"+str(round(nltk_dict[max_senti_score],round_off_val))+\")\")\r\n\r\n\r\n\r\n #text blob sentiment\r\n tb_polarity = TextBlob(text).sentiment[0]\r\n\r\n if tb_polarity == 0:\r\n tb_list.append('neutral '+\"(\"+str(round(tb_polarity,round_off_val))+\")\")\r\n elif tb_polarity < 0:\r\n tb_list.append('negative '+\"(\"+str(round(tb_polarity,round_off_val))+\")\")\r\n elif tb_polarity > 0:\r\n tb_list.append('positive '+\"(\"+str(round(tb_polarity,round_off_val))+\")\")\r\n\r\n #flair sentiment\r\n s = flair.data.Sentence(text)\r\n flair_sentiment.predict(s)\r\n total_sentiment = s.labels\r\n flair_list.append(str(total_sentiment[0]).lower())\r\n\r\n#save to dataframe\r\ndf = pd.DataFrame({'Text': text_list, 'nltk': nltk_list,'textblob': tb_list,'flair': flair_list})\r\nprint(df)\r\ndf.to_csv('multi-sentiment.csv', index=False, encoding='utf-8')\r\n\r\n\r\n"
] | [
[
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
AlexsLemonade/compendium-processing | [
"fb0316339475442c2219a7f5a7ee781bdbb48425"
] | [
"select_imputation_method/scripts/run_fancyimpute.py"
] | [
"import argparse\nimport pandas as pd\nimport numpy as np\nimport random\nfrom fancyimpute import KNN, BiScaler, SoftImpute, IterativeSVD\nfrom sklearn import preprocessing\n\n# parse arguments\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-f\", \"--file\", help = \"Masked .pcl file\")\nargs = parser.parse_args()\ninput_file = args.file \n\n# output file \"base\"\noutfile = input_file.replace(\".pcl\", \"\").replace(\"data/masked\", \"imputed\")\n\n# set random seed 2 ways cause I'm not sure what's appropriate, my suspicion\n# is numpy\nrandom.seed(123)\nnp.random.seed(123)\n\n# read in data and transpose\ndata = pd.read_csv(input_file, sep='\\t', header=0, index_col=0, \n\t\t\t\t error_bad_lines=False)\nnew_data = data.copy()\ntransposed = new_data.T\n\n# we'll need a matrix specifically for the biscaler transform, for SoftImpute\nprint(\"SoftImpute...\")\ntransposed_mat = transposed.as_matrix()\nbiscaler = BiScaler()\n\n# perform the scaling appropriate for this imputation strategy\ntransposed_normalized = biscaler.fit_transform(transposed_mat)\n\n# the imputation itself\nimputed_softimpute = SoftImpute().fit_transform(transposed_normalized)\n\n# we don't want the transformed values and we want samples to be columns\ninverse_softimpute = biscaler.inverse_transform(imputed_softimpute)\nuntransposed_softimpute = inverse_softimpute.transpose()\n\n# prepare to write to file, back to DataFrame, return indices\nsoftimpute_df = pd.DataFrame(untransposed_softimpute)\nsoftimpute_df.index = data.index\nsoftimpute_df.columns = data.columns.values\n\n# write to a tab separated values file, but we'll use the .pcl file extension\nsoftimpute_outfile = outfile + \"_softimpute.pcl\"\nsoftimpute_df.to_csv(softimpute_outfile, sep='\\t')\n\nprint(\"KNN...\")\n# KNN assumes that standard scaling has been performed\nscaler = preprocessing.StandardScaler(copy=True)\nscaler.fit(transposed)\nscaled = pd.DataFrame(scaler.transform(transposed),\n index=transposed.index,\n columns=transposed.columns\n)\n\nprint(\"\\tROW...\")\n# perform the imputation, setting k=10 as is standard for gene expression data\nimputed_knn_row = KNN(k=10).fit_transform(scaled)\n\n# inverse transformation -- we don't want the standard scores\ninverse_knn_row = scaler.inverse_transform(imputed_knn_row)\n\n# columns are samples\nuntransposed_knn_row = inverse_knn_row.transpose()\n\n# write to file\nknn_row_df = pd.DataFrame(untransposed_knn_row)\nknn_row_df.index = data.index\nknn_row_df.columns = data.columns.values\n# not to be confused with the Sleipnir KNNImputer output\nknn_row_outfile = outfile + \"_KNN_fancyimpute_row.pcl\"\nknn_row_df.to_csv(knn_row_outfile, sep='\\t')\n\nprint(\"\\tCOLUMN...\")\n# perform the imputation, setting k=10 as is standard for gene expression data\nimputed_knn_col = KNN(k=10, orientation=\"columns\").fit_transform(scaled)\n\n# inverse transformation -- we don't want the standard scores\ninverse_knn_col = scaler.inverse_transform(imputed_knn_col)\n\n# columns are samples\nuntransposed_knn_col = inverse_knn_col.transpose()\n\n# write to file\nknn_col_df = pd.DataFrame(untransposed_knn_col)\nknn_col_df.index = data.index\nknn_col_df.columns = data.columns.values\n# not to be confused with the Sleipnir KNNImputer output\nknn_col_outfile = outfile + \"_KNN_fancyimpute_column.pcl\"\nknn_col_df.to_csv(knn_col_outfile, sep='\\t')\n\nprint(\"IterativeSVD...\")\n# no transformation\nimputed_svd = IterativeSVD(rank=10).fit_transform(transposed)\n\n# columns are samples\nuntransposed_svd = imputed_svd.transpose()\n\n# write to file\nsvd_df = pd.DataFrame(untransposed_svd)\nsvd_df.index = data.index\nsvd_df.columns = data.columns.values\n# not to be confused with the Sleipnir KNNImputer output\nsvd_outfile = outfile + \"_IterativeSVD.pcl\"\nsvd_df.to_csv(svd_outfile, sep='\\t')\n"
] | [
[
"sklearn.preprocessing.StandardScaler",
"pandas.read_csv",
"numpy.random.seed",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
swing-research/xtdoa | [
"6b2abf9c244207c8e05232e883288f80038ff2b2"
] | [
"python/plot_real_data.py"
] | [
"import numpy as np\nfrom scipy.io import loadmat\nimport os\nfrom pathlib import Path\n# from mpl_toolkits.mplot3d import Axes3D \nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nimport pandas as pd\n\n\n# plotting parameters\nsns.set(font_scale=1.1)\nsns.set_context(\"talk\")\nsns.set_palette(['#701f57', '#ad1759', '#e13342', '#f37651'])\ntransparent = False\nmarkers = ['o','^','s']\nplot_types = ['box','point']\nestimator = np.median\nest ='median'\n\n# Number of microphones fixed, vary number of loudspeakers\n\npath = Path(__file__).parent / os.path.join('..','matlab','data') # path to the saved results from matlab\noutpath = os.path.join(Path(__file__).parent,'figures')\nif not os.path.exists(outpath):\n os.makedirs(outpath)\n\nKs = range(6,12) # number of loudspeakers\nM = 12 # number of microphones\nruns = 200\n\nthresh = 10**-3 # lower bound for error\n\nalgs = ['SDR + LM', 'Wang']\nsuffs = ['real_data_clean_sdr_lm', 'wang_real_data_clean']\n\nres_data = pd.DataFrame() # will load matlab results into DataFrame\nall_err = np.zeros((runs,len(Ks),len(suffs)))\nfor mi,K in enumerate(Ks):\n\n N = M + K # number of points\n print(mi,M,K)\n \n for suffi,suff in enumerate(suffs):\n filename_mat = os.path.join(suff,'matlab_%s_M%s_K%s.mat'%(suff,M,K))\n mat = loadmat(os.path.join(path,filename_mat))\n err_aft = np.real(mat['err_lm'])\n \n all_err[:,mi,suffi] = err_aft[:,0]\n print('minimum',algs[suffi],M,K, np.min(all_err[:,mi,suffi]))\n\n res = pd.DataFrame(err_aft[:,0])\n res['M'] = M\n res['K'] = K\n res.rename(columns={0: 'err'}, inplace=True)\n res = res.assign(Algorithm=algs[suffi])\n \n res_data = pd.concat([res_data,res],axis=0)\n\n# res_data.clip(lower=thresh)\nfor plot_type in plot_types:\n args ={}\n if plot_type=='point':\n args['markers'] = markers\n args['s'] = 0.75\n\n ax = sns.catplot(data=res_data, x='K', y='err', hue='Algorithm', linewidth=1, dodge=True, kind=plot_type, legend_out=True, legend=False, aspect=1.3,estimator=estimator,**args)\n ax.set_ylabels(\"Localization Error [m]\")\n plt.legend(loc='upper center', ncol=2, bbox_to_anchor=(0.5, 1.1))\n plt.tight_layout()\n plt.savefig(os.path.join(outpath,\"loc_error_compare_%s_%s_%splot.png\"%(est,suff,plot_type)), transparent=transparent)\n"
] | [
[
"matplotlib.pyplot.legend",
"pandas.concat",
"matplotlib.pyplot.tight_layout",
"numpy.min",
"pandas.DataFrame",
"numpy.real"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
harmslab/epistasis | [
"1eea1d0639db90cb08a60f583fa660bb309ffde6"
] | [
"epistasis/models/linear/elastic_net.py"
] | [
"import numpy as np\nfrom sklearn.linear_model import ElasticNet\n\nfrom ..base import BaseModel, use_sklearn\nfrom ..utils import arghandler\n\n# Suppress an annoying error from scikit-learn\nimport warnings\nwarnings.filterwarnings(action=\"ignore\", module=\"scipy\",\n message=\"^internal gelsd\")\n\n@use_sklearn(ElasticNet)\nclass EpistasisElasticNet(BaseModel):\n \"\"\"Linear, high-order epistasis model with L1 and L2 regularization.\n\n Parameters\n ----------\n order : int\n order of epistasis\n\n model_type : str (default=\"global\")\n model matrix type. See publication above for more information\n \"\"\"\n def __init__(\n self,\n order=1,\n model_type=\"global\",\n alpha=1.0,\n l1_ratio=0.5,\n precompute=False,\n max_iter=1000,\n tol=0.0001,\n warm_start=False,\n positive=False,\n random_state=None,\n selection='cyclic',\n **kwargs):\n # Set Linear Regression settings.\n self.fit_intercept = False\n self.normalize = False\n self.copy_X = True\n self.alpha = alpha\n self.l1_ratio = l1_ratio\n self.precompute = precompute\n self.max_iter = max_iter\n self.tol = tol\n self.warm_start = warm_start\n self.positive = positive\n self.random_state = random_state\n self.selection = selection\n self.l1_ratio = 1.0\n\n self.model_type = model_type\n self.order = order\n\n self.Xbuilt = {}\n\n # Store model specs.\n self.model_specs = dict(\n order=self.order,\n model_type=self.model_type,\n **kwargs)\n\n def compression_ratio(self):\n \"\"\"Compute the compression ratio for the Lasso regression\n \"\"\"\n vals = self.epistasis.values\n zeros = vals[vals == 0]\n\n numer = len(zeros)\n denom = len(vals)\n return numer/denom\n\n @property\n def num_of_params(self):\n n = 0\n n += self.epistasis.n\n return n\n\n @arghandler\n def fit(self, X=None, y=None, **kwargs):\n # If a threshold exists in the data, pre-classify genotypes\n X = np.asfortranarray(X)\n self = super(self.__class__, self).fit(X, y)\n\n # Link coefs to epistasis values.\n self.epistasis.values = np.reshape(self.coef_, (-1,))\n return self\n\n def fit_transform(self, X=None, y=None, **kwargs):\n return self.fit(X=X, y=y, **kwargs)\n\n @arghandler\n def predict(self, X=None):\n X = np.asfortranarray(X)\n return super(self.__class__, self).predict(X)\n\n @arghandler\n def predict_transform(self, X=None, y=None):\n return self.predict(X=X)\n\n @arghandler\n def score(self, X=None, y=None):\n X = np.asfortranarray(X)\n return super(self.__class__, self).score(X, y)\n\n @property\n def thetas(self):\n return self.coef_\n\n @arghandler\n def hypothesis(self, X=None, thetas=None):\n return np.dot(X, thetas)\n\n @arghandler\n def hypothesis_transform(self, X=None, y=None, thetas=None):\n return self.hypothesis(X=X, thetas=thetas)\n\n @arghandler\n def lnlike_of_data(\n self,\n X=None, y=None,\n yerr=None,\n thetas=None):\n\n # Calculate y from model.\n ymodel = self.hypothesis(X=X, thetas=thetas)\n\n # Return the likelihood of this model (with an L1 prior)\n raise Exception(\"Not implemented yet!\")\n\n @arghandler\n def lnlike_transform(\n self,\n X=None,\n y=None,\n yerr=None,\n lnprior=None,\n thetas=None):\n # Update likelihood.\n lnlike = self.lnlike_of_data(X=X, y=y, yerr=yerr, thetas=thetas)\n return lnlike + lnprior\n"
] | [
[
"numpy.reshape",
"numpy.dot",
"numpy.asfortranarray"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
doylew/datamining | [
"94c96ab6401fa8106a7e9b32ef303d41da30c9d5"
] | [
"format_py/n_gram_knn.py"
] | [
"##################################################\n######scikit_learn to do the classifications######\n##################################################\n##################################################\n##test change\n\n\nfrom sklearn import neighbors\n\n##################################################\n#####Hard coded (currently) where the datasets####\n#################are located######################\n##################################################\n\nattack_file = 'single_ngram_attack.txt'\nnormal_file = 'single_ngram_normal.txt'\ntest_file = 'single_ngram_vali.txt'\n\n##################################################\n####Create the instances for validation testing###\n##################################################\n##################################################\n\ndef makeValiInstance(fileName):\n if isinstance(fileName,str):\n my_file = open(str(fileName),\"r+\")\n words = my_file.read().split(\"\\n\")\n my_file.close()\n words.remove('')\n \n num_instances = words.count(\"new\")\n print(\"Number of Instances to Validate: \" + str(num_instances))\n \n instance = []\n data = []\n for line in words:\n if line == \"new\": \n my_data = [data] \n instance += (my_data)\n data = []\n data.extend([line.split()])\n \n for i in instance:\n for entry in i:\n if '1' in entry:\n entry.remove('1')\n if '0' in entry:\n entry.remove('0')\n \n return instance \n else:\n return -1\n\n##################################################\n#####Create the instances for training############\n##################################################\n##################################################\n\ndef makeFitInstance(fileName):\n if isinstance(fileName, str):\n my_file = open(str(fileName), \"r+\")\n words = my_file.read().split(\"\\n\")\n my_file.close()\n words.remove('')\n \n data = []\n for line in words:\n data.extend([line.split()])\n \n classi = []\n for entry in data:\n if entry[-1] == '1':\n classi.extend('a')\n entry.remove('1')\n else:\n classi.extend('n')\n entry.remove('0') \n \n instance = {}\n instance[0] = data\n instance[1] = classi\n return instance\n else:\n return -1\n \n##################################################\n#######Calculates the class of the subsequences###\n########as a ratio################################\n##################################################\n\ndef calClass(svm,data):\n normal = ['n']\n attack = ['a']\n num = 0\n total_n = 0\n total_a = 0\n if ['new'] in data:\n data.remove(['new'])\n for x in data:\n num += 1\n\t\n if svm.predict(x) == attack:\n total_a += 1\n elif svm.predict(x) == normal:\n total_n += 1\n else:\n print(\"OOPS\")\n return \n nratio = (float(total_n)/float(num))\n aratio = (float(total_a)/float(num)) \n if nratio > 0.9:\n return 'normal'\n else:\n return 'attack'\n \n##################################################\n#########Percentage validation####################\n###########of the validation data#################\n##################################################\n\ndef validateClass(svm,validation_array):\n validate = 0.0\n num = 0.0\n print(\"length: \" + str(len(validation_array)))\n for data in validation_array:\n num += 1\n if calClass(svm,data) == 'normal':\n validate += 1\n \n print(\"NUM: \" + str(int(num)) + \" CLASSIFIED AS: \" + calClass(svm,data))\n return float((validate)/(num))\n\n##################################################\n################Main##############################\n##################################################\n##################################################\n\nprint(\"Creating the training data...\")\n\n##################################################\n#############Create the attack and################\n#################normal data and combine them#####\n##################################################\n\ninstance_a = makeFitInstance(attack_file)\ninstance_n = makeFitInstance(normal_file)\n\nfit_data = instance_a[0] + instance_n[0]\nfit_classes = instance_a[1] + instance_n[1]\n\nprint(\"Training the model....\")\n\n##################################################\n##############Train the Support Vector############\n######################Machine#####################\n##################################################\n\nclf = neighbors.KNeighborsClassifier(n_neighbors=3,weights='uniform',algorithm='ball_tree')\nclf.fit(fit_data,fit_classes)\n\nprint(\"Model has been trained, building test dataset...\")\n\n##################################################\n#############Create the validation data###########\n##################################################\n##################################################\n\ninstance_v = makeValiInstance(test_file)\n\nprint(\"Validating the test dataset...\")\n\n##################################################\n############Validate the data with the trained####\n###############Support Vector Machine#############\n##################################################\n\nprint(\"Percentage validated correctly: \" + str(validateClass(clf,instance_v)))\n\n"
] | [
[
"sklearn.neighbors.KNeighborsClassifier"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AK391/kornia | [
"a2535eb7593ee2fed94d23cc720804a16f9f0e7e"
] | [
"examples/train/image_classifier/main.py"
] | [
"import hydra\nimport torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as T\nfrom hydra.core.config_store import ConfigStore\nfrom hydra.utils import to_absolute_path\n\nimport kornia as K\nfrom kornia.x import Configuration, EarlyStopping, ImageClassifierTrainer, ModelCheckpoint\n\ncs = ConfigStore.instance()\n# Registering the Config class with the name 'config'.\ncs.store(name=\"config\", node=Configuration)\n\n\[email protected](config_path=\".\", config_name=\"config.yaml\")\ndef my_app(config: Configuration) -> None:\n\n # create the model\n model = nn.Sequential(\n K.contrib.VisionTransformer(image_size=32, patch_size=16, embed_dim=128, num_heads=3),\n K.contrib.ClassificationHead(embed_size=128, num_classes=10),\n )\n\n # create the dataset\n train_dataset = torchvision.datasets.CIFAR10(\n root=to_absolute_path(config.data_path), train=True, download=True, transform=T.ToTensor())\n\n valid_dataset = torchvision.datasets.CIFAR10(\n root=to_absolute_path(config.data_path), train=False, download=True, transform=T.ToTensor())\n\n # create the dataloaders\n train_dataloader = torch.utils.data.DataLoader(\n train_dataset, batch_size=config.batch_size, shuffle=True, num_workers=8, pin_memory=True)\n\n valid_daloader = torch.utils.data.DataLoader(\n valid_dataset, batch_size=config.batch_size, shuffle=True, num_workers=8, pin_memory=True)\n\n # create the loss function\n criterion = nn.CrossEntropyLoss()\n\n # instantiate the optimizer and scheduler\n optimizer = torch.optim.AdamW(model.parameters(), lr=config.lr)\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(\n optimizer, config.num_epochs * len(train_dataloader))\n\n # define some augmentations\n augmentations = nn.Sequential(\n K.augmentation.RandomHorizontalFlip(p=0.75),\n K.augmentation.RandomVerticalFlip(p=0.75),\n K.augmentation.RandomAffine(degrees=10.),\n K.augmentation.PatchSequential(\n K.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.8),\n grid_size=(2, 2), # cifar-10 is 32x32 and vit is patch 16\n patchwise_apply=False,\n ),\n )\n\n model_checkpoint = ModelCheckpoint(\n filepath=\"./outputs\", monitor=\"top5\",\n )\n\n early_stop = EarlyStopping(monitor=\"top5\")\n\n trainer = ImageClassifierTrainer(\n model, train_dataloader, valid_daloader, criterion, optimizer, scheduler, config,\n callbacks={\n \"augmentations\": augmentations,\n \"checkpoint\": model_checkpoint, # \"terminate\": early_stop,\n }\n )\n trainer.fit()\n\nif __name__ == \"__main__\":\n my_app()\n"
] | [
[
"torch.nn.CrossEntropyLoss",
"torch.utils.data.DataLoader"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Treblegold/GraphSAINT | [
"a051742ff2de4094c97eb523d7108a4fc1d22739"
] | [
"graphsaint/tensorflow_version/model.py"
] | [
"import tensorflow as tf\r\nfrom graphsaint.globals import *\r\nfrom graphsaint.tensorflow_version.inits import *\r\nimport graphsaint.tensorflow_version.layers as layers\r\nfrom graphsaint.utils import *\r\nimport pdb\r\n\r\n\r\nclass GraphSAINT:\r\n\r\n def __init__(self, num_classes, placeholders, features,\r\n arch_gcn, train_params, adj_full_norm, **kwargs):\r\n '''\r\n Args:\r\n - placeholders: TensorFlow placeholder object.\r\n - features: Numpy array with node features.\r\n - adj: Numpy array with adjacency lists (padded with random re-samples)\r\n - degrees: Numpy array with node degrees.\r\n - sigmoid_loss: Set to true if nodes can belong to multiple classes\r\n '''\r\n if \"attention\" in arch_gcn:\r\n self.aggregator_cls = layers.AttentionAggregator\r\n self.mulhead = int(arch_gcn['attention'])\r\n else:\r\n self.aggregator_cls = layers.HighOrderAggregator\r\n self.mulhead = 1\r\n self.lr = train_params['lr']\r\n self.node_subgraph = placeholders['node_subgraph']\r\n self.num_layers = len(arch_gcn['arch'].split('-'))\r\n self.weight_decay = train_params['weight_decay']\r\n self.jk = None if 'jk' not in arch_gcn else arch_gcn['jk']\r\n self.arch_gcn = arch_gcn\r\n self.adj_subgraph = placeholders['adj_subgraph']\r\n # adj_subgraph_* are to store row-wise partitioned full graph adj tiles. \r\n self.adj_subgraph_0=placeholders['adj_subgraph_0']\r\n self.adj_subgraph_1=placeholders['adj_subgraph_1']\r\n self.adj_subgraph_2=placeholders['adj_subgraph_2']\r\n self.adj_subgraph_3=placeholders['adj_subgraph_3']\r\n self.adj_subgraph_4=placeholders['adj_subgraph_4']\r\n self.adj_subgraph_5=placeholders['adj_subgraph_5']\r\n self.adj_subgraph_6=placeholders['adj_subgraph_6']\r\n self.adj_subgraph_7=placeholders['adj_subgraph_7']\r\n self.dim0_adj_sub = placeholders['dim0_adj_sub'] #adj_full_norm.shape[0]/8\r\n self.features = tf.Variable(tf.constant(features, dtype=DTYPE), trainable=False)\r\n self.dualGPU=args_global.dualGPU\r\n _indices = np.column_stack(adj_full_norm.nonzero())\r\n _data = adj_full_norm.data\r\n _shape = adj_full_norm.shape\r\n with tf.device('/cpu:0'):\r\n self.adj_full_norm = tf.SparseTensorValue(_indices,_data,_shape)\r\n self.num_classes = num_classes\r\n self.sigmoid_loss = (arch_gcn['loss']=='sigmoid')\r\n _dims,self.order_layer,self.act_layer,self.bias_layer,self.aggr_layer = parse_layer_yml(arch_gcn,features.shape[1])\r\n # get layer index for each conv layer, useful for jk net last layer aggregation\r\n self.set_idx_conv()\r\n self.set_dims(_dims)\r\n self.placeholders = placeholders\r\n\r\n self.optimizer = tf.train.AdamOptimizer(learning_rate=self.lr)\r\n\r\n self.loss = 0\r\n self.opt_op = None\r\n self.norm_loss = placeholders['norm_loss']\r\n self.is_train = placeholders['is_train']\r\n \r\n self.build()\r\n\r\n def set_dims(self,dims):\r\n self.dims_feat = [dims[0]] + [((self.aggr_layer[l]=='concat')*self.order_layer[l]+1)*dims[l+1] for l in range(len(dims)-1)]\r\n self.dims_weight = [(self.dims_feat[l],dims[l+1]) for l in range(len(dims)-1)]\r\n\r\n def set_idx_conv(self):\r\n idx_conv = np.where(np.array(self.order_layer)>=1)[0]\r\n idx_conv = list(idx_conv[1:] - 1)\r\n idx_conv.append(len(self.order_layer)-1)\r\n _o_arr = np.array(self.order_layer)[idx_conv]\r\n if np.prod(np.ediff1d(_o_arr)) == 0:\r\n self.idx_conv = idx_conv\r\n else:\r\n self.idx_conv = list(np.where(np.array(self.order_layer)==1)[0])\r\n\r\n\r\n def build(self):\r\n \"\"\"\r\n Build the sample graph with adj info in self.sample()\r\n directly feed the sampled support vectors to tf placeholder\r\n \"\"\"\r\n self.aggregators = self.get_aggregators()\r\n _outputs_l = self.aggregate_subgraph()\r\n if self.jk == 'concat':\r\n _dim_input_jk = np.array(self.dims_feat)[np.array(self.idx_conv)+1].sum()\r\n else:\r\n _dim_input_jk = self.dims_feat[-1]\r\n self.layer_jk = layers.JumpingKnowledge(self.arch_gcn,_dim_input_jk,mode=self.jk)\r\n self.outputs = self.layer_jk([_outputs_l, self.idx_conv])\r\n # OUPTUT LAYER\r\n self.outputs = tf.nn.l2_normalize(self.outputs, 1)\r\n _dim_final = self.arch_gcn['dim'] if self.jk else self.dims_feat[-1]\r\n self.layer_pred = layers.HighOrderAggregator(_dim_final,self.num_classes,act=\"I\",\\\r\n order=0,dropout=self.placeholders[\"dropout\"],bias=\"bias\")\r\n self.node_preds = self.layer_pred((self.outputs,None,None,None,None))\r\n\r\n # BACK PROP\r\n self._loss()\r\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\r\n with tf.control_dependencies(update_ops):\r\n grads_and_vars = self.optimizer.compute_gradients(self.loss)\r\n clipped_grads_and_vars = [(tf.clip_by_value(grad, -5.0, 5.0) if grad is not None else None, var)\r\n for grad, var in grads_and_vars]\r\n self.grad, _ = clipped_grads_and_vars[0]\r\n self.opt_op = self.optimizer.apply_gradients(clipped_grads_and_vars)\r\n self.preds = self.predict()\r\n\r\n\r\n def _loss(self):\r\n # these are all the trainable var\r\n for aggregator in self.aggregators:\r\n for var in aggregator.vars.values():\r\n self.loss += self.weight_decay * tf.nn.l2_loss(var)\r\n for var in self.layer_pred.vars.values():\r\n self.loss += self.weight_decay * tf.nn.l2_loss(var)\r\n\r\n # classification loss\r\n f_loss = tf.nn.sigmoid_cross_entropy_with_logits if self.sigmoid_loss\\\r\n else tf.nn.softmax_cross_entropy_with_logits\r\n # weighted loss due to bias in appearance of vertices\r\n self.loss_terms = f_loss(logits=self.node_preds,labels=self.placeholders['labels'])\r\n if len(self.loss_terms.shape) == 1:\r\n self.loss_terms = tf.reshape(self.loss_terms,(-1,1))\r\n self._weight_loss_batch = tf.nn.embedding_lookup(self.norm_loss, self.node_subgraph)\r\n _loss_terms_weight = tf.linalg.matmul(tf.transpose(self.loss_terms),\\\r\n tf.reshape(self._weight_loss_batch,(-1,1)))\r\n self.loss += tf.reduce_sum(_loss_terms_weight)\r\n tf.summary.scalar('loss', self.loss)\r\n\r\n def predict(self):\r\n return tf.nn.sigmoid(self.node_preds) if self.sigmoid_loss \\\r\n else tf.nn.softmax(self.node_preds)\r\n\r\n\r\n def get_aggregators(self,name=None):\r\n aggregators = []\r\n for layer in range(self.num_layers):\r\n aggregator = self.aggregator_cls(self.dims_weight[layer][0], self.dims_weight[layer][1],\r\n dropout=self.placeholders['dropout'],name=name,\r\n act=self.act_layer[layer],order=self.order_layer[layer],aggr=self.aggr_layer[layer],\\\r\n is_train=self.is_train,bias=self.bias_layer[layer],\\\r\n mulhead=self.mulhead)\r\n aggregators.append(aggregator)\r\n return aggregators\r\n\r\n\r\n def aggregate_subgraph(self, batch_size=None, name=None, mode='train'):\r\n if mode == 'train':\r\n hidden = tf.nn.embedding_lookup(self.features, self.node_subgraph)\r\n adj = self.adj_subgraph\r\n else:\r\n hidden = self.features\r\n adj = self.adj_full_norm\r\n ret_l = list()\r\n _adj_partition_list = [self.adj_subgraph_0,self.adj_subgraph_1,self.adj_subgraph_2,self.adj_subgraph_3,\r\n self.adj_subgraph_4,self.adj_subgraph_5,self.adj_subgraph_6,self.adj_subgraph_7]\r\n if not args_global.dualGPU:\r\n for layer in range(self.num_layers):\r\n hidden = self.aggregators[layer]((hidden,adj,self.dims_feat[layer],_adj_partition_list,self.dim0_adj_sub))\r\n ret_l.append(hidden)\r\n else:\r\n split=int(self.num_layers/2)\r\n with tf.device('/gpu:0'):\r\n for layer in range(split):\r\n hidden = self.aggregators[layer]((hidden,adj,self.dims_feat[layer],_adj_partition_list,self.dim0_adj_sub))\r\n ret_l.append(hidden)\r\n with tf.device('/gpu:1'):\r\n for layer in range(split,self.num_layers):\r\n hidden = self.aggregators[layer]((hidden,adj,self.dims_feat[layer],_adj_partition_list,self.dim0_adj_sub))\r\n ret_l.append(hidden)\r\n return ret_l\r\n\r\n"
] | [
[
"tensorflow.nn.l2_normalize",
"tensorflow.clip_by_value",
"tensorflow.device",
"tensorflow.nn.softmax",
"tensorflow.constant",
"tensorflow.transpose",
"tensorflow.control_dependencies",
"tensorflow.nn.sigmoid",
"tensorflow.get_collection",
"tensorflow.reduce_sum",
"tensorflow.reshape",
"tensorflow.nn.l2_loss",
"tensorflow.train.AdamOptimizer",
"tensorflow.SparseTensorValue",
"tensorflow.summary.scalar",
"tensorflow.nn.embedding_lookup"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
ProxMaq/ProxVision | [
"26a336b4821582331c4f55657fea4d9928acadae"
] | [
"TRR & CDI/Cam integration for TRR & CDI .py"
] | [
"# Script implements capturing of images through webcam on click of 'Space' key\r\n# Image detection model classifies the image to 4 of the classses : \r\n #1. Handwritten text , 2.Printed Text , 3. Paper Currency or 4. Metal coin currency \r\n# Based on detection text and curreny/coins value is converted to speech(audio)\r\n\r\n#Note :Module is much faster with a GPU\r\n\r\n\r\n#required imports\r\nimport os\r\nimport cv2\r\nimport numpy as np\r\nfrom gtts import gTTS\r\nfrom PIL import Image \r\nimport easyocr\r\nfrom playsound import playsound\r\nfrom tensorflow.keras.models import load_model\r\n\r\n\r\n#Drive links for .h5 model files\r\n#1. Detection Model - https://drive.google.com/file/d/1low9yt8XfiFLuTgC_EVm9Ep44_OM6Yau/view?usp=sharing\r\n#2. Paper currency - https://drive.google.com/file/d/1f22Ay09CbgVyJ1bPOoNlh3IaCmqbq8cI/view?usp=sharing\r\n#3. Metal coins - https://drive.google.com/file/d/16ycM0mMX03-FJlZ5FS9Azylq4dsMJH-U/view?usp=sharing\r\n#4. handwritten model pending\r\n\r\n\r\n\r\n#define path variables for trained models(.h5 files)\r\nmodel_path = \"D:/ML projects/cam capture/DetectionModel_vgg_4classes.h5\"\r\nmetal_coin_model_path = \"D:/ML projects/COINS CLASSIFICATION TASK/models/metal_currency_classification.hdf5\"\r\npaper_model_path = \"D:/ML projects/Paper Currency Classification/cnn_model.h5\"\r\n\r\n\r\n#define labels list\r\nlabels = ['Handwritten_Text','Metal_Currency','Paper_Currency','Printed_Text'] #Text and Coins classification labels\r\npaper_labels = ['Ten Rupees','Hundred Rupees','Twenty Rupees','Two Hundred Rupees','Two Thousand Rupees','Fifty Rupees', 'Five Hundred Rupees','Background'] #paper currency classification labels\r\ncoin_labels = ['Head of a coin','One Rupee','Ten Rupee','Two Rupee','Five Rupee'] #metal coin classification labels\r\n\r\n\r\n\r\n#load the models to memory \r\ndetection_model = load_model(model_path) #Text and coins model\r\npaper_model = load_model(paper_model_path) #paper currency model\r\ncoin_model = load_model(metal_coin_model_path) #coin classification model\r\nreader = easyocr.Reader(['en']) #printed text recognition model\r\n\r\n\r\n#start camera to capture images\r\ndef startCamera():\r\n cam = cv2.VideoCapture(0,cv2.CAP_DSHOW)\r\n \r\n img_counter = 0\r\n \r\n while True:\r\n ret, frame = cam.read()\r\n if not ret:\r\n print(\"failed to grab frame\")\r\n break\r\n cv2.imshow(\"ProxVision CDI & TRR Detection Frame\", frame)\r\n \r\n k = cv2.waitKey(1)\r\n if k%256 == 27:\r\n # ESC pressed will quit camera\r\n print(\"Escape hit, closing...\")\r\n break\r\n elif k%256 == 32:\r\n # SPACE pressed will capture image\r\n img_name = \"Image_{}.jpg\".format(img_counter)\r\n cv2.imwrite(img_name, frame)\r\n print(\"{} written!\".format(img_name))\r\n \r\n #evaluate captured image\r\n detection(img_name)\r\n os.remove(img_name) #remove image\r\n \r\n img_counter += 1\r\n\r\n \r\n cam.release() \r\n cv2.destroyAllWindows()\r\n\r\n\r\n#choose the currecny and text models \r\ndef choose_model(text,image_path):\r\n \r\n if text == 'Printed_Text':\r\n print(\"Printed text recognition in process...\")\r\n recognize_printed_text(image_path)\r\n elif text == 'Paper_Currency':\r\n print(\"Paper currency classification in process...\")\r\n recognize_paper_currency(image_path)\r\n elif text == 'Metal_Currency':\r\n print(\"Metal Currency classification in process...\")\r\n recognize_metal_coins(image_path)\r\n \r\n #4. handwritten model pending\r\n \r\n\r\n\r\n#printed text recognition\r\ndef recognize_printed_text(image_path):\r\n \r\n #recognize text using easyocr model loaded into memory \r\n results = reader.readtext(image_path, detail = 0) \r\n print(\"reading text......\")\r\n\r\n if len(results)>0:\r\n for line in results:\r\n #print(line)\r\n text_to_speech(line)\r\n else :\r\n print(\"No text recognized\")\r\n \r\n \r\n \r\n#paper currency classification\r\ndef recognize_paper_currency(image_path):\r\n \r\n image = Image.open(image_path) #open image\r\n image = image.resize((500,250)) #reshape image input as per model requirements\r\n #image.show()\r\n image = np.asanyarray(image)\r\n \r\n #preprocess\r\n image = image.astype(\"float\") / 255.0 \r\n x = np.expand_dims(image, axis=0)\r\n \r\n #prediction \r\n prediction = paper_model.predict(x)\r\n \r\n #get predicted class\r\n text = paper_labels[np.argmax(prediction)]\r\n #print(text)\r\n text_to_speech(text)\r\n\r\n\r\n\r\n \r\n#metal coin classification \r\ndef recognize_metal_coins(image_path):\r\n \r\n image = Image.open(image_path) #open image\r\n image = image.resize((300,300)) #reshape image input as per model requirements\r\n #image.show()\r\n image = np.asanyarray(image)\r\n \r\n #preprocess\r\n image = image.astype(\"float\") / 255.0 \r\n x = np.expand_dims(image, axis=0)\r\n \r\n #prediction \r\n prediction = coin_model.predict(x)\r\n \r\n #get predicted class\r\n text = coin_labels[np.argmax(prediction)]\r\n #print(text)\r\n text_to_speech(text) \r\n \r\n \r\n#convert predicted text to audio\r\ndef text_to_speech(text): \r\n \r\n file_path = \"audio.mp3\" #file path to save audio files\r\n speech = gTTS(text=text, lang='en', slow=False) #convert text to speech \r\n speech.save(file_path) #save audio file\r\n playsound(file_path) #play sound\r\n \r\n #remove audio file\r\n if os.path.exists(file_path):\r\n os.remove(file_path)\r\n else:\r\n print(\"The file does not exist\") \r\n\r\n\r\n \r\ndef detection(image_path):\r\n \r\n img=cv2.imread(image_path) #open image\r\n img=cv2.resize(img,(224,224)) #reshape image input as per model requirements\r\n img = np.reshape(img,[1,224,224,3])\r\n\r\n #prediction \r\n prediction = detection_model.predict(img)\r\n \r\n #get predicted class\r\n text = labels[np.argmax(prediction)]\r\n print(\"Image has \",text)\r\n \r\n choose_model(text, image_path)\r\n \r\n\r\n\r\n\r\nif __name__== \"__main__\" :\r\n startCamera()"
] | [
[
"tensorflow.keras.models.load_model",
"numpy.expand_dims",
"numpy.reshape",
"numpy.asanyarray",
"numpy.argmax"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
act65/Autonav-RL-Gym | [
"30b767ced682d70457d5f19ebc19633af1ea85f8"
] | [
"src/plotter.py"
] | [
"import os\nimport json\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\npath = '/home/act65/catkin_ws/src/Autonav-RL-Gym/src/env/training_logs/'\nlogs = (os.path.join(path, fname) for fname in os.listdir(path))\n\ndef is_longer_than_N(fname, min=190, max=210):\n with open(fname, 'r') as f:\n log = f.read()\n l = len(log.split('\\n'))\n return (min < l) and (l < max)\n\nlogs = filter(is_longer_than_N, logs)\n\n# 'collision_count','ep_number','environment','goal_count', 'steps', 'reward_for_ep'\n\ndef parse_log(fname):\n data = []\n with open(fname, 'r') as f:\n for l in f:\n data.append(json.loads(l))\n return pd.DataFrame(data).values\n\nfor log in logs:\n x = parse_log(log)\n plt.plot(x[:, -1], label=x[0, 2])\nplt.legend()\nplt.show()\n\n\n\"hello world\"\n"
] | [
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
PBarde/IBoatPIE | [
"dd8038f981940b732be979b49e9b14102c3d4cca"
] | [
"code/solver/worker.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 31 10:06:46 2017\n\n@author: paul\n\"\"\"\nimport sys\nimport math\nfrom math import exp, sqrt, asin, log\nimport random as rand\nimport numpy as np\nfrom utils import Hist\nfrom master_node import MasterNode\n\nsys.path.append(\"../model/\")\nimport simulatorTLKT as SimC\nfrom simulatorTLKT import A_DICT, ACTIONS\n\n#:Exploration coefficient in the UCT formula.\nUCT_COEFF = 1 / 5 * 1 / 2 ** 0.5\n\n#:Proportion between master utility and worker utility of node utility.\nRHO = 0.3\n\n\nclass Node:\n \"\"\"\n Node of a :class:`worker.Tree`.\n\n :ivar tuple state: Only for the root Node: initial state (time, lat, lon), None for other node.\n :ivar worker.Node parent: Reference to the parent of this node.\n :ivar list origins: sequel of actions taken from to root node to this node.\n :ivar list children: Child nodes of this node.\n :ivar list actions: Remaining actions available (not expanded) from this node in random order.\n :ivar numpy.array Values: Array of :class:`utils.Hist` to save the rewards. Its size is the number of possible actions.\n :ivar int depth: Depth of the node in the Tree.\n\n \"\"\"\n\n def __init__(self, state=None, parent=None, origins=[], children=[], depth=0):\n # the list() enables to copy the state in a new list and not just copy the reference\n if state is not None:\n self.state = tuple(state) # only for the rootNode\n else:\n self.state = None\n self.parent = parent\n self.origins = list(origins)\n self.children = list(children)\n self.actions = list(SimC.ACTIONS)\n rand.shuffle(self.actions)\n self.Values = np.array([Hist() for _ in SimC.ACTIONS])\n self.depth = depth\n\n def back_up(self, reward):\n \"\"\"\n Propagates the reward through the Tree, starting from this :class:`worker.Node`, up to the root.\n\n :param float reward: The reward corresponding to the expansion of this :class:`worker.Node`.\n \"\"\"\n # the first reward of a node is put in a random action\n action = np.random.randint(len(ACTIONS))\n self.Values[action].add(reward)\n\n # then the reward is propagated to the parent node according to the action that expanded the child\n node = self\n while node.parent:\n ii = SimC.A_DICT[node.origins[-1]]\n node.parent.Values[ii].add(reward)\n node = node.parent\n\n def is_fully_expanded(self):\n \"\"\"\n\n Returns True if this :class:`worker.Node` is fully expanded (if there is not remaining actions)\n\n :return boolean: True if fully expanded, False otherwise.\n\n \"\"\"\n return len(self.actions) == 0\n\n def get_uct(self, num_parent):\n \"\"\"\n Computes the uct values of this :class:`worker.Node` (combination of exploration and exploitation)\n\n :param int num_parent: Number of times the parent of the :class:`worker.Node` has been explored.\n\n :return float: The uct value.\n\n \"\"\"\n uct_max_on_actions = 0\n num_node = 0\n for val in self.Values:\n num_node += sum(val.h)\n\n exploration = UCT_COEFF * (2 * math.log(num_parent) / num_node) ** 0.5\n\n for hist in self.Values:\n uct_value = hist.get_mean()\n\n if uct_value > uct_max_on_actions:\n uct_max_on_actions = uct_value\n\n return uct_max_on_actions + exploration\n\n\nclass Tree:\n \"\"\"\n\n A tree which represents a MCTS on one weather scenario.\n\n :ivar int id: Id of the tree, corresponding to the id scenario.\n :ivar int ite: Current number of iterations done.\n :ivar int budget: Max. number of iterations\n :ivar Simulator simulator: The simulator used to do the boat simulations (step, etc.).\n :ivar list destination: Position [lat, lon] of the wanted destination.\n :ivar float TimeMax: Time horizon of the search.\n :ivar float TimeMin: Minimum time to arrive to the destination, computed on several boats which go straight \\\n from the initial point to the destination (default policy).\n :ivar int depth: Maximum depth of the tree.\n :ivar list Nodes: List of :class:`worker.Node`, representing the tree.\n :ivar list buffer: The buffer is a list of updates to be included in the master Tree. \\\n One update is a list : [scenarioId, newNodeHash, parentHash, action, reward].\n :ivar int numScenarios: Number total of scenarios used during the MCT parallel search.\n :ivar numpy.array probability: array containing the probability of each scenario. Scenario id as a\n probability probability[id] to occur.\n \"\"\"\n\n def __init__(self, workerid, nscenario, probability=[], ite=0, budget=1000,\n simulator=None, destination=[], TimeMin=0, buffer=[]):\n self.id = workerid\n self.ite = ite\n self.budget = budget\n self.Simulator = simulator\n self.destination = destination\n self.TimeMax = self.Simulator.times[-1]\n self.TimeMin = TimeMin\n self.depth = 0\n self.Nodes = []\n self.buffer = buffer\n self.numScenarios = nscenario\n if len(probability) == 0:\n self.probability = np.array([1 / nscenario for _ in range(nscenario)])\n else:\n self.probability = probability\n\n def uct_search(self, rootState, frequency, Master_nodes):\n \"\"\"\n Launches the MCTS for the scenario.\n\n :param list rootState: State [t_index, lat, lon] of the root node.\n :param int frequency: Length of the buffer: number of iterations between each buffer integrations.\n :param dict Master_nodes: `Manager.dict() <https://docs.python.org/2/library/multiprocessing.html#sharing-state-\\\n between-processes>`_ (Dictionary of :class:`master_node.MasterNode`) which saves the nodes of every scenario.\n\n \"\"\"\n # We create the root node and add it to the tree\n rootNode = Node(state=rootState)\n self.rootNode = rootNode\n self.Nodes.append(rootNode)\n\n # While we still have computational budget we expand nodes\n while self.ite < self.budget:\n # the treePolicy gives us the reference to the newly expanded node\n leafNode = self.tree_policy(self.rootNode, Master_nodes)\n\n # The default policy gives the reward\n reward = self.default_policy(leafNode)\n\n # Propagate the reward through the tree\n leafNode.back_up(reward)\n\n # Update the buffer\n self.buffer.append(\n [self.id, hash(tuple(leafNode.origins)), hash(tuple(leafNode.origins[:-1])), leafNode.origins[-1],\n reward])\n self.ite = self.ite + 1\n\n # Print every 50 ite\n if self.ite % 50 == 0:\n print('Iteration ' + str(self.ite) + ' on ' + str(self.budget) + ' for workers ' + str(self.id) + '\\n')\n\n # Notify the master that the buffer is ready\n if self.ite % frequency == 0:\n self.integrate_buffer(Master_nodes)\n self.buffer = []\n\n def tree_policy(self, node, master_nodes):\n \"\"\"\n Method implementing the tree policy phase in the MCTS-UCT search. Starts from the root nodes and\n iteratively selects the best child of the nodes. A node must be fully expanded before we continue down\n to its best child.\n\n :param node: starting node of the tree policy, usually the root node.\n :param dict Master_nodes: `Manager.dict() <https://docs.python.org/2/library/multiprocessing.html#sharing-state-\\\n between-processes>`_ (Dictionary of :class:`master_node.MasterNode`) which saves the nodes of every scenario.\n :return: the newly expanded node\n :rtype: :class:`Node`\n \"\"\"\n while not self.is_node_terminal(node):\n if not node.is_fully_expanded():\n return self.expand(node)\n else:\n node = self.best_child(node, master_nodes)\n return node\n\n def expand(self, node):\n \"\"\"\n\n Creates a new :class:`worker.Node` from a node (its parent). The new node is expanded randomly \\\n using an available actions.\n\n :param worker.Node node: The parent node.\n :return: The new :class:`worker.Node`.\n\n \"\"\"\n action = node.actions.pop()\n newNode = Node(parent=node, origins=node.origins + [action], depth=node.depth + 1)\n self.depth = max(self.depth, newNode.depth)\n node.children.append(newNode)\n self.Nodes.append(newNode)\n return newNode\n\n def best_child(self, node, Master_nodes):\n \"\"\"\n Select the best child of a node, by comparing their uct values. The comparison is based on the value of the \\\n child in this tree, but also in the master tree, if it exists there.\n\n :param `worker.Node` node: The parent node.\n :param dict Master_nodes: `Manager.dict() <https://docs.python.org/2/library/multiprocessing.html#sharing-state-\\\n between-processes>`_ (Dictionary of :class:`master_node.MasterNode`) which saves the nodes of every scenario.\n\n :return: The best child (:class:`worker.Node`) of the parent node given in parameter.\n \"\"\"\n\n max_ucts_of_children = -1\n id_of_best_child = -1\n num_node = 0\n\n for val in node.Values:\n num_node += sum(val.h)\n\n for i, child in enumerate(node.children):\n uct_master = self.get_master_uct(hash(tuple(child.origins)), Master_nodes)\n if uct_master == 0:\n ucts_of_children = child.get_uct(num_node)\n else:\n ucts_of_children = (1 - RHO) * child.get_uct(num_node) + RHO * uct_master\n\n if ucts_of_children > max_ucts_of_children:\n max_ucts_of_children = ucts_of_children\n id_of_best_child = i\n return node.children[id_of_best_child]\n\n def default_policy(self, node):\n \"\"\"\n Policy used to compute the reward of a node. First, the state of the node is estimated with \\\n :meth:`get_sim_to_estimate_state`, then the default policy is applied (going straight to the destination).\n\n :param worker.Node node: The node one wants to evaluate.\n :return float: The rewards of the node.\n \"\"\"\n self.get_sim_to_estimate_state(node)\n dist, action = self.Simulator.getDistAndBearing(self.Simulator.state[1:], self.destination)\n atDest, frac = Tree.is_state_at_dest(self.destination, self.Simulator.prevState, self.Simulator.state)\n\n while (not atDest) \\\n and (not Tree.is_state_terminal(self.Simulator, self.Simulator.state)):\n self.Simulator.doStep(action)\n dist, action = self.Simulator.getDistAndBearing(self.Simulator.state[1:], self.destination)\n atDest, frac = Tree.is_state_at_dest(self.destination, self.Simulator.prevState, self.Simulator.state)\n\n if atDest:\n finalTime = self.Simulator.times[self.Simulator.state[0]] - (1 - frac) * (\n self.Simulator.times[self.Simulator.state[0]] - self.Simulator.times[self.Simulator.state[0] - 1])\n reward = (exp((self.TimeMax * 1.001 - finalTime) / (self.TimeMax * 1.001 - self.TimeMin)) - 1) / (\n exp(1) - 1)\n else:\n reward = 0\n\n return reward\n\n def get_sim_to_estimate_state(self, node):\n \"\"\"\n Brings the simulator to an estimate state (time, lat, lon) of a node. Since the dynamic is not deterministic, \\\n the state is an estimation.\n\n :param worker.Node node: The nodes one wants to estimate.\n \"\"\"\n listOfActions = list(node.origins)\n listOfActions.reverse()\n self.Simulator.reset(self.rootNode.state)\n\n action = listOfActions.pop()\n self.Simulator.doStep(action)\n\n while listOfActions and not Tree.is_state_terminal(self.Simulator, self.Simulator.state) \\\n and not Tree.is_state_at_dest(self.destination, self.Simulator.prevState, self.Simulator.state):\n action = listOfActions.pop()\n self.Simulator.doStep(action)\n\n def get_master_uct(self, node_hash, Master_nodes):\n \"\"\"\n Compute the uct value seen by the master tree.\n\n :param int node_hash: the corresponding hash node.\n :param dict Master_nodes: `Manager.dict() <https://docs.python.org/2/library/multiprocessing.html#sharing-state-\\\n between-processes>`_ (Dictionary of :class:`master_node.MasterNode` objects) which saves the nodes of every scenario.\n :return float: The uct value of the node passed in parameter.\n \"\"\"\n master_node = Master_nodes.get(node_hash, 0)\n idx_scenarios = []\n\n # If the node is not in the the master dictionary, the uct is 0\n if master_node == 0:\n return 0\n\n else:\n uct_per_scenario = []\n for s, reward_per_scenario in enumerate(master_node.rewards):\n uct_max_on_actions = 0\n\n num_parent = 0\n for hist in master_node.parentNode.rewards[s]:\n num_parent += sum(hist.h)\n\n num_node = 0\n for hist in master_node.rewards[s]:\n num_node += sum(hist.h)\n\n if (num_parent != 0) and (num_node != 0):\n exploration = UCT_COEFF * (2 * log(num_parent) / num_node) ** 0.5\n\n for hist in reward_per_scenario:\n uct_value = hist.get_mean()\n\n if uct_value > uct_max_on_actions:\n uct_max_on_actions = uct_value\n\n uct_per_scenario.append(uct_max_on_actions + exploration)\n idx_scenarios.append(s)\n\n # mean on the scenarios which expanded this node\n mean = np.dot(uct_per_scenario, [self.probability[i] for i in idx_scenarios])\n\n return mean\n\n def integrate_buffer(self, Master_nodes):\n \"\"\"\n Integrates the buffer of update from this scenario (the buffer is an attribute of the :class:`Tree`) \\\n . The buffer is a list of updates coming from the worker. \\\n One update is a list : [scenarioId, newNodeHash, parentHash, action, reward]\n\n :param dict Master_nodes: `Manager.dict() <https://docs.python.org/2/library/multiprocessing.html#sharing-state-\\\n between-processes>`_ (Dictionary of :class:`master_node.MasterNode` objects) which saves the nodes of every scenario.\n \"\"\"\n\n for update in self.buffer:\n\n scenarioId, newNodeHash, parentHash, action, reward = update\n\n node = Master_nodes.get(newNodeHash, 0)\n # new node if it doesn't exist\n if node == 0:\n node = MasterNode(self.numScenarios, nodehash=newNodeHash,\n parentNode=Master_nodes[parentHash], action=action)\n\n # add the reward in the expanded node\n node.add_reward(scenarioId, reward)\n\n # Back propagation\n Master_nodes[newNodeHash] = node\n while node.parentNode is not None:\n parent_hash = Master_nodes[node.hash].parentNode.hash\n parent_node = Master_nodes[parent_hash]\n parent_node.add_reward_action(scenarioId, node.arm, reward)\n Master_nodes[parent_hash] = parent_node\n node = parent_node\n\n @staticmethod\n def is_state_at_dest(destination, stateA, stateB):\n \"\"\"\n Determines if the boat has gone beyond the destination. In this case, computes how much the boat \\\n has overshot.\n\n :param destination: Destination state (goal).\n :param stateA: Previous state of the simulator.\n :param stateB: Current state of the simulator.\n\n :return: [True, frac] if the boat has reached the destination (frac is the last iteration proportion \\\n corresponding to the part stateA--destination). Returns [False, None] otherwise.\n \"\"\"\n [xa, ya, za] = SimC.Simulator.fromGeoToCartesian(stateA[1:])\n [xb, yb, zb] = SimC.Simulator.fromGeoToCartesian(stateB[1:])\n [xd, yd, zd] = SimC.Simulator.fromGeoToCartesian(destination)\n c = (yb / ya * xa - xb) / (zb - yb / ya * za)\n b = -(xa + c * za) / ya\n d = abs(xd + b * yd + c * zd) / sqrt(1 + b ** 2 + c ** 2)\n alpha = asin(d)\n\n if alpha > SimC.DESTINATION_ANGLE:\n return [False, None]\n\n else:\n vad = np.array([xd, yd, zd]) - np.array([xa, ya, za])\n vdb = np.array([xb, yb, zb]) - np.array([xd, yd, zd])\n vab = np.array([xb, yb, zb]) - np.array([xa, ya, za])\n\n p = np.dot(vad, vdb)\n\n if p < 0:\n return [False, None]\n\n else:\n return [True, np.dot(vad, vab) / np.dot(vab, vab)]\n\n @staticmethod\n def is_state_terminal(simulator, state):\n \"\"\"\n Determines if a state is considered as terminal (time is equal or larger than the time horizon, or if the boat is \\\n out of the zone of interest).\n\n :param Simulator simulator: Simulator of the scenario.\n :param list state: State one wants to test [time, lat, lon]\n :return: True if the state is considered as terminal, False otherwise.\n \"\"\"\n if simulator.times[state[0]] == simulator.times[-1]:\n return True\n\n elif state[1] < simulator.lats[0] or state[1] > simulator.lats[-1]:\n return True\n\n elif state[2] < simulator.lons[0] or state[2] > simulator.lons[-1]:\n return True\n else:\n return False\n\n def is_node_terminal(self, node):\n \"\"\"\n Checks if the corresponding time of a node is equal to the time horizon of the simulation.\n\n :param worker.Node node: The node that is checked\n :return: True if the node is terminal, False otherwise.\n \"\"\"\n return self.Simulator.times[node.depth] == self.TimeMax\n"
] | [
[
"numpy.dot",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
wiseodd/pytorch-classification | [
"31b97bdba56fadaca585ee947b7aca1bf5cc79c3"
] | [
"models/cifar/densenet.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\n\n\n__all__ = ['densenet', 'densenetbc121', 'densenetbc121_Alt']\n\n\nfrom torch.autograd import Variable\n\nclass Bottleneck(nn.Module):\n def __init__(self, inplanes, expansion=4, growthRate=12, dropRate=0):\n super(Bottleneck, self).__init__()\n planes = expansion * growthRate\n self.bn1 = nn.BatchNorm2d(inplanes)\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, growthRate, kernel_size=3,\n padding=1, bias=False)\n self.relu = nn.ReLU(inplace=True)\n self.dropRate = dropRate\n\n def forward(self, x):\n out = self.bn1(x)\n out = self.relu(out)\n out = self.conv1(out)\n out = self.bn2(out)\n out = self.relu(out)\n out = self.conv2(out)\n if self.dropRate > 0:\n out = F.dropout(out, p=self.dropRate, training=self.training)\n\n out = torch.cat((x, out), 1)\n\n return out\n\n\nclass BasicBlock(nn.Module):\n def __init__(self, inplanes, expansion=1, growthRate=12, dropRate=0):\n super(BasicBlock, self).__init__()\n planes = expansion * growthRate\n self.bn1 = nn.BatchNorm2d(inplanes)\n self.conv1 = nn.Conv2d(inplanes, growthRate, kernel_size=3,\n padding=1, bias=False)\n self.relu = nn.ReLU(inplace=True)\n self.dropRate = dropRate\n\n def forward(self, x):\n out = self.bn1(x)\n out = self.relu(out)\n out = self.conv1(out)\n if self.dropRate > 0:\n out = F.dropout(out, p=self.dropRate, training=self.training)\n\n out = torch.cat((x, out), 1)\n\n return out\n\n\nclass Transition(nn.Module):\n def __init__(self, inplanes, outplanes):\n super(Transition, self).__init__()\n self.bn1 = nn.BatchNorm2d(inplanes)\n self.conv1 = nn.Conv2d(inplanes, outplanes, kernel_size=1,\n bias=False)\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, x):\n out = self.bn1(x)\n out = self.relu(out)\n out = self.conv1(out)\n out = F.avg_pool2d(out, 2)\n return out\n\n\nclass DenseNet(nn.Module):\n\n def __init__(self, depth=100, block=Bottleneck, dropRate=0, num_classes=10, growthRate=12, compressionRate=2, feature_extractor=False):\n super(DenseNet, self).__init__()\n\n assert (depth - 4) % 3 == 0, 'depth should be 3n+4'\n n = (depth - 4) / 3 if block == BasicBlock else (depth - 4) // 6\n\n self.growthRate = growthRate\n self.dropRate = dropRate\n self.feature_extractor = feature_extractor\n\n # self.inplanes is a global variable used across multiple\n # helper functions\n self.inplanes = growthRate * 2\n self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=3, padding=1,\n bias=False)\n self.dense1 = self._make_denseblock(block, n)\n self.trans1 = self._make_transition(compressionRate)\n self.dense2 = self._make_denseblock(block, n)\n self.trans2 = self._make_transition(compressionRate)\n self.dense3 = self._make_denseblock(block, n)\n self.bn = nn.BatchNorm2d(self.inplanes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = nn.Conv2d(self.inplanes, 256, kernel_size=3, padding=1)\n self.avgpool = nn.AvgPool2d(8)\n self.fc = nn.Linear(256, num_classes)\n\n # Weight initialization\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def _make_denseblock(self, block, blocks):\n layers = []\n for i in range(blocks):\n # Currently we fix the expansion ratio as the default value\n layers.append(block(self.inplanes, growthRate=self.growthRate, dropRate=self.dropRate))\n self.inplanes += self.growthRate\n\n return nn.Sequential(*layers)\n\n def _make_transition(self, compressionRate):\n inplanes = self.inplanes\n outplanes = int(math.floor(self.inplanes // compressionRate))\n self.inplanes = outplanes\n return Transition(inplanes, outplanes)\n\n def forward(self, x):\n x = self.features(x)\n\n if self.feature_extractor:\n return x\n else:\n return self.fc(x)\n\n def features(self, x, return_acts=False):\n acts = []\n\n x = self.conv1(x)\n acts.append(x)\n x = self.trans1(self.dense1(x))\n acts.append(x)\n x = self.trans2(self.dense2(x))\n acts.append(x)\n x = self.dense3(x)\n x = self.bn(x)\n x = self.relu(x)\n acts.append(x)\n x = self.conv2(x)\n x = F.relu(x)\n acts.append(x)\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n return x if not return_acts else (x, acts)\n\n\nclass DenseNet2(nn.Module):\n\n def __init__(self, depth=100, block=Bottleneck, dropRate=0, num_classes=10, growthRate=12, compressionRate=2, feature_extractor=False):\n super(DenseNet2, self).__init__()\n\n assert (depth - 4) % 3 == 0, 'depth should be 3n+4'\n n = (depth - 4) / 3 if block == BasicBlock else (depth - 4) // 6\n\n self.growthRate = growthRate\n self.dropRate = dropRate\n self.feature_extractor = feature_extractor\n\n # self.inplanes is a global variable used across multiple\n # helper functions\n self.inplanes = growthRate * 2\n self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=3, padding=1,\n bias=False)\n self.dense1 = self._make_denseblock(block, n)\n self.trans1 = self._make_transition(compressionRate)\n self.dense2 = self._make_denseblock(block, n)\n self.trans2 = self._make_transition(compressionRate)\n self.dense3 = self._make_denseblock(block, n)\n self.bn = nn.BatchNorm2d(self.inplanes)\n self.relu = nn.ReLU(inplace=True)\n self.clf = nn.Sequential(\n nn.Conv2d(self.inplanes, 256, kernel_size=3, padding=1),\n nn.ReLU(),\n nn.AvgPool2d(8),\n nn.Flatten(),\n nn.Linear(256, num_classes)\n )\n\n # Weight initialization\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def _make_denseblock(self, block, blocks):\n layers = []\n for i in range(blocks):\n # Currently we fix the expansion ratio as the default value\n layers.append(block(self.inplanes, growthRate=self.growthRate, dropRate=self.dropRate))\n self.inplanes += self.growthRate\n\n return nn.Sequential(*layers)\n\n def _make_transition(self, compressionRate):\n inplanes = self.inplanes\n outplanes = int(math.floor(self.inplanes // compressionRate))\n self.inplanes = outplanes\n return Transition(inplanes, outplanes)\n\n def forward(self, x):\n x = self.features_before_clf(x)\n\n if self.feature_extractor:\n return x\n else:\n return self.clf(x)\n\n def features(self, x, return_acts=False):\n acts = []\n\n x = self.conv1(x)\n acts.append(x)\n x = self.trans1(self.dense1(x))\n acts.append(x)\n x = self.trans2(self.dense2(x))\n acts.append(x)\n x = self.dense3(x)\n x = self.bn(x)\n x = self.relu(x)\n acts.append(x)\n\n # Apply all but the last module in clf\n for m in list(self.clf.children())[:-1]:\n x = m(x)\n\n return x if not return_acts else (x, acts)\n\n def features_before_clf(self, x, return_acts=False):\n acts = []\n\n x = self.conv1(x)\n acts.append(x)\n x = self.trans1(self.dense1(x))\n acts.append(x)\n x = self.trans2(self.dense2(x))\n acts.append(x)\n x = self.dense3(x)\n x = self.bn(x)\n x = self.relu(x)\n acts.append(x)\n\n return x if not return_acts else (x, acts)\n\n\ndef densenet(**kwargs):\n return DenseNet(**kwargs)\n\n\ndef densenetbc121(num_classes, feature_extractor=False):\n return DenseNet(\n num_classes=num_classes, depth=100, growthRate=12,\n compressionRate=2, dropRate=0, feature_extractor=feature_extractor\n )\n\n\ndef densenetbc121_Alt(num_classes, feature_extractor=False):\n return DenseNet2(\n num_classes=num_classes, depth=100, growthRate=12,\n compressionRate=2, dropRate=0, feature_extractor=feature_extractor\n )\n"
] | [
[
"torch.nn.Sequential",
"torch.cat",
"torch.nn.functional.dropout",
"torch.nn.functional.avg_pool2d",
"torch.nn.Conv2d",
"torch.nn.Flatten",
"torch.nn.Linear",
"torch.nn.AvgPool2d",
"torch.nn.functional.relu",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
XiongPengNUS/rsome | [
"c8308870dd8338d792a0001ac6e64e9012fc709c"
] | [
"lp.py"
] | [
"from .subroutines import *\nimport numpy as np\nimport pandas as pd\nimport scipy.sparse as sp\nimport warnings\nfrom numbers import Real\nfrom scipy.sparse import csr_matrix\nfrom scipy.sparse import coo_matrix\nfrom collections import Iterable, Sized\nfrom .lpg_solver import solve as def_sol\n\n\nclass Model:\n \"\"\"\n The Model class creates an LP model object\n \"\"\"\n\n def __init__(self, nobj=False, mtype='R', name=None):\n\n self.mtype = mtype\n self.nobj = nobj\n self.name = name\n\n self.vars = []\n self.auxs = []\n self.last = 0\n self.lin_constr = []\n self.pws_constr = []\n self.bounds = []\n self.aux_constr = []\n self.aux_bounds = []\n self.obj = None\n self.sign = 1\n self.primal = None\n self.dual = None\n self.solution = None\n self.pupdate = True\n self.dupdate = True\n\n if not nobj:\n self.dvar()\n\n def dvar(self, shape=(1,), vtype='C', name=None, aux=False):\n\n if not isinstance(shape, tuple):\n shape = (shape, )\n\n new_shape = ()\n for item in shape:\n if not isinstance(item, (int, np.int8, np.int16,\n np.int32, np.int64)):\n raise TypeError('Shape dimensions must be int type!')\n new_shape += (item, )\n\n new_var = Vars(self, self.last, new_shape, vtype, name)\n\n if not aux:\n self.vars.append(new_var)\n else:\n self.auxs.append(new_var)\n self.last += np.prod(shape)\n return new_var\n\n def st(self, constr):\n\n if isinstance(constr, Iterable):\n for item in constr:\n self.st(item)\n else:\n if constr.model is not self:\n raise ValueError('Constraints are not defined for this model.')\n if isinstance(constr, LinConstr):\n self.lin_constr.append(constr)\n elif isinstance(constr, CvxConstr):\n if constr.xtype in 'AMI':\n self.pws_constr.append(constr)\n else:\n raise TypeError('Incorrect constraint type.')\n elif isinstance(constr, Bounds):\n self.bounds.append(constr)\n else:\n raise TypeError('Unknown constraint type.')\n\n self.pupdate = True\n self.dupdate = True\n\n def min(self, obj):\n \"\"\"\n Minimize the given objective function.\n\n Parameters\n ----------\n obj\n An objective function\n\n Notes\n -----\n The objective function given as an array must have the size\n to be one.\n \"\"\"\n\n if obj.size > 1:\n raise ValueError('Incorrect function dimension.')\n\n self.obj = obj\n self.sign = 1\n self.pupdate = True\n self.dupdate = True\n\n def max(self, obj):\n \"\"\"\n Maximize the given objective function.\n\n Parameters\n ----------\n obj\n An objective function\n\n Notes\n -----\n The objective function given as an array must have the size\n to be one.\n \"\"\"\n\n if obj.size > 1:\n raise ValueError('Incorrect function dimension.')\n\n self.obj = obj\n self.sign = - 1\n self.pupdate = True\n self.dupdate = True\n\n def do_math(self, primal=True, refresh=True, obj=False):\n\n if primal:\n if self.primal is not None and not self.pupdate:\n return self.primal\n\n if refresh:\n self.auxs = []\n self.aux_constr = []\n self.aux_bounds = []\n self.last = self.vars[-1].first + self.vars[-1].size\n\n more_cvx = []\n if self.obj:\n obj_constr = (self.vars[0] >= self.sign * self.obj)\n if isinstance(obj_constr, LinConstr):\n self.aux_constr.append(obj_constr)\n elif isinstance(obj_constr, CvxConstr):\n more_cvx.append(obj_constr)\n\n for constr in self.pws_constr + more_cvx:\n if constr.xtype == 'A':\n self.aux_constr.append(constr.affine_in +\n constr.affine_out <= 0)\n self.aux_constr.append(-constr.affine_in +\n constr.affine_out <= 0)\n elif constr.xtype == 'M':\n aux = self.dvar(constr.affine_in.shape, aux=True)\n self.aux_constr.append(constr.affine_in <= aux)\n self.aux_constr.append(-constr.affine_in <= aux)\n self.aux_constr.append(sum(aux) + constr.affine_out <= 0)\n elif constr.xtype == 'I':\n aux = self.dvar(1, aux=True)\n self.aux_constr.append(constr.affine_in <= aux)\n self.aux_constr.append(-constr.affine_in <= aux)\n self.aux_constr.append(aux + constr.affine_out <= 0)\n if obj:\n obj = np.array(csr_matrix(([1.0], ([0], [0])),\n (1, self.last)).todense())\n else:\n obj = np.ones((1, self.last))\n\n data_list = []\n indices_list = []\n indptr = [0]\n last = 0\n\n data_list += [item.linear.data\n for item in self.lin_constr + self.aux_constr]\n indices_list += [item.linear.indices\n for item in self.lin_constr + self.aux_constr]\n\n if data_list:\n data = np.concatenate(tuple(data_list))\n indices = np.concatenate(tuple(indices_list))\n for item in self.lin_constr + self.aux_constr:\n indptr.extend(list(item.linear.indptr[1:] + last))\n last += item.linear.indptr[-1]\n\n linear = csr_matrix((data, indices, indptr),\n (len(indptr) - 1, self.last))\n\n const_list = [item.const for item in\n self.lin_constr + self.aux_constr]\n\n sense_list = [item.sense\n if isinstance(item.sense, np.ndarray) else\n np.array([item.sense])\n for item in self.lin_constr\n + self.aux_constr]\n\n const = np.concatenate(tuple(const_list))\n sense = np.concatenate(tuple(sense_list))\n else:\n linear = csr_matrix(([], ([], [])), (1, self.last))\n const = np.array([0])\n sense = np.array([1])\n\n vtype = np.concatenate([np.array([item.vtype] * item.size)\n if len(item.vtype) == 1\n else np.array(list(item.vtype))\n for item in self.vars + self.auxs])\n\n # ub = np.array([np.infty] * linear.shape[1])\n # lb = np.array([-np.infty] * linear.shape[1])\n ub = np.array([np.infty] * self.last)\n lb = np.array([-np.infty] * self.last)\n\n for b in self.bounds + self.aux_bounds:\n if b.btype == 'U':\n ub[b.indices] = np.minimum(b.values, ub[b.indices])\n elif b.btype == 'L':\n lb[b.indices] = np.maximum(b.values, lb[b.indices])\n\n formula = LinProg(linear, const, sense,\n vtype, ub, lb, obj)\n self.primal = formula\n self.pupdate = False\n\n return formula\n\n else:\n if self.dual is not None and not self.dupdate:\n return self.dual\n\n primal = self.do_math(obj=obj)\n if 'B' in primal.vtype or 'I' in primal.vtype:\n string = '\\nIntegers detected.'\n string += '\\nDual of the continuous relaxtion is returned'\n warnings.warn(string)\n\n primal_linear = primal.linear\n primal_const = primal.const\n primal_sense = primal.sense\n indices_ub = np.where((primal.ub != 0) &\n (primal.ub != np.infty))[0]\n indices_lb = np.where((primal.lb != 0) &\n (primal.lb != - np.infty))[0]\n\n nub = len(indices_ub)\n nlb = len(indices_lb)\n nv = primal_linear.shape[1]\n if nub > 0:\n matrix_ub = csr_matrix((np.array([1] * nub), indices_ub,\n np.arange(nub + 1)), (nub, nv))\n primal_linear = sp.vstack((primal_linear, matrix_ub))\n primal_const = np.concatenate((primal_const,\n primal.ub[indices_ub]))\n primal_sense = np.concatenate((primal_sense, np.zeros(nub)))\n if nlb > 0:\n matrix_lb = csr_matrix((np.array([-1] * nlb), indices_lb,\n np.arange(nlb + 1)), (nlb, nv))\n primal_linear = sp.vstack((primal_linear, matrix_lb))\n primal_const = np.concatenate((primal_const,\n -primal.lb[indices_lb]))\n primal_sense = np.concatenate((primal_sense, np.zeros(nlb)))\n\n indices_free = np.where((primal.lb != 0) &\n (primal.ub != 0))[0]\n indices_neg = np.where(primal.ub == 0)[0]\n\n dual_linear = csr_matrix(primal_linear.T)\n ndv = dual_linear.shape[1]\n dual_obj = - primal_const\n dual_const = primal.obj.reshape((nv, ))\n dual_sense = np.zeros(dual_linear.shape[0])\n dual_sense[indices_free] = 1\n dual_ub = np.zeros(dual_linear.shape[1])\n dual_lb = - np.ones(ndv) * np.infty\n\n indices_eq = np.where(primal_sense == 1)[0]\n if len(indices_eq):\n dual_ub[indices_eq] = np.infty\n\n if len(indices_neg) > 0:\n dual_linear[indices_neg, :] = - dual_linear[indices_neg, :]\n dual_const[indices_neg] = - dual_const[indices_neg]\n\n formula = LinProg(dual_linear, dual_const, dual_sense,\n np.array(['C']*ndv), dual_ub, dual_lb, dual_obj)\n self.dual = formula\n self.dupdate = False\n\n return formula\n\n def solve(self, solver=None, display=True, export=False, params={}):\n \"\"\"\n Solve the model with the selected solver interface.\n\n Parameters\n ----------\n solver : {None, lpg_solver, mip_solver,\n clp_solver, grb_solver, msk_solver}\n Solver interface used for model solution. Use default solver\n if solver=None.\n display : bool\n Display option of the solver interface.\n export : bool\n Export option of the solver interface. A standard model file\n is generated if the option is True.\n params : dict\n A dictionary that specifies parameters of the selected solver.\n So far the argument only applies to Gurobi, CPLEX,and MOSEK.\n \"\"\"\n\n if solver is None:\n solution = def_sol(self.do_math(obj=True), display, export, params)\n else:\n solution = solver.solve(self.do_math(obj=True),\n display, export, params)\n\n if instance(solution, Solution):\n self.solution = solution\n else:\n if not solution:\n warnings.warn('No feasible solutions can be found.')\n else:\n x = solution.x\n self.solution = Solution(x[0], x, solution.status)\n\n def get(self):\n\n if self.solution is None:\n raise SyntaxError('The model is unsolved or no feasible solution.')\n return self.sign * self.solution.objval\n\n\nclass SparseVec:\n\n __array_priority__ = 200\n\n def __init__(self, index, value, nvar):\n\n self.index = index\n self.value = value\n self.nvar = nvar\n\n def __str__(self):\n\n string = 'Indices: ' + str(self.index) + ' | '\n string += 'Values: ' + str(self.value)\n\n return string\n\n def __repr__(self):\n\n return self.__str__()\n\n def __add__(self, other):\n\n return SparseVec(self.index+other.index,\n self.value+other.value, max(self.nvar, other.nvar))\n\n def __radd__(self, other):\n\n return self.__add__(other)\n\n def __mul__(self, other):\n\n values = [v*other for v in self.value]\n return SparseVec(self.index, values, self.nvar)\n\n def __rmul__(self, other):\n\n return self.__mul__(other)\n\n\nclass Vars:\n \"\"\"\n The Var class creates a variable array.\n \"\"\"\n\n __array_priority__ = 100\n\n def __init__(self, model, first, shape, vtype, name, sparray=None):\n\n self.model = model\n self.first = first\n self.shape = shape\n self.size = int(np.prod(shape))\n self.last = first + self.size\n self.ndim = len(shape)\n self.vtype = vtype\n self.name = name\n self.sparray = sparray\n\n def __str__(self):\n\n vtype = self.vtype\n if 'C' not in vtype and 'B' not in vtype and 'I' not in vtype:\n raise ValueError('Unknown variable type.')\n\n var_name = '' if self.name is None else self.name + ': '\n \"\"\"\n model_type = ('RSO model' if self.model.mtype == 'R' else\n 'Robust counterpart' if self.model.mtype == 'C' else\n 'Support' if self.model.mtype == 'S' else\n 'Expectation set' if self.model.mtype == 'E' else\n 'Probability set')\n \"\"\"\n var_type = ('continuous' if vtype == 'C' else\n 'binary' if vtype == 'B' else\n 'integer' if vtype == 'I' else\n 'Mixed-type')\n suffix = 's' if np.prod(self.shape) > 1 else ''\n\n string = var_name\n string += 'x'.join([str(size) for size in self.shape]) + ' '\n string += var_type + ' variable' + suffix\n # string += ' ({0})'.format(model_type)\n\n return string\n\n def __repr__(self):\n\n return self.__str__()\n\n def sv_array(self, index=False):\n\n shape = self.shape\n shape = shape if isinstance(shape, tuple) else (int(shape), )\n size = np.prod(shape).item()\n\n if index:\n elements = [SparseVec([i], [1], size) for i in range(size)]\n else:\n elements = [SparseVec([i], [1.0], size) for i in range(size)]\n\n return np.array(elements).reshape(shape)\n\n # noinspection PyPep8Naming\n @property\n def T(self):\n\n return self.to_affine().T\n\n def to_affine(self):\n\n dim = self.size\n\n data = np.ones(dim)\n indices = self.first + np.arange(dim)\n indptr = np.arange(dim+1)\n\n linear = csr_matrix((data, indices, indptr),\n shape=(dim, self.model.last))\n const = np.zeros(self.shape)\n\n return Affine(self.model, linear, const, self.sparray)\n\n def get_ind(self):\n\n return np.array(range(self.first, self.first + self.size))\n\n def reshape(self, shape):\n\n return self.to_affine().reshape(shape)\n\n def norm(self, degree):\n\n return self.to_affine().norm(degree)\n\n def get(self):\n\n if self.model.solution is None:\n raise SyntaxError('The model is unsolved.')\n\n indices = range(self.first, self.first + self.size)\n var_sol = np.array(self.model.solution.x)[indices]\n if isinstance(var_sol, np.ndarray):\n var_sol = var_sol.reshape(self.shape)\n\n return var_sol\n\n def __getitem__(self, item):\n\n item_array = index_array(self.shape)\n indices = item_array[item]\n if not isinstance(indices, np.ndarray):\n indices = np.array([indices]).reshape((1, ) * self.ndim)\n\n return VarSub(self, indices)\n\n def __iter__(self):\n\n shape = self.shape\n for i in range(shape[0]):\n yield self[i]\n\n def __abs__(self):\n\n return self.to_affine().__abs__()\n\n def sum(self, axis=None):\n\n return self.to_affine().sum(axis)\n\n def __mul__(self, other):\n\n return self.to_affine() * other\n\n def __rmul__(self, other):\n\n return other * self.to_affine()\n\n def __matmul__(self, other):\n\n return self.to_affine() @ other\n\n def __rmatmul__(self, other):\n\n return other @ self.to_affine()\n\n def __add__(self, other):\n\n return self.to_affine() + other\n\n def __radd__(self, other):\n\n return self.to_affine() + other\n\n def __sub__(self, other):\n\n return self.to_affine() - other\n\n def __rsub__(self, other):\n\n return (-self.to_affine()) + other\n\n def __neg__(self):\n\n return - self.to_affine()\n\n def __le__(self, other):\n\n if ((isinstance(other, (Real, np.ndarray)) or sp.issparse(other))\n and self.model.mtype not in 'EP'):\n upper = other + np.zeros(self.shape)\n upper = upper.reshape((upper.size, ))\n indices = np.arange(self.first, self.first + self.size,\n dtype=np.int32)\n return Bounds(self.model, indices, upper, 'U')\n else:\n return self.to_affine() <= other\n\n def __ge__(self, other):\n\n if ((isinstance(other, (Real, np.ndarray)) or sp.issparse(other))\n and self.model.mtype not in 'EP'):\n lower = other + np.zeros(self.shape)\n lower = lower.reshape((lower.size, ))\n indices = np.arange(self.first, self.first + self.size,\n dtype=np.int32)\n return Bounds(self.model, indices, lower, 'L')\n else:\n return self.to_affine() >= other\n\n def __eq__(self, other):\n\n return self.to_affine() == other\n\n\nclass VarSub(Vars):\n \"\"\"\n The VarSub class creates a variable array with subscript indices\n \"\"\"\n\n def __init__(self, var, indices):\n\n super().__init__(var.model, var.first,\n var.shape, var.vtype, var.name, var.sparray)\n self.indices = indices\n\n def __repr__(self):\n\n var_name = '' if self.name is None else self.name + ': '\n \"\"\"\n model_type = ('RSO model' if self.model.mtype == 'R' else\n 'Robust counterpart' if self.model.mtype == 'C' else\n 'Support' if self.model.mtype == 'S' else\n 'Expectation set' if self.model.mtype == 'E' else\n 'Probability set')\n \"\"\"\n var_type = ('continuous' if self.vtype == 'C' else\n 'binary' if self.vtype == 'B' else 'integer')\n suffix = 's' if np.prod(self.shape) > 1 else ''\n\n string = var_name\n string += 'x'.join([str(dim) for dim in self.indices.shape]) + ' '\n string += 'slice of '\n string += var_type + ' variable' + suffix\n # string += ' ({0})'.format(model_type)\n\n return string\n\n @property\n def T(self):\n\n return self.to_affine().T\n\n def get_ind(self):\n\n indices_all = super().get_ind()\n return indices_all[self.indices].flatten()\n\n def __getitem__(self, item):\n\n raise SyntaxError('Nested indexing of variables is forbidden.')\n\n def sum(self, axis=None):\n\n return self.to_affine().sum(axis)\n\n def to_affine(self):\n\n select = list(self.indices.reshape((self.indices.size,)))\n\n dim = self.size\n data = np.ones(dim)\n indices = self.first + np.arange(dim)\n indptr = np.arange(dim + 1)\n\n linear = csr_matrix((data, indices, indptr),\n shape=(dim, self.model.last))\n const = np.zeros(self.indices.shape)\n\n return Affine(self.model, linear[select, :], const)\n\n def reshape(self, shape):\n\n return self.to_affine().reshape(shape)\n\n def __add__(self, other):\n\n return self.to_affine() + other\n\n def __radd__(self, other):\n\n return self.to_affine() + other\n\n def __le__(self, other):\n\n upper = super().__le__(other)\n if isinstance(upper, Bounds):\n indices = self.indices.reshape((self.indices.size, ))\n bound_indices = upper.indices.reshape((upper.indices.size, ))[indices]\n bound_values = upper.values.reshape(upper.values.size)[indices]\n\n return Bounds(upper.model, bound_indices, bound_values, 'U')\n else:\n return self.to_affine().__le__(other)\n\n def __ge__(self, other):\n\n lower = super().__ge__(other)\n if isinstance(lower, Bounds):\n indices = self.indices.reshape((self.indices.size, ))\n bound_indices = lower.indices.reshape((lower.indices.size, ))[indices]\n bound_values = lower.values.reshape((lower.indices.size, ))[indices]\n\n return Bounds(lower.model, bound_indices, bound_values, 'L')\n else:\n return self.to_affine().__ge__(other)\n\n\nclass Affine:\n \"\"\"\n The Affine class creates an array of affine expressions\n \"\"\"\n\n __array_priority__ = 100\n\n def __init__(self, model, linear, const, sparray=None):\n\n self.model = model\n self.linear = linear\n self.const = const\n self.shape = const.shape\n self.size = np.prod(self.shape)\n self.sparray = sparray\n self.expect = False\n\n def __repr__(self):\n\n \"\"\"\n model_type = ('RSO model' if self.model.mtype == 'R' else\n 'Robust counterpart' if self.model.mtype == 'C' else\n 'Support' if self.model.mtype == 'S' else\n 'Expectation set' if self.model.mtype == 'E' else\n 'Probability set')\n \"\"\"\n string = 'x'.join([str(dim) for dim in self.shape]) + ' '\n string += 'affine expressions '\n # string += '({0})'.format(model_type)\n\n return string\n\n def __getitem__(self, item):\n\n if self.sparray is None:\n # self.sparray = sparse_array(self.shape)\n self.sparray = self.sv_array()\n\n indices = self.sparray[item]\n if not isinstance(indices, np.ndarray):\n indices = np.array([indices]).reshape((1, ))\n\n # linear = array_to_sparse(indices) @ self.linear\n linear = sv_to_csr(indices) @ self.linear\n const = self.const[item]\n if not isinstance(const, np.ndarray):\n const = np.array([const])\n\n return Affine(self.model, linear, const)\n\n def to_affine(self):\n\n return self\n\n def rand_to_roaffine(self, rc_model):\n\n size = self.size\n num_rand = self.model.vars[-1].last\n reduced_linear = self.linear[:, :num_rand]\n num_dec = rc_model.last\n\n raffine = Affine(rc_model,\n csr_matrix((size*num_rand, num_dec)),\n reduced_linear.toarray())\n affine = Affine(rc_model, csr_matrix((size, num_dec)),\n self.const)\n\n return RoAffine(raffine, affine, self.model)\n\n def sv_array(self, index=False):\n\n shape = self.shape\n shape = shape if isinstance(shape, tuple) else (int(shape), )\n size = np.prod(shape).item()\n\n if index:\n elements = [SparseVec([i], [1], size) for i in range(size)]\n else:\n elements = [SparseVec([i], [1.0], size) for i in range(size)]\n\n return np.array(elements).reshape(shape)\n\n def sv_zeros(self, nvar):\n\n shape = (self.shape if isinstance(self.shape, tuple) else\n (int(self.shape),))\n size = np.prod(self.shape).item()\n elements = [SparseVec([], [], nvar) for _ in range(size)]\n\n return np.array(elements).reshape(shape)\n\n # noinspection PyPep8Naming\n @property\n def T(self):\n\n linear = sp_trans(self) @ self.linear\n const = self.const.T\n\n return Affine(self.model, linear, const)\n\n def reshape(self, shape):\n\n new_const = self.const.reshape(shape)\n return Affine(self.model, self.linear, new_const)\n\n def sum(self, axis=None):\n\n if self.sparray is None:\n # self.sparray = sparse_array(self.shape)\n self.sparray = self.sv_array()\n\n indices = self.sparray.sum(axis=axis)\n if not isinstance(indices, np.ndarray):\n indices = np.array([indices])\n\n # linear = array_to_sparse(indices) @ self.linear\n linear = sv_to_csr(indices) @ self.linear\n const = self.const.sum(axis=axis)\n if not isinstance(const, np.ndarray):\n const = np.array([const])\n\n return Affine(self.model, linear, const)\n\n def __abs__(self):\n\n return Convex(self, np.zeros(self.shape), 'A', 1)\n\n def abs(self):\n\n return self.__abs__()\n\n def norm(self, degree):\n\n shape = self.shape\n if np.prod(shape) != max(shape):\n raise ValueError('Funciton \"norm\" only applies to vectors.')\n\n new_shape = (1,) * len(shape)\n if degree == 1:\n return Convex(self, np.zeros(new_shape), 'M', 1)\n elif degree == np.infty or degree == 'inf':\n return Convex(self, np.zeros(new_shape), 'I', 1)\n elif degree == 2:\n return Convex(self, np.zeros(new_shape), 'E', 1)\n else:\n raise ValueError('Incorrect degree for the norm function.')\n\n def square(self):\n\n size = self.size\n shape = self.shape\n\n return Convex(self.reshape((size,)), np.zeros(shape), 'S', 1)\n\n def sumsqr(self):\n\n shape = self.shape\n if np.prod(shape) != max(shape):\n raise ValueError('Funciton \"sumsqr\" only applies to vectors.')\n\n new_shape = (1,) * len(shape)\n return Convex(self, np.zeros(new_shape), 'Q', 1)\n\n def __mul__(self, other):\n\n if isinstance(other, (Vars, VarSub, Affine)):\n if self.model.mtype in 'VR' and other.model.mtype in 'SM':\n other = other.to_affine()\n if self.shape != other.shape:\n raffine = self * np.ones(other.to_affine().shape)\n other = np.ones(self.shape) * other.to_affine()\n else:\n raffine = self\n other = other.to_affine()\n\n raffine = raffine.reshape((raffine.size, 1))\n\n rvar_last = other.model.vars[-1].last\n reduced_linear = other.linear[:, :rvar_last]\n trans_sparray = np.array([line for line in reduced_linear])\n\n raffine = raffine * array_to_sparse(trans_sparray)\n affine = self * other.const\n\n return RoAffine(raffine, affine, other.model)\n else:\n return other.__mul__(self)\n\n else:\n other = check_numeric(other)\n\n if isinstance(other, Real):\n other = np.array([other])\n\n new_linear = sparse_mul(other, self.to_affine()) @ self.linear\n new_const = self.const * other\n\n return Affine(self.model, new_linear, new_const)\n\n def __rmul__(self, other):\n\n if isinstance(other, (Vars, VarSub, Affine)):\n if self.model.mtype in 'VR' and other.model.mtype == 'S':\n\n other = other.to_affine()\n if self.shape != other.shape:\n raffine = self * np.ones(other.to_affine().shape)\n other = np.ones(self.shape) * other.to_affine()\n else:\n raffine = self\n other = other.to_affine()\n\n raffine = raffine.reshape((raffine.size, 1))\n\n rvar_last = other.model.vars[-1].last\n reduced_linear = other.linear[:, :rvar_last]\n trans_sparray = np.array([line for line in reduced_linear])\n\n raffine = raffine * array_to_sparse(trans_sparray)\n affine = self * other.const\n\n return RoAffine(raffine, affine, other.model)\n else:\n return other.__rmul__(self)\n else:\n other = check_numeric(other)\n\n if isinstance(other, Real):\n other = np.array([other])\n\n new_linear = sparse_mul(other, self.to_affine()) @ self.linear\n new_const = self.const * other\n\n return Affine(self.model, new_linear, new_const)\n\n def __matmul__(self, other):\n\n if isinstance(other, (Vars, VarSub, Affine)):\n if self.model.mtype in 'VR' and other.model.mtype in 'SM':\n\n other = other.to_affine()\n affine = self @ other.const\n num_rand = other.model.vars[-1].last\n\n ind_array = self.sv_array()\n temp = ind_array @ np.arange(other.size).reshape(other.shape)\n if isinstance(temp, np.ndarray):\n all_items = list(temp.reshape((temp.size, )))\n else:\n all_items = [temp]\n temp = np.array([temp])\n col_ind = np.concatenate(tuple(item.index\n for item in all_items))\n row_ind = tuple(np.array(all_items[i].value) + i*other.size\n for i in range(len(all_items)))\n row_ind = np.concatenate(row_ind)\n csr_temp = csr_matrix((np.ones(len(col_ind)),\n (row_ind, col_ind)),\n shape=(temp.size*other.size, self.size))\n self_flat = self.reshape(self.size)\n affine_temp = (csr_temp @ self_flat).reshape((temp.size,\n other.size))\n raffine = affine_temp @ other.linear[:, :num_rand]\n\n return RoAffine(raffine, affine, other.model)\n elif self.model.mtype in 'SM' and other.model.mtype in 'VR':\n\n affine = self.const @ other\n other = other.to_affine()\n num_rand = self.model.vars[-1].last\n\n ind_array = self.sv_array()\n temp = ind_array @ np.arange(other.size).reshape(other.shape)\n if isinstance(temp, np.ndarray):\n all_items = list(temp.reshape((temp.size, )))\n else:\n all_items = [temp]\n temp = np.array([temp])\n col_ind = np.concatenate(tuple(item.value\n for item in all_items))\n row_ind = tuple(np.array(all_items[i].index) + i*self.size\n for i in range(len(all_items)))\n row_ind = np.concatenate(row_ind)\n csr_temp = csr_matrix((np.ones(len(col_ind)),\n (row_ind, col_ind)),\n shape=(temp.size*self.size, other.size))\n other_flat = other.reshape(other.size)\n affine_temp = (csr_temp @ other_flat).reshape((temp.size,\n self.size))\n raffine = affine_temp @ self.linear[:, :num_rand]\n\n roaffine = RoAffine(raffine, affine, self.model)\n\n if isinstance(other, DecAffine):\n return DecRoAffine(roaffine, other.event_adapt, 'R')\n else:\n return roaffine\n else:\n other = check_numeric(other)\n\n new_const = self.const @ other\n if not isinstance(new_const, np.ndarray):\n new_const = np.array([new_const])\n\n new_linear = sp_lmatmul(other, self, new_const.shape) @ self.linear\n\n return Affine(self.model, new_linear, new_const)\n\n def __rmatmul__(self, other):\n\n other = check_numeric(other)\n\n new_const = other @ self.const\n if not isinstance(new_const, np.ndarray):\n new_const = np.array([new_const])\n\n new_linear = sp_matmul(other, self, new_const.shape) @ self.linear\n\n return Affine(self.model, new_linear, new_const)\n\n def __add__(self, other):\n\n if isinstance(other, (Vars, VarSub, Affine)):\n # if isinstance(other, (Vars, VarSub)):\n other = other.to_affine()\n\n if self.model.mtype != other.model.mtype:\n if self.model.mtype in 'VR':\n return other.rand_to_roaffine(self.model).__add__(self)\n # elif other.model.mtype == 'R':\n # return self.rand_to_roaffine(other.model).__add__(other)\n elif other.model.mtype in 'VR':\n temp = self.rand_to_roaffine(other.model)\n return other.__add__(temp)\n else:\n raise ValueError('Models mismatch.')\n\n new_const = other.const + self.const\n\n if self.shape == other.shape:\n new_linear = add_linear(self.linear, other.linear)\n else:\n\n left_linear = (self * np.ones(other.shape)).linear\n right_linear = (other * np.ones(self.shape)).linear\n\n new_linear = add_linear(left_linear, right_linear)\n elif isinstance(other, np.ndarray):\n other = check_numeric(other)\n new_const = other + self.const\n\n if self.shape == other.shape:\n new_linear = self.linear\n else:\n if self.shape != other.shape:\n # sparray = self.sv_array()\n # zero = self.sv_zeros(other.size)\n # sparse = sv_to_csr(sparray + zero)\n\n new_linear = (self*np.ones(other.shape)).linear\n else:\n new_linear = self.linear\n elif isinstance(other, Real):\n other = check_numeric(other)\n new_const = other + self.const\n new_linear = self.linear\n else:\n # raise TypeError('Incorrect data type.')\n return other.__add__(self)\n\n return Affine(self.model, new_linear, new_const)\n\n def __radd__(self, other):\n\n return self + other\n\n def __neg__(self):\n\n return Affine(self.model, -self.linear, -self.const)\n\n def __sub__(self, other):\n\n return self + (-other)\n\n def __rsub__(self, other):\n\n return (-self) + other\n\n def __le__(self, other):\n\n left = self - other\n if isinstance(left, Affine) and not isinstance(left, DecAffine):\n return LinConstr(left.model, left.linear,\n -left.const.reshape((left.const.size, )),\n np.zeros(left.const.size))\n else:\n return left.__le__(0)\n\n def __ge__(self, other):\n\n left = other - self\n if isinstance(left, Affine) and not isinstance(left, DecAffine):\n return LinConstr(left.model, left.linear,\n -left.const.reshape((left.const.size,)),\n np.zeros(left.const.size))\n else:\n return left.__le__(0)\n\n def __eq__(self, other):\n\n left = self - other\n if isinstance(left, Affine) and not isinstance(left, DecAffine):\n return LinConstr(left.model, left.linear,\n -left.const.reshape((left.const.size,)),\n np.ones(left.const.size))\n else:\n return left.__eq__(0)\n ##########\n\n\nclass Convex:\n \"\"\"\n The Convex class creates an object of convex functions\n \"\"\"\n\n def __init__(self, affine_in, affine_out, xtype, sign):\n\n self.model = affine_in.model\n self.affine_in = affine_in\n self.affine_out = affine_out\n self.size = affine_out.size\n self.xtype = xtype\n self.sign = sign\n\n def __repr__(self):\n xtypes = {'A': 'Absolute functions',\n 'M': 'One-norm functions',\n 'E': 'Eclidean norm functions',\n 'I': 'Infinity norm functions',\n 'S': 'Element-wise square functions',\n 'Q': 'Quadratic functions'}\n shapes = 'x'.join([str(dim) for dim in self.affine_out.shape])\n string = shapes + ' ' + xtypes[self.xtype]\n\n return string\n\n def __str__(self):\n\n return self.__repr__()\n\n def __neg__(self):\n\n return Convex(self.affine_in, -self.affine_out, self.xtype, -self.sign)\n\n def __add__(self, other):\n\n affine_in = self.affine_in\n affine_out = self.affine_out + other\n if not isinstance(affine_out,\n (Vars, VarSub, Affine, Real, np.ndarray)):\n raise TypeError('Incorrect data types.')\n\n new_convex = Convex(affine_in, affine_out, self.xtype, self.sign)\n\n return new_convex\n\n def __radd__(self, other):\n\n return self.__add__(other)\n\n def __sub__(self, other):\n\n return self.__add__(-other)\n\n def __rsub__(self, other):\n\n return (-self).__add__(other)\n\n def __mul__(self, other):\n\n if not isinstance(other, Real):\n raise SyntaxError('Incorrect syntax.')\n\n if self.xtype in 'AMIE':\n multiplier = abs(other)\n elif self.xtype in 'SQ':\n multiplier = abs(other) ** 0.5\n else:\n raise ValueError('Unknown type of convex function.')\n return Convex(multiplier * self.affine_in, other * self.affine_out,\n self.xtype, np.sign(other)*self.sign)\n\n def __rmul__(self, other):\n\n return self.__mul__(other)\n\n def __le__(self, other):\n\n left = self - other\n if left.sign == -1:\n raise ValueError('Non-convex constraints.')\n\n return CvxConstr(left.model, left.affine_in, left.affine_out,\n left.xtype)\n\n def __ge__(self, other):\n\n right = other - self\n if right.sign == -1:\n raise ValueError('Nonconvex constraints.')\n\n return CvxConstr(right.model, right.affine_in, right.affine_out,\n right.xtype)\n\n\nclass RoAffine:\n \"\"\"\n The Roaffine class creats an object of uncertain affine functions\n \"\"\"\n\n __array_priority__ = 101\n\n def __init__(self, raffine, affine, rand_model):\n\n self.dec_model = raffine.model\n self.rand_model = rand_model\n self.raffine = raffine\n self.affine = affine\n self.shape = affine.shape\n self.ndim = len(affine.shape)\n self.size = affine.size\n\n def sv_array(self, index=False):\n\n shape = self.shape\n shape = shape if isinstance(shape, tuple) else (int(shape), )\n size = np.prod(shape).item()\n\n if index:\n elements = [SparseVec([i], [1], size) for i in range(size)]\n else:\n elements = [SparseVec([i], [1.0], size) for i in range(size)]\n\n return np.array(elements).reshape(shape)\n\n def sv_zeros(self, nvar):\n\n shape = (self.shape if isinstance(self.shape, tuple) else\n (int(self.shape),))\n size = np.prod(self.shape).item()\n elements = [SparseVec([], [], nvar) for _ in range(size)]\n\n return np.array(elements).reshape(shape)\n\n def reshape(self, shape):\n\n return RoAffine(self.raffine, self.affine.reshape(shape),\n self.rand_model)\n\n @property\n def T(self):\n\n raffine = sp_trans(self) @ self.raffine\n affine = self.affine.T\n\n return RoAffine(raffine, affine, self.rand_model)\n\n def __neg__(self):\n\n return RoAffine(-self.raffine, -self.affine, self.rand_model)\n\n def __add__(self, other):\n\n if isinstance(other, (DecRule, DecRuleSub)):\n return self.__add__(other.to_affine())\n if isinstance(other, RoAffine):\n if other.shape != self.shape:\n left = self + np.zeros(other.shape)\n right = other + np.zeros(self.shape)\n else:\n left = self\n right = other\n raffine = left.raffine + right.raffine\n affine = left.affine + right.affine\n if self.dec_model is not other.dec_model or \\\n self.rand_model is not other.rand_model:\n raise ValueError('Models mismatch.')\n return RoAffine(raffine, affine, self.rand_model)\n elif isinstance(other, (Affine, Vars, VarSub)):\n other = other.to_affine()\n if other.model == self.rand_model:\n if other.shape != self.shape:\n left = self + np.zeros(other.shape)\n right = other + np.zeros(self.shape)\n else:\n left = self\n right = other.to_affine()\n\n right_term = right.rand_to_roaffine(left.dec_model)\n return left.__add__(right_term)\n elif other.model == self.dec_model:\n if other.shape != self.shape:\n left = self * np.ones(other.shape)\n right = other + np.zeros(self.shape)\n else:\n left = self\n right = other.to_affine()\n\n raffine = left.raffine\n affine = left.affine + right\n\n return RoAffine(raffine, affine, self.rand_model)\n else:\n raise TypeError('Unknown model types.')\n elif isinstance(other, (Real, np.ndarray)):\n if isinstance(other, Real):\n other = np.array([other])\n\n if other.shape == self.shape:\n raffine = self.raffine\n else:\n sparray = (np.arange(self.size).reshape(self.shape)\n + np.zeros(other.shape))\n index = sparray.flatten()\n size = sparray.size\n sparse = csr_matrix(([1]*size, index, np.arange(size+1)),\n shape=[size, self.size])\n raffine = sparse @ self.raffine\n\n affine = self.affine + other\n return RoAffine(raffine, affine, self.rand_model)\n else:\n raise SyntaxError('Syntax error.')\n\n def __radd__(self, other):\n\n return self.__add__(other)\n\n def __sub__(self, other):\n\n return self.__add__(-other)\n\n def __rsub__(self, other):\n\n return (-self).__add__(other)\n\n def __mul__(self, other):\n\n new_affine = self.affine * other\n if isinstance(other, Real):\n other = np.array([other])\n\n new_raffine = sparse_mul(other, self) @ self.raffine\n\n return RoAffine(new_raffine, new_affine, self.rand_model)\n\n def __rmul__(self, other):\n\n new_affine = other * self.affine\n if isinstance(other, Real):\n other = np.array([other])\n\n new_raffine = sparse_mul(other, self) @ self.raffine\n\n return RoAffine(new_raffine, new_affine, self.rand_model)\n\n def __matmul__(self, other):\n\n other = check_numeric(other)\n\n new_affine = self.affine @ other\n\n new_raffine = sp_lmatmul(other, self, new_affine.shape) @ self.raffine\n\n return RoAffine(new_raffine, new_affine, self.rand_model)\n\n def __rmatmul__(self, other):\n\n other = check_numeric(other)\n\n new_affine = other @ self.affine\n\n new_raffine = sp_matmul(other, self, new_affine.shape) @ self.raffine\n\n return RoAffine(new_raffine, new_affine, self.rand_model)\n\n def sum(self, axis=None):\n\n new_affine = self.affine.sum(axis=axis)\n\n svarray = self.affine.sv_array()\n new_svarray = svarray.sum(axis=axis)\n if not isinstance(new_svarray, np.ndarray):\n new_svarray = np.array([new_svarray])\n\n new_raffine = sv_to_csr(new_svarray) @ self.raffine\n\n return RoAffine(new_raffine, new_affine, self.rand_model)\n\n def __le__(self, other):\n\n left = self - other\n return RoConstr(left, sense=0)\n\n def __ge__(self, other):\n\n right = other - self\n return RoConstr(right, sense=0)\n\n def __eq__(self, other):\n\n left = self - other\n return RoConstr(left, sense=1)\n\n\nclass LinConstr:\n \"\"\"\n The LinConstr class creates an array of linear constraints.\n \"\"\"\n\n def __init__(self, model, linear, const, sense, sign=1):\n\n self.model = model\n self.linear = linear\n self.const = const\n self.sense = sense\n self.sign = sign\n\n\nclass CvxConstr:\n \"\"\"\n The CvxConstr class creates an object of convex constraints\n \"\"\"\n\n def __init__(self, model, affine_in, affine_out, xtype):\n\n self.model = model\n self.affine_in = affine_in\n self.affine_out = affine_out\n self.xtype = xtype\n\n\nclass Bounds:\n \"\"\"\n The Bounds class creates an object for upper or lower bounds\n \"\"\"\n\n def __init__(self, model, indices, values, btype):\n\n self.model = model\n self.indices = indices\n self.values = values\n self.btype = btype\n\n\nclass ConeConstr:\n \"\"\"\n The ConeConstr class creates an object of second-order cone constraints\n \"\"\"\n\n def __init__(self, model, left_var, left_index, right_var, right_index):\n\n self.model = model\n self.left_var = left_var\n self.right_var = right_var\n self.left_index = left_index\n self.right_index = right_index\n\n\nclass RoConstr:\n \"\"\"\n The Roaffine class creats an object of uncertain affine functions\n \"\"\"\n\n def __init__(self, roaffine, sense):\n\n self.dec_model = roaffine.dec_model\n self.rand_model = roaffine.rand_model\n self.raffine = roaffine.raffine\n self.affine = roaffine.affine\n self.shape = roaffine.shape\n self.sense = sense\n self.support = None\n\n def forall(self, *args):\n \"\"\"\n Specify the uncertainty set of the constraints involving random\n variables. The given arguments are constraints or collections of\n constraints used for defining the uncertainty set.\n\n Notes\n -----\n The uncertainty set defined by this method overrides the default\n uncertainty set defined for the worst-case objective.\n \"\"\"\n\n constraints = []\n for items in args:\n if isinstance(items, Iterable):\n constraints.extend(list(items))\n else:\n constraints.append(items)\n\n sup_model = constraints[0].model\n sup_model.reset()\n for item in constraints:\n if item.model is not sup_model:\n raise SyntaxError('Models mismatch.')\n sup_model.st(item)\n\n self.support = sup_model.do_math(primal=False)\n\n return self\n\n def le_to_rc(self, support=None):\n\n num_constr, num_rand = self.raffine.shape\n support = self.support if not support else support\n size_support = support.linear.shape[1]\n num_rand = min(num_rand, support.linear.shape[0])\n\n dual_var = self.dec_model.dvar((num_constr, size_support))\n\n constr1 = ([email protected] +\n self.affine.reshape(num_constr) <= 0)\n\n left = dual_var @ support.linear[:num_rand].T\n left = left + self.raffine[:, :num_rand] * support.const[:num_rand]\n sense2 = np.tile(support.sense[:num_rand], num_constr)\n num_rc_constr = left.const.size\n constr2 = LinConstr(left.model, left.linear,\n -left.const.reshape(num_rc_constr),\n sense2)\n\n bounds = ()\n index_pos = (support.ub == 0)\n if any(index_pos):\n bounds += (dual_var[:, index_pos] <= 0, )\n index_neg = (support.lb == 0)\n if any(index_neg):\n bounds += (dual_var[:, index_neg] >= 0, )\n\n if num_rand == support.linear.shape[0]:\n constr_tuple = constr1, constr2\n constr_tuple += () if bounds is None else (bounds,)\n # constr_tuple = ((constr1, constr2) if bounds is None else\n # (constr1, constr2, bounds))\n else:\n left = dual_var @ support.linear[num_rand:].T\n sense3 = np.tile(support.sense[num_rand:], num_constr)\n num_rc_constr = left.const.size\n constr3 = LinConstr(left.model, left.linear,\n left.const.reshape(num_rc_constr),\n sense3)\n # constr_tuple= ((constr1, constr2, constr3) if bounds is None else\n # (constr1, constr2, constr3, bounds))\n constr_tuple = constr1, constr2, constr3\n constr_tuple += () if bounds is None else (bounds,)\n\n for n in range(num_constr):\n for qconstr in support.qmat:\n indices = np.array(qconstr, dtype=int) + n*size_support\n cone_constr = ConeConstr(self.dec_model, dual_var, indices[1:],\n dual_var, indices[0])\n constr_tuple = constr_tuple + (cone_constr,)\n\n return constr_tuple\n\n\nclass DecVar(Vars):\n \"\"\"\n The DecVar class creates an object of generic variable array\n (here-and-now or wait-and-see) for adaptive DRO models\n \"\"\"\n\n def __init__(self, dro_model, dvars, fixed=True, name=None):\n\n super().__init__(dvars.model, dvars.first, dvars.shape,\n dvars.vtype, dvars.name)\n self.dro_model = dro_model\n self.event_adapt = [list(range(dro_model.num_scen))]\n self.rand_adapt = None\n self.ro_first = None\n self.fixed = fixed\n self.name = name\n\n def __getitem__(self, item):\n\n item_array = index_array(self.shape)\n indices = item_array[item]\n if not isinstance(indices, np.ndarray):\n indices = np.array([indices]).reshape((1, ) * self.ndim)\n\n return DecVarSub(self.dro_model, self, indices)\n\n def to_affine(self):\n\n expr = super().to_affine()\n return DecAffine(self.dro_model, expr, self.event_adapt, self.fixed)\n\n def adapt(self, to):\n\n if isinstance(to, (Scen, Sized, int)):\n self.evtadapt(to)\n elif isinstance(to, (RandVar, RandVarSub)):\n self.affadapt(to)\n else:\n raise ValueError('Can not define adaption for the inputs.')\n\n def evtadapt(self, scens):\n\n # self.fixed = False\n if self.event_adapt is None:\n self.event_adapt = [list(range(self.dro_model.num_scen))]\n\n if isinstance(scens, Scen):\n events = scens.series\n else:\n events = scens\n # events = list(events) if isinstance(events, Iterable) else [events]\n events = [events] if isinstance(events, (str, Real)) else list(events)\n\n for event in events:\n index = self.dro_model.series_scen[event]\n if index in self.event_adapt[0]:\n self.event_adapt[0].remove(index)\n else:\n raise ValueError('Wrong scenario index or {0} '.format(event) +\n 'has been redefined.')\n\n if not self.event_adapt[0]:\n self.event_adapt.pop(0)\n\n self.event_adapt.append(list(self.dro_model.series_scen[events]))\n\n def affadapt(self, rvars):\n\n self.fixed = False\n self[:].affadapt(rvars)\n\n def __le__(self, other):\n\n return self.to_affine().__le__(other)\n\n def __ge__(self, other):\n\n return self.to_affine().__ge__(other)\n\n def __eq__(self, other):\n\n return self.to_affine().__eq__(other)\n\n def get(self, rvar=None):\n\n dro_model = self.dro_model\n var_sol = dro_model.ro_model.rc_model.vars[1].get()\n num_scen = dro_model.num_scen\n edict = event_dict(self.event_adapt)\n if rvar is None:\n outputs = []\n for eindex in range(len(self.event_adapt)):\n indices = (self.ro_first + eindex*self.size\n + np.arange(self.size, dtype=int))\n outputs.append(var_sol[indices].reshape(self.shape))\n\n if len(outputs) > 1:\n ind_label = self.dro_model.series_scen.index\n return pd.Series([outputs[edict[key]] for key in edict],\n index=ind_label)\n else:\n return outputs[0]\n else:\n outputs = []\n drule_list = dro_model.rule_var()\n if isinstance(drule_list[0], Affine):\n raise ValueError('Decision not affinely adaptive!')\n for eindex in self.event_adapt:\n s = eindex[0]\n drule = drule_list[s]\n\n sp = drule.raffine[self.get_ind(), :][:, rvar.get_ind()].linear\n sp = coo_matrix(sp)\n\n sol_vec = np.array(dro_model.solution.x)[sp.col]\n sol_indices = sp.row\n\n coeff = np.ones(sp.shape[0]) * np.NaN\n coeff[sol_indices] = sol_vec\n\n if rvar.to_affine().size == 1:\n outputs.append(coeff.reshape(self.shape))\n else:\n rv_shape = rvar.to_affine().shape\n outputs.append(coeff.reshape(self.shape + rv_shape))\n\n if len(outputs) > 1:\n ind_label = self.dro_model.series_scen.index\n return pd.Series([outputs[edict[key]] for key in edict],\n index=ind_label)\n else:\n return outputs[0]\n\n\n @property\n def E(self):\n\n return DecAffine(self.dro_model, self.to_affine(), ctype='E')\n\n\nclass DecVarSub(VarSub):\n\n def __init__(self, dro_model, dvars, indices, fixed=True):\n\n super().__init__(dvars, indices)\n self.dro_model = dro_model\n self.event_adapt = dvars.event_adapt\n self.rand_adapt = dvars.rand_adapt\n self.dvars = dvars\n self.fixed = fixed\n\n def to_affine(self):\n\n expr = super().to_affine()\n return DecAffine(self.dro_model, expr, self.event_adapt, self.fixed)\n\n def adapt(self, rvars):\n\n self.fixed = False\n if not isinstance(rvars, (RandVar, RandVarSub)):\n raise TypeError('Affine adaptation requires a random variable.')\n\n self.affadapt(rvars)\n\n def affadapt(self, rvars):\n\n self.fixed = False\n if self.rand_adapt is None:\n sup_model = self.dro_model.sup_model\n self.rand_adapt = np.zeros((self.size, sup_model.vars[-1].last),\n dtype=np.int8)\n\n dec_indices = self.indices\n dec_indices = dec_indices.reshape((dec_indices.size, 1))\n rand_indices = rvars.get_ind()\n rand_indices = rand_indices.reshape(rand_indices.size)\n\n dec_indices_flat = (dec_indices *\n np.ones(rand_indices.shape, dtype=int)).flatten()\n rand_indices_flat = (np.ones(dec_indices.shape, dtype=int) *\n rand_indices).flatten()\n\n if self.rand_adapt[dec_indices_flat, rand_indices_flat].any():\n raise SyntaxError('Redefinition of adaptation is not allowed.')\n\n self.rand_adapt[dec_indices_flat, rand_indices_flat] = 1\n self.dvars.rand_adapt = self.rand_adapt\n\n def __le__(self, other):\n\n \"\"\"\n if isinstance(other, (Real, np.ndarray)):\n bounds = super().__le__(other)\n return DecBounds(bounds, self.event_adapt)\n else:\n return self.to_affine().__le__(other)\n \"\"\"\n return self.to_affine().__le__(other)\n\n def __ge__(self, other):\n\n \"\"\"\n if isinstance(other, (Real, np.ndarray)):\n bounds = super().__ge__(other)\n return DecBounds(bounds, self.event_adapt)\n else:\n return self.to_affine().__ge__(other)\n \"\"\"\n return self.to_affine().__ge__(other)\n\n @property\n def E(self):\n\n return DecAffine(self.dro_model, self.to_affine(), ctype='E')\n\n\nclass RandVar(Vars):\n \"\"\"\n The RandVar class creates an object of random variable array\n \"\"\"\n\n def __init__(self, svars, evars):\n\n super().__init__(svars.model, svars.first,\n svars.shape, svars.vtype, svars.name, svars.sparray)\n self.e = evars\n\n @property\n def E(self):\n\n return self.e\n\n def __getitem__(self, item):\n\n item_array = index_array(self.shape)\n indices = item_array[item]\n if not isinstance(indices, np.ndarray):\n indices = np.array([indices]).reshape((1, ) * self.ndim)\n\n return RandVarSub(self, indices)\n\n def __add__(self, other):\n\n expr = super().__add__(other)\n if isinstance(expr, RoAffine):\n expr = DecRoAffine(expr, other.event_adapt, other.ctype)\n\n return expr\n\n def __neg__(self):\n\n return super().__neg__()\n\n def __mul__(self, other):\n\n return super().__mul__(other)\n\n def __matmul__(self, other):\n\n return super().__matmul__(other)\n\n def __rmatmul__(self, other):\n\n return super().__rmatmul__(other)\n\n\nclass RandVarSub(VarSub):\n\n def __init__(self, rvars, indices):\n\n super().__init__(rvars, indices)\n self.e = VarSub(rvars.e, indices)\n\n @property\n def E(self):\n\n return self.e\n\n\nclass DecAffine(Affine):\n\n def __init__(self, dro_model, affine,\n event_adapt=None, fixed=True, ctype='R'):\n\n super().__init__(affine.model, affine.linear,\n affine.const, affine.sparray)\n self.dro_model = dro_model\n self.event_adapt = (event_adapt if event_adapt else\n [list(range(dro_model.num_scen))])\n self.fixed = fixed\n self.ctype = ctype\n\n def reshape(self, shape):\n\n expr = super().reshape(shape)\n\n return DecAffine(self.dro_model, expr,\n self.event_adapt, self.fixed, self.ctype)\n\n def sum(self, axis=None):\n\n expr = super().sum(axis)\n\n return DecAffine(expr.dro_model, expr,\n self.event_adapt, self.fixed, self.ctype)\n\n def to_affine(self):\n\n expr = super().to_affine()\n\n return DecAffine(self.dro_model, expr, self.event_adapt,\n self.fixed, self.ctype)\n\n @property\n def T(self):\n\n expr = super().T\n\n return DecAffine(self.dro_model, expr, self.event_adapt,\n self.fixed, self.ctype)\n\n def __mul__(self, other):\n\n expr = super().__mul__(other)\n if isinstance(expr, Affine):\n return DecAffine(self.dro_model, expr,\n event_adapt=self.event_adapt,\n ctype=self.ctype, fixed=self.fixed)\n elif isinstance(expr, RoAffine):\n return DecRoAffine(expr, self.event_adapt, 'R')\n\n def __rmul__(self, other):\n\n return self.__mul__(other)\n\n def __matmul__(self, other):\n\n expr = super().__matmul__(other)\n if isinstance(expr, Affine):\n return DecAffine(self.dro_model, expr,\n event_adapt=self.event_adapt,\n ctype=self.ctype, fixed=self.fixed)\n elif isinstance(expr, RoAffine):\n return DecRoAffine(expr, self.event_adapt, 'R')\n\n def __rmatmul__(self, other):\n\n if isinstance(other, (Real, np.ndarray)) or sp.issparse(other):\n expr = super().__rmatmul__(other)\n else:\n expr = other.__matmul__(super().to_affine())\n\n if isinstance(expr, Affine):\n return DecAffine(self.dro_model, expr,\n event_adapt=self.event_adapt,\n ctype=self.ctype, fixed=self.fixed)\n elif isinstance(expr, RoAffine):\n return DecRoAffine(expr, self.event_adapt, 'R')\n\n def __neg__(self):\n\n expr = super().__neg__()\n\n return DecAffine(self.dro_model, expr,\n event_adapt=self.event_adapt,\n ctype=self.ctype, fixed=self.fixed)\n\n def __add__(self, other):\n\n expr = super().__add__(other)\n if isinstance(other, (DecAffine, DecVar, DecVarSub)):\n other = other.to_affine()\n self_is_fixed = self.fixed and len(self.event_adapt) == 1\n other_is_fixed = other.fixed and len(other.event_adapt) == 1\n if self.ctype == 'E' and other.ctype == 'R' and not other_is_fixed:\n raise TypeError('Incorrect expectation expressions.')\n if other.ctype == 'E' and self.ctype == 'R' and not self_is_fixed:\n raise TypeError('Incorrect expectation expressions.')\n event_adapt = comb_set(self.event_adapt, other.event_adapt)\n ctype = other.ctype\n elif isinstance(other, DecRoAffine):\n event_adapt = comb_set(self.event_adapt, other.event_adapt)\n ctype = other.ctype\n elif isinstance(other, (Real, np.ndarray, Affine, RoAffine,\n Vars, VarSub)) or sp.issparse(other):\n event_adapt = self.event_adapt\n ctype = 'R'\n else:\n return other.__add__(self)\n\n if len(event_adapt) == 1:\n fixed = True\n else:\n fixed = False\n\n fixed = fixed and self.fixed\n ctype = 'E' if 'E' in (self.ctype + ctype) else 'R'\n\n if isinstance(expr, Affine):\n return DecAffine(self.dro_model, expr,\n event_adapt=event_adapt,\n ctype=ctype, fixed=fixed)\n elif isinstance(expr, RoAffine):\n if isinstance(other, DecRoAffine):\n ctype = other.ctype\n else:\n ctype = 'R'\n return DecRoAffine(expr, event_adapt, ctype)\n\n def __abs__(self):\n\n expr = super().__abs__()\n\n return DecConvex(expr, self.event_adapt)\n\n def abs(self):\n\n return self.__abs__()\n\n def norm(self, degree):\n\n if not self.fixed:\n raise SyntaxError('Incorrect convex expressions.')\n\n expr = super().norm(degree)\n\n return DecConvex(expr, self.event_adapt)\n\n def square(self):\n\n if not self.fixed:\n raise SyntaxError('Incorrect convex expressions.')\n\n expr = super().square()\n\n return DecConvex(expr, self.event_adapt)\n\n def sumsqr(self):\n\n if not self.fixed:\n raise SyntaxError('Incorrect convex expressions.')\n\n expr = super().sumsqr()\n\n return DecConvex(expr, self.event_adapt)\n\n def sum(self, axis=None):\n\n expr = super().sum(axis)\n\n return DecAffine(self.dro_model, expr, self.event_adapt, self.fixed)\n\n def __le__(self, other):\n\n left = self - other\n\n if isinstance(left, DecAffine):\n return DecLinConstr(left.model, left.linear, -left.const,\n np.zeros(left.size), left.event_adapt,\n left.ctype)\n elif isinstance(left, DecRoAffine):\n return DecRoConstr(left, 0, left.event_adapt, left.ctype)\n elif isinstance(left, DecConvex):\n return DecCvxConstr(left, left.event_adapt)\n\n def __ge__(self, other):\n\n left = other - self\n\n if isinstance(left, DecAffine):\n return DecLinConstr(left.model, left.linear, -left.const,\n np.zeros(left.size), left.event_adapt,\n left.ctype)\n elif isinstance(left, DecRoAffine):\n return DecRoConstr(left, 0, left.event_adapt, left.ctype)\n elif isinstance(left, DecConvex):\n return DecCvxConstr(left, left.event_adapt)\n\n def __eq__(self, other):\n\n left = self - other\n if isinstance(left, DecAffine):\n return DecLinConstr(left.model, left.linear, -left.const,\n np.ones(left.size), left.event_adapt)\n elif isinstance(left, DecRoAffine):\n return DecRoConstr(left, 1, left.event_adapt, left.ctype)\n\n @property\n def E(self):\n\n affine = Affine(self.model, self.linear, self.const)\n return DecAffine(self.dro_model, affine, ctype='E')\n\n\nclass DecConvex(Convex):\n\n def __init__(self, convex, event_adapt):\n\n super().__init__(convex.affine_in, convex.affine_out,\n convex.xtype, convex.sign)\n self.event_adapt = event_adapt\n\n def __neg__(self):\n\n expr = super().__neg__()\n return DecConvex(expr, self.event_adapt)\n\n def __add__(self, other):\n\n expr = super().__add__(other)\n\n if isinstance(other, (Real, np.ndarray)) or sp.issparse(other):\n event_adapt = self.event_adapt\n else:\n event_adapt = comb_set(self.event_adapt, other.event_adapt)\n\n return DecConvex(expr, event_adapt)\n\n def __mul__(self, other):\n\n expr = super().__mul__(other)\n\n return DecConvex(expr, self.event_adapt)\n\n def __rmul__(self, other):\n\n expr = super().__rmul__(other)\n\n return DecConvex(expr, self.event_adapt)\n\n def __le__(self, other):\n\n constr = super().__le__(other)\n\n return DecCvxConstr(constr, self.event_adapt)\n\n def __ge__(self, other):\n\n constr = super().__ge__(other)\n\n return DecCvxConstr(constr, self.event_adapt)\n\n\nclass DecRoAffine(RoAffine):\n\n def __init__(self, roaffine, event_adapt, ctype):\n\n super().__init__(roaffine.raffine, roaffine.affine,\n roaffine.rand_model)\n\n self.event_adapt = event_adapt\n self.ctype = ctype\n\n def sum(self, axis=None):\n\n expr = super().sum(axis)\n\n return DecRoAffine(expr, self.event_adapt, self.ctype)\n\n def __neg__(self):\n\n expr = super().__neg__()\n\n return DecRoAffine(expr, self.event_adapt, self.ctype)\n\n def __add__(self, other):\n\n if isinstance(other, (DecVar, DecVarSub, DecAffine, DecRoAffine)):\n if isinstance(other, DecRoAffine):\n if self.ctype != other.ctype:\n raise TypeError('Incorrect expectation expressions.')\n else:\n other = other.to_affine()\n if self.ctype != other.ctype:\n if ((self.ctype == 'E'\n and (not other.fixed or len(other.event_adapt) > 1))\n or other.ctype == 'E'):\n raise TypeError('Incorrect expectation expressions.')\n other = other.to_affine()\n event_adapt = comb_set(self.event_adapt, other.event_adapt)\n ctype = 'E' if 'E' in self.ctype + other.ctype else 'R'\n elif (isinstance(other, (Real, np.ndarray, RoAffine))\n or sp.issparse(other)):\n event_adapt = self.event_adapt\n ctype = self.ctype\n elif isinstance(other, (Vars, VarSub, Affine)):\n if other.model.mtype != 'V':\n if self.ctype == 'E':\n raise SyntaxError('Incorrect affine expressions.')\n event_adapt = self.event_adapt\n ctype = self.ctype\n else:\n raise TypeError('Unknown expression type.')\n\n expr = super().__add__(other)\n\n return DecRoAffine(expr, event_adapt, ctype)\n\n def __sub__(self, other):\n\n return self.__add__(-other)\n\n def __mul__(self, other):\n\n expr = super().__mul__(other)\n\n return DecRoAffine(expr, self.event_adapt, self.ctype)\n\n def __rmul__(self, other):\n\n expr = super().__rmul__(other)\n\n return DecRoAffine(expr, self.event_adapt, self.ctype)\n\n def __matmul__(self, other):\n\n expr = super().__matmul__(other)\n\n return DecRoAffine(expr, self.event_adapt, self.ctype)\n\n def __rmatmul__(self, other):\n\n expr = super().__rmatmul__(other)\n\n return DecRoAffine(expr, self.event_adapt, self.ctype)\n\n def __le__(self, other):\n\n left = self - other\n\n return DecRoConstr(left, 0, left.event_adapt, left.ctype)\n\n def __ge__(self, other):\n\n left = other - self\n\n return DecRoConstr(left, 0, left.event_adapt, left.ctype)\n\n def __eq__(self, other):\n\n left = self - other\n\n return DecRoConstr(left, 1, left.event_adapt, left.ctype)\n\n @property\n def E(self):\n\n roaffine = RoAffine(self.raffine, self.affine, self.rand_model)\n return DecRoAffine(roaffine, self.event_adapt, ctype='E')\n\n\nclass DecLinConstr(LinConstr):\n\n def __init__(self, model, linear, const, sense,\n event_adapt=None, ctype='R'):\n\n super().__init__(model, linear, const, sense)\n self.event_adapt = event_adapt\n self.ctype = ctype\n self.ambset = None\n\n\nclass DecBounds(Bounds):\n\n def __init__(self, bounds, event_adapt=None):\n\n super().__init__(bounds.model, bounds.indices, bounds.values,\n bounds.btype)\n self.event_adapt = event_adapt\n\n\nclass DecCvxConstr(CvxConstr):\n\n def __init__(self, constr, event_adapt):\n\n super().__init__(constr.model, constr.affine_in,\n constr.affine_out, constr.xtype)\n self.event_adapt = event_adapt\n\n\nclass DecRoConstr(RoConstr):\n\n def __init__(self, roaffine, sense, event_adapt, ctype):\n\n super().__init__(roaffine, sense)\n\n self.event_adapt = event_adapt\n self.ctype = ctype\n self.ambset = None\n\n def forall(self, ambset):\n\n self.ambset = ambset\n\n return self\n\nclass DecRule:\n\n __array_priority__ = 102\n\n def __init__(self, model, shape=(1,), name=None,):\n\n self.model = model\n self.name = name\n self.fixed = model.dvar(shape, 'C')\n self.shape = self.fixed.shape\n self.size = np.prod(self.shape)\n self.depend = None\n self.roaffine = None\n self.var_coeff = None\n\n def __str__(self):\n\n suffix = 's' if np.prod(self.shape) > 1 else ''\n\n string = '' if self.name is None else self.name + ': '\n string += 'x'.join([str(size) for size in self.shape]) + ' '\n string += 'decision rule variable' + suffix\n\n return string\n\n def __repr__(self):\n\n return self.__str__()\n\n def reshape(self, shape):\n\n return self.to_affine().reshape(shape)\n\n def adapt(self, rvar, ldr_indices=None):\n\n if self.roaffine is not None:\n raise SyntaxError('Adaptation must be defined ' +\n 'before used in constraints')\n\n if self.depend is None:\n self.depend = np.zeros((self.size,\n self.model.sup_model.vars[-1].last),\n dtype=int)\n\n indices = rvar.get_ind()\n if ldr_indices is None:\n ldr_indices = np.arange(self.depend.shape[0], dtype=int)\n ldr_indices = ldr_indices.reshape((ldr_indices.size, 1))\n\n row_ind = (ldr_indices *\n np.ones(indices.shape, dtype=int)).flatten()\n col_ind = (np.ones(ldr_indices.shape, dtype=int) * indices).flatten()\n\n if self.depend[row_ind, col_ind].any():\n raise SyntaxError('Redefinition of adaptation is not allowed.')\n\n self.depend[ldr_indices, indices] = 1\n\n def to_affine(self):\n\n if self.roaffine is not None:\n return self.roaffine\n else:\n if self.depend is not None:\n num_ones = self.depend.sum()\n var_coeff = self.model.dvar(num_ones)\n self.var_coeff = var_coeff\n row_ind = np.where(self.depend.flatten() == 1)[0]\n col_ind = var_coeff.get_ind()\n num_rand = self.model.sup_model.vars[-1].last\n row = self.size * num_rand\n col = self.model.rc_model.vars[-1].last\n raffine_linear = csr_matrix((np.ones(num_ones),\n (row_ind, col_ind)),\n shape=(row, col))\n raffine = Affine(self.model.rc_model,\n raffine_linear,\n np.zeros((self.size, num_rand)))\n roaffine = RoAffine(raffine, np.zeros(self.shape),\n self.model.sup_model)\n self.roaffine = self.fixed + roaffine\n\n else:\n self.roaffine = self.fixed.to_affine()\n\n return self.roaffine\n\n def __getitem__(self, item):\n\n item_array = index_array(self.shape)\n indices = item_array[item]\n if not isinstance(indices, np.ndarray):\n indices = np.array([indices]).reshape((1, ) * indices.ndim)\n\n return DecRuleSub(self, indices, item)\n\n def __neg__(self):\n\n return - self.to_affine()\n\n def __add__(self, other):\n\n return self.to_affine().__add__(other)\n\n def __radd__(self, other):\n\n return self.__add__(other)\n\n def __sub__(self, other):\n\n return self.to_affine().__sub__(other)\n\n def __rsub__(self, other):\n\n return self.to_affine().__rsub__(other)\n\n def __mul__(self, other):\n\n check_numeric(other)\n\n return self.to_affine().__mul__(other)\n\n def __rmul__(self, other):\n\n check_numeric(other)\n\n return self.to_affine().__rmul__(other)\n\n def __matmul__(self, other):\n\n check_numeric(other)\n\n return self.to_affine().__matmul__(other)\n\n def __rmatmul__(self, other):\n\n check_numeric(other)\n\n return self.to_affine().__rmatmul__(other)\n\n def sum(self, axis=None):\n\n return self.to_affine().sum(axis)\n\n def __le__(self, other):\n\n return (self - other).__le__(0)\n\n def __ge__(self, other):\n\n return (other - self).__le__(0)\n\n def __eq__(self, other):\n\n return (self - other).__eq__(0)\n\n def get(self, rvar=None):\n\n if rvar is None:\n return self.fixed.get()\n else:\n if rvar.model.mtype != 'S':\n ValueError('The input is not a random variable.')\n ldr_coeff = np.ones((self.size,\n self.model.rc_model.vars[-1].last)) * np.NAN\n rand_ind = rvar.get_ind()\n row_ind, col_ind = np.where(self.depend == 1)\n ldr_coeff[row_ind, col_ind] = self.var_coeff.get()\n\n if rvar.to_affine().size == 1:\n return ldr_coeff[:, rand_ind].reshape(self.shape)\n else:\n rv_shape = rvar.to_affine().shape\n return ldr_coeff[:, rand_ind].reshape(self.shape + rv_shape)\n\n\nclass DecRuleSub:\n\n __array_priority__ = 105\n\n def __init__(self, dec_rule, indices, item):\n\n self.dec_rule = dec_rule\n self.shape = indices.shape\n self.indices = indices.flatten()\n self.item = item\n\n def adapt(self, rvar):\n\n self.dec_rule.adapt(rvar, self.indices)\n\n def to_affine(self):\n\n roaffine = self.dec_rule.to_affine()\n raffine = roaffine.raffine[self.indices, :]\n affine = roaffine.affine[self.item]\n\n return RoAffine(raffine, affine, self.dec_rule.model.sup_model)\n\n def __neg__(self):\n\n return - self.to_affine()\n\n def __add__(self, other):\n\n return self.to_affine().__add__(other)\n\n def __sub__(self, other):\n\n return self.to_affine().__sub__(other)\n\n def __rsub__(self, other):\n\n return self.to_affine().__rsub__(other)\n\n def __mul__(self, other):\n\n check_numeric(other)\n\n return self.to_affine().__mul__(other)\n\n def __rmul__(self, other):\n\n check_numeric(other)\n\n return self.to_affine().__rmul__(other)\n\n def __matmul__(self, other):\n\n check_numeric(other)\n\n return self.to_affine().__matmul__(other)\n\n def __rmatmul__(self, other):\n\n check_numeric(other)\n\n return self.to_affine().__rmatmul__(other)\n\n def sum(self, axis=None):\n\n return self.to_affine().sum(axis)\n\n def __le__(self, other):\n\n return (self - other).__le__(0)\n\n def __ge__(self, other):\n\n return (other - self).__le__(0)\n\n def __eq__(self, other):\n\n return (self - other).__eq__(0)\n\n\nclass LinProg:\n \"\"\"\n The LinProg class creates an object of linear program\n \"\"\"\n\n def __init__(self, linear, const, sense, vtype, ub, lb, obj=None):\n\n self.obj = obj\n self.linear = linear\n self.const = const\n self.sense = sense\n self.vtype = vtype\n self.ub = ub\n self.lb = lb\n\n def __repr__(self, header=True):\n\n linear = self.linear\n nc, nb, ni = (sum(self.vtype == 'C'),\n sum(self.vtype == 'B'),\n sum(self.vtype == 'I'))\n nineq, neq = sum(self.sense == 0), sum(self.sense == 1)\n nnz = self.linear.indptr[-1]\n\n if header:\n string = 'Linear program object:\\n'\n else:\n string = ''\n string += '=============================================\\n'\n string += 'Number of variables: {0}\\n'.format(linear.shape[1])\n string += 'Continuous/binaries/integers: {0}/{1}/{2}\\n'.format(nc,\n nb, ni)\n string += '---------------------------------------------\\n'\n string += 'Number of linear constraints: {0}\\n'.format(linear.shape[0])\n string += 'Inequalities/equalities: {0}/{1}\\n'.format(nineq, neq)\n string += 'Number of coefficients: {0}\\n'.format(nnz)\n\n return string\n\n def showlc(self):\n\n var_names = ['x{0}'.format(i)\n for i in range(1, self.linear.shape[1] + 1)]\n constr_names = ['LC{0}'.format(j)\n for j in range(1, self.linear.shape[0] + 1)]\n table = pd.DataFrame(self.linear.todense(), columns=var_names,\n index=constr_names)\n table['sense'] = ['==' if sense else '<=' for sense in self.sense]\n table['constant'] = self.const\n\n return table\n\n def solve(self, solver):\n\n return solver.solve(self)\n\n\nclass Solution:\n\n def __init__(self, objval, x, stats):\n\n self.objval = objval\n self.x = x\n self.stats = stats\n\n\nclass Scen:\n\n def __init__(self, ambset, series, pr):\n\n # super().__init__(data=series.values, index=series.index)\n self.ambset = ambset\n self.series = series\n self.p = pr\n\n def __str__(self):\n\n if isinstance(self.series, Sized):\n return 'Scenario indices: \\n' + self.series.__str__()\n else:\n return 'Scenario index: \\n' + self.series.__str__()\n\n def __repr__(self):\n\n return self.__str__()\n\n def __getitem__(self, indices):\n\n indices_p = self.series[indices]\n return Scen(self.ambset, self.series[indices], self.p[indices_p])\n\n @property\n def loc(self):\n\n return ScenLoc(self)\n\n @property\n def iloc(self):\n\n return ScenILoc(self)\n\n def suppset(self, *args):\n \"\"\"\n Specify the support set(s) of an ambiguity set.\n\n Parameters\n ----------\n args : tuple\n Constraints or collections of constraints as iterable type of\n objects, used for defining the feasible region of the support set.\n\n Notes\n -----\n RSOME leaves the support set unspecified if the input argument is\n an empty iterable object.\n \"\"\"\n\n args = flat(args)\n if len(args) == 0:\n return\n\n for arg in args:\n if arg.model is not self.ambset.model.sup_model:\n raise ValueError('Constraints are not for this support.')\n\n # for i in self.series:\n indices = (self.series if isinstance(self.series, pd.Series)\n else [self.series])\n for i in indices:\n self.ambset.sup_constr[i] = tuple(args)\n\n def exptset(self, *args):\n \"\"\"\n Specify the uncertainty set of the expected values of random\n variables for an ambiguity set.\n\n Parameters\n ----------\n args : tuple\n Constraints or collections of constraints as iterable type of\n objects, used for defining the feasible region of the uncertainty\n set of expectations.\n\n Notes\n -----\n RSOME leaves the uncertainty set of expectations unspecified if the\n input argument is an empty iterable object.\n \"\"\"\n\n args = flat(args)\n if len(args) == 0:\n return\n\n for arg in args:\n if arg.model is not self.ambset.model.exp_model:\n raise ValueError('Constraints are not defined for ' +\n 'expectation sets.')\n\n self.ambset.exp_constr.append(tuple(args))\n if not isinstance(self.series, Iterable):\n indices = [self.series]\n else:\n indices = self.series\n self.ambset.exp_constr_indices.append(indices)\n\n\nclass ScenLoc:\n\n def __init__(self, scens):\n\n self.scens = scens\n self.indices = []\n\n def __getitem__(self, indices):\n\n indices_s = self.scens.series.loc[indices]\n\n return Scen(self.scens.ambset, indices_s, self.scens.p[indices_s])\n\n\nclass ScenILoc:\n\n def __init__(self, scens):\n\n self.scens = scens\n self.indices = []\n\n def __getitem__(self, indices):\n\n indices_s = self.scens.series.iloc[indices]\n\n return Scen(self.scens.ambset, indices_s, self.scens.p[indices_s])\n"
] | [
[
"scipy.sparse.coo_matrix",
"numpy.minimum",
"pandas.Series",
"numpy.maximum",
"numpy.arange",
"numpy.tile",
"scipy.sparse.csr_matrix",
"numpy.ones",
"numpy.concatenate",
"numpy.sign",
"numpy.prod",
"numpy.array",
"numpy.zeros",
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
ebadkamil/nicos | [
"94cb4d172815919481f8c6ee686f21ebb76f2068"
] | [
"nicos/devices/datasinks/fits.py"
] | [
"# -*- coding: utf-8 -*-\n# *****************************************************************************\n# NICOS, the Networked Instrument Control System of the MLZ\n# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)\n#\n# This program is free software; you can redistribute it and/or modify it under\n# the terms of the GNU General Public License as published by the Free Software\n# Foundation; either version 2 of the License, or (at your option) any later\n# version.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n# details.\n#\n# You should have received a copy of the GNU General Public License along with\n# this program; if not, write to the Free Software Foundation, Inc.,\n# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n#\n# Module authors:\n# Alexander Lenz <[email protected]>\n#\n# *****************************************************************************\n\nfrom collections import OrderedDict\nfrom time import localtime, strftime, time as currenttime\n\nimport numpy\n\nfrom nicos.core import NicosError\nfrom nicos.core.params import Override\nfrom nicos.devices.datasinks.image import ImageFileReader, ImageSink, \\\n SingleFileSinkHandler\nfrom nicos.utils import toAscii\n\ntry:\n import astropy.io.fits as pyfits\nexcept ImportError:\n try:\n import pyfits\n except ImportError:\n pyfits = None\n\n\nclass FITSImageSinkHandler(SingleFileSinkHandler):\n\n filetype = 'fits'\n defer_file_creation = True\n accept_final_images_only = True\n\n def writeData(self, fp, data):\n # ensure numpy type\n npData = numpy.array(data)\n\n # create primary hdu from image data\n hdu = pyfits.PrimaryHDU(npData)\n\n # create fits header from nicos header and add entries to hdu\n self._buildHeader(self.dataset.metainfo, hdu)\n\n # write full fits file\n hdu.writeto(fp)\n\n def _buildHeader(self, info, hdu):\n\n finished = currenttime()\n header = {}\n\n for (dev, param), (_, strvalue, unit, _) in info.items():\n header['%s/%s' % (dev, param)] = ('%s %s' % (strvalue,\n unit)).strip()\n\n header = OrderedDict(\n [('begintime',\n strftime('%Y-%m-%d %H:%M:%S', localtime(self.dataset.started))),\n ('endtime',\n strftime('%Y-%m-%d %H:%M:%S', localtime(finished)))\n ] + sorted(header.items())\n )\n\n for key, value in header.items():\n # The FITS standard defines max 8 characters for a header key.\n # To make longer keys possible, we use the HIERARCH keyword\n # here (67 chars max).\n # To get a consistent looking header, add it to every key\n key = 'HIERARCH %s' % key\n\n # use only ascii characters and escapes if necessary.\n value = toAscii(str(value))\n\n # Determine maximum possible value length (key dependend).\n maxValLen = 63 - len(key)\n\n # Split the dataset into several header entries if necessary\n # (due to the limited length)\n splittedHeaderItems = [value[i:i + maxValLen]\n for i in range(0, len(value), maxValLen)]\n\n for item in splittedHeaderItems:\n hdu.header.append((key, item))\n\n\nclass FITSImageSink(ImageSink):\n \"\"\"Writes data to a FITS (Flexible image transport system) format file.\n\n NICOS headers are also written into the file using the standard FITS header\n facility, with HIERARCH type keys.\n\n Requires the pyfits library to be installed.\n \"\"\"\n\n parameter_overrides = {\n 'filenametemplate': Override(default=['%(pointcounter)08d.fits']),\n }\n\n handlerclass = FITSImageSinkHandler\n\n def doPreinit(self, _mode):\n # Stop creation of the FITSImageSink as it would make no sense\n # without pyfits.\n if pyfits is None:\n raise NicosError(self, 'pyfits module is not available. Check'\n ' if it is installed and in your PYTHONPATH')\n\n def isActiveForArray(self, arraydesc):\n return len(arraydesc.shape) == 2\n\n\nclass FITSFileReader(ImageFileReader):\n filetypes = [('fits', 'FITS File (*.fits)')]\n\n @classmethod\n def fromfile(cls, filename):\n hdu_list = pyfits.open(filename)\n return hdu_list[0].data\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
verypluming/SyGNS | [
"bc082193812e4b13c1486ccdfd1cad9acb25e507"
] | [
"scripts/evaluate.py"
] | [
"# -*- coding: utf-8 -*-\nimport pandas as pd\nfrom statistics import stdev\nimport argparse\nimport glob\n\nparser = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter)\nparser.add_argument(\"--outdir\", nargs='?', type=str, help=\"output dir\")\nparser.add_argument(\"--setting\", nargs='?', type=str, default=None, help=\"setting\")\nparser.add_argument(\"--format\", nargs='?', type=str, default=\"fol\", help=\"format\")\nargs = parser.parse_args()\n\ndef compute_f(match_num, test_num, gold_num):\n if test_num == 0 or gold_num == 0:\n return 0.00, 0.00, 0.00\n precision = round(float(match_num) / float(test_num), 2)\n recall = round(float(match_num) / float(gold_num), 2)\n if precision < 0.0 or precision > 1.0 or recall < 0.0 or recall > 1.0:\n raise ValueError(\"Precision and recall should never be outside (0.0-1.0), now {0} and {1}\".format(precision, recall))\n\n if (precision + recall) != 0:\n f_score = round(2 * precision * recall / (precision + recall), 2)\n return precision, recall, f_score\n else:\n return precision, recall, 0.00\n\ndef form_tags(a):\n fir = []\n sec = []\n for i, tmp in enumerate(a):\n if i%2 == 0:\n fir.append(tmp.replace(' ', ''))\n else:\n fir.append(tmp.replace(' ', ''))\n sec.append(tuple(fir))\n fir = []\n return sec\n\ndef select_elem(taga, tagb, pol=\"1\"):\n newtaga, newtagb, words = [], [], []\n for tmp in taga:\n if tmp[1] == pol:\n newtaga.append(tmp)\n words.append(tmp[0])\n for tmp in tagb:\n if tmp[0] in words:\n newtagb.append(tmp)\n return newtaga, newtagb\n\ndef phenomena(test, pheno):\n if pheno == \"adj\":\n return test.query('phenomena_tags.str.contains(\"adjective:yes\") and \\\n phenomena_tags.str.contains(\"adverb:no\") and \\\n phenomena_tags.str.contains(\"conjunction:no\") and \\\n phenomena_tags.str.contains(\"disjunction:no\") and \\\n phenomena_tags.str.contains(\"negation:no\")')\n elif pheno == \"adj_neg\":\n return test.query('phenomena_tags.str.contains(\"adjective:yes\") and \\\n phenomena_tags.str.contains(\"adverb:no\") and \\\n phenomena_tags.str.contains(\"conjunction:no\") and \\\n phenomena_tags.str.contains(\"disjunction:no\") and \\\n phenomena_tags.str.contains(\"negation:yes\")')\n elif pheno == \"adv\":\n return test.query('phenomena_tags.str.contains(\"adjective:no\") and \\\n phenomena_tags.str.contains(\"adverb:yes\") and \\\n phenomena_tags.str.contains(\"conjunction:no\") and \\\n phenomena_tags.str.contains(\"disjunction:no\") and \\\n phenomena_tags.str.contains(\"negation:no\")')\n elif pheno == \"adv_neg\":\n return test.query('phenomena_tags.str.contains(\"adjective:no\") and \\\n phenomena_tags.str.contains(\"adverb:yes\") and \\\n phenomena_tags.str.contains(\"conjunction:no\") and \\\n phenomena_tags.str.contains(\"disjunction:no\") and \\\n phenomena_tags.str.contains(\"negation:yes\")')\n elif pheno == \"conj_disj\":\n return test.query('phenomena_tags.str.contains(\"adjective:no\") and \\\n phenomena_tags.str.contains(\"adverb:no\") and \\\n phenomena_tags.str.contains(\"negation:no\")')\n elif pheno == \"conj_disj_neg\":\n return test.query('phenomena_tags.str.contains(\"adjective:no\") and \\\n phenomena_tags.str.contains(\"adverb:no\") and \\\n phenomena_tags.str.contains(\"negation:yes\")')\n\ndef main():\n tsvs = glob.glob(args.outdir+\"/prediction_eval[1-5].tsv\")\n phenos = [\"adj\", \"adj_neg\", \"adv\", \"adv_neg\", \"conj_disj\", \"conj_disj_neg\"]\n uniave, exiave, numave = [], [], []\n for pheno in phenos:\n print(f'phenomena: {pheno}')\n totave = []\n for tsv in tsvs:\n totacc = 0 \n tmptsv = pd.read_csv(tsv, sep=\"\\t\")\n etsv = phenomena(tmptsv, pheno)\n if args.format == \"fol\" or args.format == \"free\" or args.format == \"clf\":\n totacc = len(etsv[etsv['sentence_fol_gold'] == etsv['sentence_fol_pred']])/len(etsv)\n else:\n totacc = len(etsv[etsv['sentence'] == etsv['pred']])/len(etsv)\n totave.append(totacc)\n print(f'total ave: {sum(totave)/len(totave)*100:.1f}, stdev: {stdev(totave):.1f}')\n with open(args.outdir+\"/pheno.txt\", \"a\") as f:\n f.write(f'{sum(totave)/len(totave)*100:.1f}')\n f.write('\\n')\n for tsv in tsvs:\n uniacc, exiacc, numacc = 0, 0, 0\n etsv = pd.read_csv(tsv, sep=\"\\t\")\n uni = etsv.query('sentence.str.contains(\"every \") or sentence.str.startswith(\"all \") or sentence.str.contains(\" all \")')\n exi = etsv.query('sentence.str.contains(\"one \") or sentence.str.contains(\"a \")')\n num = etsv.query('sentence.str.contains(\"two \") or sentence.str.contains(\"three \")')\n if args.format == \"fol\" or args.format == \"free\" or args.format == \"clf\":\n uniacc = len(uni[uni['sentence_fol_gold'] == uni['sentence_fol_pred']])/len(uni)\n exiacc = len(exi[exi['sentence_fol_gold'] == exi['sentence_fol_pred']])/len(exi)\n numacc = len(num[num['sentence_fol_gold'] == num['sentence_fol_pred']])/len(num)\n else:\n uniacc = len(uni[uni['sentence'] == uni['pred']])/len(uni)\n exiacc = len(exi[exi['sentence'] == exi['pred']])/len(exi)\n numacc = len(num[num['sentence'] == num['pred']])/len(num)\n uniave.append(uniacc)\n exiave.append(exiacc)\n numave.append(numacc)\n print(f'existential ave: {sum(exiave)/len(exiave)*100:.1f}, stdev: {stdev(exiave):.1f}')\n print(f'numeral ave: {sum(numave)/len(numave)*100:.1f}, stdev: {stdev(numave):.1f}')\n print(f'universal ave: {sum(uniave)/len(uniave)*100:.1f}, stdev: {stdev(uniave):.1f}')\n with open(args.outdir+\"/quant.txt\", \"w\") as f:\n f.write(f'{sum(exiave)/len(exiave)*100:.1f}')\n f.write('\\n')\n f.write(f'{sum(numave)/len(numave)*100:.1f}')\n f.write('\\n')\n f.write(f'{sum(uniave)/len(uniave)*100:.1f}')\n f.write('\\n')\n\n\n if args.setting == \"depth\":\n tsvs = glob.glob(outdir+\"/\"+setting+\"/prediction_eval[1-5].tsv\")\n for i in range(2,5):\n totave = []\n print(i)\n for tsv in tsvs:\n print(tsv)\n tmp = pd.read_csv(tsv, sep=\"\\t\")\n etsv = tmp.query(\"depth==@i\")\n if args.format == \"fol\" or args.format == \"free\" or args.format == \"clf\":\n totacc = len(etsv[etsv['sentence_fol_gold'] == etsv['sentence_fol_pred']])/len(etsv)\n else:\n totacc = len(etsv[etsv['sentence'] == etsv['pred']])/len(etsv)\n totave.append(totacc)\n print(f'total ave: {sum(totave)/len(totave)*100:.2f}, stdev: {stdev(totave):.2f}')\n\n if setting == \"polarity\":\n tsvs = glob.glob(outdir+\"/\"+setting+\"/prediction_eval[1-5]_polacc.tsv\")\n aveprec, averec, avef1 = [], [], []\n for tsv in tsvs:\n tprec, trec, tf1 = [], [], []\n for idx, row in tsv.iterrows():\n a = re.sub(\"\\[|\\]|\\(|\\)|\\'\", \"\", row['gold']).split(\",\")\n taga = form_tags(a)\n b = re.sub(\"\\[|\\]|\\(|\\)|\\'\", \"\", row['pred']).split(\",\")\n tagb = form_tags(b)\n taga, tagb = select_elem(taga, tagb, \"0\")\n if len(taga) == 0:\n continue\n pmatch = set(tagb) & set(taga)\n prec, rec, f1 = compute_f(len(pmatch), len(tagb), len(taga))\n tprec.append(prec)\n trec.append(rec)\n tf1.append(f1)\n aprec = sum(tprec)*100 / len(tprec)\n arec = sum(trec)*100 / len(trec)\n af1 = sum(tf1)*100 / len(tf1)\n aveprec.append(aprec)\n averec.append(arec)\n avef1.append(af1)\n print(f'{sum(aveprec)/len(aveprec)*100:.2f}, {sum(averec)/len(averec)*100:.2f}, {sum(avef1)/len(avef1)*100:.2f}')\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
yaicv/predict-solar-power-generation | [
"c8d09cd1ee5ef239bf3470dd450e5b4f0b843f31"
] | [
"sunlight-main/v1.py"
] | [
"import pandas as pd\nimport numpy as np\nimport os\nimport glob\nimport random\nimport math\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\ntrain = pd.read_csv('./data/train/train.csv')\nsubmission = pd.read_csv('./data/sample_submission.csv')\n\ndef preprocess_data(data, is_train=True):\n \n temp = data.copy()\n temp = temp[['Hour', 'TARGET', 'DHI','DNI','WS', 'RH', 'T']]\n temp = temp.assign(GHI=lambda x: x['DHI'] + x['DNI'] * np.cos(((180 * (x['Hour']+1) / 24) - 90)/180*np.pi))\n temp = temp.assign(WP=lambda y: (0.7284+ 0.003492*y['T'] + 0.1731*y['WS']- 0.000148*y['T']*y['T'] - 0.0007319*y['T']*y['WS']-0.01289*y['WS']*y['WS']))\n temp = temp[['Hour', 'TARGET','GHI','DHI','DNI','RH','T','WS','WP']]\n \n if is_train==True:\n temp['Target1'] = temp['TARGET'].shift(-48).fillna(method='ffill')\n temp['Target2'] = temp['TARGET'].shift(-48*2).fillna(method='ffill')\n return temp.iloc[:-96]\n\n elif is_train==False: \n return temp.iloc[-48:, :]\n\ndf_train = preprocess_data(train)\ntest = []\n\nfor i in range(81):\n file_path = './data/test/' + str(i) + '.csv'\n temp = pd.read_csv(file_path)\n temp = preprocess_data(temp, is_train=False).iloc[-48:]\n test.append(temp)\n\nX_test = pd.concat(test)\n\nfrom sklearn.model_selection import train_test_split\nX_train_1, X_valid_1, Y_train_1, Y_valid_1 = train_test_split(df_train.iloc[:, :-2], df_train.iloc[:, -2], test_size=0.3, random_state=0)\nX_train_2, X_valid_2, Y_train_2, Y_valid_2 = train_test_split(df_train.iloc[:, :-2], df_train.iloc[:, -1], test_size=0.3, random_state=0)\n\nquantiles = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\n\nfrom lightgbm import LGBMRegressor\n\nparams = {\n 'objective': 'quantile',\n 'metric': 'quantile',\n #'max_depth': -1,\n #'num_leaves': 144,\n #'num_iterations' : 1000,\n 'learning_rate': 0.01,\n 'n_estimators': 10000,\n #'min_data_in_leaf':600,\n 'boosting_type': 'dart'\n}\n\n# Get the model and the predictions in (a) - (b)\ndef LGBM(q, X_train, Y_train, X_valid, Y_valid, X_test):\n # (a) Modeling \n model = LGBMRegressor(alpha=q, bagging_fraction=0.7, subsample=0.7,**params) \n \n model.fit(X_train, Y_train, eval_metric = ['quantile'], \n eval_set=[(X_valid, Y_valid)], early_stopping_rounds=300,verbose=300)\n\n # (b) Predictions\n pred = pd.Series(model.predict(X_test).round(2))\n return pred, model\n\ndef train_data(X_train, Y_train, X_valid, Y_valid, X_test):\n \n LGBM_models=[]\n LGBM_actual_pred = pd.DataFrame()\n\n for q in quantiles:\n print(q)\n pred , model = LGBM(q, X_train, Y_train, X_valid, Y_valid, X_test)\n LGBM_models.append(model)\n LGBM_actual_pred = pd.concat([LGBM_actual_pred,pred],axis=1)\n\n LGBM_actual_pred.columns=quantiles\n \n return LGBM_models, LGBM_actual_pred\n\nmodels_1, results_1 = train_data(X_train_1, Y_train_1, X_valid_1, Y_valid_1, X_test)\nmodels_2, results_2 = train_data(X_train_2, Y_train_2, X_valid_2, Y_valid_2, X_test)\n\nsubmission.loc[submission.id.str.contains(\"Day7\"), \"q_0.1\":] = results_1.sort_index().values\nsubmission.loc[submission.id.str.contains(\"Day8\"), \"q_0.1\":] = results_2.sort_index().values\n\nsubmission.to_csv('./data/submission.csv', index=False)"
] | [
[
"pandas.concat",
"pandas.read_csv",
"numpy.cos",
"sklearn.model_selection.train_test_split",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
qkaren/texar | [
"38bbb70ea9d389e3e2c092d213389e9c6b99b824"
] | [
"examples/chat/utils/preprocess.py"
] | [
"# Copyright 2018 The Texar 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\"\"\"\npreprocessing text data. Generally it's to generate plain text vocab file,\ntruncate sequence by length, generate the preprocessed dataset.\n\"\"\"\nfrom __future__ import unicode_literals\nimport collections\nimport re\nimport json\nimport os\nimport numpy as np\nimport pickle\nimport argparse\nfrom io import open\n#pylint:disable=invalid-name\n\nsplit_pattern = re.compile(r'([.,!?\"\\':;)(])')\ndigit_pattern = re.compile(r'\\d')\nSpecial_Seq = collections.namedtuple('Special_Seq', \\\n ['PAD', 'BOS', 'EOS', 'UNK'])\nVocab_Pad = Special_Seq(PAD=0, BOS=1, EOS=2, UNK=3)\n\ndef split_sentence(s, tok=False):\n \"\"\"split sentence with some segmentation rules.\"\"\"\n if tok:\n s = s.lower()\n s = s.replace('\\u2019', \"'\")\n s = digit_pattern.sub('0', s)\n words = []\n for word in s.split():\n if tok:\n words.extend(split_pattern.split(word))\n else:\n words.append(word)\n words = [w for w in words if w]\n return words\n\n\ndef open_file(path):\n \"\"\"more robust open function\"\"\"\n return open(path, encoding='utf-8')\n\ndef read_file(path, tok=False):\n \"\"\"a generator to generate each line of file.\"\"\"\n with open_file(path) as f:\n for line in f.readlines():\n words = split_sentence(line.strip(), tok)\n yield words\n\n\ndef count_words(path, max_vocab_size=40000, tok=False):\n \"\"\"count all words in the corpus and output a counter\"\"\"\n counts = collections.Counter()\n for words in read_file(path, tok):\n for word in words:\n counts[word] += 1\n\n vocab = [word for (word, _) in counts.most_common(max_vocab_size)]\n return vocab\n\ndef count_words_multi(paths, max_vocab_size=40000, tok=False):\n \"\"\"count all words in the corpus and output a counter\"\"\"\n counts = collections.Counter()\n\n for path in paths:\n for words in read_file(path, tok):\n for word in words:\n counts[word] += 1\n\n vocab = [word for (word, _) in counts.most_common(max_vocab_size)]\n return vocab\n\ndef make_array(word_id, words):\n \"\"\"generate id numpy array from plain text words.\"\"\"\n ids = [word_id.get(word, Vocab_Pad.UNK) for word in words]\n return np.array(ids, 'i')\n\ndef make_dataset(path, w2id, tok=False):\n \"\"\"generate dataset.\"\"\"\n dataset, npy_dataset = [], []\n token_count, unknown_count = 0, 0\n for words in read_file(path, tok):\n array = make_array(w2id, words)\n npy_dataset.append(array)\n dataset.append(words)\n token_count += array.size\n unknown_count += (array == Vocab_Pad.UNK).sum()\n print('# of tokens:{}'.format(token_count))\n print('# of unknown {} {:.2}'.format(unknown_count,\\\n 100. * unknown_count / token_count))\n return dataset, npy_dataset\n\ndef get_preprocess_args():\n \"\"\"Data preprocessing options.\"\"\"\n class Config(): pass\n config = Config()\n parser = argparse.ArgumentParser(description='Preprocessing Options')\n parser.add_argument('--source_vocab', type=int, default=40000,\n help='Vocabulary size of source language')\n parser.add_argument('--target_vocab', type=int, default=40000,\n help='Vocabulary size of target language')\n parser.add_argument('--fact_vocab', type=int, default=40000,\n help='Vocabulary size of fact language')\n parser.add_argument('--tok', dest='tok', action='store_true',\n help='tokenized and lowercased')\n parser.set_defaults(tok=False)\n parser.add_argument('--max_seq_length', type=int, default=70)\n parser.add_argument('--pre_encoding', type=str, default='spm')\n parser.add_argument('--src', type=str, default='en')\n parser.add_argument('--tgt', type=str, default='vi')\n parser.add_argument('--fact', type=str, default='fact')\n parser.add_argument('--input_dir', '-i', type=str, \\\n default='./data/en_vi/data/', help='Input directory')\n parser.add_argument('--save_data', type=str, default='preprocess', \\\n help='Output file for the prepared data')\n parser.parse_args(namespace=config)\n\n #keep consistent with original implementation\n #pylint:disable=attribute-defined-outside-init\n config.input = config.input_dir\n config.source_train = 'train.' + config.src\n config.target_train = 'train.' + config.tgt\n config.fact_train = 'train.' + config.fact\n config.source_valid = 'valid.' + config.src\n config.target_valid = 'valid.' + config.tgt\n config.fact_valid = 'valid.' + config.fact\n config.source_test = 'test.'+ config.src\n config.target_test = 'test.' + config.tgt\n config.fact_test = 'test.' + config.fact\n return config\n\nif __name__ == \"__main__\":\n args = get_preprocess_args()\n\n print(json.dumps(args.__dict__, indent=4))\n\n #pylint:disable=no-member\n # Vocab Construction\n source_path = os.path.join(args.input_dir, args.source_train)\n target_path = os.path.join(args.input_dir, args.target_train)\n fact_path = os.path.join(args.input_dir, args.fact_train)\n\n #src_cntr = count_words(source_path, args.source_vocab, args.tok)\n #trg_cntr = count_words(target_path, args.target_vocab, args.tok)\n #fact_cntr = count_words(fact_path, args.fact_vocab, args.tok)\n #all_words = sorted(list(set(src_cntr + trg_cntr + fact_cntr)))\n all_cntr = count_words_multi([source_path, target_path, fact_path], args.source_vocab, args.tok)\n all_words = sorted(list(set(all_cntr)))\n\n vocab = ['<PAD>', '<BOS>', '<EOS>', '<UNK>'] + all_words\n\n w2id = {word: index for index, word in enumerate(vocab)}\n\n # Train Dataset\n source_data, source_npy = make_dataset(source_path, w2id, args.tok)\n target_data, target_npy = make_dataset(target_path, w2id, args.tok)\n fact_data, fact_npy = make_dataset(fact_path, w2id, args.tok)\n assert len(source_data) == len(target_data)\n assert len(source_data) == len(fact_data)\n\n train_data = [(s, t, f) for s, t, f in zip(source_data, target_data, fact_data)\n if s #and len(s) < args.max_seq_length\n and t #and len(t) < args.max_seq_length\n and f\n ] # TODO(1013): Do not filter\n train_npy = [(s, t, f) for s, t, f in zip(source_npy, target_npy, fact_npy)\n if len(s) > 0 #and len(s) < args.max_seq_length\n and len(t) > 0 #and len(t) < args.max_seq_length\n and len(f) > 0\n ] # TODO(1013): Do not filter\n assert len(train_data) == len(train_npy)\n\n # Display corpus statistics\n print(\"Vocab: {} with special tokens\".format(len(vocab)))\n print('Original training data size: %d' % len(source_data))\n print('Filtered training data size: %d' % len(train_data))\n\n # Valid Dataset\n source_path = os.path.join(args.input_dir, args.source_valid)\n source_data, source_npy = make_dataset(source_path, w2id, args.tok)\n target_path = os.path.join(args.input_dir, args.target_valid)\n target_data, target_npy = make_dataset(target_path, w2id, args.tok)\n fact_path = os.path.join(args.input_dir, args.fact_valid)\n fact_data, fact_npy = make_dataset(fact_path, w2id, args.tok)\n assert len(source_data) == len(target_data)\n assert len(source_data) == len(fact_data)\n\n valid_data = [(s, t, f) for s, t, f in zip(source_data, target_data, fact_data)\n if s and t and f]\n valid_npy = [(s, t, f) for s, t, f in zip(source_npy, target_npy, fact_npy)\n if len(s) > 0 and len(t) > 0 and len(f) > 0]\n assert len(valid_data) == len(valid_npy)\n print('Original dev data size: %d' % len(source_data))\n print('Filtered dev data size: %d' % len(valid_data))\n\n # Test Dataset\n source_path = os.path.join(args.input_dir, args.source_test)\n source_data, source_npy = make_dataset(source_path, w2id, args.tok)\n target_path = os.path.realpath(\n os.path.join(args.input_dir, args.target_test))\n target_data, target_npy = make_dataset(target_path, w2id, args.tok)\n fact_path = os.path.join(args.input_dir, args.fact_test)\n fact_data, fact_npy = make_dataset(fact_path, w2id, args.tok)\n assert len(source_data) == len(target_data)\n assert len(source_data) == len(fact_data)\n test_data = [(s, t, f) for s, t, f in zip(source_data, target_data, fact_data)\n if s and t and f]\n test_npy = [(s, t, f) for s, t, f in zip(source_npy, target_npy, fact_npy)\n if len(s)>0 and len(t)>0 and len(f)>0]\n print('Original test data size: %d' % len(source_data))\n print('Filtered test data size: %d' % len(test_data))\n id2w = {i: w for w, i in w2id.items()}\n\n # Save the dataset to numpy files\n train_src_output = os.path.join(args.input_dir, \\\n args.save_data + 'train.' + args.src+ '.txt')\n train_tgt_output = os.path.join(args.input_dir, \\\n args.save_data + 'train.' + args.tgt + '.txt')\n train_fact_output = os.path.join(args.input_dir, \\\n args.save_data + 'train.' + args.fact + '.txt')\n dev_src_output = os.path.join(args.input_dir, \\\n args.save_data + 'dev.' + args.src+ '.txt')\n dev_tgt_output = os.path.join(args.input_dir, \\\n args.save_data + 'dev.' + args.tgt+ '.txt')\n dev_fact_output = os.path.join(args.input_dir, \\\n args.save_data + 'dev.' + args.fact+ '.txt')\n test_src_output = os.path.join(args.input_dir, \\\n args.save_data + 'test.' + args.src+ '.txt')\n test_tgt_output = os.path.join(args.input_dir, \\\n args.save_data + 'test.' + args.tgt + '.txt')\n test_fact_output = os.path.join(args.input_dir, \\\n args.save_data + 'test.' + args.fact + '.txt')\n\n np.save(os.path.join(args.input, args.save_data + 'train.npy'),\n train_npy)\n np.save(os.path.join(args.input, args.save_data + 'valid.npy'),\n valid_npy)\n np.save(os.path.join(args.input, args.save_data + 'test.npy'),\n test_npy)\n with open(os.path.join(args.input, args.save_data + 'vocab.pickle'), 'wb')\\\n as f:\n pickle.dump(id2w, f, protocol=pickle.HIGHEST_PROTOCOL)\n\n with open(train_src_output, 'w+', encoding='utf-8') as fsrc, \\\n open(train_tgt_output, 'w+', encoding='utf-8') as ftgt, \\\n open(train_fact_output, 'w+', encoding='utf-8') as ffact:\n for words in train_data:\n fsrc.write('{}\\n'.format(' '.join(words[0])))\n ftgt.write('{}\\n'.format(' '.join(words[1])))\n ffact.write('{}\\n'.format(' '.join(words[2])))\n with open(dev_src_output, 'w+', encoding='utf-8') as fsrc, \\\n open(dev_tgt_output, 'w+', encoding='utf-8') as ftgt, \\\n open(dev_fact_output, 'w+', encoding='utf-8') as ffact:\n for words in valid_data:\n fsrc.write('{}\\n'.format(' '.join(words[0])))\n ftgt.write('{}\\n'.format(' '.join(words[1])))\n ffact.write('{}\\n'.format(' '.join(words[2])))\n with open(test_src_output, 'w+', encoding='utf-8') as fsrc, \\\n open(test_tgt_output, 'w+', encoding='utf-8') as ftgt, \\\n open(test_fact_output, 'w+', encoding='utf-8') as ffact:\n for words in test_data:\n fsrc.write('{}\\n'.format(' '.join(words[0])))\n ftgt.write('{}\\n'.format(' '.join(words[1])))\n ffact.write('{}\\n'.format(' '.join(words[2])))\n with open(os.path.join(args.input_dir, \\\n args.save_data + args.pre_encoding + '.vocab.text'), 'w+', encoding='utf-8') as f:\n max_size = len(id2w)\n for idx in range(4, max_size):\n f.write('{}\\n'.format(id2w[idx]))\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Abhinav-Patidar/datasciencecoursera | [
"5802881a6fbad52924f42c09973a99db5239a54b"
] | [
"detect_recognize.py"
] | [
"import dlib\nfrom skimage import io, transform\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport glob\nimport openface\nimport pickle \nimport os\nimport sys\nimport argparse\nimport time\n\nfrom sklearn.svm import SVC\nfrom sklearn.preprocessing import LabelEncoder\n\nface_detector = dlib.get_frontal_face_detector()\nface_encoder = dlib.face_recognition_model_v1('./model/dlib_face_recognition_resnet_model_v1.dat')\nface_pose_predictor = dlib.shape_predictor('./model/shape_predictor_68_face_landmarks.dat')\n\ndef get_detected_faces(filename):\n \"\"\"\n Detect faces in a picture using HOG\n :param filename: picture filename\n :return: picture numpy array, face detector object with detected faces\n \"\"\"\n image = cv2.imread(filename)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n return image, face_detector(image, 1)\n\ndef get_face_encoding(image, detected_face):\n \"\"\"\n Encode face into 128 measurements using a neural net\n :param image: picture numpy array\n :param detected_face: face detector object with one detected face\n :return: measurement (128,) numpy array \n \"\"\"\n pose_landmarks = face_pose_predictor(image, detected_face)\n face_encoding = face_encoder.compute_face_descriptor(image, pose_landmarks, 1)\n return np.array(face_encoding)\n\ndef training(people):\n \"\"\"\n Training our classifier (Linear SVC). Saving model using pickle.\n We need to have only one person/face per picture.\n :param people: people to classify and recognize\n \"\"\"\n # parsing labels and reprensations\n df = pd.DataFrame()\n for p in people:\n l = []\n for filename in glob.glob('./data/%s/*' % p):\n image, face_detect = get_detected_faces(filename)\n face_encoding = get_face_encoding(image, face_detect[0])\n l.append(np.append(face_encoding, [p]))\n temp = pd.DataFrame(np.array(l))\n df = pd.concat([df, temp])\n df.reset_index(drop=True, inplace=True)\n\n # converting labels into int\n le = LabelEncoder()\n y = le.fit_transform(df[128])\n print(\"Training for {} classes.\".format(len(le.classes_)))\n X = df.drop(128, axis=1)\n print(\"Training with {} pictures.\".format(len(X)))\n\n # training\n clf = SVC(C=1, kernel='linear', probability=True)\n clf.fit(X, y)\n\n # dumping model\n fName = \"./classifier.pkl\"\n print(\"Saving classifier to '{}'\".format(fName))\n with open(fName, 'wb') as f:\n pickle.dump((le, clf), f)\n\ndef predict(filename, le=None, clf=None, verbose=False):\n \"\"\"\n Detect and recognize a face using a trained classifier.\n :param filename: picture filename\n :param le:\n :paral clf:\n :param verbose:\n :return: picture with bounding boxes and prediction\n \"\"\"\n if not le and not clf:\n with open(\"./classifier.pkl\", 'rb') as f:\n (le, clf) = pickle.load(f)\n image, detected_faces = get_detected_faces(filename)\n prediction = []\n # Verbose for debugging\n if verbose:\n print('{} faces detected.'.format(len(detected_faces)))\n img = np.copy(image)\n font = cv2.FONT_HERSHEY_SIMPLEX\n for face_detect in detected_faces:\n # draw bounding boxes\n cv2.rectangle(img, (face_detect.left(), face_detect.top()), \n (face_detect.right(), face_detect.bottom()), (255, 0, 0), 2)\n start_time = time.time()\n # predict each face\n p = clf.predict_proba(get_face_encoding(image, face_detect).reshape(1, 128))\n # throwing away prediction with low confidence\n a = np.sort(p[0])[::-1]\n if a[0]-a[1] > 0.5:\n y_pred = le.inverse_transform(np.argmax(p))\n prediction.append([y_pred, (face_detect.left(), face_detect.top()), \n (face_detect.right(), face_detect.bottom())])\n else:\n y_pred = 'unknown'\n # Verbose for debugging\n if verbose:\n print('\\n'.join(['%s : %.3f' % (k[0], k[1]) for k in list(zip(map(le.inverse_transform, \n np.argsort(p[0])), \n np.sort(p[0])))[::-1]]))\n print('Prediction took {:.2f}s'.format(time.time()-start_time))\n \n cv2.putText(img, y_pred, (face_detect.left(), face_detect.top()-5), font, np.max(img.shape[:2])/1800, (255, 0, 0))\n return img, prediction\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('mode', type=str, help='train or predict')\n parser.add_argument('--training_data',\n type=str,\n help=\"Path to training data folder.\",\n default='./data/')\n parser.add_argument('--testing_data',\n type=str,\n help=\"Path to test data folder.\",\n default='./test/')\n\n args = parser.parse_args()\n people = os.listdir(args.training_data)\n print('{} people will be classified.'.format(len(people)))\n if args.mode == 'train':\n training(people)\n elif args.mode == 'test':\n with open(\"./classifier.pkl\", 'rb') as f:\n (le, clf) = pickle.load(f)\n for i, f in enumerate(glob.glob(args.testing_data)):\n img, _ = predict(f, le, clf)\n cv2.imwrite(args.testing_data + 'test_{}.jpg'.format(i), img)\n\n"
] | [
[
"pandas.concat",
"pandas.DataFrame",
"numpy.sort",
"numpy.max",
"numpy.copy",
"numpy.append",
"numpy.argmax",
"sklearn.svm.SVC",
"numpy.argsort",
"numpy.array",
"sklearn.preprocessing.LabelEncoder"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
stacktracehq/scispacy | [
"81a19bf20520a63dea444787fad6dec4238a7adf"
] | [
"scripts/linking.py"
] | [
"\"\"\"\nLinking using char-n-gram with approximate nearest neighbors.\n\"\"\"\nimport os\nimport os.path\nimport sys\nsys.path.insert(0, os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir))))\nfrom typing import List, Dict, Tuple, NamedTuple, Any, Set\nimport json\nimport argparse\nimport datetime\nfrom collections import defaultdict\nfrom tqdm import tqdm\nimport scipy\nimport numpy as np\nfrom joblib import dump, load\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.base import ClassifierMixin\nimport nmslib\nfrom nmslib.dist import FloatIndex\nimport spacy\nfrom spacy.tokens import Span\nfrom spacy.language import Language\nfrom scispacy.abbreviation import AbbreviationDetector\nfrom scispacy import data_util\n\ndef load_umls_kb(umls_path: str) -> List[Dict]:\n \"\"\"\n Reads a UMLS json release and return it as a list of concepts.\n Each concept is a dictionary.\n \"\"\"\n with open(umls_path) as f:\n print(f'Loading umls concepts from {umls_path}')\n umls_concept_list = json.load(f)\n print(f'Number of umls concepts: {len(umls_concept_list)}')\n return umls_concept_list\n\n\nclass MentionCandidate(NamedTuple):\n concept_id: str\n distances: List[float]\n aliases: List[str]\n\nclass CandidateGenerator:\n\n \"\"\"\n A candidate generator for entity linking to the Unified Medical Language System (UMLS).\n\n It uses a sklearn.TfidfVectorizer to embed mention text into a sparse embedding of character 3-grams.\n These are then compared via cosine distance in a pre-indexed approximate nearest neighbours index of\n a subset of all entities and aliases in UMLS.\n\n Once the K nearest neighbours have been retrieved, they are canonicalized to their UMLS canonical ids.\n This step is required because the index also includes entity aliases, which map to a particular canonical\n entity. This point is important for two reasons:\n\n 1. K nearest neighbours will return a list of Y possible neighbours, where Y < K, because the entity ids\n are canonicalized.\n\n 2. A single string may be an alias for multiple canonical entities. For example, \"Jefferson County\" may be an\n alias for both the canonical ids \"Jefferson County, Iowa\" and \"Jefferson County, Texas\". These are completely\n valid and important aliases to include, but it means that using the candidate generator to implement a naive\n k-nn baseline linker results in very poor performance, because there are multiple entities for some strings\n which have an exact char3-gram match, as these entities contain the same alias string. This situation results\n in multiple entities returned with a distance of 0.0, because they exactly match an alias, making a k-nn baseline\n effectively a random choice between these candidates. However, this doesn't matter if you have a classifier\n on top of the candidate generator, as is intended!\n\n Parameters\n ----------\n ann_index: FloatIndex\n An nmslib approximate nearest neighbours index.\n tfidf_vectorizer: TfidfVectorizer\n The vectorizer used to encode mentions.\n ann_concept_aliases_list: List[str]\n A list of strings, mapping the indices used in the ann_index to canonical UMLS ids.\n mention_to_concept: Dict[str, Set[str]], required.\n A mapping from aliases to canonical ids that they are aliases of.\n verbose: bool\n Setting to true will print extra information about the generated candidates\n\n \"\"\"\n def __init__(self,\n ann_index: FloatIndex,\n tfidf_vectorizer: TfidfVectorizer,\n ann_concept_aliases_list: List[str],\n mention_to_concept: Dict[str, Set[str]],\n verbose: bool = True) -> None:\n\n self.ann_index = ann_index\n self.vectorizer = tfidf_vectorizer\n self.ann_concept_aliases_list = ann_concept_aliases_list\n self.mention_to_concept = mention_to_concept\n self.verbose = verbose\n\n\n def nmslib_knn_with_zero_vectors(self, vectors: np.ndarray, k: int) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n ann_index.knnQueryBatch crashes if any of the vectors is all zeros.\n This function is a wrapper around `ann_index.knnQueryBatch` that solves this problem. It works as follows:\n - remove empty vectors from `vectors`.\n - call `ann_index.knnQueryBatch` with the non-empty vectors only. This returns `neighbors`,\n a list of list of neighbors. `len(neighbors)` equals the length of the non-empty vectors.\n - extend the list `neighbors` with `None`s in place of empty vectors.\n - return the extended list of neighbors and distances.\n \"\"\"\n empty_vectors_boolean_flags = np.array(vectors.sum(axis=1) != 0).reshape(-1,)\n empty_vectors_count = vectors.shape[0] - sum(empty_vectors_boolean_flags)\n if self.verbose:\n print(f'Number of empty vectors: {empty_vectors_count}')\n\n # remove empty vectors before calling `ann_index.knnQueryBatch`\n vectors = vectors[empty_vectors_boolean_flags]\n\n # call `knnQueryBatch` to get neighbors\n original_neighbours = self.ann_index.knnQueryBatch(vectors, k=k)\n neighbors, distances = zip(*[(x[0].tolist(), x[1].tolist()) for x in original_neighbours])\n neighbors = list(neighbors)\n distances = list(distances)\n # all an empty list in place for each empty vector to make sure len(extended_neighbors) == len(vectors)\n\n # init extended_neighbors with a list of Nones\n extended_neighbors = np.empty((len(empty_vectors_boolean_flags),), dtype=object)\n extended_distances = np.empty((len(empty_vectors_boolean_flags),), dtype=object)\n\n # neighbors need to be convected to an np.array of objects instead of ndarray of dimensions len(vectors)xk\n # Solution: add a row to `neighbors` with any length other than k. This way, calling np.array(neighbors)\n # returns an np.array of objects\n neighbors.append([])\n distances.append([])\n # interleave `neighbors` and Nones in `extended_neighbors`\n extended_neighbors[empty_vectors_boolean_flags] = np.array(neighbors)[:-1]\n extended_distances[empty_vectors_boolean_flags] = np.array(distances)[:-1]\n\n return extended_neighbors, extended_distances\n\n def generate_candidates(self, mention_texts: List[str], k: int) -> List[Dict[str, List[int]]]:\n \"\"\"\n Given a list of mention texts, returns a list of candidate neighbors.\n\n NOTE: Because we include canonical name aliases in the ann index, the list\n of candidates returned will not necessarily be of length k for each candidate,\n because we then map these to canonical ids only.\n # TODO Mark: We should be able to use this signal somehow, maybe a voting system?\n args:\n mention_texts: list of mention texts\n k: number of ann neighbors\n\n returns:\n A list of dictionaries, each containing the mapping from umls concept ids -> a list of\n the cosine distances between them. Note that these are lists for each concept id, because\n the index contains aliases which are canonicalized, so multiple values may map to the same\n canonical id.\n \"\"\"\n if self.verbose:\n print(f'Generating candidates for {len(mention_texts)} mentions')\n tfidfs = self.vectorizer.transform(mention_texts)\n start_time = datetime.datetime.now()\n\n # `ann_index.knnQueryBatch` crashes if one of the vectors is all zeros.\n # `nmslib_knn_with_zero_vectors` is a wrapper around `ann_index.knnQueryBatch` that addresses this issue.\n batch_neighbors, batch_distances = self.nmslib_knn_with_zero_vectors(tfidfs, k)\n end_time = datetime.datetime.now()\n total_time = end_time - start_time\n if self.verbose:\n print(f'Finding neighbors took {total_time.total_seconds()} seconds')\n neighbors_by_concept_ids = []\n for neighbors, distances in zip(batch_neighbors, batch_distances):\n if neighbors is None:\n neighbors = []\n\n if distances is None:\n distances = []\n predicted_umls_concept_ids = defaultdict(list)\n for n, d in zip(neighbors, distances):\n mention = self.ann_concept_aliases_list[n]\n concepts_for_mention = self.mention_to_concept[mention]\n for concept_id in concepts_for_mention:\n predicted_umls_concept_ids[concept_id].append((mention, d))\n\n neighbors_by_concept_ids.append({**predicted_umls_concept_ids})\n return neighbors_by_concept_ids\n\n\nclass Linker:\n \"\"\"\n An entity linker for the Unified Medical Language System (UMLS).\n\n Given a mention and a list of candidates (generated by CandidateGenerator), it uses an sklearn classifier\n to sort the candidates by their probabilty of being the the right entity for the mention.\n\n Parameters\n ----------\n umls_concept_dict_by_id: Dict\n A dictionary of the UMLS concepts.\n classifier: ClassifierMixin\n An sklearn classifier that takes a mention and a candidate and evaluate them.\n If classifier is None, the linking function returns the same list with no sorting.\n Also, `classifier_example` and `featurizer` functions are still useful for generating\n classifier training data.\n \"\"\"\n\n def __init__(self,\n umls_concept_dict_by_id: Dict,\n classifier: ClassifierMixin = None) -> None:\n self.umls_concept_dict_by_id = umls_concept_dict_by_id\n self.classifier = classifier\n\n @classmethod\n def featurizer(cls, example: Dict):\n \"\"\"Featurize a dictionary of values for the linking classifier.\"\"\"\n features = []\n features.append(int(example['has_definition'])) # 0 if candidate doesn't have definition, 1 otherwise\n\n features.append(min(example['distances']))\n features.append(max(example['distances']))\n features.append(len(example['distances']))\n features.append(np.mean(example['distances']))\n\n gold_types = set(example['mention_types'])\n candidate_types = set(example['candidate_types'])\n\n features.append(len(gold_types))\n features.append(len(candidate_types))\n features.append(len(candidate_types.intersection(gold_types)))\n\n return features\n\n def classifier_example(self, candidate_id: str, candidate: List[Tuple[str, float]], mention_text: str, mention_types: List[str]):\n \"\"\"Given a candidate and a mention, return a dictionary summarizing relevant information for classification.\"\"\"\n has_definition = 'definition' in self.umls_concept_dict_by_id[candidate_id]\n distances = [distance for aliase, distance in candidate]\n candidate_types = self.umls_concept_dict_by_id[candidate_id]['types']\n\n return {'has_definition': has_definition,\n 'distances': distances,\n 'mention_types': mention_types,\n 'candidate_types': candidate_types}\n\n def link(self, candidates: Dict[str, List[Tuple[str, float]]], mention_text: str, mention_types: List[str]):\n \"\"\"\n Given a dictionary of candidates and a mention, return a list of candidate ids sorted by\n probability it is the right entity for the mention.\n\n args:\n candidates: dictionary of candidates of the form candidate id -> list((aliase, distance)).\n mention_text: mention text.\n mention_types: list of mention types.\n\n returns:\n A list of candidate ids sorted by the probability it is the right entity for the mention.\n \"\"\"\n features = []\n candidate_ids = list(candidates.keys())\n if self.classifier is None:\n return candidate_ids\n\n for candidate_id in candidate_ids:\n candidate = candidates[candidate_id]\n classifier_example = self.classifier_example(candidate_id, candidate, mention_text, mention_types)\n features.append(self.featurizer(classifier_example))\n if len(features) == 0:\n return []\n scores = self.classifier.predict_proba(features)\n return [candidate_ids[i] for i in np.argsort(-scores[:, 1], kind='mergesort')] # mergesort is stable\n\n\ndef create_tfidf_ann_index(model_path: str, text_to_concept: Dict[str, Set[str]]) -> None:\n \"\"\"\n Build tfidf vectorizer and ann index.\n \"\"\"\n tfidf_vectorizer_path = f'{model_path}/tfidf_vectorizer.joblib'\n ann_index_path = f'{model_path}/nmslib_index.bin'\n tfidf_vectors_path = f'{model_path}/tfidf_vectors_sparse.npz'\n uml_concept_aliases_path = f'{model_path}/concept_aliases.json'\n\n # nmslib hyperparameters (very important)\n # guide: https://github.com/nmslib/nmslib/blob/master/python_bindings/parameters.md\n # default values resulted in very low recall\n M = 100 # set to the maximum recommended value. Improves recall at the expense of longer indexing time\n efC = 2000 # `C` for Construction. Set to the maximum recommended value\n # Improves recall at the expense of longer indexing time\n efS = 1000 # `S` for Search. This controls performance at query time. Maximum recommended value is 2000.\n # It makes the query slow without significant gain in recall.\n num_threads = 60 # set based on the machine\n index_params = {'M': M, 'indexThreadQty': num_threads, 'efConstruction': efC, 'post' : 0}\n\n print(f'No tfidf vectorizer on {tfidf_vectorizer_path} or ann index on {ann_index_path}')\n uml_concept_aliases = list(text_to_concept.keys())\n\n uml_concept_aliases = np.array(uml_concept_aliases)\n\n print(f'Fitting tfidf vectorizer on {len(uml_concept_aliases)} aliases')\n tfidf_vectorizer = TfidfVectorizer(analyzer='char_wb', ngram_range=(3, 3), min_df=10, dtype=np.float32)\n start_time = datetime.datetime.now()\n uml_concept_alias_tfidfs = tfidf_vectorizer.fit_transform(uml_concept_aliases)\n print(f'Saving tfidf vectorizer to {tfidf_vectorizer_path}')\n dump(tfidf_vectorizer, tfidf_vectorizer_path)\n end_time = datetime.datetime.now()\n total_time = (end_time - start_time)\n print(f'Fitting and saving vectorizer took {total_time.total_seconds()} seconds')\n\n print(f'Finding empty (all zeros) tfidf vectors')\n empty_tfidfs_boolean_flags = np.array(uml_concept_alias_tfidfs.sum(axis=1) != 0).reshape(-1,)\n deleted_aliases = uml_concept_aliases[empty_tfidfs_boolean_flags == False]\n number_of_non_empty_tfidfs = len(deleted_aliases)\n total_number_of_tfidfs = uml_concept_alias_tfidfs.shape[0]\n\n print(f'Deleting {number_of_non_empty_tfidfs}/{total_number_of_tfidfs} aliases because their tfidf is empty')\n # remove empty tfidf vectors, otherwise nmslib will crash\n uml_concept_aliases = uml_concept_aliases[empty_tfidfs_boolean_flags]\n uml_concept_alias_tfidfs = uml_concept_alias_tfidfs[empty_tfidfs_boolean_flags]\n print(deleted_aliases)\n\n print(f'Saving list of concept ids and tfidfs vectors to {uml_concept_aliases_path} and {tfidf_vectors_path}')\n json.dump(uml_concept_aliases.tolist(), open(uml_concept_aliases_path, \"w\"))\n scipy.sparse.save_npz(tfidf_vectors_path, uml_concept_alias_tfidfs.astype(np.float16))\n\n print(f'Fitting ann index on {len(uml_concept_aliases)} aliases (takes 2 hours)')\n start_time = datetime.datetime.now()\n ann_index = nmslib.init(method='hnsw', space='cosinesimil_sparse', data_type=nmslib.DataType.SPARSE_VECTOR)\n ann_index.addDataPointBatch(uml_concept_alias_tfidfs)\n ann_index.createIndex(index_params, print_progress=True)\n ann_index.saveIndex(ann_index_path)\n end_time = datetime.datetime.now()\n elapsed_time = end_time - start_time\n print(f'Fitting ann index took {elapsed_time.total_seconds()} seconds')\n\ndef load_tfidf_ann_index(model_path: str):\n # `S` for Search. This controls performance at query time. Maximum recommended value is 2000.\n # It makes the query slow without significant gain in recall.\n efS = 1000\n\n tfidf_vectorizer_path = f'{model_path}/tfidf_vectorizer.joblib'\n ann_index_path = f'{model_path}/nmslib_index.bin'\n tfidf_vectors_path = f'{model_path}/tfidf_vectors_sparse.npz'\n uml_concept_aliases_path = f'{model_path}/concept_aliases.json'\n\n start_time = datetime.datetime.now()\n print(f'Loading list of concepted ids from {uml_concept_aliases_path}')\n uml_concept_aliases = json.load(open(uml_concept_aliases_path))\n\n print(f'Loading tfidf vectorizer from {tfidf_vectorizer_path}')\n tfidf_vectorizer = load(tfidf_vectorizer_path)\n if isinstance(tfidf_vectorizer, TfidfVectorizer):\n print(f'Tfidf vocab size: {len(tfidf_vectorizer.vocabulary_)}')\n\n print(f'Loading tfidf vectors from {tfidf_vectors_path}')\n uml_concept_alias_tfidfs = scipy.sparse.load_npz(tfidf_vectors_path).astype(np.float32)\n\n print(f'Loading ann index from {ann_index_path}')\n ann_index = nmslib.init(method='hnsw', space='cosinesimil_sparse', data_type=nmslib.DataType.SPARSE_VECTOR)\n ann_index.addDataPointBatch(uml_concept_alias_tfidfs)\n ann_index.loadIndex(ann_index_path)\n query_time_params = {'efSearch': efS}\n ann_index.setQueryTimeParams(query_time_params)\n\n end_time = datetime.datetime.now()\n total_time = (end_time - start_time)\n\n print(f'Loading concept ids, vectorizer, tfidf vectors and ann index took {total_time.total_seconds()} seconds')\n return uml_concept_aliases, tfidf_vectorizer, ann_index\n\n\ndef load_linking_classifier(model_path: str):\n linking_classifier_path = f'{model_path}/linking_classifier.joblib'\n\n print(f'Loading linking classifier from {linking_classifier_path}')\n try:\n linking_classifier = load(linking_classifier_path)\n except:\n print('Loading linking classifier failed')\n return None\n return linking_classifier\n\ndef get_mention_text_and_ids(data: List[data_util.MedMentionExample],\n umls: Dict[str, Any]):\n missing_entity_ids = [] # entities in MedMentions but not in UMLS\n\n # don't care about context for now. Just do the processing based on mention text only\n # collect all the data in one list to use ann.knnQueryBatch which is a lot faster than\n # calling ann.knnQuery for each individual example\n mention_texts = []\n gold_umls_ids = []\n\n for example in data:\n for entity in example.entities:\n if entity.umls_id not in umls:\n missing_entity_ids.append(entity) # the UMLS release doesn't contan all UMLS concepts\n continue\n\n mention_texts.append(entity.mention_text)\n gold_umls_ids.append(entity.umls_id)\n continue\n\n return mention_texts, gold_umls_ids, missing_entity_ids\n\n\n\ndef maybe_substitute_span(doc, entity, abbreviations):\n maybe_ent_span = doc.char_span(entity.start, entity.end)\n if maybe_ent_span is None:\n maybe_ent_span = doc.char_span(entity.start, entity.end + 1)\n if maybe_ent_span in abbreviations:\n return maybe_ent_span, str(abbreviations[maybe_ent_span])\n else:\n return None, None\n\ndef get_mention_text_and_ids_by_doc(data: List[data_util.MedMentionExample],\n umls: Dict[str, Any],\n nlp: Language,\n substitute_abbreviations=False):\n \"\"\"\n Returns a list of tuples containing a MedMentionExample and the texts and ids contianed in it\n\n Parameters\n ----------\n data: List[data_util.MedMentionExample]\n A list of MedMentionExamples being evaluated\n umls: Dict[str, Any]\n A dictionary of UMLS concepts\n nlp : Language\n A spacy NLP model.\n substitute_abbreviations: bool, default = False\n Whether or not to search for and replace abbreviations when generating mention candidates.\n Note that this can be applied on both gold and predicted mentions.\n \"\"\"\n missing_entity_ids = [] # entities in MedMentions but not in UMLS\n examples_with_labels = []\n\n substituted = 0\n total = 0\n\n for example in data:\n\n doc = nlp(example.text)\n abbreviations = {}\n if substitute_abbreviations:\n for full, shorts in doc._.abbreviations:\n for short in shorts:\n abbreviations[short] = full\n\n mention_texts = []\n predicted_mention_texts = []\n gold_umls_ids = []\n for entity in example.entities:\n if entity.umls_id not in umls:\n missing_entity_ids.append(entity) # the UMLS release doesn't contan all UMLS concepts\n continue\n\n _, mention_string = maybe_substitute_span(doc, entity, abbreviations)\n if mention_string is None:\n mention_string = entity.mention_text\n\n if mention_string != entity.mention_text:\n substituted += 1\n mention_texts.append(mention_string)\n\n gold_umls_ids.append(entity.umls_id)\n total += 1\n\n\n # Note that because we might substitute some entities for their abbreviations,\n # the entities on the doc may not match predicted_mention_texts.\n for entity in doc.ents:\n new_span, _ = maybe_substitute_span(doc, entity, abbreviations)\n if new_span is None:\n predicted_mention_texts.append(entity)\n else:\n # We have to manually create a new span with the new start and end points, but with the old label,\n # as spans are read only views of a document.\n span_with_label = Span(doc, start=new_span.start, end=new_span.end, label=entity.label_)\n predicted_mention_texts.append(span_with_label)\n\n examples_with_labels.append((doc, example, mention_texts, predicted_mention_texts, gold_umls_ids))\n\n print(f\"Substituted {100 * substituted/total} percent of entities\")\n return examples_with_labels, missing_entity_ids\n\n\ndef get_predicted_mention_candidates_and_types(span,\n ner_entities,\n filtered_batch_candidate_neighbor_ids,\n predicted_mention_types,\n use_soft_matching):\n \"\"\"\n This function returns three lists, candidates, mention types, and mention spans. These lists will be the same length and have\n length equal to the number of predicted entities that overlap with the input gold entity. When not using soft mentions,\n this length will be equal to one, as only one predicted entity can exactly match a gold entity.\n \"\"\"\n candidates = []\n mention_types = []\n mention_spans = []\n\n if span is not None:\n for j, predicted_entity in enumerate(ner_entities):\n if not use_soft_matching and span == predicted_entity:\n candidates.append(filtered_batch_candidate_neighbor_ids[j])\n mention_types.append(predicted_mention_types[j])\n mention_spans.append(predicted_entity)\n break\n elif use_soft_matching:\n # gold span starts inside the predicted span\n if (span.start_char <= predicted_entity.start_char <= span.end_char\n # predicted span starts inside gold span.\n or predicted_entity.start_char <= span.start_char <= predicted_entity.end_char):\n candidates.append(filtered_batch_candidate_neighbor_ids[j])\n mention_types.append(predicted_mention_types[j])\n mention_spans.append(predicted_entity)\n\n return candidates, mention_types, mention_spans\n\n\ndef eval_candidate_generation_and_linking(examples: List[data_util.MedMentionExample],\n umls_concept_dict_by_id: Dict[str, Dict],\n candidate_generator: CandidateGenerator,\n k_list: List[int],\n thresholds: List[float],\n use_gold_mentions: bool,\n nlp: Language,\n generate_linking_classifier_training_data: bool,\n linker: Linker = None,\n use_soft_matching: bool = False,\n substitute_abbreviations: bool = False):\n \"\"\"\n Evaluate candidate generation and linking using either gold mentions or spacy mentions.\n The evaluation is done both at the mention level and at the document level. If the evaluation\n is done with spacy mentions at the mention level, a pair is only considered correct if\n both the mention and the entity are exactly correct. This could potentially be relaxed, but this \n matches the evaluation setup from the MedMentions paper.\n\n Parameters\n ----------\n examples: List[data_util.MedMentionExample]\n An list of MedMentionExamples being evaluted\n umls_concept_dict_by_id: Dict[str, Dict]\n A dictionary of UMLS concepts\n candidate_generator: CandidateGenerator\n A CandidateGenerator instance for generating linking candidates for mentions\n k_list: List[int]\n A list of values determining how many candidates are generated.\n thresholds: List[float]\n A list of threshold values determining the cutoff score for candidates\n use_gold_mentions: bool\n Evalute using gold mentions and types or predicted spacy ner mentions and types\n spacy_model: str\n Name (or path) of a spacy model to use for ner predictions\n generate_linking_classifier_training_data: bool\n If true, collect training data for the linking classifier\n linker: Linker\n A linker to evaluate. If None, skip linking evaluation\n use_soft_matching:\n If true, allow predicted mentions with any overlap with the gold mention to count as correct,\n else only count exact matches as correct\n substitute_abbreviations: bool\n Whether or not to substitute abbreviations when doing mention generation.\n \"\"\"\n\n examples_with_text_and_ids, missing_entity_ids = get_mention_text_and_ids_by_doc(examples,\n umls_concept_dict_by_id,\n nlp,\n substitute_abbreviations)\n\n linking_classifier_training_data = []\n for k in k_list:\n for threshold in thresholds:\n\n\n entity_correct_links_count = 0 # number of correctly linked entities\n entity_wrong_links_count = 0 # number of wrongly linked entities\n entity_no_links_count = 0 # number of entities that are not linked\n num_candidates = []\n num_filtered_candidates = []\n\n doc_entity_correct_links_count = 0 # number of correctly linked entities\n doc_entity_missed_count = 0 # number of gold entities missed\n doc_mention_no_links_count = 0 # number of ner mentions that did not have any linking candidates\n doc_num_candidates = []\n doc_num_filtered_candidates = []\n doc_linking_correct_count = 0\n doc_linking_golds_in_candidates = 0\n doc_linking_total_predictions = 0\n\n all_golds_per_doc_set = []\n all_golds = []\n all_mentions = []\n\n # Note: these counts correspond to the number of gold entities that were correctly identified using either\n # predicted mentions or gold mentions. It does not mean that these counts are only for using gold mentions\n gold_entities_linker_correct = defaultdict(int)\n gold_entities_linker_incorrect = defaultdict(int)\n\n predicted_entities_linker_correct = defaultdict(int)\n predicted_entities_linker_incorrect = defaultdict(int)\n\n for doc, example, gold_entities, predicted_entities, gold_umls_ids in tqdm(examples_with_text_and_ids,\n desc=\"Iterating over examples\",\n total=len(examples_with_text_and_ids)):\n\n\n entities = [entity for entity in example.entities if entity.umls_id in umls_concept_dict_by_id]\n gold_umls_ids = [entity.umls_id for entity in entities]\n doc_golds = set(gold_umls_ids)\n doc_candidates = set()\n doc_linker_predictions = set()\n doc_all_entities_in_candidates = set()\n\n if use_gold_mentions:\n mention_texts = gold_entities\n mention_types = [[ent.mention_type] for ent in example.entities]\n else:\n mention_types = [[ent.label_] for ent in predicted_entities]\n mention_texts = [ent.text for ent in predicted_entities]\n\n batch_candidate_neighbor_ids = candidate_generator.generate_candidates(mention_texts, k)\n\n filtered_batch_candidate_neighbor_ids = []\n for candidate_neighbor_ids, mention_text, mention_type \\\n in zip(batch_candidate_neighbor_ids, mention_texts, mention_types):\n # Keep only canonical entities for which at least one mention has a score less than the threshold.\n filtered_ids = {k: v for k, v in candidate_neighbor_ids.items() if any([z[1] <= threshold for z in v])}\n filtered_batch_candidate_neighbor_ids.append(filtered_ids)\n num_candidates.append(len(candidate_neighbor_ids))\n num_filtered_candidates.append(len(filtered_ids))\n doc_candidates.update(filtered_ids)\n # Note: doing linking here means that each entity is linked twice, which is inefficient. However the main\n # loop below loops over gold entities, so to compute the document level metrics we first link for all predicted\n # entities here. This could be refactored to remove the inefficiency\n if len(filtered_ids) != 0:\n sorted_candidate_ids = linker.link(filtered_ids, mention_text, mention_type)\n doc_all_entities_in_candidates.update(filtered_ids)\n doc_linker_predictions.add(sorted_candidate_ids[0])\n\n for i, gold_entity in enumerate(entities):\n if use_gold_mentions:\n candidates_by_mention = [filtered_batch_candidate_neighbor_ids[i]] # for gold mentions, len(entities) == len(filtered_batch_candidate_neighbor_ids)\n mention_types_by_mention = [umls_concept_dict_by_id[gold_entity.umls_id]['types']] # use gold types\n overlapping_mention_spans = doc.char_span(gold_entity.start, gold_entity.end)\n else:\n # for each gold entity, search for a corresponding predicted entity that has the same span\n span_from_doc = doc.char_span(gold_entity.start, gold_entity.end)\n if span_from_doc is None:\n # one case is that the spacy span has an extra period attached to the end of it\n span_from_doc = doc.char_span(gold_entity.start, gold_entity.end+1)\n\n candidates_by_mention, mention_types_by_mention, overlapping_mention_spans = get_predicted_mention_candidates_and_types(span_from_doc, predicted_entities,\n filtered_batch_candidate_neighbor_ids,\n mention_types, use_soft_matching)\n mention_text = \"\" # not used \n\n # Evaluating candidate generation\n if len(candidates_by_mention) == 0 or len(candidates_by_mention[0]) == 0:\n entity_no_links_count += 1\n elif any(gold_entity.umls_id in candidates for candidates in candidates_by_mention):\n entity_correct_links_count += 1\n else:\n entity_wrong_links_count += 1\n\n # Evaluating linking\n if linker:\n linking_predictions_by_mention = []\n for candidates, mention_type in zip(candidates_by_mention, mention_types_by_mention):\n sorted_candidate_ids = linker.link(candidates, mention_text, mention_type)\n linking_predictions_by_mention.append(sorted_candidate_ids)\n\n for linker_k in [1, 3, 5, 10]:\n if any(gold_entity.umls_id in linking_predictions[:linker_k] for linking_predictions in linking_predictions_by_mention):\n gold_entities_linker_correct[linker_k] += 1\n else:\n gold_entities_linker_incorrect[linker_k] += 1\n\n for mention_index, linking_predictions in enumerate(linking_predictions_by_mention):\n if gold_entity.umls_id in linking_predictions[:linker_k]:\n predicted_entities_linker_correct[linker_k] += 1\n else:\n predicted_entities_linker_incorrect[linker_k] += 1\n\n # Generate training data for the linking classifier\n if generate_linking_classifier_training_data:\n for candidates, mention_types_for_mention in zip(candidates_by_mention, mention_types_by_mention):\n for candidate_id, candidate in candidates.items():\n classifier_example = linker.classifier_example(candidate_id, candidate, mention_text, mention_types_for_mention)\n classifier_example['label'] = int(gold_entity.umls_id == candidate_id)\n linking_classifier_training_data.append(classifier_example)\n\n # the number of correct entities for a given document is the number of gold entities contained in the candidates\n # produced for that document\n doc_entity_correct_links_count += len(doc_candidates.intersection(doc_golds))\n # the number of incorrect entities for a given document is the number of gold entities not contained in the candidates\n # produced for that document\n doc_entity_missed_count += len(doc_golds - doc_candidates)\n\n doc_linking_correct_count += len(doc_linker_predictions.intersection(doc_golds))\n doc_linking_golds_in_candidates += len(doc_golds.intersection(doc_all_entities_in_candidates))\n doc_linking_total_predictions += len(doc_linker_predictions)\n\n all_golds_per_doc_set += list(doc_golds)\n all_golds += gold_umls_ids\n all_mentions += mention_texts\n\n print(f'MedMentions entities not in UMLS: {len(missing_entity_ids)}')\n print(f'MedMentions entities found in UMLS: {len(gold_umls_ids)}')\n print(f'K: {k}, Filtered threshold : {threshold}')\n print('Gold concept in candidates: {0:.2f}%'.format(100 * entity_correct_links_count / len(all_golds)))\n print('Gold concept not in candidates: {0:.2f}%'.format(100 * entity_wrong_links_count / len(all_golds)))\n print('Doc level gold concept in candidates: {0:.2f}%'.format(100 * doc_entity_correct_links_count / len(all_golds_per_doc_set)))\n print('Doc level gold concepts missed: {0:.2f}%'.format(100 * doc_entity_missed_count / len(all_golds_per_doc_set)))\n print('Candidate generation failed: {0:.2f}%'.format(100 * entity_no_links_count / len(all_golds)))\n if linker:\n print('Mention linking precision {0:.2f}%'.format(100 * predicted_entities_linker_correct[1] / (predicted_entities_linker_correct[1] + predicted_entities_linker_incorrect[1])))\n print('Doc linking precision {0:.2f}%'.format(100 * doc_linking_correct_count / doc_linking_total_predictions))\n print('Normalized doc linking precision {0:.2f}%'.format(100 * doc_linking_correct_count / doc_linking_golds_in_candidates))\n print('Doc linking recall {0:.2f}%'.format(100 * doc_linking_correct_count / len(all_golds_per_doc_set)))\n for linker_k in [1, 3, 5, 10]:\n correct = gold_entities_linker_correct[linker_k]\n total = len(all_golds)\n print('Linking mention-level recall@{0}: {1:.2f}%'.format(linker_k, 100 * correct / total))\n print('Normalized linking mention-level recall@{0}: {1:.2f}%'.format(linker_k, 100 * correct / entity_correct_links_count))\n print('Mean, std, min, max candidate ids: {0:.2f}, {1:.2f}, {2}, {3}'.format(np.mean(num_candidates), np.std(num_candidates), np.min(num_candidates), np.max(num_candidates)))\n print('Mean, std, min, max filtered candidate ids: {0:.2f}, {1:.2f}, {2}, {3}'.format(np.mean(num_filtered_candidates), np.std(num_filtered_candidates), np.min(num_filtered_candidates), np.max(num_filtered_candidates)))\n\n return linking_classifier_training_data\n\ndef main(medmentions_path: str,\n umls_path: str,\n model_path: str,\n ks: str,\n thresholds,\n use_gold_mentions: bool = False,\n train: bool = False,\n spacy_model: str = \"\",\n generate_linker_data: bool = False,\n use_soft_matching: bool = False,\n substitute_abbreviations: bool = False):\n\n umls_concept_list = load_umls_kb(umls_path)\n umls_concept_dict_by_id = {c['concept_id']: c for c in umls_concept_list}\n\n # We need to keep around a map from text to possible canonical ids that they map to.\n text_to_concept_id: Dict[str, Set[str]] = defaultdict(set)\n\n for concept in umls_concept_list:\n for alias in set(concept[\"aliases\"]).union({concept[\"canonical_name\"]}):\n text_to_concept_id[alias].add(concept[\"concept_id\"])\n\n if train:\n create_tfidf_ann_index(model_path, text_to_concept_id)\n ann_concept_aliases_list, tfidf_vectorizer, ann_index = load_tfidf_ann_index(model_path)\n candidate_generator = CandidateGenerator(ann_index, tfidf_vectorizer, ann_concept_aliases_list, text_to_concept_id, False)\n\n linking_classifier = load_linking_classifier(model_path)\n linker = Linker(umls_concept_dict_by_id, linking_classifier)\n\n print('Reading MedMentions...')\n train_examples, dev_examples, test_examples = data_util.read_full_med_mentions(medmentions_path,\n spacy_format=False)\n\n k_list = [int(k) for k in ks.split(',')]\n if thresholds is None:\n thresholds = [1.0]\n else:\n thresholds = [float(x) for x in thresholds.split(\",\")]\n\n if len(thresholds) > 1 or len(k_list) > 1:\n assert not generate_linker_data, \\\n 'generating linker training data should be for a single threshold and k'\n\n nlp = spacy.load(spacy_model)\n if substitute_abbreviations:\n abbreviation_detector = AbbreviationDetector(nlp)\n nlp.add_pipe(abbreviation_detector, last=True)\n\n if generate_linker_data:\n examples_list = [train_examples, dev_examples, test_examples]\n filenames = [f'{model_path}/train.jsonl', f'{model_path}/dev.jsonl', f'{model_path}/test.jsonl']\n for examples, filename in zip(examples_list, filenames):\n supervised_data = eval_candidate_generation_and_linking(examples, umls_concept_dict_by_id, candidate_generator, k_list, thresholds,\n use_gold_mentions, nlp, generate_linker_data, linker, use_soft_matching, substitute_abbreviations)\n with open(filename, 'w') as f:\n for d in supervised_data:\n f.write(f'{json.dumps(d)}\\n')\n else:\n print('Results on the DEV set')\n eval_candidate_generation_and_linking(dev_examples, umls_concept_dict_by_id, candidate_generator, k_list, thresholds,\n use_gold_mentions, nlp, generate_linker_data, linker, use_soft_matching, substitute_abbreviations)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--medmentions_path',\n help='Path to the MedMentions dataset.'\n )\n parser.add_argument(\n '--umls_path',\n help='Path to the json UMLS release.'\n )\n parser.add_argument(\n '--model_path',\n help='Path to a directory with tfidf vectorizer and nmslib ann index.'\n )\n parser.add_argument(\n '--ks',\n help='Comma separated list of number of candidates.',\n )\n parser.add_argument(\n '--thresholds',\n default=None,\n help='Comma separated list of threshold values.',\n )\n parser.add_argument(\n '--train',\n action=\"store_true\",\n help='Fit the tfidf vectorizer and create the ANN index.',\n )\n parser.add_argument(\n '--use_gold_mentions',\n action=\"store_true\",\n help=\"Use gold mentions for evaluation rather than a model's predicted mentions\"\n )\n parser.add_argument(\n '--spacy_model',\n default=\"\",\n help=\"The name of the spacy model to use for evaluation (when not using gold mentions)\"\n )\n parser.add_argument(\n '--generate_linker_data',\n action=\"store_true\",\n help=\"Collect and save training data for the classifier.\"\n )\n\n parser.add_argument(\n '--abbreviations',\n action=\"store_true\",\n help=\"Detect abbreviations when doing mention detection.\"\n )\n parser.add_argument(\n '--use_soft_matching',\n action=\"store_true\",\n help=\"When using predicted mentions, use soft matching to allow mentions with any overlap with the gold mention to count as correct\"\n )\n\n args = parser.parse_args()\n main(args.medmentions_path,\n args.umls_path,\n args.model_path,\n args.ks,\n args.thresholds,\n args.use_gold_mentions,\n args.train,\n args.spacy_model,\n args.generate_linker_data,\n args.use_soft_matching,\n args.abbreviations)\n"
] | [
[
"numpy.min",
"scipy.sparse.load_npz",
"numpy.max",
"numpy.std",
"numpy.mean",
"numpy.argsort",
"numpy.array",
"sklearn.feature_extraction.text.TfidfVectorizer"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.6",
"1.10",
"1.4",
"1.9",
"0.19",
"1.5",
"1.2",
"1.7",
"1.0",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
astonzhang/gluon-nlp | [
"e7a8b9fdad1e02a7b3c581215b55b765176ae7e6"
] | [
"scripts/bert/dataset.py"
] | [
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and DMLC.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"BERT datasets.\"\"\"\n\n__all__ = [\n 'MRPCDataset', 'QQPDataset', 'QNLIDataset', 'RTEDataset', 'STSBDataset',\n 'COLADataset', 'MNLIDataset', 'WNLIDataset', 'SSTDataset',\n 'BERTDatasetTransform'\n]\n\nimport os\nimport warnings\nimport numpy as np\nfrom mxnet.metric import Accuracy, F1, MCC, PearsonCorrelation, CompositeEvalMetric\nfrom gluonnlp.data import TSVDataset, BERTSentenceTransform\nfrom gluonnlp.data.registry import register\n\n\n@register(segment=['train', 'dev', 'test'])\nclass MRPCDataset(TSVDataset):\n \"\"\"The Microsoft Research Paraphrase Corpus dataset.\n Parameters\n ----------\n segment : str or list of str, default 'train'\n Dataset segment. Options are 'train', 'dev', 'test' or their combinations.\n root : str, default '$GLUE_DIR/MRPC'\n Path to the folder which stores the MRPC dataset.\n The datset can be downloaded by the following script:\n https://gist.github.com/W4ngatang/60c2bdb54d156a41194446737ce03e2e\n \"\"\"\n task_name = 'MRPC'\n is_pair = True\n\n def __init__(self,\n segment='train',\n root=os.path.join(\n os.getenv('GLUE_DIR', 'glue_data'), task_name)):\n self._supported_segments = ['train', 'dev', 'test']\n assert segment in self._supported_segments, 'Unsupported segment: %s' % segment\n path = os.path.join(root, '%s.tsv' % segment)\n A_IDX, B_IDX, LABEL_IDX = 3, 4, 0\n fields = [A_IDX, B_IDX, LABEL_IDX]\n super(MRPCDataset, self).__init__(\n path, num_discard_samples=1, field_indices=fields)\n\n @staticmethod\n def get_labels():\n \"\"\"Get classification label ids of the dataset.\"\"\"\n return ['0', '1']\n\n @staticmethod\n def get_metric():\n \"\"\"Get metrics Accuracy and F1\"\"\"\n metric = CompositeEvalMetric()\n for child_metric in [Accuracy(), F1()]:\n metric.add(child_metric)\n return metric\n\n\nclass GLUEDataset(TSVDataset):\n \"\"\"GLUEDataset class\"\"\"\n\n def __init__(self, path, num_discard_samples, fields):\n self.fields = fields\n super(GLUEDataset, self).__init__(\n path, num_discard_samples=num_discard_samples)\n\n def _read(self):\n all_samples = super(GLUEDataset, self)._read()\n largest_field = max(self.fields)\n # to filter out error records\n final_samples = [[s[f] for f in self.fields] for s in all_samples\n if len(s) >= largest_field + 1]\n residuals = len(all_samples) - len(final_samples)\n if residuals > 0:\n warnings.warn(\n '{} samples have been filtered out due to parsing error.'.\n format(residuals))\n return final_samples\n\n\n@register(segment=['train', 'dev', 'test'])\nclass QQPDataset(GLUEDataset):\n \"\"\"Dataset for Quora Question Pairs.\n\n Parameters\n ----------\n segment : str or list of str, default 'train'\n Dataset segment. Options are 'train', 'dev', 'test' or their combinations.\n root : str, default '$GLUE_DIR/QQP'\n Path to the folder which stores the QQP dataset.\n The datset can be downloaded by the following script:\n https://gist.github.com/W4ngatang/60c2bdb54d156a41194446737ce03e2e\n \"\"\"\n task_name = 'QQP'\n is_pair = True\n\n def __init__(self,\n segment='train',\n root=os.path.join(\n os.getenv('GLUE_DIR', 'glue_data'), task_name)):\n self._supported_segments = ['train', 'dev', 'test']\n assert segment in self._supported_segments, 'Unsupported segment: %s' % segment\n path = os.path.join(root, '%s.tsv' % segment)\n if segment in ['train', 'dev']:\n A_IDX, B_IDX, LABEL_IDX = 3, 4, 5\n fields = [A_IDX, B_IDX, LABEL_IDX]\n elif segment == 'test':\n A_IDX, B_IDX = 1, 2\n fields = [A_IDX, B_IDX]\n super(QQPDataset, self).__init__(\n path, num_discard_samples=1, fields=fields)\n\n @staticmethod\n def get_labels():\n \"\"\"Get classification label ids of the dataset.\"\"\"\n return ['0', '1']\n\n @staticmethod\n def get_metric():\n \"\"\"Get metrics Accuracy and F1\"\"\"\n metric = CompositeEvalMetric()\n for child_metric in [Accuracy(), F1()]:\n metric.add(child_metric)\n return metric\n\n\n@register(segment=['train', 'dev', 'test'])\nclass RTEDataset(GLUEDataset):\n \"\"\"Task class for Recognizing Textual Entailment\n\n Parameters\n ----------\n segment : str or list of str, default 'train'\n Dataset segment. Options are 'train', 'dev', 'test' or their combinations.\n root : str, default '$GLUE_DIR/RTE'\n Path to the folder which stores the RTE dataset.\n The datset can be downloaded by the following script:\n https://gist.github.com/W4ngatang/60c2bdb54d156a41194446737ce03e2e\n \"\"\"\n task_name = 'RTE'\n is_pair = True\n\n def __init__(self,\n segment='train',\n root=os.path.join(\n os.getenv('GLUE_DIR', 'glue_data'), task_name)):\n self._supported_segments = ['train', 'dev', 'test']\n assert segment in self._supported_segments, 'Unsupported segment: %s' % segment\n path = os.path.join(root, '%s.tsv' % segment)\n if segment in ['train', 'dev']:\n A_IDX, B_IDX, LABEL_IDX = 1, 2, 3\n fields = [A_IDX, B_IDX, LABEL_IDX]\n elif segment == 'test':\n A_IDX, B_IDX = 1, 2\n fields = [A_IDX, B_IDX]\n super(RTEDataset, self).__init__(\n path, num_discard_samples=1, fields=fields)\n\n @staticmethod\n def get_labels():\n \"\"\"Get classification label ids of the dataset.\"\"\"\n return ['not_entailment', 'entailment']\n\n @staticmethod\n def get_metric():\n \"\"\"Get metrics Accuracy\"\"\"\n return Accuracy()\n\n\n@register(segment=['train', 'dev', 'test'])\nclass QNLIDataset(GLUEDataset):\n \"\"\"Task class for SQuAD NLI\n\n Parameters\n ----------\n segment : str or list of str, default 'train'\n Dataset segment. Options are 'train', 'dev', 'test' or their combinations.\n root : str, default '$GLUE_DIR/QNLI'\n Path to the folder which stores the QNLI dataset.\n The datset can be downloaded by the following script:\n https://gist.github.com/W4ngatang/60c2bdb54d156a41194446737ce03e2e\n \"\"\"\n task_name = 'QNLI'\n is_pair = True\n\n def __init__(self,\n segment='train',\n root=os.path.join(\n os.getenv('GLUE_DIR', 'glue_data'), task_name)):\n self._supported_segments = ['train', 'dev', 'test']\n assert segment in self._supported_segments, 'Unsupported segment: %s' % segment\n path = os.path.join(root, '%s.tsv' % segment)\n if segment in ['train', 'dev']:\n A_IDX, B_IDX, LABEL_IDX = 1, 2, 3\n fields = [A_IDX, B_IDX, LABEL_IDX]\n elif segment == 'test':\n A_IDX, B_IDX = 1, 2\n fields = [A_IDX, B_IDX]\n super(QNLIDataset, self).__init__(\n path, num_discard_samples=1, fields=fields)\n\n @staticmethod\n def get_labels():\n \"\"\"Get classification label ids of the dataset.\"\"\"\n return ['not_entailment', 'entailment']\n\n @staticmethod\n def get_metric():\n \"\"\"Get metrics Accuracy\"\"\"\n return Accuracy()\n\n\n@register(segment=['train', 'dev', 'test'])\nclass STSBDataset(GLUEDataset):\n \"\"\"Task class for Sentence Textual Similarity Benchmark.\n\n Parameters\n ----------\n segment : str or list of str, default 'train'\n Dataset segment. Options are 'train', 'dev', 'test' or their combinations.\n root : str, default '$GLUE_DIR/STS-B'\n Path to the folder which stores the STS dataset.\n The datset can be downloaded by the following script:\n https://gist.github.com/W4ngatang/60c2bdb54d156a41194446737ce03e2e\n \"\"\"\n task_name = 'STS-B'\n is_pair = True\n\n def __init__(self,\n segment='train',\n root=os.path.join(\n os.getenv('GLUE_DIR', 'glue_data'), task_name)):\n self._supported_segments = ['train', 'dev', 'test']\n assert segment in self._supported_segments, 'Unsupported segment: %s' % segment\n path = os.path.join(root, '%s.tsv' % segment)\n if segment in ['train', 'dev']:\n A_IDX, B_IDX, LABEL_IDX = 7, 8, 9\n fields = [A_IDX, B_IDX, LABEL_IDX]\n elif segment == 'test':\n A_IDX, B_IDX = 7, 8\n fields = [A_IDX, B_IDX]\n super(STSBDataset, self).__init__(\n path, num_discard_samples=1, fields=fields)\n\n @staticmethod\n def get_metric():\n \"\"\"\n Get metrics Accuracy\n \"\"\"\n return PearsonCorrelation()\n\n @staticmethod\n def get_labels():\n \"\"\"Get classification label ids of the dataset.\"\"\"\n return None\n\n\n@register(segment=['train', 'dev', 'test'])\nclass COLADataset(GLUEDataset):\n \"\"\"Class for Warstdadt acceptability task\n\n Parameters\n ----------\n segment : str or list of str, default 'train'\n Dataset segment. Options are 'train', 'dev', 'test' or their combinations.\n root : str, default '$GLUE_DIR/CoLA\n Path to the folder which stores the CoLA dataset.\n The datset can be downloaded by the following script:\n https://gist.github.com/W4ngatang/60c2bdb54d156a41194446737ce03e2e\n \"\"\"\n task_name = 'CoLA'\n is_pair = False\n\n def __init__(self,\n segment='train',\n root=os.path.join(\n os.getenv('GLUE_DIR', 'glue_data'), task_name)):\n self._supported_segments = ['train', 'dev', 'test']\n assert segment in self._supported_segments, 'Unsupported segment: %s' % segment\n path = os.path.join(root, '%s.tsv' % segment)\n if segment in ['train', 'dev']:\n A_IDX, LABEL_IDX = 3, 1\n fields = [A_IDX, LABEL_IDX]\n super(COLADataset, self).__init__(\n path, num_discard_samples=0, fields=fields)\n elif segment == 'test':\n A_IDX = 3\n fields = [A_IDX]\n super(COLADataset, self).__init__(\n path, num_discard_samples=1, fields=fields)\n\n @staticmethod\n def get_metric():\n \"\"\"Get metrics Matthews Correlation Coefficient\"\"\"\n return MCC(average='micro')\n\n @staticmethod\n def get_labels():\n \"\"\"Get classification label ids of the dataset.\"\"\"\n return ['0', '1']\n\n\n@register(segment=['train', 'dev', 'test'])\nclass SSTDataset(GLUEDataset):\n \"\"\"Task class for Stanford Sentiment Treebank.\n\n Parameters\n ----------\n segment : str or list of str, default 'train'\n Dataset segment. Options are 'train', 'dev', 'test' or their combinations.\n root : str, default '$GLUE_DIR/SST-2\n Path to the folder which stores the SST-2 dataset.\n The datset can be downloaded by the following script:\n https://gist.github.com/W4ngatang/60c2bdb54d156a41194446737ce03e2e\n \"\"\"\n task_name = 'SST'\n is_pair = False\n\n def __init__(self,\n segment='train',\n root=os.path.join(\n os.getenv('GLUE_DIR', 'glue_data'), 'SST-2')):\n self._supported_segments = ['train', 'dev', 'test']\n assert segment in self._supported_segments, 'Unsupported segment: %s' % segment\n path = os.path.join(root, '%s.tsv' % segment)\n if segment in ['train', 'dev']:\n A_IDX, LABEL_IDX = 0, 1\n fields = [A_IDX, LABEL_IDX]\n elif segment == 'test':\n A_IDX = 1\n fields = [A_IDX]\n super(SSTDataset, self).__init__(\n path, num_discard_samples=1, fields=fields)\n\n @staticmethod\n def get_metric():\n \"\"\"Get metrics Accuracy\"\"\"\n return Accuracy()\n\n @staticmethod\n def get_labels():\n \"\"\"Get classification label ids of the dataset.\"\"\"\n return ['0', '1']\n\n\n@register(segment=[\n 'dev_matched', 'dev_mismatched', 'test_matched', 'test_mismatched',\n 'train'\n]) # pylint: disable=c0301\nclass MNLIDataset(GLUEDataset):\n \"\"\"Task class for Multi-Genre Natural Language Inference\n Parameters\n ----------\n segment : str or list of str, default 'train'\n Dataset segment. Options are 'dev_matched', 'dev_mismatched',\n 'test_matched', 'test_mismatched', 'train' or their combinations.\n root : str, default '$GLUE_DIR/MNLI'\n Path to the folder which stores the MNLI dataset.\n The datset can be downloaded by the following script:\n https://gist.github.com/W4ngatang/60c2bdb54d156a41194446737ce03e2e\n \"\"\"\n\n task_name = 'MNLI'\n is_pair = True\n\n def __init__(self,\n segment='train',\n root=os.path.join(os.getenv('GLUE_DIR', 'glue_data'),\n 'MNLI')): # pylint: disable=c0330\n self._supported_segments = [\n 'train', 'dev_matched', 'dev_mismatched',\n 'test_matched', 'test_mismatched',\n ]\n assert segment in self._supported_segments, 'Unsupported segment: %s' % segment\n path = os.path.join(root, '%s.tsv' % segment)\n if segment in ['train', 'dev_matched', 'dev_mismatched']:\n A_IDX, B_IDX = 8, 9\n LABEL_IDX = 11 if segment == 'train' else 15\n fields = [A_IDX, B_IDX, LABEL_IDX]\n elif segment in ['test_matched', 'test_mismatched']:\n A_IDX, B_IDX = 8, 9\n fields = [A_IDX, B_IDX]\n super(MNLIDataset, self).__init__(\n path, num_discard_samples=1, fields=fields)\n\n @staticmethod\n def get_labels():\n \"\"\"Get classification label ids of the dataset.\"\"\"\n return ['neutral', 'entailment', 'contradiction']\n\n @staticmethod\n def get_metric():\n \"\"\"Get metrics Accuracy\"\"\"\n return Accuracy()\n\n\n@register(segment=['train', 'dev', 'test'])\nclass WNLIDataset(GLUEDataset):\n \"\"\"Class for Winograd NLI task\n\n Parameters\n ----------\n segment : str or list of str, default 'train'\n Dataset segment. Options are 'train', 'val', 'test' or their combinations.\n root : str, default '$GLUE_DIR/WNLI'\n Path to the folder which stores the WNLI dataset.\n The datset can be downloaded by the following script:\n https://gist.github.com/W4ngatang/60c2bdb54d156a41194446737ce03e2e\n \"\"\"\n task_name = 'WNLI'\n is_pair = True\n\n def __init__(self,\n segment='train',\n root=os.path.join(\n os.getenv('GLUE_DIR', 'glue_data'), task_name)):\n self._supported_segments = ['train', 'dev', 'test']\n assert segment in self._supported_segments, 'Unsupported segment: %s' % segment\n path = os.path.join(root, '%s.tsv' % segment)\n if segment in ['train', 'dev']:\n A_IDX, B_IDX, LABEL_IDX = 1, 2, 3\n fields = [A_IDX, B_IDX, LABEL_IDX]\n elif segment == 'test':\n A_IDX, B_IDX = 1, 2\n fields = [A_IDX, B_IDX]\n super(WNLIDataset, self).__init__(\n path, num_discard_samples=1, fields=fields)\n\n @staticmethod\n def get_labels():\n \"\"\"Get classification label ids of the dataset.\"\"\"\n return ['0', '1']\n\n @staticmethod\n def get_metric():\n \"\"\"Get metrics Accuracy\"\"\"\n return Accuracy()\n\n\nclass BERTDatasetTransform(object):\n \"\"\"Dataset Transformation for BERT-style Sentence Classification or Regression.\n\n Parameters\n ----------\n tokenizer : BERTTokenizer.\n Tokenizer for the sentences.\n max_seq_length : int.\n Maximum sequence length of the sentences.\n labels : list of int , float or None. defaults None\n List of all label ids for the classification task and regressing task.\n If labels is None, the default task is regression\n pad : bool, default True\n Whether to pad the sentences to maximum length.\n pair : bool, default True\n Whether to transform sentences or sentence pairs.\n label_dtype: int32 or float32, default float32\n label_dtype = int32 for classification task\n label_dtype = float32 for regression task\n \"\"\"\n\n def __init__(self,\n tokenizer,\n max_seq_length,\n labels=None,\n pad=True,\n pair=True,\n label_dtype='float32'):\n self.label_dtype = label_dtype\n self.labels = labels\n if self.labels:\n self._label_map = {}\n for (i, label) in enumerate(labels):\n self._label_map[label] = i\n self._bert_xform = BERTSentenceTransform(\n tokenizer, max_seq_length, pad=pad, pair=pair)\n\n def __call__(self, line):\n \"\"\"Perform transformation for sequence pairs or single sequences.\n\n The transformation is processed in the following steps:\n - tokenize the input sequences\n - insert [CLS], [SEP] as necessary\n - generate type ids to indicate whether a token belongs to the first\n sequence or the second sequence.\n - generate valid length\n\n For sequence pairs, the input is a tuple of 3 strings:\n text_a, text_b and label.\n\n Inputs:\n text_a: 'is this jacksonville ?'\n text_b: 'no it is not'\n label: '0'\n Tokenization:\n text_a: 'is this jack ##son ##ville ?'\n text_b: 'no it is not .'\n Processed:\n tokens: '[CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]'\n type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n valid_length: 14\n label: 0\n\n For single sequences, the input is a tuple of 2 strings: text_a and label.\n Inputs:\n text_a: 'the dog is hairy .'\n label: '1'\n Tokenization:\n text_a: 'the dog is hairy .'\n Processed:\n text_a: '[CLS] the dog is hairy . [SEP]'\n type_ids: 0 0 0 0 0 0 0\n valid_length: 7\n label: 1\n\n Parameters\n ----------\n line: tuple of str\n Input strings. For sequence pairs, the input is a tuple of 3 strings:\n (text_a, text_b, label). For single sequences, the input is a tuple\n of 2 strings: (text_a, label).\n\n Returns\n -------\n np.array: input token ids in 'int32', shape (batch_size, seq_length)\n np.array: valid length in 'int32', shape (batch_size,)\n np.array: input token type ids in 'int32', shape (batch_size, seq_length)\n np.array: classification task: label id in 'int32', shape (batch_size, 1),\n regression task: label in 'float32', shape (batch_size, 1)\n \"\"\"\n input_ids, valid_length, segment_ids = self._bert_xform(line[:-1])\n\n label = line[-1]\n if self.labels: # for classification task\n label = self._label_map[label]\n label = np.array([label], dtype=self.label_dtype)\n\n return input_ids, valid_length, segment_ids, label\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
efogliatto/Tesis | [
"058fa0c2e23cd538621d17d41bb216a4db4d211a"
] | [
"Imagenes/FC72/Fint/Coexistencia/postMaxwell.py"
] | [
"import os\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nimport argparse\n\nimport collections\n\nimport glob\n\nimport MaxwellConstruction as mx\n\nfrom paraview.simple import *\n\nimport locale\n\n\n\n\n\n\nif __name__ == \"__main__\":\n\n\n\n # Argumentos de consola\n \n parser = argparse.ArgumentParser(description='Resolución del problema de construcción de Maxwell para diferentes constantes')\n\n parser.add_argument('-png', help='Imagen en formato png', action='store_true') \n\n args = parser.parse_args()\n \n\n \n # Estilo\n\n plt.style.use('thesis_classic')\n\n colorList = ['r', 'b', 'g', 'y']\n\n mkList = ['o', 's', '^', '*'] \n\n \n\n # Lista con parametros\n\n paramList = [ [1./50., 2./21., 0.5, 0.125, 1.25],\n [1./50., 2./21., 0.5, 0.1, 1.25] ]\n \n\n\n # Directorio del caso y limpieza\n \n main_dir = os.getcwd() \n\n \n\n\n # Movimiento en todos los parametros\n \n for i,param in enumerate(paramList):\n\n\n # Deteccion de Temperaturas simuladas\n \n cases_dir = main_dir + '/a_{:.4f}_b_{:.4f}_w_{:.4f}_sigma_{:.4f}_beta_{:.4f}/'.format(param[0], param[1], param[2], param[3], param[4])\n\n flist = glob.glob( cases_dir + '/Tr_' + '*' ) \n \n trlist = {}\n\n for a in flist:\n \n trlist[a] = float( a[len(cases_dir)+3:] )\n\n\n\n # Carga del caso en paraview\n\n rhogList = []\n\n rholList = []\n\n TList = []\n\n for fname, Tr in trlist.items():\n\n \n # Carga del caso\n\n lbmcase = EnSightReader( CaseFileName = fname + '/lbm.case')\n\n times = lbmcase.TimestepValues\n\n lbmcase.PointArrays = ['rho']\n\n \n\n # Ultimo paso de tiempo\n\n lbmcase.UpdatePipeline( times[-1] )\n\n \n\n # Valores maximos\n\n extrema = lbmcase.PointData.GetArray('rho').GetRange()\n\n\n # Listas para graficos\n\n TList.append(Tr)\n\n prob = mx.EOS( 'Peng-Robinson', a = param[0], b = param[1], w = param[2] )\n \n rhogList.append( extrema[0]/prob.rhoc() )\n\n rholList.append( extrema[1]/prob.rhoc() ) \n\n\n locale.setlocale(locale.LC_ALL, \"es_AR.UTF-8\")\n\n plt.plot( rhogList,\n TList,\n label = r'$\\sigma={:n}$'.format(param[3]),\n linestyle = 'None',\n mec = colorList[i],\n marker = mkList[i],\n mfc = 'None')\n\n plt.plot( rholList,\n TList,\n linestyle = 'None',\n mec = colorList[i],\n marker = mkList[i],\n mfc = 'None')\n\n\n\n\n\n\n # Curva de coexistencia de Van Der Waals\n\n\n def ordToList( dict ):\n \n col = collections.OrderedDict(sorted(dict.items()))\n\n x = []\n \n y = []\n \n for k,v in col.items():\n\n x.append(k)\n y.append(v)\n\n return x,y\n\n\n \n\n TEos = np.concatenate( [np.arange(0.6,0.925,0.025) , np.array([0.925, 0.94, 0.95, 0.975, 0.98, 0.99, 0.9925, 0.995]) ] )\n\n prob = mx.EOS('Peng-Robinson', w = param[2])\n\n coex = {1:1}\n\n for i,T in enumerate(TEos): \n\n step = 0.999\n if T < 0.6:\n step = 0.9999\n \n \n if T >= 0.8:\n Vrmin,Vrmax = mx.coexistencia(prob, T, plotPV=False, Vspace=(0.3,50,10000), step_size=step)\n\n else:\n Vrmin,Vrmax = mx.coexistencia(prob, T, plotPV=False, Vspace=(0.28,4000,200000), step_size=step) \n\n coex[1/Vrmin] = T\n coex[1/Vrmax] = T\n\n coex = ordToList( collections.OrderedDict(sorted(coex.items())) )\n\n locale.setlocale(locale.LC_ALL, \"es_AR.UTF-8\")\n \n plt.plot(coex[0], coex[1], color='k', label=r'Peng-Robinson ($\\omega$={:n})'.format(param[2]))\n\n \n\n\n locale.setlocale(locale.LC_ALL, \"es_AR.UTF-8\")\n \n plt.ylabel(r'$T/T_c$')\n\n plt.xlabel(r'$\\rho/\\rho_c$')\n\n plt.xscale('log')\n\n plt.legend(loc = 'best', framealpha=1)\n\n\n \n if args.png == True:\n\n plt.savefig( 'pr_sigma.png', format='png', bbox_inches = 'tight', dpi=600 )\n\n else:\n \n plt.savefig( 'pr_sigma.pdf', format='pdf', bbox_inches = 'tight', dpi=600 )\n\n \n\n plt.gcf().clear()\n\n \n\n\n \n\n\n \n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xscale",
"numpy.arange",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
djmango/bumblebeetrashcan | [
"ebb05f207801dd93b01e77e85b66324cabef8ce2"
] | [
"train.py"
] | [
"import os\nfrom pathlib import Path\nimport os\nimport torch\nimport pandas as pd\nfrom skimage import io, transform\nimport numpy as np\nimport time\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\n\nHERE = Path(__file__).parent.absolute()\n\nclass ClockDataset(Dataset):\n \"\"\" Clock dataset \"\"\"\n\n def __init__(self, csv_file, root_dir, transform=None):\n \"\"\"\n Args:\n csv_file (string): Path to the csv file with annotations.\n root_dir (string): Directory with all the images.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n self.annotations_frame = pd.read_csv(csv_file)\n self.root_dir = root_dir\n self.transform = transform\n\n def __len__(self):\n return len(self.annotations_frame)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n\n img_name = os.path.join(self.root_dir,\n self.annotations_frame.iloc[idx, 0])\n image = io.imread(img_name)\n landmarks = self.annotations_frame.iloc[idx, 1:]\n landmarks = np.array([landmarks])\n landmarks = landmarks.astype('float')\n sample = {'image': image, 'annotations': landmarks}\n\n if self.transform:\n sample = self.transform(sample)\n\n return sample\n\nclass Rescale(object):\n \"\"\"Rescale the image in a sample to a given size.\n\n Args:\n output_size (tuple or int): Desired output size. If tuple, output is\n matched to output_size. If int, smaller of image edges is matched\n to output_size keeping aspect ratio the same.\n \"\"\"\n\n def __init__(self, output_size):\n assert isinstance(output_size, (int, tuple))\n self.output_size = output_size\n\n def __call__(self, sample):\n image, annotations = sample['image'], sample['annotations']\n\n h, w = image.shape[:2]\n if isinstance(self.output_size, int):\n if h > w:\n new_h, new_w = self.output_size * h / w, self.output_size\n else:\n new_h, new_w = self.output_size, self.output_size * w / h\n else:\n new_h, new_w = self.output_size\n\n new_h, new_w = int(new_h), int(new_w)\n\n img = transform.resize(image, (new_h, new_w))\n\n return {'image': img, 'annotations': annotations}\n\nclass ToTensor(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n\n def __call__(self, sample):\n image, annotations = sample['image'], sample['annotations']\n\n # swap color axis because\n # numpy image: H x W x C\n # torch image: C X H X W\n image = image.transpose((2, 0, 1))\n return {'image': torch.from_numpy(image),\n 'annotations': torch.from_numpy(annotations)}\n\ndef clock():\n files = sorted(os.listdir(HERE.joinpath('traindata', 'clock')))\n dataset = ClockDataset(csv_file='traindata/clock/annotations.csv', root_dir='traindata/clock/')\n\n for i in range(len(dataset)):\n sample = dataset[i]\n print(i, sample['image'].shape, sample['annotations'].shape)\n\n\nif __name__ == '__main__':\n pass"
] | [
[
"torch.from_numpy",
"numpy.array",
"pandas.read_csv",
"torch.is_tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
yogeshk4/EduMeet | [
"b86dfbe525a2f4da6946d8684816333cdda6654b"
] | [
"src/train.py"
] | [
"import argparse\nfrom pathlib import Path\n\nfrom tensorflow.keras.applications import Xception\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.layers import GlobalAveragePooling2D, Dense\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.losses import SparseCategoricalCrossentropy\nfrom tensorflow.keras.callbacks import EarlyStopping, TensorBoard\n# GPU config if using gpu then uncomment following lines\n# import tensorflow as tf\n# gpus = tf.config.experimental.list_physical_devices('GPU')\n# tf.config.experimental.set_memory_growth(gpus[0], True)\n\nfrom input_pipeline import get_dataset, img_width, img_height\n\n\nfinetune_at = 116\nbase_learning_rate = 0.0001\nold_epoch = 0\nepochs = 10\n\n\ndef get_model(weight_dir, out_dir, fullyconnected=False, finetune=False):\n \"\"\"\n Creates custom model on top of Xception for user engagement\n recognition.\n\n Returns:\n model for the training.\n \"\"\"\n weights = Path(weight_dir)\n if finetune:\n if fullyconnected:\n base_model = load_model(str(out_dir) + \"/Xception_on_DAiSEE_fc.h5\")\n else:\n base_model = load_model(str(out_dir) + \"/Xception_on_DAiSEE.h5\")\n\n base_model.trainable = True\n for layer in base_model.layers[:finetune_at]:\n layer.trainable = False\n return base_model\n else:\n xception = \"xception_weights_tf_dim_ordering_tf_kernels_notop.h5\"\n weights = weights / xception\n base_model = Xception(weights=str(weights),\n include_top=False,\n input_shape=(img_width, img_height, 3))\n\n base_model.trainable = False\n x = GlobalAveragePooling2D()(base_model.output)\n if fullyconnected:\n x = Dense(128, activation=\"relu\", name=\"fc1\")(x)\n x = Dense(64, activation=\"relu\", name=\"fc2\")(x)\n boredom = Dense(4, name=\"y1\")(x)\n engagement = Dense(4, name=\"y2\")(x)\n confusion = Dense(4, name=\"y3\")(x)\n frustration = Dense(4, name=\"y4\")(x)\n model = Model(inputs=base_model.input,\n outputs=[boredom, engagement, confusion, frustration])\n return model\n\n\ndef main(weight_dir, numpy_dir, out_dir, fullyconnected=False, finetune=False):\n \"\"\"\n Creates trained model for user engagement recognition.\n\n Args:\n weight_dir: Directory which contains pretrained weights for\n Xception with include_top=False.\n numpy_dir: Directory which contains filepath and labels array.\n out_dir: Directory to store models and logs.\n fullyconnected: Boolean indicating wheater to add two fully\n connected layers on top of Xception before the\n classification head or not, default to False.\n finetune: Boolean indicating wheater to finetune the model or\n not, default to False.\n \"\"\"\n global old_epoch\n out_dir = Path(out_dir)\n out_dir.mkdir(parents=True, exist_ok=True)\n log_dir = out_dir / \"logs\"\n log_dir.mkdir(parents=True, exist_ok=True)\n\n train_ds = get_dataset(\"Train\", numpy_dir)\n validation_ds = get_dataset(\"Validation\", numpy_dir)\n model = get_model(weight_dir, out_dir, fullyconnected, finetune)\n\n if finetune:\n lr = base_learning_rate / 10\n finetune_epochs = 10\n if fullyconnected:\n model_path = str(out_dir) + \"/Xception_on_DAiSEE_finetune_fc.h5\"\n else:\n model_path = str(out_dir) + \"/Xception_on_DAiSEE_finetune.h5\"\n else:\n lr = base_learning_rate\n finetune_epochs = 0\n if fullyconnected:\n model_path = str(out_dir) + \"/Xception_on_DAiSEE_fc.h5\"\n else:\n model_path = str(out_dir) + \"/Xception_on_DAiSEE.h5\"\n\n model.compile(optimizer=RMSprop(learning_rate=lr),\n loss={\"y1\": SparseCategoricalCrossentropy(from_logits=True),\n \"y2\": SparseCategoricalCrossentropy(from_logits=True),\n \"y3\": SparseCategoricalCrossentropy(from_logits=True),\n \"y4\": SparseCategoricalCrossentropy(from_logits=True)},\n metrics={\"y1\": \"sparse_categorical_accuracy\",\n \"y2\": \"sparse_categorical_accuracy\",\n \"y3\": \"sparse_categorical_accuracy\",\n \"y4\": \"sparse_categorical_accuracy\"})\n print(model.summary())\n\n callbacks = [\n EarlyStopping(monitor='val_loss', min_delta=1e-2,\n patience=2, verbose=1),\n TensorBoard(log_dir=str(log_dir))\n ]\n\n total_epochs = epochs + finetune_epochs\n history = model.fit(train_ds,\n epochs=total_epochs,\n initial_epoch=old_epoch,\n callbacks=callbacks,\n validation_data=validation_ds)\n if finetune:\n old_epoch = 0\n else:\n old_epoch = history.epoch[-1]\n print(history.history)\n model.save(model_path)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Get trained model.\")\n grp = parser.add_argument_group(\"Required arguments\")\n grp.add_argument(\"-i\", \"--weight_dir\", type=str, required=True,\n help=\"Directory which contains pretrained weights for \"\n \"Xception.\")\n grp.add_argument(\"-n\", \"--numpy_dir\", type=str, required=True,\n help=\"Directory which contains filepath and label array.\")\n grp.add_argument(\"-o\", \"--out_dir\", type=str, required=True,\n help=\"Directory to store trained model and logs.\")\n args = parser.parse_args()\n main(args.weight_dir, args.numpy_dir, args.out_dir)\n main(args.weight_dir, args.numpy_dir, args.out_dir, finetune=True)\n main(args.weight_dir, args.numpy_dir, args.out_dir, fullyconnected=True)\n main(args.weight_dir, args.numpy_dir, args.out_dir,\n fullyconnected=True, finetune=True)\n"
] | [
[
"tensorflow.keras.layers.GlobalAveragePooling2D",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.optimizers.RMSprop",
"tensorflow.keras.Model",
"tensorflow.keras.callbacks.EarlyStopping"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
eric11eca/inference-information-probing | [
"f55156201992cb024edf112e06dd2d7fe09381e4"
] | [
"inform_prob/process.py"
] | [
"import os\nimport sys\nimport argparse\nimport logging\nimport torch\nimport fasttext\nimport fasttext.util\nfrom conllu import parse_incr\nfrom scipy.sparse import lil_matrix\nfrom transformers import BertTokenizer, BertModel\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-m\", \"--batch-size\",\n help=\"The size of the mini batches\",\n default=8,\n required=False,\n type=int)\n parser.add_argument(\"--language\",\n help=\"The language to use\",\n required=True,\n type=str)\n parser.add_argument(\"--ud-path\",\n help=\"The path to raw ud data\",\n default='data/ud/ud-treebanks-v2.5/',\n required=False,\n type=str)\n parser.add_argument(\"--output-path\",\n help=\"The path to save processed data\",\n default='data/processed/',\n required=False,\n type=str)\n args = parser.parse_args()\n logging.info(args)\n\n return args\n\n\ndef load_fasttext():\n ft_path = '../data/fasttext'\n ft_fname = os.path.join(ft_path, 'cc.english.300.bin')\n if not os.path.exists(ft_fname):\n logging.info(\"Downloading fasttext model\")\n temp_fname = fasttext.util.download_model(\n \"english\", if_exists='ignore')\n os.rename(temp_fname, ft_fname)\n os.rename(temp_fname + '.gz', ft_fname + '.gz')\n\n logging.info(\"Loading fasttext model\")\n return fasttext.load_model(ft_fname)\n\n\ndef get_fasttext(fasttext_model, words):\n embeddings = [[fasttext_model[word] for word in sentence]\n for sentence in words]\n return embeddings\n\n\ndef process_file(words, fasttext_model, output_file):\n logging.info(\"PHASE FOUR: getting fasttext embeddings\")\n fast_embeddings = get_fasttext(fasttext_model, words)\n\n logging.info(\"PHASE FIVE: saving\")\n output_data_raw = list(\n zip(bert_embeddings, fast_embeddings, all_ud, words))\n del bert_embeddings, fast_embeddings, all_ud, words\n\n # Prune the failed attempts:\n output_data = [(bert_embs, fast_embs, ud, words) for (\n bert_embs, fast_embs, ud, words) in output_data_raw if bert_embs != []]\n del output_data_raw\n output_ud = [(ud, words) for (_, _, ud, words) in output_data]\n output_bert = [(bert_embs, words)\n for (bert_embs, _, _, words) in output_data]\n output_fast = [(fast_embeddings, words)\n for (_, fast_embs, _, words) in output_data]\n del output_data\n\n # Pickle, compress, and save\n util.write_data(output_file % 'fast', output_fast)\n del output_fast\n\n logging.info(\"Completed {}\".format(ud_file))\n\n\ndef process(language, ud_path, batch_size, bert_name, output_path):\n logging.info(\"Loading FastText Embedding\")\n fasttext_model = load_fasttext(language)\n\n logging.info(\"Precessing language %s\" % language)\n ud_file_base = get_ud_file_base(ud_path, language)\n output_file_base = get_data_file_base(output_path, language)\n for mode in ['train', 'dev', 'test']:\n ud_file = ud_file_base % mode\n output_file = output_file_base % (mode, '%s')\n process_file(bert_model, bert_tokenizer, fasttext_model,\n batch_size, language, ud_file, output_file)\n\n logging.info(\"Process finished\")\n\n\ndef main():\n logging.basicConfig(\n format='%(asctime)s : %(levelname)s : %(processName)s : %(message)s', level=logging.INFO)\n args = get_args()\n\n batch_size = args.batch_size\n language = args.language\n ud_path = args.ud_path\n output_path = args.output_path\n bert_name = 'bert-base-multilingual-cased'\n\n with torch.no_grad():\n process(language, ud_path, batch_size, bert_name, output_path)\n\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"torch.no_grad"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jamesxwang/monitoring-athletes-performance | [
"7df504711202a31a408ae1072ca5e8fbaf1cb5f9"
] | [
"main/fit_file_convert/check_empty.py"
] | [
"import os\nimport pandas as pd\n\n\ndef check_empty():\n fit_csv_path = '{}/fit_processing/subject_data/mysubjectname/fit_csv'.format(os.path.pardir)\n # fit_csv_path = '{}/fit_processing/activities'.format(os.path.pardir)\n dirs = os.listdir(fit_csv_path)\n total_count = 0\n empty_count = 0\n for file_name in dirs:\n total_count += 1\n if file_name.endswith(\".csv\"):\n csv_file = '{}/{}'.format(fit_csv_path, file_name)\n data = pd.read_csv(csv_file)\n if data.shape[0] == 0:\n empty_count += 1\n print(\"Total count: \", total_count, \"Empty count: \", empty_count)\n\n\nif __name__ == '__main__':\n check_empty()"
] | [
[
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
SuperCowPowers/zat | [
"fed88c4310cf70c8b01c9a7eb0918b8c4d117e77"
] | [
"zat/data_generator.py"
] | [
"\"\"\"Silly data generator (Faker (https://github.com/joke2k/faker) and others\n are much better, but we just need something simple\"\"\"\n\nimport string\n\n# Third Party\nimport pandas as pd\nimport numpy as np\n\n\ndef df_random(num_numeric=3, num_categorical=3, num_rows=100):\n \"\"\"Generate a dataframe with random data. This is a general method\n to easily generate a random dataframe, for more control of the\n random 'distributions' use the column methods (df_numeric_column, df_categorical_column)\n For other distributions you can use numpy methods directly (see example at bottom of this file)\n Args:\n num_numeric (int): The number of numeric columns (default = 3)\n num_categorical (int): The number of categorical columns (default = 3)\n num_rows (int): The number of rows to generate (default = 100)\n \"\"\"\n\n # Construct DataFrame\n df = pd.DataFrame()\n column_names = string.ascii_lowercase\n\n # Create numeric columns\n for name in column_names[:num_numeric]:\n df[name] = df_numeric_column(num_rows=num_rows)\n\n # Create categorical columns\n for name in column_names[num_numeric:num_numeric+num_categorical]:\n df[name] = df_categorical_column(['foo', 'bar', 'baz'], num_rows=num_rows)\n\n # Return the dataframe\n return df\n\n\ndef df_numeric_column(min_value=0, max_value=1, num_rows=100):\n \"\"\"Generate a numeric column with random data\n Args:\n min_value (float): Minimum value (default = 0)\n max_value (float): Maximum value (default = 1)\n num_rows (int): The number of rows to generate (default = 100)\n \"\"\"\n # Generate numeric column\n return pd.Series(np.random.uniform(min_value, max_value, num_rows))\n\n\ndef df_categorical_column(category_values, num_rows=100, probabilities=None):\n \"\"\"Generate a categorical column with random data\n Args:\n category_values (list): A list of category values (e.g. ['red', 'blue', 'green'])\n num_rows (int): The number of rows to generate (default = 100)\n probabilities (list): A list of probabilities of each value (e.g. [0.6, 0.2, 0.2]) (default=None an equal probability)\n \"\"\"\n splitter = np.random.choice(range(len(category_values)), num_rows, p=probabilities)\n return pd.Series(pd.Categorical.from_codes(splitter, categories=category_values))\n\n\ndef test():\n \"\"\"Test the data generator methods\"\"\"\n df = df_random()\n print('Random DataFrame')\n print(df.head())\n\n # Test the numerical column generator\n df['delta_v'] = df_numeric_column(-100, 100)\n print('\\nNumerical column generator (added delta_v)')\n print(df.head())\n\n # Test the categorical column generator\n df['color'] = df_categorical_column(['red', 'green', 'blue'])\n print('\\nCategorical column generator (added color)')\n print(df.head())\n\n # Test the categorical column generator with probabilities\n df['color'] = df_categorical_column(['red', 'green', 'blue'], probabilities=[0.6, 0.3, 0.1])\n print('\\nProbabilities should be ~60% red, %30 green and %10 blue')\n print(df['color'].value_counts())\n\n # Also we can just use the built in Numpy method for detailed control\n # over the numeric distribution\n my_series = pd.Series(np.random.normal(0, 1, 1000))\n print('\\nStats on numpy normal (gaussian) distribution')\n print(my_series.describe())\n\n\nif __name__ == '__main__':\n test()\n"
] | [
[
"pandas.Categorical.from_codes",
"numpy.random.uniform",
"numpy.random.normal",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
Rahul-Dwivedi-07/Autonomous-Vehicle-Self-Driving-Car- | [
"1441bcbf71187cdf8e8250eb0c0a0556fa08b8f5"
] | [
"lanes_coordinates_print.py"
] | [
"import cv2\r\nimport numpy as np\r\n\r\ndef canny(image):\r\n gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)\r\n blur = cv2.GaussianBlur(gray,(5,5),0)\r\n #canny = cv2.Canny(blur,low_threshold,high_threshold)\r\n canny = cv2.Canny(blur,50,150)\r\n return canny\r\n\r\ndef region_of_interest(image):\r\n height = image.shape[0]\r\n polygons = np.array([\r\n [(200,height),(1100,height),(550,250)]\r\n ])\r\n mask = np.zeros_like(image)\r\n cv2.fillPoly(mask,polygons,255)\r\n masked_image = cv2.bitwise_and(image,mask)\r\n return masked_image\r\n\r\ndef average_slope_intercept(image,lines):\r\n left_fit = []\r\n right_fit = []\r\n for line in lines:\r\n print(line)\r\n x1,y1,x2,y2 = line.reshape(4)\r\n parameters = np.polyfit((x1,x2),(y1,y2),1)\r\n\r\nimage = cv2.imread('test_image.jpg')\r\nlane_image = np.copy(image)\r\n\r\ncanny_image = canny(lane_image)\r\ncropped_image = region_of_interest(canny_image)\r\n\r\nlines = cv2.HoughLinesP(cropped_image,2,np.pi/180,100,np.array([]),minLineLength=40,maxLineGap=5) #Threshold optimum value is 100\r\naverage_lines = average_slope_intercept(lane_image,lines)\r\n\r\ncv2.imshow('result',average_lines)\r\ncv2.waitKey(0)\r\n"
] | [
[
"numpy.copy",
"numpy.array",
"numpy.zeros_like",
"numpy.polyfit"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
SeanAchtatou/deepjanusexperiments | [
"c14585b7aef4c89e03a30e69b5d8bbac896d6a6a"
] | [
"DeepJanus-MNIST/archive_manager2.py"
] | [
"import csv\nimport json\nfrom os.path import join\n\nfrom folder import Folder\nfrom timer import Timer\nfrom utils import get_distance\nfrom evaluator import eval_archive_dist\nimport numpy as np\n\nfrom config import ARCHIVE_THRESHOLD, POPSIZE, NGEN, MUTLOWERBOUND, MUTUPPERBOUND, \\\n RESEEDUPPERBOUND, K_SD, MODEL_TUNED3, EXPLABEL, STOP_CONDITION, RUNTIME, REPORT_NAME, STEPSIZE\nfrom metrics import get_diameter, get_radius_reference\n\n\nclass Archive:\n\n def __init__(self):\n self.archive = list()\n self.archived_seeds = set()\n\n def get_archive(self):\n return self.archive\n\n def update_archive(self, ind):\n if ind not in self.archive:\n if len(self.archive) == 0:\n self.archive.append(ind)\n self.archived_seeds.add(ind.seed)\n else:\n # Find the member of the archive that is closest to the candidate.\n closest_archived = None\n d_min = np.inf\n i = 0\n while i < len(self.archive):\n distance_archived = eval_archive_dist(ind, self.archive[i])\n if distance_archived < d_min:\n closest_archived = self.archive[i]\n d_min = distance_archived\n i += 1\n # Decide whether to add the candidate to the archive\n # Verify whether the candidate is close to the existing member of the archive\n # Note: 'close' is defined according to a user-defined threshold\n if d_min <= ARCHIVE_THRESHOLD:\n # The candidate replaces the closest archive member if its members' distance is better\n dist_ind = ind.members_distance\n dist_archived_ind = get_distance(closest_archived.m1.purified,\n closest_archived.m2.purified)\n if dist_ind <= dist_archived_ind:\n self.archive.remove(closest_archived)\n self.archive.append(ind)\n self.archived_seeds.add(ind.seed)\n else:\n # Add the candidate to the archive if it is distant from all the other archive members\n self.archive.append(ind)\n self.archived_seeds.add(ind.seed)\n\n def get_min_distance_from_archive(self, seed):\n distances = list()\n for archived_ind in self.archive:\n dist_member1 = np.linalg.norm(archived_ind.m1.purified - seed)\n dist_member2 = np.linalg.norm(archived_ind.m2.purified - seed)\n avg_dist = (dist_member1 + dist_member2) / 2\n distances.append(avg_dist)\n min_dist = min(distances)\n return min_dist\n\n def create_report(self, x_test, seeds, generation):\n # Retrieve the solutions belonging to the archive.\n if generation == STEPSIZE:\n dst = join(Folder.DST, REPORT_NAME)\n with open(dst, mode='w') as report_file:\n report_writer = csv.writer(report_file,\n delimiter=',',\n quotechar='\"',\n quoting=csv.QUOTE_MINIMAL)\n\n report_writer.writerow([\"run\",\n 'iteration',\n 'timestamp',\n 'archive_len',\n 'sparseness',\n 'total_seeds',\n 'covered_seeds',\n 'final seeds',\n 'members_dist_min',\n 'members_dist_max',\n 'members_dist_avg',\n 'members_dist_std',\n 'radius_ref_out',\n 'radius_ref_in',\n 'diameter_out',\n 'diameter_in',\n 'iteration'])\n solution = [ind for ind in self.archive]\n n = len(solution)\n\n # Obtain misclassified member of an individual on the frontier.\n outer_frontier = []\n # Obtain correctly classified member of an individual on the frontier.\n inner_frontier = []\n for ind in solution:\n if ind.m1.predicted_label != ind.m1.expected_label:\n misclassified_member = ind.m1\n correct_member = ind.m2\n else:\n misclassified_member = ind.m2\n correct_member = ind.m1\n outer_frontier.append(misclassified_member)\n inner_frontier.append(correct_member)\n\n avg_sparseness = 0\n if n > 1:\n # Calculate sparseness of the solutions\n sumsparseness = 0\n\n for dig1 in outer_frontier:\n sumdistances = 0\n for dig2 in outer_frontier:\n if dig1 != dig2:\n sumdistances += np.linalg.norm(dig1.purified - dig2.purified)\n dig1.sparseness = sumdistances / (n - 1)\n sumsparseness += dig1.sparseness\n avg_sparseness = sumsparseness / n\n\n out_radius = None\n in_radius = None\n out_radius_ref = None\n in_radius_ref = None\n out_diameter = None\n in_diameter = None\n stats = [None] * 4\n final_seeds = []\n if len(solution) > 0:\n reference_filename = 'ref_digit/cinque_rp.npy'\n reference = np.load(reference_filename)\n out_diameter = get_diameter(outer_frontier)\n in_diameter = get_diameter(inner_frontier)\n final_seeds = self.get_seeds()\n stats = self.get_dist_members()\n out_radius_ref = get_radius_reference(outer_frontier, reference)\n in_radius_ref = get_radius_reference(inner_frontier, reference)\n\n if STOP_CONDITION == \"iter\":\n budget = NGEN\n elif STOP_CONDITION == \"time\":\n budget = RUNTIME\n else:\n budget = \"no budget\"\n config = {\n 'popsize': str(POPSIZE),\n 'budget': str(budget),\n 'budget_type': str(STOP_CONDITION),\n # TODO: unbound ind\n # 'label': str(ind.member1.expected_label),\n 'label': str(EXPLABEL),\n 'archive tshd': str(ARCHIVE_THRESHOLD),\n 'mut low': str(MUTLOWERBOUND),\n 'mut up': str(MUTUPPERBOUND),\n 'reseed': str(RESEEDUPPERBOUND),\n 'K': str(K_SD),\n 'model': str(MODEL_TUNED3),\n }\n\n dst = join(Folder.DST, \"config.json\")\n\n # dst = RESULTS_PATH + '/config.json'\n with open(dst, 'w') as f:\n (json.dump(config, f, sort_keys=True, indent=4))\n\n dst = join(Folder.DST, REPORT_NAME)\n with open(dst, mode='a') as report_file:\n report_writer = csv.writer(report_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\n timestamp, elapsed_time = Timer.get_timestamps()\n report_writer.writerow([Folder.run_id,\n str(generation),\n str(elapsed_time),\n str(n),\n str(avg_sparseness),\n str(len(seeds)),\n str(len(self.archived_seeds)),\n str(len(final_seeds)),\n str(stats[0]),\n str(stats[1]),\n str(stats[2]),\n str(stats[3]),\n str(out_radius_ref),\n str(in_radius_ref),\n str(out_radius),\n str(in_radius),\n str(out_diameter),\n str(in_diameter),\n str(generation)])\n\n def get_seeds(self):\n seeds = set()\n for ind in self.get_archive():\n seeds.add(ind.seed)\n return seeds\n\n def get_dist_members(self):\n distances = list()\n stats = [None] * 4\n for ind in self.get_archive():\n distances.append(ind.members_distance)\n\n stats[0] = np.min(distances)\n stats[1] = np.max(distances)\n stats[2] = np.mean(distances)\n stats[3] = np.std(distances)\n return stats\n"
] | [
[
"numpy.min",
"numpy.linalg.norm",
"numpy.max",
"numpy.std",
"numpy.mean",
"numpy.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ludwigwinkler/pytorch_MCMC | [
"4637cfea7e25031a85b1956446e4faa48e17918e"
] | [
"src/MCMC_Chain.py"
] | [
"import future, sys, os, datetime, argparse, copy, warnings, time\nfrom collections import MutableSequence, Iterable, OrderedDict\nfrom itertools import compress\nimport numpy as np\nfrom tqdm import tqdm\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\nmatplotlib.rcParams[\"figure.figsize\"] = [10, 10]\n\nimport torch\nfrom torch.nn import Module, Parameter\nfrom torch.nn import Linear, Tanh, ReLU\nimport torch.nn.functional as F\n\nTensor = torch.Tensor\nFloatTensor = torch.FloatTensor\n\ntorch.set_printoptions(precision=4, sci_mode=False)\nnp.set_printoptions(precision=4, suppress=True)\n\nsys.path.append(\"../../..\") # Up to -> KFAC -> Optimization -> PHD\nfrom pytorch_MCMC.src.MCMC_ProbModel import ProbModel\nfrom pytorch_MCMC.src.MCMC_Optim import SGLD_Optim, MetropolisHastings_Optim, MALA_Optim, HMC_Optim, SGNHT_Optim\nfrom pytorch_MCMC.src.MCMC_Acceptance import SDE_Acceptance, MetropolisHastingsAcceptance\nfrom Utils.Utils import RunningAverageMeter\n\n'''\nPython Container Time Complexity: https://wiki.python.org/moin/TimeComplexity\n'''\n\n\nclass Chain(MutableSequence):\n\n\t'''\n\tA container for storing the MCMC chain conveniently:\n\tsamples: list of state_dicts\n\tlog_probs: list of log_probs\n\taccepts: list of bools\n\tstate_idx:\n\t\tinit index of last accepted via np.where(accepts==True)[0][-1]\n\t\tcan be set via len(samples) while sampling\n\n\t@property\n\tsamples: filters the samples\n\n\n\t'''\n\n\tdef __init__(self, probmodel=None):\n\n\t\tsuper().__init__()\n\n\t\tif probmodel is None:\n\t\t\t'''\n\t\t\tCreate an empty chain\n\t\t\t'''\n\t\t\tself.state_dicts = []\n\t\t\tself.log_probs = []\n\t\t\tself.accepts = []\n\n\t\tif probmodel is not None:\n\t\t\t'''\n\t\t\tInitialize chain with given model\n\t\t\t'''\n\t\t\tassert isinstance(probmodel, ProbModel)\n\n\t\t\tself.state_dicts = [copy.deepcopy(probmodel.state_dict())]\n\t\t\tlog_prob = probmodel.log_prob(*next(probmodel.dataloader.__iter__()))\n\t\t\tlog_prob['log_prob'].detach_()\n\t\t\tself.log_probs = [copy.deepcopy(log_prob)]\n\t\t\tself.accepts = [True]\n\t\t\tself.last_accepted_idx = 0\n\n\t\t\tself.running_avgs = {}\n\t\t\tfor key, value in log_prob.items():\n\t\t\t\tself.running_avgs.update({key: RunningAverageMeter(0.99)})\n\n\t\tself.running_accepts = RunningAverageMeter(0.999)\n\n\tdef __len__(self):\n\t\treturn len(self.state_dicts)\n\n\tdef __iter__(self):\n\t\treturn zip(self.state_dicts, self.log_probs, self.accepts)\n\n\tdef __delitem__(self):\n\t\traise NotImplementedError\n\n\tdef __setitem__(self):\n\t\traise NotImplementedError\n\n\tdef insert(self):\n\t\traise NotImplementedError\n\n\tdef __repr__(self):\n\t\treturn f'MCMC Chain: Length:{len(self)} Accept:{self.accept_ratio:.2f}'\n\n\tdef __getitem__(self, i):\n\t\tchain = copy.deepcopy(self)\n\t\tchain.state_dicts = self.samples[i]\n\t\tchain.log_probs = self.log_probs[i]\n\t\tchain.accepts = self.accepts[i]\n\t\treturn chain\n\n\tdef __add__(self, other):\n\n\t\tif type(other) in [tuple, list]:\n\t\t\tassert len(other) == 3, f\"Invalid number of information pieces passed: {len(other)} vs len(Iterable(model, log_prob, accept, ratio))==4\"\n\t\t\tself.append(*other)\n\t\telif isinstance(other, Chain):\n\t\t\tself.cat(other)\n\n\t\treturn self\n\n\tdef __iadd__(self, other):\n\n\t\tif type(other) in [tuple, list]:\n\t\t\tassert len(other)==3, f\"Invalid number of information pieces passed: {len(other)} vs len(Iterable(model, log_prob, accept, ratio))==4\"\n\t\t\tself.append(*other)\n\t\telif isinstance(other, Chain):\n\t\t\tself.cat_chains(other)\n\n\t\treturn self\n\n\t@property\n\tdef state_idx(self):\n\t\t'''\n\t\tReturns the index of the last accepted sample a.k.a. the state of the chain\n\n\t\t'''\n\t\tif not hasattr(self, 'state_idx'):\n\t\t\t'''\n\t\t\tIf the chain hasn't a state_idx, compute it from self.accepts by taking the last True of self.accepts\n\t\t\t'''\n\t\t\tself.last_accepted_idx = np.where(self.accepts==True)[0][-1]\n\t\t\treturn self.last_accepted_idx\n\t\telse:\n\t\t\t'''\n\t\t\tCheck that the state of the chain is actually the last True in self.accepts\n\t\t\t'''\n\t\t\tlast_accepted_sample_ = np.where(self.accepts == True)[0][-1]\n\t\t\tassert last_accepted_sample_ == self.last_accepted_idx\n\t\t\tassert self.accepts[self.last_accepted_idx]==True\n\t\t\treturn self.last_accepted_idx\n\n\n\t@property\n\tdef samples(self):\n\t\t'''\n\t\tFilters the list of state_dicts with the list of bools from self.accepts\n\t\t:return: list of accepted state_dicts\n\t\t'''\n\t\treturn list(compress(self.state_dicts, self.accepts))\n\n\t@property\n\tdef accept_ratio(self):\n\t\t'''\n\t\tSum the boolean list (=total number of Trues) and divides it by its length\n\t\t:return: float valued accept ratio\n\t\t'''\n\t\treturn sum(self.accepts)/len(self.accepts)\n\n\t@property\n\tdef state(self):\n\t\treturn {'state_dict': self.state_dicts[self.last_accepted_idx], 'log_prob': self.log_probs[self.last_accepted_idx]}\n\n\tdef cat_chains(self, other):\n\n\t\tassert isinstance(other, Chain)\n\t\tself.state_dicts += other.state_dicts\n\t\tself.log_probs += other.log_probs\n\t\tself.accepts += other.accepts\n\n\t\tfor key, value in other.running_avgs.items():\n\t\t\tself.running_avgs[key].avg = 0.5*self.running_avgs[key].avg + 0.5 * other.running_avgs[key].avg\n\n\n\tdef append(self, probmodel, log_prob, accept):\n\n\t\tif isinstance(probmodel, ProbModel):\n\t\t\tparams_state_dict = copy.deepcopy(probmodel.state_dict())\n\t\telif isinstance(probmodel, OrderedDict):\n\t\t\tparams_state_dict = copy.deepcopy(probmodel)\n\t\tassert isinstance(log_prob, dict)\n\t\tassert type(log_prob['log_prob'])==torch.Tensor\n\t\tassert log_prob['log_prob'].numel()==1\n\n\t\tlog_prob['log_prob'].detach_()\n\n\n\t\tself.accepts.append(accept)\n\t\tself.running_accepts.update(1 * accept)\n\n\t\tif accept:\n\t\t\tself.state_dicts.append(params_state_dict)\n\t\t\tself.log_probs.append(copy.deepcopy(log_prob))\n\t\t\tself.last_accepted_idx = len(self.state_dicts)-1\n\t\t\tfor key, value in log_prob.items():\n\t\t\t\tself.running_avgs[key].update(value.item())\n\n\t\telif not accept:\n\t\t\tself.state_dicts.append(False)\n\t\t\tself.log_probs.append(False)\n\nclass Sampler_Chain:\n\n\tdef __init__(self, probmodel, step_size, num_steps, burn_in, pretrain, tune):\n\n\t\tself.probmodel = probmodel\n\t\tself.chain = Chain(probmodel=self.probmodel)\n\n\t\tself.step_size = step_size\n\t\tself.num_steps = num_steps\n\t\tself.burn_in = burn_in\n\n\t\tself.pretrain = pretrain\n\t\tself.tune = tune\n\n\tdef propose(self):\n\t\traise NotImplementedError\n\n\tdef __repr__(self):\n\t\traise NotImplementedError\n\n\tdef tune_step_size(self):\n\n\t\ttune_interval_length = 100\n\t\tnum_tune_intervals = int(self.burn_in // tune_interval_length)\n\n\t\tverbose = True\n\n\t\tprint(f'Tuning: Init Step Size: {self.optim.param_groups[0][\"step_size\"]:.5f}')\n\n\t\tself.probmodel.reset_parameters()\n\t\ttune_chain = Chain(probmodel=self.probmodel)\n\t\ttune_chain.running_accepts.momentum = 0.5\n\n\t\tprogress = tqdm(range(self.burn_in))\n\t\tfor tune_step in progress:\n\n\n\n\t\t\tsample_log_prob, sample = self.propose()\n\t\t\taccept, log_ratio = self.acceptance(sample_log_prob['log_prob'], self.chain.state['log_prob']['log_prob'])\n\t\t\ttune_chain += (self.probmodel, sample_log_prob, accept)\n\n\t\t\t# if tune_step < self.burn_in and tune_step % tune_interval_length == 0 and tune_step > 0:\n\t\t\tif tune_step > 1:\n\t\t\t\t# self.optim.dual_average_tune(tune_chain, np.exp(log_ratio.item()))\n\t\t\t\tself.optim.dual_average_tune(tune_chain.accepts[-tune_interval_length:], tune_step, np.exp(log_ratio.item()))\n\t\t\t\t# self.optim.tune(tune_chain.accepts[-tune_interval_length:])\n\n\t\t\tif not accept:\n\n\t\t\t\tif torch.isnan(sample_log_prob['log_prob']):\n\t\t\t\t\tprint(self.chain.state)\n\t\t\t\t\texit()\n\t\t\t\tself.probmodel.load_state_dict(self.chain.state['state_dict'])\n\n\t\t\tdesc = f'Tuning: Accept: {tune_chain.running_accepts.avg:.2f}/{tune_chain.accept_ratio:.2f} StepSize: {self.optim.param_groups[0][\"step_size\"]:.5f}'\n\n\t\t\tprogress.set_description(\n\t\t\t\tdesc=desc)\n\n\n\n\t\ttime.sleep(0.1) # for cleaner printing in the console\n\n\tdef sample_chain(self):\n\n\t\tself.probmodel.reset_parameters()\n\n\t\tif self.pretrain:\n\t\t\ttry:\n\t\t\t\tself.probmodel.pretrain()\n\t\t\texcept:\n\t\t\t\twarnings.warn(f'Tried pretraining but couldnt find a probmodel.pretrain() method ... Continuing wihtout pretraining.')\n\n\t\tif self.tune:\n\t\t\tself.tune_step_size()\n\n\t\t# print(f\"After Tuning Step Size: {self.optim.param_groups[0]['step_size']=}\")\n\n\t\tself.chain = Chain(probmodel=self.probmodel)\n\n\t\tprogress = tqdm(range(self.num_steps))\n\t\tfor step in progress:\n\n\t\t\tproposal_log_prob, sample = self.propose()\n\t\t\taccept, log_ratio = self.acceptance(proposal_log_prob['log_prob'], self.chain.state['log_prob']['log_prob'])\n\t\t\tself.chain += (self.probmodel, proposal_log_prob, accept)\n\n\t\t\tif not accept:\n\n\t\t\t\tif torch.isnan(proposal_log_prob['log_prob']):\n\t\t\t\t\tprint(self.chain.state)\n\t\t\t\t\texit()\n\t\t\t\tself.probmodel.load_state_dict(self.chain.state['state_dict'])\n\n\t\t\tdesc = f'{str(self)}: Accept: {self.chain.running_accepts.avg:.2f}/{self.chain.accept_ratio:.2f} \\t'\n\t\t\tfor key, running_avg in self.chain.running_avgs.items():\n\t\t\t\tdesc += f' {key}: {running_avg.avg:.2f} '\n\t\t\tdesc += f'StepSize: {self.optim.param_groups[0][\"step_size\"]:.3f}'\n\t\t\t# desc +=f\" Std: {F.softplus(self.probmodel.log_std.detach()).item():.3f}\"\n\t\t\tprogress.set_description(desc=desc)\n\n\t\tself.chain = self.chain[self.burn_in:]\n\n\t\treturn self.chain\n\nclass SGLD_Chain(Sampler_Chain):\n\n\tdef __init__(self, probmodel, step_size=0.0001, num_steps=2000, burn_in=100, pretrain=False, tune=False):\n\n\t\tSampler_Chain.__init__(self, probmodel, step_size, num_steps, burn_in, pretrain, tune)\n\n\t\tself.optim = SGLD_Optim(self.probmodel,\n\t\t\t\t\tstep_size=step_size,\n\t\t\t\t\tprior_std=1.,\n\t\t\t\t\taddnoise=True)\n\n\t\tself.acceptance = SDE_Acceptance()\n\n\tdef __repr__(self):\n\t\treturn 'SGLD'\n\n\[email protected]_grad()\n\tdef propose(self):\n\n\t\tself.optim.zero_grad()\n\t\tbatch = next(self.probmodel.dataloader.__iter__())\n\t\tlog_prob = self.probmodel.log_prob(*batch)\n\t\t(-log_prob['log_prob']).backward()\n\t\tself.optim.step()\n\n\t\treturn log_prob, self.probmodel\n\nclass MALA_Chain(Sampler_Chain):\n\n\tdef __init__(self, probmodel, step_size=0.1, num_steps=2000, burn_in=100, pretrain=False, tune=False, num_chain=0):\n\n\t\tSampler_Chain.__init__(self, probmodel, step_size, num_steps, burn_in, pretrain, tune)\n\n\t\tself.num_chain = num_chain\n\n\t\tself.optim = MALA_Optim(self.probmodel,\n\t\t\t\t\tstep_size=step_size,\n\t\t\t\t\tprior_std=1.,\n\t\t\t\t\taddnoise=True)\n\n\t\tself.acceptance = MetropolisHastingsAcceptance()\n\t\t# self.acceptance = SDE_Acceptance()\n\n\tdef __repr__(self):\n\t\treturn 'MALA'\n\n\[email protected]_grad()\n\tdef propose(self):\n\n\t\tself.optim.zero_grad()\n\t\tbatch = next(self.probmodel.dataloader.__iter__())\n\t\tlog_prob = self.probmodel.log_prob(*batch)\n\t\t(-log_prob['log_prob']).backward()\n\t\tself.optim.step()\n\n\t\treturn log_prob, self.probmodel\n\nclass HMC_Chain(Sampler_Chain):\n\n\tdef __init__(self, probmodel, step_size=0.0001, num_steps=2000, burn_in=100, pretrain=False, tune=False,\n\t\t traj_length=20):\n\n\t\t# assert probmodel.log_prob().keys()[:3] == ['log_prob', 'data', ]\n\n\t\tSampler_Chain.__init__(self, probmodel, step_size, num_steps, burn_in, pretrain, tune)\n\n\t\tself.traj_length = traj_length\n\n\t\tself.optim = HMC_Optim(self.probmodel,\n\t\t\t\t\tstep_size=step_size,\n\t\t\t\t\tprior_std=1.)\n\n\t\t# self.acceptance = SDE_Acceptance()\n\t\tself.acceptance = MetropolisHastingsAcceptance()\n\n\tdef __repr__(self):\n\t\treturn 'HMC'\n\n\tdef sample_chain(self):\n\n\t\tself.probmodel.reset_parameters()\n\n\t\tif self.pretrain:\n\t\t\ttry:\n\t\t\t\tself.probmodel.pretrain()\n\t\t\texcept:\n\t\t\t\twarnings.warn(f'Tried pretraining but couldnt find a probmodel.pretrain() method ... Continuing wihtout pretraining.')\n\n\t\tif self.tune: self.tune_step_size()\n\n\t\tself.chain = Chain(probmodel=self.probmodel)\n\n\t\tprogress = tqdm(range(self.num_steps))\n\t\tfor step in progress:\n\n\t\t\t_ = self.propose() # values are added directly to self.chain\n\n\t\t\tdesc = f'{str(self)}: Accept: {self.chain.running_accepts.avg:.2f}/{self.chain.accept_ratio:.2f} \\t'\n\t\t\tfor key, running_avg in self.chain.running_avgs.items():\n\t\t\t\tdesc += f' {key}: {running_avg.avg:.2f} '\n\t\t\tdesc += f'StepSize: {self.optim.param_groups[0][\"step_size\"]:.3f}'\n\t\t\tprogress.set_description(desc=desc)\n\n\t\tself.chain = self.chain[self.burn_in:]\n\n\t\treturn self.chain\n\n\tdef propose(self):\n\t\t'''\n\t\t1) sample momentum for each parameter\n\t\t2) sample one minibatch for an entire trajectory\n\t\t3) solve trajectory forward for self.traj_length steps\n\t\t'''\n\n\t\thamiltonian_solver = ['euler', 'leapfrog'][0]\n\n\t\tself.optim.sample_momentum()\n\t\tbatch = next(self.probmodel.dataloader.__iter__()) # samples one minibatch from dataloader\n\n\t\tdef closure():\n\t\t\t'''\n\t\t\tComputes the gradients once for batch\n\t\t\t'''\n\t\t\tself.optim.zero_grad()\n\t\t\tlog_prob = self.probmodel.log_prob(*batch)\n\t\t\t(-log_prob['log_prob']).backward()\n\t\t\treturn log_prob\n\n\t\tif hamiltonian_solver=='leapfrog': log_prob = closure() # compute initial grads\n\n\t\tfor traj_step in range(self.traj_length):\n\t\t\tif hamiltonian_solver=='euler':\n\t\t\t\tproposal_log_prob = closure()\n\t\t\t\tself.optim.step()\n\t\t\telif hamiltonian_solver=='leapfrog':\n\t\t\t\tproposal_log_prob = self.optim.leapfrog_step(closure)\n\n\t\taccept, log_ratio = self.acceptance(proposal_log_prob['log_prob'], self.chain.state['log_prob']['log_prob'])\n\n\t\tif not accept:\n\t\t\tif torch.isnan(proposal_log_prob['log_prob']):\n\t\t\t\tprint(f\"{proposal_log_prob=}\")\n\t\t\t\tprint(self.chain.state)\n\t\t\t\texit()\n\t\t\tself.probmodel.load_state_dict(self.chain.state['state_dict'])\n\n\t\tself.chain += (self.probmodel, proposal_log_prob, accept)\n\nclass SGNHT_Chain(Sampler_Chain):\n\n\tdef __init__(self, probmodel, step_size=0.0001, num_steps=2000, burn_in=100, pretrain=False, tune=False,\n\t\t traj_length=20):\n\n\t\t# assert probmodel.log_prob().keys()[:3] == ['log_prob', 'data', ]\n\n\t\tSampler_Chain.__init__(self, probmodel, step_size, num_steps, burn_in, pretrain, tune)\n\n\t\tself.traj_length = traj_length\n\n\t\tself.optim = SGNHT_Optim(self.probmodel,\n\t\t\t\t\tstep_size=step_size,\n\t\t\t\t\tprior_std=1.)\n\n\t\t# print(f\"{self.optim.A=}\")\n\t\t# print(f\"{self.optim.num_params=}\")\n\t\t# print(f\"{self.optim.A=}\")\n\t\t# exit()\n\n\t\t# self.acceptance = SDE_Acceptance()\n\t\tself.acceptance = MetropolisHastingsAcceptance()\n\n\tdef __repr__(self):\n\t\treturn 'SGNHT'\n\n\tdef sample_chain(self):\n\n\t\tself.probmodel.reset_parameters()\n\n\t\tif self.pretrain:\n\t\t\ttry:\n\t\t\t\tself.probmodel.pretrain()\n\t\t\texcept:\n\t\t\t\twarnings.warn(f'Tried pretraining but couldnt find a probmodel.pretrain() method ... Continuing wihtout pretraining.')\n\n\t\tif self.tune: self.tune_step_size()\n\n\t\tself.chain = Chain(probmodel=self.probmodel)\n\t\tself.optim.sample_momentum()\n\t\tself.optim.sample_thermostat()\n\n\t\tprogress = tqdm(range(self.num_steps))\n\t\tfor step in progress:\n\n\t\t\tproposal_log_prob, sample = self.propose()\n\t\t\taccept, log_ratio = self.acceptance(proposal_log_prob['log_prob'], self.chain.state['log_prob']['log_prob'])\n\t\t\tself.chain += (self.probmodel, proposal_log_prob, accept)\n\n\t\t\tdesc = f'{str(self)}: Accept: {self.chain.running_accepts.avg:.2f}/{self.chain.accept_ratio:.2f} \\t'\n\t\t\tfor key, running_avg in self.chain.running_avgs.items():\n\t\t\t\tdesc += f' {key}: {running_avg.avg:.2f} '\n\t\t\tdesc += f'StepSize: {self.optim.param_groups[0][\"step_size\"]:.3f}'\n\t\t\tprogress.set_description(desc=desc)\n\n\t\tself.chain = self.chain[self.burn_in:]\n\n\t\treturn self.chain\n\n\tdef propose(self):\n\t\t'''\n\t\t1) sample momentum for each parameter\n\t\t2) sample one minibatch for an entire trajectory\n\t\t3) solve trajectory forward for self.traj_length steps\n\t\t'''\n\n\t\thamiltonian_solver = ['euler', 'leapfrog'][0]\n\n\t\t# self.optim.sample_momentum()\n\t\t# self.optim.sample_thermostat()\n\t\tbatch = next(self.probmodel.dataloader.__iter__()) # samples one minibatch from dataloader\n\n\t\tself.optim.zero_grad()\n\t\tproposal_log_prob = self.probmodel.log_prob(*batch)\n\t\t(-proposal_log_prob['log_prob']).backward()\n\t\tself.optim.step()\n\n\t\t# def closure():\n\t\t# \t'''\n\t\t# \tComputes the gradients once for batch\n\t\t# \t'''\n\t\t# \tself.optim.zero_grad()\n\t\t# \tlog_prob = self.probmodel.log_prob(*batch)\n\t\t# \t(-log_prob['log_prob']).backward()\n\t\t# \treturn log_prob\n\t\t#\n\t\t# if hamiltonian_solver=='leapfrog': log_prob = closure() # compute initial grads\n\t\t#\n\t\t# for traj_step in range(self.traj_length):\n\t\t# \tif hamiltonian_solver=='euler':\n\t\t# \t\tproposal_log_prob = closure()\n\t\t# \t\tself.optim.step()\n\t\t# \telif hamiltonian_solver=='leapfrog':\n\t\t# \t\tproposal_log_prob = self.optim.leapfrog_step(closure)\n\t\t#\n\t\t# accept, log_ratio = self.acceptance(proposal_log_prob['log_prob'], self.chain.state['log_prob']['log_prob'])\n\t\t#\n\t\t# if not accept:\n\t\t# \tif torch.isnan(proposal_log_prob['log_prob']):\n\t\t# \t\tprint(f\"{proposal_log_prob=}\")\n\t\t# \t\tprint(self.chain.state)\n\t\t# \t\texit()\n\t\t# \tself.probmodel.load_state_dict(self.chain.state['state_dict'])\n\n\t\treturn proposal_log_prob, self.probmodel\n\n"
] | [
[
"torch.enable_grad",
"torch.isnan",
"torch.set_printoptions",
"numpy.set_printoptions",
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
xlouba/Transfer-Optimization | [
"a6131cd43a920b5d7005cb08b95626fb2e4280ea"
] | [
"problems/knapsack_generator.py"
] | [
"import os\r\n\r\nimport numpy as np\r\nfrom utils.data_manipulators import Tools\r\n\r\n\r\ndef is_positive_integer(X):\r\n return np.logical_and((X>0),(np.floor(X)==X))\r\n\r\ndef knapsack(weights, values, W):\r\n \"\"\"KNAPSACK Solves the 0-1 knapsack problem for positive integer weights\r\n\r\n [BEST AMOUNT] = KNAPSACK(WEIGHTS, VALUES, CONSTRAINT)\r\n \r\n WEIGHTS : The weight of every item (1-by-N)\r\n VALUES : The value of every item (1-by-N)\r\n CONSTRAINT : The weight constraint of the knapsack (scalar)\r\n\r\n BEST : Value of best possible knapsack (scalar)\r\n AMOUNT : 1-by-N vector specifying the amount to use of each item (0 or 1)\r\n\r\n\r\n EXAMPLE :\r\n\r\n weights = [1 1 1 1 2 2 3];\r\n values = [1 1 2 3 1 3 5];\r\n [best amount] = KNAPSACK(weights, values, 7)\r\n\r\n best =\r\n\r\n 13\r\n\r\n\r\n amount =\r\n\r\n 0 0 1 1 0 1 1\r\n\r\n\r\n See <a href=\"http://en.wikipedia.org/wiki/Knapsack_problem\">Knapsack problem</a> on Wikipedia.\r\n\r\n Copyright 2009 Petter Strandmark\r\n <a href=\"mailto:[email protected]\">[email protected]</a>\"\"\"\r\n\r\n if not all(is_positive_integer(weights)) or not is_positive_integer(W):\r\n raise Exception('Weights must be positive integers')\r\n \r\n # We work in one dimension\r\n# M, N = weights.shape;\r\n weights = weights[:]\r\n values = values[:]\r\n if len(weights) != len(values):\r\n raise Exception('The size of weights must match the size of values')\r\n \r\n# if len(W) > 1:\r\n# raise Exception('Only one constraint allowed');\r\n \r\n \r\n # Solve the problem\r\n \r\n # Note that A would ideally be indexed from A(0..N,0..W) but MATLAB \r\n # does not allow this.\r\n A = np.zeros((len(weights)+1,W+1))\r\n # A(j+1,Y+1) means the value of the best knapsack with capacity Y using\r\n # the first j items.\r\n for j in range(len(weights)):\r\n for Y in range(W):\r\n if weights[j] > Y+1:\r\n A[j+1,Y+1] = A[j,Y+1]\r\n else:\r\n A[j+1,Y+1] = max(A[j,Y+1], values[j] + A[j,int(Y-weights[j]+1)])\r\n \r\n \r\n \r\n\r\n best = A[-1, -1];\r\n #print(A)\r\n #Now backtrack \r\n amount = np.zeros(len(weights))\r\n a = best\r\n j = len(weights)-1\r\n Y = W-1\r\n while a > 0:\r\n while A[j+1,Y+1] == a:\r\n j = j - 1\r\n \r\n j = j + 1 # This item has to be in the knapsack\r\n amount[j] = 1\r\n Y = int(Y - weights[j])\r\n j = j - 1\r\n a = A[j+1,Y+1]\r\n\r\n \r\n # amount = reshape(amount,M,N);\r\n return best, amount\r\n\r\ndef knapsack_generator(n=1000, v=10, r=5, type_wp='uc', type_c='rk', addr=\"problems/knapsack\", add_name=''):\r\n \r\n assert type_wp in ['uc', 'wc', 'sc'], 'type_wp is not valid'\r\n assert type_c in ['rk', 'ak'], 'type_wp is not valid'\r\n# type_wp = 'uc'; strong or weakly or un-correlated\r\n# type_c = 'rk'; average or restrictive knapsack --- ALWAYS we choose average\r\n w = (1+np.round(np.random.rand(n)*(v-1)))\r\n if type_wp == 'uc':\r\n p = 1+np.round(np.random.rand(n)*(v-1))\r\n elif type_wp == 'wc':\r\n p = w + np.round(r - 2*r*np.random.rand(n))\r\n p[p <= 0] = w[p <= 0]\r\n elif type_wp =='sc':\r\n p = w+r\r\n \r\n if type_c == 'rk':\r\n cap = int(2*v)\r\n elif type_c == 'ak':\r\n cap = int(0.5*np.sum(w))\r\n \r\n# print(w, p, cap)\r\n th_best, _ = knapsack(w, p, cap)\r\n \r\n KP_uc_rk = {}\r\n KP_uc_rk['w'] = w\r\n KP_uc_rk['p'] = p\r\n KP_uc_rk['cap'] = cap\r\n KP_uc_rk['opt'] = th_best\r\n \r\n Tools.save_to_file(os.path.join(addr,'KP_{}_{}{}'.format(type_wp, type_c, add_name)), KP_uc_rk)\r\n"
] | [
[
"numpy.sum",
"numpy.random.rand",
"numpy.floor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
CalvinYan/smashscan | [
"354b4be6b40117d84ad292806341b84f4c905df8"
] | [
"ocr.py"
] | [
"import time\nimport cv2\nimport pytesseract\nimport numpy as np\n\n# SmashScan libraries\nimport util\n\n# https://github.com/tesseract-ocr/tesseract/wiki/Command-Line-Usage\n# 7 - single text line, 8 - single word, 8 works well with background blobs.\n\ndef show_ocr_result(frame):\n start_time = time.time()\n text = pytesseract.image_to_string(frame, lang=\"eng\", config=\"--psm 8\")\n print(text)\n util.display_total_time(start_time)\n\n start_time = time.time()\n pytess_result = pytesseract.image_to_boxes(frame, lang=\"eng\",\n config=\"--psm 8\", output_type=pytesseract.Output.DICT)\n print(pytess_result)\n util.display_total_time(start_time)\n\n bbox_list = list()\n for i, _ in enumerate(pytess_result['bottom']):\n tl = (pytess_result['left'][i], pytess_result['bottom'][i])\n br = (pytess_result['right'][i], pytess_result['top'][i])\n bbox_list.append((tl, br))\n util.show_frame(frame, bbox_list=bbox_list, wait_flag=True)\n\n start_time = time.time()\n pytess_data = pytesseract.image_to_data(frame, lang=\"eng\",\n config=\"--psm 8\", output_type=pytesseract.Output.DICT)\n print(pytess_data)\n util.display_total_time(start_time)\n\n bbox_list = list()\n for i, conf in enumerate(pytess_data['conf']):\n if int(conf) != -1:\n print(\"\\tconf: {}\".format(conf))\n tl = (pytess_data['left'][i], pytess_data['top'][i])\n br = (tl[0]+pytess_data['width'][i], tl[1]+pytess_data['height'][i])\n bbox_list.append((tl, br))\n util.show_frame(frame, bbox_list=bbox_list, wait_flag=True)\n\n\ndef ocr_test(img, hsv_flag, avg_flag=False, gau_flag=False,\n med_flag=False, bil_flag=False, inv_flag=True):\n\n # Create a grayscale and HSV copy of the input image.\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\n # If the HSV flag is enabled, select white OR red -> (High S AND Mid H)'\n if hsv_flag:\n mask = cv2.inRange(img_hsv, (15, 50, 0), (160, 255, 255))\n result_img = cv2.bitwise_and(img_gray, img_gray,\n mask=cv2.bitwise_not(mask))\n else:\n result_img = img_gray\n\n # Apply a post blurring filter according to the input flag given.\n # https://docs.opencv.org/3.4.5/d4/d13/tutorial_py_filtering.html\n if avg_flag:\n result_img = cv2.blur(result_img, (5, 5))\n elif gau_flag:\n result_img = cv2.GaussianBlur(result_img, (5, 5), 0)\n elif med_flag:\n result_img = cv2.medianBlur(result_img, 5)\n elif bil_flag:\n result_img = cv2.bilateralFilter(result_img, 9, 75, 75)\n\n # Invert the image to give the image a black on white background.\n if inv_flag:\n result_img = cv2.bitwise_not(result_img)\n\n display_ocr_test_flags(hsv_flag, avg_flag, gau_flag,\n med_flag, bil_flag, inv_flag)\n show_ocr_result(result_img)\n\n\n# Display the OCR test flags in a structured format.\ndef display_ocr_test_flags(hsv_flag, avg_flag, gau_flag,\n med_flag, bil_flag, inv_flag):\n print(\"hsv_flag={}\".format(hsv_flag))\n\n if avg_flag:\n print(\"avg_flag={}\".format(avg_flag))\n elif gau_flag:\n print(\"gau_flag={}\".format(gau_flag))\n elif med_flag:\n print(\"med_flag={}\".format(med_flag))\n elif bil_flag:\n print(\"bil_flag={}\".format(bil_flag))\n\n print(\"inv_flag={}\".format(inv_flag))\n\n\ndef contour_test(img):\n _, contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)\n img_d = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n cv2.drawContours(img_d, contours, -1, (255, 0, 0), 2)\n cv2.imshow('test', img_d)\n cv2.waitKey(0)\n res = np.zeros(img.shape, np.uint8)\n\n for i, contour in enumerate(contours):\n img_d = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n cv2.drawContours(img_d, contour, -1, (255, 0, 0), 3)\n\n moment = cv2.moments(contour)\n if moment['m00']: # Removes single points\n cx = int(moment['m10']/moment['m00'])\n cy = int(moment['m01']/moment['m00'])\n print(\"Center: {}\".format((cx, cy)))\n cv2.circle(img_d, (cx, cy), 3, (0, 0, 255), -1)\n\n print(\"Area: {}\".format(cv2.contourArea(contour)))\n print(\"Permeter: {} \".format(cv2.arcLength(contour, True)))\n\n cv2.imshow('test', img_d)\n cv2.waitKey(0)\n\n # The result displayed is an accumulation of previous contours.\n mask = np.zeros(img.shape, np.uint8)\n cv2.drawContours(mask, contours, i, 255, cv2.FILLED)\n mask = cv2.bitwise_and(img, mask)\n res = cv2.bitwise_or(res, mask)\n cv2.imshow('test', res)\n cv2.waitKey(0)\n\n\nfor fnum in [5320, 7020]: # 3400 works fine\n capture = cv2.VideoCapture(\"videos/tbh1.mp4\")\n frame = util.get_frame(capture, fnum, gray_flag=True)\n frame = frame[300:340, 80:220] # 300:340, 200:320\n cv2.imshow('frame', frame)\n cv2.waitKey(0)\n\n #frame = cv2.imread('videos/test4.png', cv2.IMREAD_GRAYSCALE)\n #show_ocr_result(frame)\n\n #img2 = cv2.imread('videos/test4.png', cv2.IMREAD_COLOR)\n #ocr_test(img2, hsv_flag=False)\n #ocr_test(img2, hsv_flag=False, avg_flag=True)\n #ocr_test(img2, hsv_flag=False, gau_flag=True)\n #ocr_test(img2, hsv_flag=False, med_flag=True)\n #ocr_test(img2, hsv_flag=False, bil_flag=True)\n\n #ocr_test(img2, hsv_flag=True)\n #ocr_test(img2, hsv_flag=True, avg_flag=True)\n #ocr_test(img2, hsv_flag=True, gau_flag=True)\n #ocr_test(img2, hsv_flag=True, med_flag=True)\n #ocr_test(img2, hsv_flag=True, bil_flag=True)\n\n # https://docs.opencv.org/3.4.5/d7/d4d/tutorial_py_thresholding.html\n print(\"thresh\")\n blur = cv2.GaussianBlur(frame, (5, 5), 0)\n _, thresh = cv2.threshold(blur, 127, 255, cv2.THRESH_BINARY)\n th = cv2.medianBlur(thresh, 5)\n show_ocr_result(cv2.bitwise_not(th))\n\n print(\"adaothresh\")\n _, th2 = cv2.threshold(blur, 0, 255, cv2.THRESH_OTSU)\n show_ocr_result(cv2.bitwise_not(th2))\n\n contour_test(th2)\n"
] | [
[
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
UlovHer/LearnTransformer | [
"c696f108ea2ba623f0a06f8449f1d27af10c332f"
] | [
"BERT/BERT.py"
] | [
"\"\"\"\norginal from :\nhttps://github.com/graykode/nlp-tutorial/tree/master/5-2.BERT\n\"\"\"\nimport math\nimport re\nfrom random import *\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\n# sample IsNext and NotNext to be same in small batch size\ndef make_batch():\n batch = []\n positive = negative = 0 ## 为了记录NSP任务中的正样本和负样本的个数,比例最好是在一个batch中接近1:1\n while positive != batch_size/2 or negative != batch_size/2:\n tokens_a_index, tokens_b_index= randrange(len(sentences)), randrange(len(sentences)) # 比如tokens_a_index=3,tokens_b_index=1;从整个样本中抽取对应的样本;\n tokens_a, tokens_b= token_list[tokens_a_index], token_list[tokens_b_index]## 根据索引获取对应样本:tokens_a=[5, 23, 26, 20, 9, 13, 18] tokens_b=[27, 11, 23, 8, 17, 28, 12, 22, 16, 25]\n input_ids = [word_dict['[CLS]']] + tokens_a + [word_dict['[SEP]']] + tokens_b + [word_dict['[SEP]']] ## 加上特殊符号,CLS符号是1,sep符号是2:[1, 5, 23, 26, 20, 9, 13, 18, 2, 27, 11, 23, 8, 17, 28, 12, 22, 16, 25, 2]\n segment_ids = [0] * (1 + len(tokens_a) + 1) + [1] * (len(tokens_b) + 1)##分割句子符号:[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n\n # MASK LM\n n_pred = min(max_pred, max(1, int(round(len(input_ids) * 0.15)))) # n_pred=3;整个句子的15%的字符可以被mask掉,这里取和max_pred中的最小值,确保每次计算损失的时候没有那么多字符以及信息充足,有15%做控制就够了;其实可以不用加这个,单个句子少了,就要加上足够的训练样本\n cand_maked_pos = [i for i, token in enumerate(input_ids)\n if token != word_dict['[CLS]'] and token != word_dict['[SEP]']] ## cand_maked_pos=[1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];整个句子input_ids中可以被mask的符号必须是非cls和sep符号的,要不然没意义\n shuffle(cand_maked_pos)## 打乱顺序:cand_maked_pos=[6, 5, 17, 3, 1, 13, 16, 10, 12, 2, 9, 7, 11, 18, 4, 14, 15] 其实取mask对应的位置有很多方法,这里只是一种使用shuffle的方式\n masked_tokens, masked_pos = [], []\n for pos in cand_maked_pos[:n_pred]:## 取其中的三个;masked_pos=[6, 5, 17] 注意这里对应的是position信息;masked_tokens=[13, 9, 16] 注意这里是被mask的元素之前对应的原始单字数字;\n masked_pos.append(pos)\n masked_tokens.append(input_ids[pos])\n if random() < 0.8: # 80%\n input_ids[pos] = word_dict['[MASK]'] # make mask\n elif random() < 0.5: # 10%\n index = randint(0, vocab_size - 1) # random index in vocabulary\n input_ids[pos] = word_dict[number_dict[index]] # replace\n\n # Zero Paddings\n n_pad = maxlen - len(input_ids)##maxlen=30;n_pad=10\n input_ids.extend([0] * n_pad)#在input_ids后面补零\n segment_ids.extend([0] * n_pad)# 在segment_ids 后面补零;这里有一个问题,0和之前的重了,这里主要是为了区分不同的句子,所以无所谓啊;他其实是另一种维度的位置信息;\n\n # Zero Padding (100% - 15%) tokens 是为了计算一个batch中句子的mlm损失的时候可以组成一个有效矩阵放进去;不然第一个句子预测5个字符,第二句子预测7个字符,第三个句子预测8个字符,组不成一个有效的矩阵;\n ## 这里非常重要,为什么是对masked_tokens是补零,而不是补其他的字符????我补1可不可以??\n if max_pred > n_pred:\n n_pad = max_pred - n_pred\n masked_tokens.extend([0] * n_pad)## masked_tokens= [13, 9, 16, 0, 0] masked_tokens 对应的是被mask的元素的原始真实标签是啥,也就是groundtruth\n masked_pos.extend([0] * n_pad)## masked_pos= [6, 5, 17,0,0] masked_pos是记录哪些位置被mask了\n\n if tokens_a_index + 1 == tokens_b_index and positive < batch_size/2:\n batch.append([input_ids, segment_ids, masked_tokens, masked_pos, True]) # IsNext\n positive += 1\n elif tokens_a_index + 1 != tokens_b_index and negative < batch_size/2:\n batch.append([input_ids, segment_ids, masked_tokens, masked_pos, False]) # NotNext\n negative += 1\n return batch\n# Proprecessing Finished\n\ndef get_attn_pad_mask(seq_q, seq_k):\n batch_size, len_q = seq_q.size()\n batch_size, len_k = seq_k.size()\n # eq(zero) is PAD token\n pad_attn_mask = seq_k.data.eq(0).unsqueeze(1) # batch_size x 1 x len_k(=len_q), one is masking\n return pad_attn_mask.expand(batch_size, len_q, len_k) # batch_size x len_q x len_k\n\ndef gelu(x):\n \"Implementation of the gelu activation function by Hugging Face\"\n return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))\n\nclass Embedding(nn.Module):\n def __init__(self):\n super(Embedding, self).__init__()\n self.tok_embed = nn.Embedding(vocab_size, d_model) # token embedding\n self.pos_embed = nn.Embedding(maxlen, d_model) # position embedding\n self.seg_embed = nn.Embedding(n_segments, d_model) # segment(token type) embedding\n self.norm = nn.LayerNorm(d_model)\n\n def forward(self, x, seg):\n seq_len = x.size(1)\n pos = torch.arange(seq_len, dtype=torch.long)\n pos = pos.unsqueeze(0).expand_as(x) # (seq_len,) -> (batch_size, seq_len)\n embedding = self.tok_embed(x) + self.pos_embed(pos) + self.seg_embed(seg)\n return self.norm(embedding)\n\nclass ScaledDotProductAttention(nn.Module):\n def __init__(self):\n super(ScaledDotProductAttention, self).__init__()\n\n def forward(self, Q, K, V, attn_mask):\n scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k) # scores : [batch_size x n_heads x len_q(=len_k) x len_k(=len_q)]\n scores.masked_fill_(attn_mask, -1e9) # Fills elements of self tensor with value where mask is one.\n attn = nn.Softmax(dim=-1)(scores)\n context = torch.matmul(attn, V)\n return context, attn\n\nclass MultiHeadAttention(nn.Module):\n def __init__(self):\n super(MultiHeadAttention, self).__init__()\n self.W_Q = nn.Linear(d_model, d_k * n_heads)\n self.W_K = nn.Linear(d_model, d_k * n_heads)\n self.W_V = nn.Linear(d_model, d_v * n_heads)\n def forward(self, Q, K, V, attn_mask):\n # q: [batch_size x len_q x d_model], k: [batch_size x len_k x d_model], v: [batch_size x len_k x d_model]\n residual, batch_size = Q, Q.size(0)\n # (B, S, D) -proj-> (B, S, D) -split-> (B, S, H, W) -trans-> (B, H, S, W)\n q_s = self.W_Q(Q).view(batch_size, -1, n_heads, d_k).transpose(1,2) # q_s: [batch_size x n_heads x len_q x d_k]\n k_s = self.W_K(K).view(batch_size, -1, n_heads, d_k).transpose(1,2) # k_s: [batch_size x n_heads x len_k x d_k]\n v_s = self.W_V(V).view(batch_size, -1, n_heads, d_v).transpose(1,2) # v_s: [batch_size x n_heads x len_k x d_v]\n\n attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1) # attn_mask : [batch_size x n_heads x len_q x len_k]\n\n # context: [batch_size x n_heads x len_q x d_v], attn: [batch_size x n_heads x len_q(=len_k) x len_k(=len_q)]\n context, attn = ScaledDotProductAttention()(q_s, k_s, v_s, attn_mask)\n context = context.transpose(1, 2).contiguous().view(batch_size, -1, n_heads * d_v) # context: [batch_size x len_q x n_heads * d_v]\n output = nn.Linear(n_heads * d_v, d_model)(context)\n return nn.LayerNorm(d_model)(output + residual), attn # output: [batch_size x len_q x d_model]\n\nclass PoswiseFeedForwardNet(nn.Module):\n def __init__(self):\n super(PoswiseFeedForwardNet, self).__init__()\n self.fc1 = nn.Linear(d_model, d_ff)\n self.fc2 = nn.Linear(d_ff, d_model)\n\n def forward(self, x):\n # (batch_size, len_seq, d_model) -> (batch_size, len_seq, d_ff) -> (batch_size, len_seq, d_model)\n return self.fc2(gelu(self.fc1(x)))\n\nclass EncoderLayer(nn.Module):\n def __init__(self):\n super(EncoderLayer, self).__init__()\n self.enc_self_attn = MultiHeadAttention()\n self.pos_ffn = PoswiseFeedForwardNet()\n\n def forward(self, enc_inputs, enc_self_attn_mask):\n enc_outputs, attn = self.enc_self_attn(enc_inputs, enc_inputs, enc_inputs, enc_self_attn_mask) # enc_inputs to same Q,K,V\n enc_outputs = self.pos_ffn(enc_outputs) # enc_outputs: [batch_size x len_q x d_model]\n return enc_outputs, attn\n\n## 1. BERT模型整体架构\nclass BERT(nn.Module):\n def __init__(self):\n super(BERT, self).__init__()\n self.embedding = Embedding() ## 词向量层,构建词表矩阵\n self.layers = nn.ModuleList([EncoderLayer() for _ in range(n_layers)]) ## 把N个encoder堆叠起来,具体encoder实现一会看\n self.fc = nn.Linear(d_model, d_model) ## 前馈神经网络-cls\n self.activ1 = nn.Tanh() ## 激活函数-cls\n self.linear = nn.Linear(d_model, d_model)#-mlm\n self.activ2 = gelu ## 激活函数--mlm\n self.norm = nn.LayerNorm(d_model)\n self.classifier = nn.Linear(d_model, 2)## cls 这是一个分类层,维度是从d_model到2,对应我们架构图中就是这种:\n # decoder is shared with embedding layer\n embed_weight = self.embedding.tok_embed.weight\n n_vocab, n_dim = embed_weight.size()\n self.decoder = nn.Linear(n_dim, n_vocab, bias=False)\n self.decoder.weight = embed_weight\n self.decoder_bias = nn.Parameter(torch.zeros(n_vocab))\n\n def forward(self, input_ids, segment_ids, masked_pos):\n output = self.embedding(input_ids, segment_ids)## 生成input_ids对应的embdding;和segment_ids对应的embedding\n enc_self_attn_mask = get_attn_pad_mask(input_ids, input_ids)\n for layer in self.layers:\n output, enc_self_attn = layer(output, enc_self_attn_mask)\n # output : [batch_size, len, d_model], attn : [batch_size, n_heads, d_mode, d_model]\n # it will be decided by first token(CLS)\n h_pooled = self.activ1(self.fc(output[:, 0])) # [batch_size, d_model]\n logits_clsf = self.classifier(h_pooled) # [batch_size, 2]\n\n masked_pos = masked_pos[:, :, None].expand(-1, -1, output.size(-1)) # [batch_size, max_pred, d_model] 其中一个 masked_pos= [6, 5, 17,0,0]\n # get masked position from final output of transformer.\n h_masked = torch.gather(output, 1, masked_pos) # masking position [batch_size, max_pred, d_model]\n h_masked = self.norm(self.activ2(self.linear(h_masked)))\n logits_lm = self.decoder(h_masked) + self.decoder_bias # [batch_size, max_pred, n_vocab]\n\n return logits_lm, logits_clsf\n\nif __name__ == '__main__':\n # BERT Parameters\n maxlen = 30 # 句子的最大长度 cover住95% 不要看平均数 或者99% 直接取最大可以吗?当然也可以,看你自己\n batch_size = 6 # 每一组有多少个句子一起送进去模型\n max_pred = 5 # max tokens of prediction\n n_layers = 6 # number of Encoder of Encoder Layer\n n_heads = 12 # number of heads in Multi-Head Attention\n d_model = 768 # Embedding Size\n d_ff = 3072 # 4*d_model, FeedForward dimension\n d_k = d_v = 64 # dimension of K(=Q), V\n n_segments = 2\n\n text = (\n 'Hello, how are you? I am Romeo.\\n'\n 'Hello, Romeo My name is Juliet. Nice to meet you.\\n'\n 'Nice meet you too. How are you today?\\n'\n 'Great. My baseball team won the competition.\\n'\n 'Oh Congratulations, Juliet\\n'\n 'Thanks you Romeo'\n )\n sentences = re.sub(\"[.,!?\\\\-]\", '', text.lower()).split('\\n') # filter '.', ',', '?', '!'\n word_list = list(set(\" \".join(sentences).split()))\n word_dict = {'[PAD]': 0, '[CLS]': 1, '[SEP]': 2, '[MASK]': 3}\n for i, w in enumerate(word_list):\n word_dict[w] = i + 4\n number_dict = {i: w for i, w in enumerate(word_dict)}\n vocab_size = len(word_dict)\n\n token_list = list()\n for sentence in sentences:\n arr = [word_dict[s] for s in sentence.split()]\n token_list.append(arr)\n\n batch = make_batch()\n input_ids, segment_ids, masked_tokens, masked_pos, isNext = map(torch.LongTensor, zip(*batch))\n\n\n model = BERT()\n criterion = nn.CrossEntropyLoss(ignore_index=0)\n optimizer = optim.Adam(model.parameters(), lr=0.001)\n\n\n\n for epoch in range(100):\n optimizer.zero_grad()\n logits_lm, logits_clsf = model(input_ids, segment_ids, masked_pos)## logits_lm 【6,5,29】 bs*max_pred*voca logits_clsf:[6*2]\n loss_lm = criterion(logits_lm.transpose(1, 2), masked_tokens) # for masked LM ;masked_tokens [6,5]\n loss_lm = (loss_lm.float()).mean()\n loss_clsf = criterion(logits_clsf, isNext) # for sentence classification\n loss = loss_lm + loss_clsf\n if (epoch + 1) % 10 == 0:\n print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.6f}'.format(loss))\n loss.backward()\n optimizer.step()\n\n # Predict mask tokens ans isNext\n input_ids, segment_ids, masked_tokens, masked_pos, isNext = map(torch.LongTensor, zip(batch[0]))\n print(text)\n print([number_dict[w.item()] for w in input_ids[0] if number_dict[w.item()] != '[PAD]'])\n\n logits_lm, logits_clsf = model(input_ids, segment_ids, masked_pos)\n logits_lm = logits_lm.data.max(2)[1][0].data.numpy()\n print('masked tokens list : ',[pos.item() for pos in masked_tokens[0] if pos.item() != 0])\n print('predict masked tokens list : ',[pos for pos in logits_lm if pos != 0])\n\n logits_clsf = logits_clsf.data.max(1)[1].data.numpy()[0]\n print('isNext : ', True if isNext else False)\n print('predict isNext : ',True if logits_clsf else False)\n\n\n\n\n"
] | [
[
"torch.nn.Softmax",
"torch.nn.CrossEntropyLoss",
"numpy.sqrt",
"torch.zeros",
"torch.nn.Embedding",
"torch.nn.LayerNorm",
"torch.nn.Tanh",
"torch.matmul",
"torch.nn.Linear",
"torch.arange",
"torch.gather"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Goobley/MsLightweaver2d | [
"8d36b2a47fb7c447fc78240a56bc496d1ac629aa"
] | [
"MsLightweaverInterpQSManager.py"
] | [
"import pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom lightweaver.rh_atoms import H_6_atom, C_atom, O_atom, OI_ord_atom, Si_atom, Al_atom, Fe_atom, FeI_atom, MgII_atom, N_atom, Na_atom, S_atom, CaII_atom\nfrom lightweaver.atmosphere import Atmosphere, ScaleType\nfrom lightweaver.atomic_table import DefaultAtomicAbundance\nfrom lightweaver.atomic_set import RadiativeSet, SpeciesStateTable\nfrom lightweaver.molecule import MolecularTable\nfrom lightweaver.LwCompiled import LwContext\nfrom lightweaver.utils import InitialSolution, planck, NgOptions, ConvergenceError\nimport lightweaver.constants as Const\nimport lightweaver as lw\nfrom typing import List\nfrom copy import deepcopy\nfrom MsLightweaverAtoms import H_6, CaII, H_6_nasa, CaII_nasa\nimport os\nimport os.path as path\nimport time\nfrom radynpy.matsplotlib import OpcFile\nfrom radynpy.utils import hydrogen_absorption\nfrom numba import njit\nfrom pathlib import Path\nfrom scipy.linalg import solve\nfrom scipy.interpolate import interp1d, PchipInterpolator\nimport warnings\nfrom weno4 import weno4\nimport pdb\nfrom copy import copy\nimport zarr\n\n# https://stackoverflow.com/a/21901260\nimport subprocess\ndef mslightweaver_revision():\n p = Path(__file__).parent\n isGitRepo = subprocess.check_output(['git', 'rev-parse', '--is-inside-work-tree'], cwd=p).decode('ascii').strip() == 'true'\n if not isGitRepo:\n raise ValueError('Cannot find git info.')\n\n gitChanges = subprocess.check_output(['git', 'status', '--porcelain', '--untracked-files=no'], cwd=p).decode('ascii').strip()\n if len(gitChanges) > 0:\n raise ValueError('Uncommitted changes to tracked files, cannot procede:\\n%s' % gitChanges)\n\n return subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=p).decode('ascii').strip()\n\ndef check_write_git_revision(outputDir):\n revision = mslightweaver_revision()\n with open(outputDir + 'GitRevision.txt', 'w') as f:\n f.write(revision)\n\ndef FastBackground(*args):\n import lightweaver.LwCompiled\n return lightweaver.LwCompiled.FastBackground(*args, Nthreads=16)\n\n@njit\ndef time_dep_update_impl(theta, dt, Gamma, GammaPrev, n, nPrev):\n Nlevel = n.shape[0]\n Nspace = n.shape[1]\n\n GammaPrev = GammaPrev if GammaPrev is not None else np.empty_like(Gamma)\n Gam = np.zeros((Nlevel, Nlevel))\n nk = np.zeros(Nlevel)\n nPrevIter = np.zeros(Nlevel)\n nCurrent = np.zeros(Nlevel)\n atomDelta = 0.0\n\n for k in range(Nspace):\n nCurrent[:] = n[:, k]\n nPrevIter[:] = nPrev[:, k]\n Gam[...] = -theta * Gamma[:,:, k] * dt\n Gam += np.eye(Nlevel)\n if theta != 1.0:\n nk[:] = (1.0 - theta) * dt * GammaPrev[:,:, k] @ nPrevIter + nPrevIter\n else:\n nk[:] = nPrevIter\n\n nNew = np.linalg.solve(Gam, nk)\n n[:, k] = nNew\n atomDelta = max(atomDelta, np.nanmax(np.abs(1.0 - nCurrent / nNew)))\n\n return atomDelta\n\nclass MsLightweaverInterpQSManager:\n def __init__(self, atmost, outputDir,\n fixedZGrid, atoms,\n activeAtoms=['H', 'Ca'],\n startingCtx=None, conserveCharge=False,\n prd=False, Nthreads=16):\n # check_write_git_revision(outputDir)\n self.atmost = atmost\n self.outputDir = outputDir\n self.conserveCharge = conserveCharge\n self.abund = DefaultAtomicAbundance\n self.idx = 0\n self.nHTot = atmost.d1 / (self.abund.massPerH * Const.Amu)\n self.prd = prd\n self.fixedZGrid = fixedZGrid\n self.Nthreads = Nthreads\n\n self.zarrStore = zarr.convenience.open(outputDir + 'MsLw1dFixedQS.zarr')\n if startingCtx is not None:\n self.ctx = startingCtx\n args = startingCtx.kwargs\n self.atmos = args['atmos']\n self.spect = args['spect']\n self.aSet = self.spect.radSet\n self.eqPops = args['eqPops']\n self.nltePopsStore = self.zarrStore['SimOutput/Populations/NLTE']\n self.ltePopsStore = self.zarrStore['SimOutput/Populations/LTE']\n self.radStore = self.zarrStore['SimOutput/Radiation']\n self.neStore = self.zarrStore['SimOutput/ne']\n else:\n temperature = weno4(self.fixedZGrid, atmost.z1[0], atmost.tg1[0])\n vlos = weno4(self.fixedZGrid, atmost.z1[0], atmost.vz1[0])\n vturb = np.ones_like(vlos) * 2e3\n ne1 = weno4(self.fixedZGrid, atmost.z1[0], atmost.ne1[0])\n nHTot = weno4(self.fixedZGrid, atmost.z1[0], self.nHTot[0])\n self.atmos = Atmosphere.make_1d(scale=ScaleType.Geometric, depthScale=np.copy(self.fixedZGrid), temperature=np.copy(temperature),\n vlos=np.copy(vlos), vturb=np.copy(vturb), ne=np.copy(ne1), nHTot=nHTot)\n\n self.atmos.quadrature(5)\n\n self.aSet = RadiativeSet(atoms)\n self.aSet.set_active(*activeAtoms)\n\n self.spect = self.aSet.compute_wavelength_grid()\n\n if self.conserveCharge:\n self.eqPops = self.aSet.iterate_lte_ne_eq_pops(self.atmos)\n else:\n self.eqPops = self.aSet.compute_eq_pops(self.atmos)\n\n self.ctx = lw.Context(self.atmos, self.spect, self.eqPops,\n initSol=InitialSolution.Lte,\n conserveCharge=self.conserveCharge,\n Nthreads=self.Nthreads,\n backgroundProvider=FastBackground)\n simOut = self.zarrStore.require_group('SimOutput')\n pops = simOut.require_group('Populations')\n self.nltePopsStore = pops.require_group('NLTE')\n self.ltePopsStore = pops.require_group('LTE')\n self.radStore = simOut.require_group('Radiation')\n simParams = self.zarrStore.require_group('SimParams')\n simParams['wavelength'] = self.ctx.spect.wavelength\n simParams['zAxisInitial'] = np.copy(self.fixedZGrid)\n\n self.radStore['J'] = np.zeros((0, *self.ctx.spect.J.shape))\n self.radStore['I'] = np.zeros((0, *self.ctx.spect.I.shape))\n simOut['zAxis'] = np.zeros((0, self.fixedZGrid.shape[0]))\n self.zGridStore = simOut['zAxis']\n for atom in self.eqPops.atomicPops:\n if atom.pops is not None:\n self.ltePopsStore[atom.element.name] = np.zeros((0, *atom.nStar.shape))\n self.nltePopsStore[atom.element.name] = np.zeros((0, *atom.pops.shape))\n simOut['ne'] = np.zeros((0, *self.atmos.ne.shape))\n self.neStore = simOut['ne']\n\n self.atmos.bHeat = np.ones(self.atmos.Nspace) * 1e-20\n self.atmos.hPops = self.eqPops['H']\n\n\n def stat_eq(self, Nscatter=3, NmaxIter=1000, popsTol=1e-3, JTol=3e-3,\n overwritePops=True):\n if self.prd:\n self.ctx.configure_hprd_coeffs()\n\n for i in range(NmaxIter):\n dJ = self.ctx.formal_sol_gamma_matrices()\n if i < Nscatter:\n continue\n\n delta = self.ctx.stat_equil()\n if self.prd:\n self.ctx.prd_redistribute()\n\n if self.ctx.crswDone and dJ < JTol and delta < popsTol:\n print('Stat eq converged in %d iterations' % (i+1))\n break\n else:\n raise ConvergenceError('Stat Eq did not converge.')\n\n # if overwritePops:\n # # NOTE(cmo): Overwrite the initial versions of these\n # for atom in self.eqPops.atomicPops:\n # if atom.pops is not None:\n # self.nltePopsStore[atom.element.name][0, ...] = atom.pops\n # self.neStore[0, :] = self.atmos.ne\n\n def save_timestep(self, forceOverwrite=False):\n if self.idx == 0 and self.radStore['I'].shape[0] > 0 and not forceOverwrite:\n return\n self.radStore['J'].append(np.expand_dims(self.ctx.spect.J, 0))\n self.radStore['I'].append(np.expand_dims(self.ctx.spect.I, 0))\n for atom in self.eqPops.atomicPops:\n if atom.pops is not None:\n self.ltePopsStore[atom.element.name].append(np.expand_dims(atom.nStar, 0))\n self.nltePopsStore[atom.element.name].append(np.expand_dims(atom.pops, 0))\n self.neStore.append(np.expand_dims(self.atmos.ne, 0))\n self.zGridStore.append(np.expand_dims(self.fixedZGrid, 0))\n\n\n def load_timestep(self, stepNum):\n self.idx = stepNum\n zGrid = self.zGridStore[self.idx]\n zRadyn = self.atmost.z1[self.idx]\n self.atmos.temperature[:] = weno4(zGrid, zRadyn, self.atmost.tg1[0])\n self.atmos.vlos[:] = weno4(zGrid, zRadyn, self.atmost.vz1[0])\n\n self.atmos.nHTot[:] = weno4(zGrid, zRadyn, self.nHTot[0])\n self.atmos.bHeat[:] = weno4(zGrid, zRadyn, self.atmost.bheat1[0])\n\n for name, pops in self.nltePopsStore.items():\n self.eqPops.atomicPops[name].pops[:] = pops[self.idx]\n # NOTE(cmo): Remove entries after the one being loaded\n pops.resize(self.idx+1, pops.shape[1], pops.shape[2])\n\n for name, pops in self.ltePopsStore.items():\n self.eqPops.atomicPops[name].nStar[:] = pops[self.idx]\n pops.resize(self.idx+1, pops.shape[1], pops.shape[2])\n\n neStore = self.neStore\n self.atmos.ne[:] = neStore[self.idx]\n neStore.resize(self.idx+1, *neStore.shape[1:])\n\n shape = self.radStore['I'].shape\n self.ctx.spect.I[:] = self.radStore['I'][self.idx]\n self.radStore['I'].resize(self.idx+1, *shape[1:])\n\n shape = self.radStore['J'].shape\n self.ctx.spect.J[:] = self.radStore['J'][self.idx]\n self.radStore['J'].resize(self.idx+1, *shape[1:])\n\n self.ctx.update_deps()\n\n def increment_step(self, newZGrid):\n self.idx += 1\n prevZGrid = self.fixedZGrid\n\n self.fixedZGrid = newZGrid\n zGrid = self.fixedZGrid\n zRadyn = self.atmost.z1[0]\n self.atmos.z[:] = zGrid\n self.atmos.temperature[:] = weno4(zGrid, zRadyn, self.atmost.tg1[0])\n self.atmos.vlos[:] = weno4(zGrid, zRadyn, self.atmost.vz1[0])\n if not self.conserveCharge:\n self.atmos.ne[:] = weno4(zGrid, zRadyn, self.atmost.ne1[0])\n else:\n self.atmos.ne[:] = weno4(zGrid, prevZGrid, self.atmos.ne)\n\n self.atmos.nHTot[:] = weno4(zGrid, zRadyn, self.nHTot[0])\n self.atmos.bHeat[:] = weno4(zGrid, zRadyn, self.atmost.bheat1[0])\n\n self.ctx.spect.I[...] = 0.0\n self.ctx.spect.J[...] = 0.0\n\n\n for atom in self.eqPops.atomicPops:\n if atom.pops is not None:\n atom.update_nTotal(self.atmos)\n for i in range(atom.pops.shape[0]):\n atom.pops[i] = weno4(zGrid, prevZGrid, atom.pops[i])\n # NOTE(cmo): We have the new nTotal from nHTot after update_deps()\n atom.pops *= (atom.nTotal / np.sum(atom.pops, axis=0))[None, :]\n\n\n self.ctx.update_deps()\n\n if self.prd:\n self.ctx.configure_hprd_coeffs()\n\n\n def time_dep_prev_state(self, evalGamma=False):\n if evalGamma:\n self.ctx.formal_sol_gamma_matrices()\n s = {}\n s['pops'] = [np.copy(a.n) for a in self.ctx.activeAtoms]\n s['Gamma'] = [np.copy(a.Gamma) if evalGamma else None for a in self.ctx.activeAtoms]\n return s\n\n def time_dep_update(self, dt, prevState, theta=0.5):\n atoms = self.ctx.activeAtoms\n Nspace = self.atmos.Nspace\n\n maxDelta = 0.0\n for i, atom in enumerate(atoms):\n atomDelta = time_dep_update_impl(theta, dt, atom.Gamma, prevState['Gamma'][i],\n atom.n, prevState['pops'][i])\n\n maxDelta = max(maxDelta, atomDelta)\n s = ' %s delta = %6.4e' % (atom.atomicModel.element, atomDelta)\n print(s)\n\n return maxDelta\n\n def compute_2d_bc_rays(self, muz, wmu):\n atmos = copy(self.atmos)\n atmos.rays(muz, wmu=2.0*wmu)\n print('------')\n print('ctxRays BC')\n print('------')\n ctxRays = lw.Context(atmos, self.ctx.kwargs['spect'], self.ctx.eqPops, Nthreads=16)\n ctxRays.spect.J[:] = self.ctx.spect.J\n ctxRays.depthData.fill = True\n for i in range(50):\n dJ = ctxRays.formal_sol_gamma_matrices()\n if dJ < 1e-3:\n break\n\n\n return ctxRays.depthData.I\n\n\n def time_dep_step(self, nSubSteps=200, popsTol=1e-3, JTol=3e-3, theta=1.0, dt=None):\n dt = dt if dt is not None else self.atmost.dt[self.idx+1]\n dNrPops = 0.0\n if self.prd:\n for atom in self.ctx.activeAtoms:\n for t in atom.trans:\n try:\n t.rhoPrd.fill(1.0)\n t.gII[0,0,0] = -1.0\n except:\n pass\n\n self.ctx.configure_hprd_coeffs()\n self.ctx.formal_sol_gamma_matrices()\n self.ctx.prd_redistribute(200)\n\n prevState = self.time_dep_prev_state(evalGamma=(theta!=1.0))\n for sub in range(nSubSteps):\n if self.prd and sub > 1:\n if delta > 5e-1:\n pass\n else:\n self.ctx.prd_redistribute(maxIter=5, tol=min(1e-1, 10*delta))\n\n dJ = self.ctx.formal_sol_gamma_matrices()\n delta = self.time_dep_update(dt, prevState, theta=theta)\n # if sub > 0 and self.conserveCharge:\n # self.ctx.update_deps()\n\n if self.conserveCharge:\n dNrPops = self.ctx.nr_post_update(timeDependentData={'dt': dt, 'nPrev': prevState['pops']})\n\n if sub > 1 and ((delta < popsTol and dJ < JTol and dNrPops < popsTol)\n or (delta < 0.1*popsTol and dNrPops < 0.1*popsTol)\n or (dJ < 1e-6)):\n break\n else:\n self.ctx.depthData.fill = True\n self.ctx.formal_sol_gamma_matrices()\n self.ctx.depthData.fill = False\n\n sourceData = {\n 'chi': np.copy(self.ctx.depthData.chi),\n 'eta': np.copy(self.ctx.depthData.eta),\n 'chiBg': np.copy(self.ctx.background.chi),\n 'etaBg': np.copy(self.ctx.background.eta),\n 'scaBg': np.copy(self.ctx.background.sca),\n 'J': np.copy(self.ctx.spect.J)\n }\n with open(self.outputDir + 'Fails.txt', 'a') as f:\n f.write('%d, %.4e %.4e\\n' % (self.idx, delta, dJ))\n\n with open(self.outputDir + 'NonConvergenceData_%.6d.pickle' % (self.idx), 'wb') as pkl:\n pickle.dump(sourceData, pkl)\n\n print('NON-CONVERGED')\n\n\ndef convert_atomic_pops(atom):\n d = {}\n if atom.pops is not None:\n d['n'] = atom.pops\n else:\n d['n'] = atom.pops\n d['nStar'] = atom.nStar\n return d\n\ndef distill_pops(eqPops):\n d = {}\n for atom in eqPops.atomicPops:\n d[atom.element.name] = convert_atomic_pops(atom)\n return d\n"
] | [
[
"numpy.linalg.solve",
"numpy.expand_dims",
"numpy.abs",
"numpy.ones_like",
"numpy.empty_like",
"numpy.eye",
"numpy.ones",
"numpy.copy",
"numpy.zeros",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
damo-cv/ELSA | [
"3abc389221a0fe2737372c0fd5db92951a9d3f84"
] | [
"cls/utils/utils.py"
] | [
"\"\"\"\nThis file is copied from VOLO: https://github.com/sail-sg/volo\n\"\"\"\nimport torch\nimport math\n\nimport logging\nimport os\nfrom collections import OrderedDict\nimport torch.nn.functional as F\n\n_logger = logging.getLogger(__name__)\n\n\ndef resize_pos_embed(posemb, posemb_new):\n '''\n resize position embedding with class token\n example: 224:(14x14+1)-> 384: (24x24+1)\n return: new position embedding\n '''\n ntok_new = posemb_new.shape[1]\n\n posemb_tok, posemb_grid = posemb[:, :1], posemb[0,1:] # posemb_tok is for cls token, posemb_grid for the following tokens\n ntok_new -= 1\n gs_old = int(math.sqrt(len(posemb_grid))) # 14\n gs_new = int(math.sqrt(ntok_new)) # 24\n _logger.info('Position embedding grid-size from %s to %s', gs_old, gs_new)\n posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(\n 0, 3, 1, 2) # [1, 196, dim]->[1, 14, 14, dim]->[1, dim, 14, 14]\n posemb_grid = F.interpolate(\n posemb_grid, size=(gs_new, gs_new),\n mode='bicubic') # [1, dim, 14, 14] -> [1, dim, 24, 24]\n posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(\n 1, gs_new * gs_new, -1) # [1, dim, 24, 24] -> [1, 24*24, dim]\n posemb = torch.cat([posemb_tok, posemb_grid], dim=1) # [1, 24*24+1, dim]\n return posemb\n\n\ndef resize_pos_embed_without_cls(posemb, posemb_new):\n '''\n resize position embedding without class token\n example: 224:(14x14)-> 384: (24x24)\n return new position embedding\n '''\n ntok_new = posemb_new.shape[1]\n posemb_grid = posemb[0]\n gs_old = int(math.sqrt(len(posemb_grid))) # 14\n gs_new = int(math.sqrt(ntok_new)) # 24\n _logger.info('Position embedding grid-size from %s to %s', gs_old, gs_new)\n posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(\n 0, 3, 1, 2) # [1, 196, dim]->[1, 14, 14, dim]->[1, dim, 14, 14]\n posemb_grid = F.interpolate(\n posemb_grid, size=(gs_new, gs_new),\n mode='bicubic') # [1, dim, 14, 14] -> [1, dim, 24, 24]\n posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(\n 1, gs_new * gs_new, -1) # [1, dim, 24, 24] -> [1, 24*24, dim]\n return posemb_grid\n\n\ndef resize_pos_embed_4d(posemb, posemb_new):\n '''return new position embedding'''\n # Rescale the grid of position embeddings when loading from state_dict. Adapted from\n # https://github.com/google-research/vision_transformer/blob/00883dd691c63a6830751563748663526e811cee/vit_jax/checkpoint.py#L224\n gs_old = posemb.shape[1] # 14\n gs_new = posemb_new.shape[1] # 24\n _logger.info('Position embedding grid-size from %s to %s', gs_old, gs_new)\n posemb_grid = posemb\n posemb_grid = posemb_grid.permute(0, 3, 1,\n 2) # [1, 14, 14, dim]->[1, dim, 14, 14]\n posemb_grid = F.interpolate(posemb_grid, size=(gs_new, gs_new), mode='bicubic') # [1, dim, 14, 14] -> [1, dim, 24, 24]\n posemb_grid = posemb_grid.permute(0, 2, 3, 1) # [1, dim, 24, 24]->[1, 24, 24, dim]\n return posemb_grid\n\ndef load_state_dict(checkpoint_path, model, use_ema=False, num_classes=1000):\n # load state_dict\n if checkpoint_path and os.path.isfile(checkpoint_path):\n checkpoint = torch.load(checkpoint_path, map_location='cpu')\n state_dict_key = 'state_dict'\n if isinstance(checkpoint, dict):\n if use_ema and 'state_dict_ema' in checkpoint:\n state_dict_key = 'state_dict_ema'\n if state_dict_key and state_dict_key in checkpoint:\n new_state_dict = OrderedDict()\n for k, v in checkpoint[state_dict_key].items():\n # strip `module.` prefix\n name = k[7:] if k.startswith('module') else k\n new_state_dict[name] = v\n state_dict = new_state_dict\n else:\n state_dict = checkpoint\n _logger.info(\"Loaded {} from checkpoint '{}'\".format(\n state_dict_key, checkpoint_path))\n if num_classes != 1000:\n # completely discard fully connected for all other differences between pretrained and created model\n del state_dict['head' + '.weight']\n del state_dict['head' + '.bias']\n old_aux_head_weight = state_dict.pop('aux_head.weight', None)\n old_aux_head_bias = state_dict.pop('aux_head.bias', None)\n\n old_posemb = state_dict['pos_embed']\n if model.pos_embed.shape != old_posemb.shape: # need resize the position embedding by interpolate\n if len(old_posemb.shape) == 3:\n if int(math.sqrt(\n old_posemb.shape[1]))**2 == old_posemb.shape[1]:\n new_posemb = resize_pos_embed_without_cls(\n old_posemb, model.pos_embed)\n else:\n new_posemb = resize_pos_embed(old_posemb, model.pos_embed)\n elif len(old_posemb.shape) == 4:\n new_posemb = resize_pos_embed_4d(old_posemb, model.pos_embed)\n state_dict['pos_embed'] = new_posemb\n\n return state_dict\n else:\n _logger.error(\"No checkpoint found at '{}'\".format(checkpoint_path))\n raise FileNotFoundError()\n\n\ndef load_pretrained_weights(model,\n checkpoint_path,\n use_ema=False,\n strict=True,\n num_classes=1000):\n '''load pretrained weight for VOLO models'''\n state_dict = load_state_dict(checkpoint_path, model, use_ema, num_classes)\n model.load_state_dict(state_dict, strict=strict)\n\n\ndef get_mean_and_std(dataset):\n '''Compute the mean and std value of dataset.'''\n dataloader = torch.utils.data.DataLoader(dataset,\n batch_size=1,\n shuffle=True,\n num_workers=2)\n mean = torch.zeros(3)\n std = torch.zeros(3)\n print('==> Computing mean and std..')\n for inputs, targets in dataloader:\n for i in range(3):\n mean[i] += inputs[:, i, :, :].mean()\n std[i] += inputs[:, i, :, :].std()\n mean.div_(len(dataset))\n std.div_(len(dataset))\n return mean, std\n"
] | [
[
"torch.load",
"torch.zeros",
"torch.cat",
"torch.utils.data.DataLoader",
"torch.nn.functional.interpolate"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MamoruDS/darts | [
"5d146e0f85080a370ec5d8bec9dbae9c5a7da84c"
] | [
"cnn/architect.py"
] | [
"import torch\nimport numpy as np\nimport torch.autograd\nimport torch.optim\nimport torch.nn as nn\n\nfrom model_search import Network\n\n\ndef _concat(xs):\n return torch.cat([x.view(-1) for x in xs])\n\n\nclass Architect(object):\n def __init__(self, model: Network, args):\n self.network_momentum: float = args.momentum\n self.network_weight_decay: float = args.weight_decay\n self.model = model\n print(\n f's:{type(self.model.arch_parameters)}; s():{type(self.model.arch_parameters())}; s()[0]:{type(self.model.arch_parameters()[0])}'\n )\n self.optimizer = torch.optim.Adam(\n self.model.arch_parameters(),\n lr=args.arch_learning_rate,\n betas=(0.5, 0.999),\n weight_decay=args.arch_weight_decay\n )\n\n def _compute_unrolled_model(self, input, target, eta, network_optimizer):\n loss = self.model._loss(input, target)\n theta: torch.Tensor = _concat(self.model.parameters()).data\n try:\n moment = _concat(\n network_optimizer.state[v]['momentum_buffer']\n for v in self.model.parameters()\n ).mul_(self.network_momentum)\n except:\n moment = torch.zeros_like(theta)\n dtheta = _concat(\n torch.autograd.grad(loss, list(self.model.parameters()))\n ).data + self.network_weight_decay * theta\n unrolled_model = self._construct_model_from_theta(\n torch.sub(\n input=theta, other=(moment + dtheta), alpha=eta, out=theta\n )\n )\n return unrolled_model\n\n def step(\n self, input_train, target_train, input_valid, target_valid, eta,\n network_optimizer, unrolled\n ):\n self.optimizer.zero_grad()\n if unrolled:\n self._backward_step_unrolled(\n input_train, target_train, input_valid, target_valid, eta,\n network_optimizer\n )\n else:\n self._backward_step(input_valid, target_valid)\n self.optimizer.step()\n\n def _backward_step(self, input_valid, target_valid):\n loss = self.model._loss(input_valid, target_valid)\n loss.backward()\n\n def _backward_step_unrolled(\n self, input_train, target_train, input_valid, target_valid, eta,\n network_optimizer\n ):\n unrolled_model = self._compute_unrolled_model(\n input_train, target_train, eta, network_optimizer\n )\n unrolled_loss = unrolled_model._loss(input_valid, target_valid)\n\n unrolled_loss.backward()\n dalpha: list[torch.Tensor\n ] = [v.grad for v in unrolled_model.arch_parameters()]\n vector: list[torch.Tensor\n ] = [v.grad.data for v in unrolled_model.parameters()]\n implicit_grads = self._hessian_vector_product(\n vector, input_train, target_train\n )\n\n for g, ig in zip(dalpha, implicit_grads):\n torch.sub(g.data, ig.data, alpha=eta, out=g.data)\n\n for v, g in zip(self.model.arch_parameters(), dalpha):\n if v.grad is None:\n v.grad = g.data\n else:\n v.grad.data.copy_(g.data)\n\n def _construct_model_from_theta(self, theta):\n model_new = self.model.new()\n model_dict = self.model.state_dict()\n\n params, offset = {}, 0\n for k, v in self.model.named_parameters():\n v_length = np.prod(v.size())\n params[k] = theta[offset:offset + v_length].view(v.size())\n offset += v_length\n\n assert offset == len(theta)\n model_dict.update(params)\n model_new.load_state_dict(model_dict)\n return model_new.cuda()\n\n def _hessian_vector_product(\n self, vector: list[torch.Tensor], input, target, r=1e-2\n ):\n R: torch.Tensor = r / _concat(vector).norm()\n for p, v in zip(self.model.parameters(), vector):\n torch.add(p.data, v, alpha=R.item(), out=p.data) # TBD\n loss = self.model._loss(input, target)\n grads_p = torch.autograd.grad(loss, self.model.arch_parameters())\n\n for p, v in zip(self.model.parameters(), vector):\n torch.sub(p.data, v, alpha=R.item(), out=p.data) # TBD\n loss = self.model._loss(input, target)\n grads_n = torch.autograd.grad(loss, self.model.arch_parameters())\n\n for p, v in zip(self.model.parameters(), vector):\n torch.add(p.data, v, alpha=R.item(), out=p.data) # TBD\n\n return [(x - y).div_(2 * R) for x, y in zip(grads_p, grads_n)]\n"
] | [
[
"torch.zeros_like",
"torch.sub"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
YoelPH/Adaptive-fractionation | [
"4e04062089848c6bec740d71188b262cc708ee4c"
] | [
"adaptfx/t_distribution/3D_GUI.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nGUI for 3D adaptive fractionation with minimum and maximum dose\n\"\"\"\n\nimport tkinter as tk\nimport numpy as np\nfrom scipy.stats import invgamma\nfrom tkinter import filedialog as fd\nfrom tkinter.messagebox import showinfo\nimport tkinter.ttk as ttk\nimport pandas as pd\nimport interpol3D_tdist as intp3\nimport threading\n\nclass VerticalScrolledFrame(tk.Frame):\n \"\"\"A pure Tkinter scrollable frame that actually works!\n * Use the 'interior' attribute to place widgets inside the scrollable frame\n * Construct and pack/place/grid normally\n * This frame only allows vertical scrolling\n\n \"\"\"\n def __init__(self, parent, *args, **kw):\n tk.Frame.__init__(self, parent, *args, **kw) \n\n # create a canvas object and a vertical scrollbar for scrolling it\n vscrollbar = ttk.Scrollbar(self, orient=tk.VERTICAL)\n vscrollbar.pack(fill=tk.Y, side=tk.RIGHT, expand=tk.FALSE)\n canvas = tk.Canvas(self, bd=0, highlightthickness=0,\n yscrollcommand=vscrollbar.set,height = 1000)\n canvas.pack(side=tk.LEFT, fill= tk.BOTH, expand= tk.TRUE)\n vscrollbar.config(command=canvas.yview)\n # reset the view\n canvas.xview_moveto(0)\n canvas.yview_moveto(0)\n\n # create a frame inside the canvas which will be scrolled with it\n self.interior = interior = tk.Frame(canvas)\n interior_id = canvas.create_window(0, 0, window=interior,\n anchor=tk.NW)\n\n # track changes to the canvas and frame width and sync them,\n # also updating the scrollbar\n def _configure_interior(event):\n # update the scrollbars to match the size of the inner frame\n size = (interior.winfo_reqwidth(), interior.winfo_reqheight())\n canvas.config(scrollregion=\"0 0 %s %s\" % size)\n if interior.winfo_reqwidth() != canvas.winfo_width():\n # update the canvas's width to fit the inner frame\n canvas.config(width=interior.winfo_reqwidth())\n interior.bind('<Configure>', _configure_interior)\n\n def _configure_canvas(event):\n if interior.winfo_reqwidth() != canvas.winfo_width():\n # update the inner frame's width to fill the canvas\n canvas.itemconfigure(interior_id, width=canvas.winfo_width())\n canvas.bind('<Configure>', _configure_canvas)\n\n\n\nclass Task(threading.Thread):\n def __init__(self, master, task):\n threading.Thread.__init__(self, target=task)\n\n if not hasattr(master, 'thread_compute') or not master.thread_compute.is_alive():\n master.thread_compute = self\n self.start()\n\nclass GUIextended3D:\n def __init__(self, master):\n self.master = master\n master.title(\"3D Adaptive fractionation calculator extended\")\n self.frame = VerticalScrolledFrame(master)\n self.frame.pack()\n self.frm_probdis = tk.Frame(master = self.frame.interior,relief=tk.SUNKEN, borderwidth=3)\n self.frm_probdis.pack()\n self.data = []\n self.info_funcs = [self.info1,self.info2,self.info3,self.info4,self.info5] \n self.info_buttons =[\"btn_path\",\"btn_mean\",\"btn_std\",\"btn_shae\",\"btn_scale\"]\n for idx in range(len(self.info_funcs)):\n globals()[self.info_buttons[idx]] = tk.Button(master = self.frm_probdis,text = '?',command = self.info_funcs[idx])\n globals()[self.info_buttons[idx]].grid(row=idx+1,column=4)\n for idx in range(len(self.info_funcs)):\n globals()[self.info_buttons[idx]] = tk.Button(master = self.frm_probdis,text = '?',command = self.info_funcs[idx])\n globals()[self.info_buttons[idx]].grid(row=idx+1,column=4)\n \n self.var_radio = tk.IntVar()\n self.var_radio.set(1)\n self.hyper_insert = tk.Radiobutton(master = self.frm_probdis,text = 'hyperparameters',justify = \"left\",variable = self.var_radio, value = 1, command = self.checkbox1)\n self.hyper_insert.grid(row= 0, column = 0)\n self.file_insert = tk.Radiobutton(master = self.frm_probdis,text = 'prior data',justify = \"left\",variable = self.var_radio, value = 2, command = self.checkbox1)\n self.file_insert.grid(row= 0, column = 1)\n self.fixed_insert = tk.Radiobutton(master = self.frm_probdis, text = 'define normal distribution',justify= \"left\",variable = self.var_radio,value = 3, command = self.checkbox1)\n self.fixed_insert.grid(row= 0, column = 2)\n \n \n # open button\n self.lbl_open = tk.Label(master = self.frm_probdis, text = 'load patient data for prior')\n self.lbl_open.grid(row = 1, column = 0)\n self.btn_open = tk.Button(\n self.frm_probdis,\n text='Open a File',\n command=self.select_file)\n self.ent_file = tk.Entry(master=self.frm_probdis, width=20)\n self.btn_open.grid(row = 1, column = 1)\n \n self.lbl_mean = tk.Label(master = self.frm_probdis, text = 'mean of normal distribution:')\n self.lbl_mean.grid(row=2,column = 0)\n self.ent_mean = tk.Entry(master = self.frm_probdis, width = 30)\n self.ent_mean.grid(row = 2, column = 1,columnspan = 2)\n \n self.lbl_std = tk.Label(master = self.frm_probdis, text = 'std of normal distribution:')\n self.lbl_std.grid(row=3,column = 0)\n self.ent_std = tk.Entry(master = self.frm_probdis, width = 30)\n self.ent_std.grid(row = 3, column = 1,columnspan = 2)\n \n self.lbl_alpha = tk.Label(master = self.frm_probdis, text = \"shape of inverse-gamma distribution (alpha):\")\n self.lbl_alpha.grid(row=4,column = 0)\n self.ent_alpha = tk.Entry(master = self.frm_probdis, width = 30)\n self.ent_alpha.grid(row = 4, column = 1,columnspan = 2)\n \n self.lbl_beta = tk.Label(master = self.frm_probdis, text = \"scale of inverse-gamma distribution (beta):\")\n self.lbl_beta.grid(row=5,column = 0)\n self.ent_beta = tk.Entry(master = self.frm_probdis, width = 30)\n self.ent_beta.grid(row = 5, column = 1,columnspan = 2)\n \n self.btn_open.configure(state = 'disabled')\n self.ent_alpha.configure(state = 'normal')\n self.ent_beta.configure(state = 'normal')\n self.ent_file.configure(state = 'disabled')\n self.ent_mean.configure(state = 'disabled')\n self.ent_std.configure(state = 'disabled')\n self.ent_alpha.insert(0,\"0.6133124926763415\")\n self.ent_beta.insert(0,\"0.0004167968394550765\")\n \n \n #produce master with extra option like number of fractions. \n self.frm_extras = tk.Frame(master = self.frame.interior,relief = tk.SUNKEN, borderwidth = 3)\n self.frm_extras.pack()\n \n self.lbl_fractions = tk.Label(master = self.frm_extras, text = 'Total number of fractions')\n self.lbl_fractions.grid(row=0,column = 0)\n self.ent_fractions = tk.Entry(master = self.frm_extras, width = 30)\n self.ent_fractions.grid(row = 0, column = 1,columnspan = 2)\n self.ent_fractions.insert(0,\"5\")\n self.btn_infofrac = tk.Button(master = self.frm_extras, text = '?', command = self.infofrac)\n self.btn_infofrac.grid(row=0,column = 3)\n \n self.lbl_mindose = tk.Label(master = self.frm_extras, text = 'minimum dose')\n self.lbl_mindose.grid(row = 1, column = 0)\n self.ent_mindose = tk.Entry(master = self.frm_extras, width = 30)\n self.ent_mindose.grid(row = 1, column = 1,columnspan = 2)\n self.ent_mindose.insert(0,\"0\")\n self.btn_mindose = tk.Button(master = self.frm_extras, text = '?', command = self.infomin)\n self.btn_mindose.grid(row=1,column = 3)\n \n self.lbl_maxdose = tk.Label(master = self.frm_extras, text = 'maximum dose')\n self.lbl_maxdose.grid(row = 2, column = 0)\n self.ent_maxdose = tk.Entry(master = self.frm_extras, width = 30)\n self.ent_maxdose.grid(row = 2, column = 1,columnspan = 2)\n self.ent_maxdose.insert(0,\"22.3\")\n self.btn_maxdose = tk.Button(master = self.frm_extras, text = '?', command = self.infomin)\n self.btn_maxdose.grid(row=2,column = 3)\n \n # Create a new frame `frm_form` to contain the Label\n # and Entry widgets for entering variable values\n self.frm_form = tk.Frame(master = self.frame.interior, relief=tk.SUNKEN, borderwidth=3)\n # Pack the frame into the master\n self.frm_form.pack()\n \n self.frm_buttons = tk.Frame()\n self.frm_buttons.pack(fill=tk.X, ipadx=5, ipady=5)\n \n self.frm_output = tk.Frame(master = self.frame.interior,relief=tk.SUNKEN, borderwidth = 3)\n \n #add label and entry for filename\n self.label = tk.Label(master=self.frm_form, text='file path of prior patients')\n self.ent_file = tk.Entry(master=self.frm_form, width=50)\n self.label.grid(row=0, column=0, sticky=\"e\")\n self.ent_file.grid(row=0, column=1)\n self.info_funcs = [self.info10,self.info11,self.info12,self.info13,self.info14,self.info15,self.info16] \n self.info_buttons =[\"self.btn_sf\",\"self.btn_abt\",\"self.btn_abn\",\"self.btn_OARlimit\",\"self.btn_tumorlimit\",\"self.btn_tumorBED\",\"self.btn_OARBED\"]\n # List of field labels\n self.labels = [\n \"sparing factors separated by spaces:\",\n \"alpha-beta ratio of tumor:\",\n \"alpha-beta ratio of OAR:\", \n \"OAR limit:\",\n \"prescribed tumor dose:\",\n \"accumulated tumor dose:\",\n \"accumulated OAR dose:\"\n ]\n self.ent_sf = tk.Entry(master=self.frm_form, width=50)\n self.lbl_sf = tk.Label(master = self.frm_form, text = self.labels[0])\n self.example_list = [\"sparing factors separated by space\",10,3,90,72,\"only needed if we calculate the dose for a single fraction\",\"only needed if we calculate the dose for a single fraction\"]\n self.lbl_sf.grid(row=0, column=0, sticky=\"e\")\n self.ent_sf.grid(row=0, column=1)\n self.ent_sf.insert(0,f\"{self.example_list[0]}\")\n self.btn_sf = tk.Button(master = self.frm_form,text = '?',command = self.info_funcs[0])\n self.btn_sf.grid(row=0,column=2)\n \n self.ent_abt = tk.Entry(master=self.frm_form, width=50)\n self.lbl_abt = tk.Label(master = self.frm_form, text = self.labels[1])\n self.lbl_abt.grid(row=1, column=0, sticky=\"e\")\n self.ent_abt.grid(row=1, column=1)\n self.ent_abt.insert(0,f\"{self.example_list[1]}\")\n self.btn_abt = tk.Button(master = self.frm_form,text = '?',command = self.info_funcs[1])\n self.btn_abt.grid(row=1,column=2)\n \n self.ent_abn = tk.Entry(master=self.frm_form, width=50)\n self.lbl_abn = tk.Label(master = self.frm_form, text = self.labels[2])\n self.lbl_abn.grid(row=2, column=0, sticky=\"e\")\n self.ent_abn.grid(row=2, column=1)\n self.ent_abn.insert(0,f\"{self.example_list[2]}\")\n self.btn_abn = tk.Button(master = self.frm_form,text = '?',command = self.info_funcs[2])\n self.btn_abn.grid(row=2,column=2)\n \n self.ent_OARlimit = tk.Entry(master=self.frm_form, width=50)\n self.lbl_OARlimit = tk.Label(master = self.frm_form, text = self.labels[3])\n self.lbl_OARlimit.grid(row=3, column=0, sticky=\"e\")\n self.ent_OARlimit.grid(row=3, column=1)\n self.ent_OARlimit.insert(0,f\"{self.example_list[3]}\")\n self.btn_OARlimit = tk.Button(master = self.frm_form,text = '?',command = self.info_funcs[3])\n self.btn_OARlimit.grid(row=3,column=2)\n \n self.ent_tumorlimit = tk.Entry(master=self.frm_form, width=50)\n self.lbl_tumorlimit = tk.Label(master = self.frm_form, text = self.labels[4])\n self.lbl_tumorlimit.grid(row=4, column=0, sticky=\"e\")\n self.ent_tumorlimit.grid(row=4, column=1)\n self.ent_tumorlimit.insert(0,f\"{self.example_list[4]}\")\n self.btn_tumorlimit = tk.Button(master = self.frm_form,text = '?',command = self.info_funcs[4])\n self.btn_tumorlimit.grid(row=4,column=2)\n \n self.ent_BED_tumor = tk.Entry(master=self.frm_form, width=50)\n self.lbl_BED_tumor = tk.Label(master = self.frm_form, text = self.labels[5])\n self.lbl_BED_tumor.grid(row=5, column=0, sticky=\"e\")\n self.ent_BED_tumor.grid(row=5, column=1)\n self.ent_BED_tumor.insert(0,f\"{self.example_list[5]}\")\n self.btn_BED_tumor = tk.Button(master = self.frm_form,text = '?',command = self.info_funcs[5])\n self.btn_BED_tumor.grid(row=5,column=2)\n \n self.ent_BED_OAR = tk.Entry(master=self.frm_form, width=50)\n self.lbl_BED_OAR = tk.Label(master = self.frm_form, text = self.labels[6])\n self.lbl_BED_OAR.grid(row=6, column=0, sticky=\"e\")\n self.ent_BED_OAR.grid(row=6, column=1)\n self.ent_BED_OAR.insert(0,f\"{self.example_list[6]}\")\n self.btn_BED_OAR = tk.Button(master = self.frm_form,text = '?',command = self.info_funcs[6])\n self.btn_BED_OAR.grid(row=6,column=2)\n \n self.ent_BED_OAR.configure(state = 'disabled')\n self.ent_BED_tumor.configure(state = 'disabled')\n \n # Create a new frame `frm_buttons` to contain the compute button\n self.frm_buttons = tk.Frame(master = self.frame.interior)\n self.frm_buttons.pack(fill=tk.X, ipadx=5, ipady=5)\n self.btn_compute = tk.Button(master=self.frm_buttons, text=\"compute plan\",command=lambda :Task(self, self.compute_plan))\n self.btn_compute.pack(side=tk.BOTTOM, ipadx=10)\n self.var = tk.IntVar()\n self.chk_single_fraction = tk.Checkbutton(master = self.frm_buttons,text = \"Calculate dose only for actual fraction\",variable = self.var,onvalue = 1,offvalue = 0, command=self.checkbox)\n self.chk_single_fraction.pack(side = tk.BOTTOM, padx = 10, ipadx = 10)\n self.lbl_info = tk.Label(master = self.frm_output, text = \"There are several default values set. Only the sparing factors have to been inserted.\\nThis program might take some minutes to calculate\")\n self.lbl_info.pack()\n \n \n self.frm_output.pack(fill=tk.BOTH, ipadx = 10, ipady = 10)\n \n \n # progressbar\n self.pb = ttk.Progressbar(\n master = self.frm_output,\n orient='horizontal',\n mode='determinate',\n length=500\n )\n # place the progressbar\n self.pb.pack(pady = 10) \n def select_file(self):\n filetypes = (\n ('csv files', '*.csv'),\n ('All files', '*.*')\n )\n \n filename = fd.askopenfilename(\n title='Open a file',\n initialdir='/',\n filetypes=filetypes)\n \n showinfo(\n title='Selected File',\n message=self.filename\n )\n\n self.ent_file.insert(0,filename)\n self.data = np.array(pd.read_csv(self.ent_file.get(),sep = ';'))\n self.variances = self.data.var(axis = 1)\n self.alpha,self.loc,self.beta = invgamma.fit(self.variances,floc = 0)\n self.ent_alpha.configure(state = 'normal')\n self.ent_beta.configure(state = 'normal')\n self.ent_alpha.delete(0, 'end')\n self.ent_beta.delete(0,'end')\n self.ent_alpha.insert(0,self.alpha)\n self.ent_beta.insert(0,self.beta)\n self.ent_alpha.configure(state = 'disabled')\n self.ent_beta.configure(state = 'disabled')\n \n def checkbox1(self):\n if self.var_radio.get() == 1:\n self.btn_open.configure(state = 'disabled')\n self.ent_alpha.configure(state = 'normal')\n self.ent_beta.configure(state = 'normal')\n self.ent_file.configure(state = 'disabled')\n self.ent_mean.configure(state = 'disabled')\n self.ent_std.configure(state = 'disabled')\n elif self.var_radio.get() == 2:\n self.ent_file.configure(state = 'normal')\n self.btn_open.configure(state = 'normal')\n self.ent_alpha.configure(state = 'disabled')\n self.ent_beta.configure(state = 'disabled')\n self.ent_mean.configure(state = 'disabled')\n self.ent_std.configure(state = 'disabled')\n elif self.var_radio.get() == 3:\n self.ent_mean.configure(state = 'normal')\n self.ent_std.configure(state = 'normal')\n self.ent_alpha.configure(state = 'disabled')\n self.ent_beta.configure(state = 'disabled')\n self.btn_open.configure(state = 'disabled')\n self.ent_file.configure(state = 'disabled')\n \n #assign infobutton commands\n def info1(self):\n self.lbl_info[\"text\"] = 'Insert the path of your prior patient data in here. \\nThis is only needed, if the checkbox for prior data is marked. \\nIf not, one can directly insert the hyperparameters below. \\nThe file with the prior data must be of the shape n x k,\\nwhere each new patient n is on a row and each fraction for patient n is in column k'\n def info2(self):\n self.lbl_info[\"text\"] = 'Insert the mean of the sparing factor distribution. \\nwith this option the distribution is not updated'\n def info3(self):\n self.lbl_info[\"text\"] = 'Insert the standard deviation of the sparing factor distribution. \\nwith this option the distribution is not updated'\n def info4(self):\n self.lbl_info[\"text\"] = 'Insert the shape parameter for the inverse-gamme distribution.'\n def info5(self):\n self.lbl_info[\"text\"] = 'Insert the scale parameter for the inverse-gamme distribution.' \n \n \n def infofrac(self):\n self.lbl_info[\"text\"] = 'Insert the number of fractions to be delivered to the patient. \\n5 fractions is set a standard SBRT treatment.'\n \n \n \n def infomin(self):\n self.lbl_info[\"text\"] = 'Insert the minimal physical dose that shall be delivered to the PTV95 in one fraction.\\nIt is recommended to not put too high minimum dose constraints to allow adaptation'\n \n \n def infomax(self):\n self.lbl_info[\"text\"] = 'Insert the maximal physical dose that shall be delivered to the PTV95 in one fraction.'\n \n \n \n#assign infobutton commands\n\n def info10(self):\n self.lbl_info[\"text\"] = 'Insert the sparing factors that were observed so far.\\n The sparing factor of the planning session must be included!.\\nThe sparing factors must be separated by spaces e.g.:\\n1.1 0.95 0.88\\nFor a whole plan 6 sparing factors are needed.'\n def info11(self):\n self.lbl_info[\"text\"] = 'Insert the alpha-beta ratio of the tumor tissue.'\n def info12(self):\n self.lbl_info[\"text\"] = 'Insert the alpha-beta ratio of the dose-limiting Organ at risk.'\n def info13(self):\n self.lbl_info[\"text\"] = 'Insert the maximum dose delivered to the dose-limiting OAR in BED.'\n def info14(self):\n self.lbl_info[\"text\"] = 'Insert the prescribed biological effectiv dose to be delivered to the tumor.'\n def info15(self):\n self.lbl_info[\"text\"] = 'Insert the accumulated tumor BED so far. (If fraction one, it is zero).'\n def info16(self):\n self.lbl_info[\"text\"] = 'Insert the accumulated OAR dose so far. (If fraction one, it is zero).'\n def compute_plan(self):\n self.btn_compute.configure(state = 'disabled')\n number_of_fractions = int(self.ent_fractions.get())\n alpha = float(self.ent_alpha.get())\n beta = float(self.ent_beta.get())\n min_dose = float(self.ent_mindose.get())\n max_dose = float(self.ent_maxdose.get())\n if self.var_radio.get() != 3:\n fixed_prob = 0\n fixed_mean = 0\n fixed_std = 0\n elif self.var_radio.get() == 3:\n fixed_prob = 1\n fixed_mean = float(self.ent_mean.get())\n fixed_std = float(self.ent_std.get())\n try:\n global lbl_output\n self.lbl_output.destroy()\n except:\n pass\n if self.var.get() == 0:\n try:\n sparing_factors_str = (self.ent_sf.get()).split()\n sparing_factors = [float(i) for i in sparing_factors_str]\n abt = float(self.ent_abt.get())\n abn = float(self.ent_abn.get())\n OAR_limit = float(self.ent_OARlimit.get())\n tumor_limit = float(self.ent_tumorlimit.get())\n physical_doses = np.zeros(number_of_fractions)\n tumor_doses = np.zeros(number_of_fractions)\n OAR_doses = np.zeros(number_of_fractions)\n accumulated_OAR_dose = 0\n accumulated_tumor_dose = 0\n self.pb['value'] = 0\n for looper in range(0,number_of_fractions):\n [actual_policy,accumulated_tumor_dose,accumulated_OAR_dose,tumor_dose,OAR_dose] = intp3.value_eval(looper+1,number_of_fractions,accumulated_OAR_dose,accumulated_tumor_dose,sparing_factors[0:looper+2],abt,abn,OAR_limit,tumor_limit,alpha,beta,min_dose,max_dose,fixed_prob, fixed_mean, fixed_std)\n physical_doses[looper] = actual_policy\n tumor_doses[looper] = tumor_dose\n OAR_doses[looper] = OAR_dose\n self.pb['value'] += 100/number_of_fractions\n self.lbl_output = tk.Frame(master = self.frame.interior)\n self.lbl_output.pack()\n frame = tk.Frame(master = self.lbl_output, relief = tk.RAISED, borderwidth = 1)\n frame.grid(row = 0,column = 0)\n label= tk.Label(master = frame, text = \"fraction number\")\n label.pack()\n frame = tk.Frame(master = self.lbl_output, relief = tk.RAISED, borderwidth = 1)\n frame.grid(row = 0,column = 1)\n label= tk.Label(master = frame, text = \"sparing factor\")\n label.pack()\n frame = tk.Frame(master = self.lbl_output, relief = tk.RAISED, borderwidth = 1)\n frame.grid(row = 0,column = 2)\n label= tk.Label(master = frame, text = \"physical dose delivered to PTV95\")\n label.pack()\n frame = tk.Frame(master = self.lbl_output, relief = tk.RAISED, borderwidth = 1)\n frame.grid(row = 0,column = 3)\n label= tk.Label(master = frame, text = \"BED delivered to tumor\")\n label.pack()\n frame = tk.Frame(master = self.lbl_output, relief = tk.RAISED, borderwidth = 1)\n frame.grid(row = 0,column = 4)\n label= tk.Label(master = frame, text = \"BED delivered to OAR\")\n label.pack()\n for i in range(1,number_of_fractions +1):\n for j in range(5):\n if j == 0:\n frame = tk.Frame(master = self.lbl_output)\n frame.grid(row = i,column = 0)\n label = tk.Label(master= frame, text = f\"fraction {i}\")\n label.pack()\n elif j == 1:\n frame = tk.Frame(master = self.lbl_output)\n frame.grid(row = i,column = 1)\n label = tk.Label(master= frame, text = f\" {sparing_factors[i]}\")\n label.pack()\n elif j == 2:\n frame = tk.Frame(master = self.lbl_output)\n frame.grid(row = i,column = 2)\n label = tk.Label(master= frame, text = f\" {np.round(physical_doses[i-1],2)}\")\n label.pack() \n elif j == 3:\n frame = tk.Frame(master = self.lbl_output)\n frame.grid(row = i,column = 3)\n label = tk.Label(master= frame, text = f\" {np.round(tumor_doses[i-1],2)}\")\n label.pack()\n elif j == 4:\n frame = tk.Frame(master = self.lbl_output)\n frame.grid(row = i,column = 4)\n label = tk.Label(master= frame, text = f\" {np.round(OAR_doses[i-1],2)}\")\n label.pack()\n frame = tk.Frame(master = self.lbl_output, relief = tk.RAISED, borderwidth = 1)\n frame.grid(row = number_of_fractions +1,column = 0)\n label= tk.Label(master = frame, text = \"accumulated doses\")\n label.pack()\n frame = tk.Frame(master = self.lbl_output, relief = tk.RAISED, borderwidth = 1)\n frame.grid(row = number_of_fractions +1 ,column = 3)\n label = tk.Label(master= frame, text = f\" {np.round(np.sum(tumor_doses),2)}\")\n label.pack()\n frame = tk.Frame(master = self.lbl_output, relief = tk.RAISED, borderwidth = 1)\n frame.grid(row = number_of_fractions + 1,column = 4)\n label = tk.Label(master= frame, text = f\" {np.sum(OAR_doses)}\")\n label.pack()\n \n except ValueError:\n self.lbl_info[\"text\"] = \"please enter correct values. Use the ? boxes for further information.\"\n else:\n try:\n sparing_factors_str = (self.ent_sf.get()).split()\n sparing_factors = [float(i) for i in sparing_factors_str]\n abt = float(self.ent_abt.get())\n abn = float(self.ent_abn.get())\n OAR_limit = float(self.ent_OARlimit.get())\n tumor_limit = float(self.ent_tumorlimit.get())\n BED_tumor = float(self.ent_BED_tumor.get())\n BED_OAR = float(self.ent_BED_OAR.get())\n [optimal_dose,total_dose_delivered_tumor,total_dose_delivered_OAR,tumor_dose,OAR_dose] = intp3.value_eval(len(sparing_factors)-1,number_of_fractions,BED_OAR,BED_tumor,sparing_factors,abt,abn,OAR_limit,tumor_limit,alpha,beta,min_dose,max_dose,fixed_prob,fixed_mean,fixed_std)\n self.lbl_info[\"text\"] = f\"The optimal dose for fraction {len(sparing_factors)-1} = {optimal_dose}\\naccumulated dose in tumor = {total_dose_delivered_tumor}\\naccumulated dose OAR = {total_dose_delivered_OAR}\"\n except ValueError:\n self.lbl_info[\"text\"] = \"please enter correct values. Use the ? boxes for further information.\" \n self.btn_compute.configure(state = 'normal')\n\n def checkbox(self):\n if self.var.get() == 0:\n self.ent_BED_tumor.configure(state = 'disabled')\n self.ent_BED_OAR.configure(state = 'disabled')\n else:\n self.ent_BED_tumor.configure(state = 'normal')\n self.ent_BED_OAR.configure(state = 'normal')\n\n \n \n \n \n \nif __name__=='__main__':\n root = tk.Tk()\n GUI = GUIextended3D(root)\n # Start the application\n root.mainloop()\n \n \n \n"
] | [
[
"numpy.round",
"scipy.stats.invgamma.fit",
"numpy.zeros",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zuston/submarine | [
"71ef07de51b01a4b6896b2aa0db05fb071eaf145"
] | [
"submarine-sdk/pysubmarine/submarine/ml/model/deepfm.py"
] | [
"# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nTensorflow implementation of DeepFM\n\nReference:\n[1] DeepFM: A Factorization-Machine based Neural Network for CTR Prediction,\n Huifeng Guo, Ruiming Tang, Yunming Yey, Zhenguo Li, Xiuqiang He\n[2] Tensorflow implementation of DeepFM for CTR prediction\n https://github.com/ChenglongChen/tensorflow-DeepFM\n[3] DeepCTR implementation of DeepFM for CTR prediction\n https://github.com/shenweichen/DeepCTR\n\"\"\"\n\nimport logging\nimport tensorflow as tf\nimport numpy as np\nfrom submarine.ml.model.base_tf_model import BaseTFModel\nfrom submarine.utils.tf_utils import get_estimator_spec\n\nlogger = logging.getLogger(__name__)\n\n\ndef batch_norm_layer(x, train_phase, scope_bn, batch_norm_decay):\n bn_train = tf.contrib.layers.batch_norm(x, decay=batch_norm_decay, center=True, scale=True,\n updates_collections=None, is_training=True,\n reuse=None, scope=scope_bn)\n bn_infer = tf.contrib.layers.batch_norm(x, decay=batch_norm_decay, center=True, scale=True,\n updates_collections=None, is_training=False,\n reuse=True, scope=scope_bn)\n z = tf.cond(tf.cast(train_phase, tf.bool), lambda: bn_train, lambda: bn_infer)\n return z\n\n\nclass DeepFM(BaseTFModel):\n def model_fn(self, features, labels, mode, params):\n field_size = params[\"training\"][\"field_size\"]\n feature_size = params[\"training\"][\"feature_size\"]\n embedding_size = params[\"training\"][\"embedding_size\"]\n l2_reg = params[\"training\"][\"l2_reg\"]\n batch_norm = params[\"training\"][\"batch_norm\"]\n batch_norm_decay = params[\"training\"][\"batch_norm_decay\"]\n seed = params[\"training\"][\"seed\"]\n layers = params[\"training\"][\"deep_layers\"]\n dropout = params[\"training\"][\"dropout\"]\n\n np.random.seed(seed)\n tf.set_random_seed(seed)\n\n fm_bias = tf.get_variable(name='fm_bias', shape=[1],\n initializer=tf.constant_initializer(0.0))\n fm_weight = tf.get_variable(name='fm_weight', shape=[feature_size],\n initializer=tf.glorot_normal_initializer())\n fm_vector = tf.get_variable(name='fm_vector', shape=[feature_size, embedding_size],\n initializer=tf.glorot_normal_initializer())\n\n with tf.variable_scope(\"Feature\"):\n feat_ids = features['feat_ids']\n feat_ids = tf.reshape(feat_ids, shape=[-1, field_size])\n feat_vals = features['feat_vals']\n feat_vals = tf.reshape(feat_vals, shape=[-1, field_size])\n\n with tf.variable_scope(\"First_order\"):\n feat_weights = tf.nn.embedding_lookup(fm_weight, feat_ids)\n y_w = tf.reduce_sum(tf.multiply(feat_weights, feat_vals), 1)\n\n with tf.variable_scope(\"Second_order\"):\n embeddings = tf.nn.embedding_lookup(fm_vector, feat_ids)\n feat_vals = tf.reshape(feat_vals, shape=[-1, field_size, 1])\n embeddings = tf.multiply(embeddings, feat_vals)\n sum_square = tf.square(tf.reduce_sum(embeddings, 1))\n square_sum = tf.reduce_sum(tf.square(embeddings), 1)\n y_v = 0.5 * tf.reduce_sum(tf.subtract(sum_square, square_sum), 1)\n\n with tf.variable_scope(\"Deep-part\"):\n if batch_norm:\n if mode == tf.estimator.ModeKeys.TRAIN:\n train_phase = True\n else:\n train_phase = False\n\n deep_inputs = tf.reshape(embeddings, shape=[-1, field_size * embedding_size])\n for i in range(len(layers)):\n deep_inputs = tf.contrib.layers.fully_connected(\n inputs=deep_inputs, num_outputs=layers[i],\n weights_regularizer=tf.contrib.layers.l2_regularizer(l2_reg),\n scope='mlp%d' % i)\n if batch_norm:\n deep_inputs = batch_norm_layer(\n deep_inputs, train_phase=train_phase,\n scope_bn='bn_%d' % i, batch_norm_decay=batch_norm_decay)\n if mode == tf.estimator.ModeKeys.TRAIN:\n deep_inputs = tf.nn.dropout(deep_inputs, keep_prob=dropout[i])\n\n y_deep = tf.contrib.layers.fully_connected(\n inputs=deep_inputs, num_outputs=1, activation_fn=tf.identity,\n weights_regularizer=tf.contrib.layers.l2_regularizer(l2_reg),\n scope='deep_out')\n y_d = tf.reshape(y_deep, shape=[-1])\n\n with tf.variable_scope(\"DeepFM-out\"):\n y_bias = fm_bias * tf.ones_like(y_d, dtype=tf.float32)\n logit = y_bias + y_w + y_v + y_d\n\n return get_estimator_spec(logit, labels, mode, params, [fm_vector, fm_weight])\n"
] | [
[
"tensorflow.multiply",
"tensorflow.glorot_normal_initializer",
"numpy.random.seed",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.reshape",
"tensorflow.ones_like",
"tensorflow.set_random_seed",
"tensorflow.constant_initializer",
"tensorflow.subtract",
"tensorflow.variable_scope",
"tensorflow.square",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.contrib.layers.batch_norm",
"tensorflow.nn.embedding_lookup",
"tensorflow.nn.dropout"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
blakete/Cool-GAN | [
"de52b04419292fabe68282a8c0e3046dfa32c0ca"
] | [
"use-gan.py"
] | [
"# example of loading the generator model and generating images\nfrom tensorflow.keras.models import load_model\nfrom numpy.random import randn\nfrom matplotlib import pyplot\n \n# generate points in latent space as input for the generator\ndef generate_latent_points(latent_dim, n_samples):\n\t# generate points in the latent space\n\tx_input = randn(latent_dim * n_samples)\n\t# reshape into a batch of inputs for the network\n\tx_input = x_input.reshape(n_samples, latent_dim)\n\treturn x_input\n \n# create and save a plot of generated images (reversed grayscale)\ndef save_plot(examples, n):\n\t# plot images\n\tfor i in range(n * n):\n\t\t# define subplot\n\t\tpyplot.subplot(n, n, 1 + i)\n\t\t# turn off axis\n\t\tpyplot.axis('off')\n\t\t# plot raw pixel data\n\t\tpyplot.imshow(examples[i, :, :, 0], cmap='gray_r')\n\tpyplot.show()\n \n# load model\nmodel = load_model('generator_model_100.h5')\n# generate images\nlatent_points = generate_latent_points(100, 25)\n# generate images\nX = model.predict(latent_points)\n# plot the result\nsave_plot(X, 5)"
] | [
[
"tensorflow.keras.models.load_model",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.subplot",
"numpy.random.randn",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
ZongwuYang/tf-imagenet | [
"7ffdc3059df5e515d891c3722c7229fc72a99705",
"7ffdc3059df5e515d891c3722c7229fc72a99705"
] | [
"preprocessing/preprocessing_cifar10.py",
"preprocessing/preprocessing_imagenet.py"
] | [
"# ==============================================================================\n# Copyright 2018 Paul Balanca. 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\"\"\"Cifar-10 pre-processing.\n\"\"\"\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nimport tensorflow as tf\n\nclass Cifar10ImagePreprocessor(object):\n \"\"\"Preprocessor for Cifar10 input images.\n \"\"\"\n def __init__(self,\n height,\n width,\n batch_size,\n num_splits,\n dtype,\n train,\n distortions,\n resize_method,\n eval_method,\n shift_ratio,\n summary_verbosity=0,\n distort_color_in_yiq=False,\n fuse_decode_and_crop=False):\n # Process images of this size. Depending on the model configuration, the\n # size of the input layer might differ from the original size of 32 x 32.\n self.height = height or 32\n self.width = width or 32\n self.depth = 3\n self.batch_size = batch_size\n self.num_splits = num_splits\n self.dtype = dtype\n self.train = train\n self.distortions = distortions\n self.shift_ratio = shift_ratio\n del distort_color_in_yiq\n del fuse_decode_and_crop\n del resize_method\n del shift_ratio # unused, because a RecordInput is not used\n if self.batch_size % self.num_splits != 0:\n raise ValueError(\n ('batch_size must be a multiple of num_splits: '\n 'batch_size %d, num_splits: %d') %\n (self.batch_size, self.num_splits))\n self.batch_size_per_split = self.batch_size // self.num_splits\n self.summary_verbosity = summary_verbosity\n\n def _distort_image(self, image):\n \"\"\"Distort one image for training a network.\n\n Adopted the standard data augmentation scheme that is widely used for\n this dataset: the images are first zero-padded with 4 pixels on each side,\n then randomly cropped to again produce distorted images; half of the images\n are then horizontally mirrored.\n\n Args:\n image: input image.\n Returns:\n distored image.\n \"\"\"\n image = tf.image.resize_image_with_crop_or_pad(\n image, self.height + 8, self.width + 8)\n distorted_image = tf.random_crop(\n image, [self.height, self.width, self.depth])\n # Randomly flip the image horizontally.\n distorted_image = tf.image.random_flip_left_right(distorted_image)\n if self.summary_verbosity >= 3:\n tf.summary.image('distorted_image', tf.expand_dims(distorted_image, 0))\n return distorted_image\n\n def _eval_image(self, image):\n \"\"\"Get the image for model evaluation.\"\"\"\n distorted_image = tf.image.resize_image_with_crop_or_pad(\n image, self.width, self.height)\n if self.summary_verbosity >= 3:\n tf.summary.image('cropped.image', tf.expand_dims(distorted_image, 0))\n return distorted_image\n\n def preprocess(self, raw_image):\n \"\"\"Preprocessing raw image.\"\"\"\n if self.summary_verbosity >= 3:\n tf.summary.image('raw.image', tf.expand_dims(raw_image, 0))\n if self.train and self.distortions:\n image = self._distort_image(raw_image)\n else:\n image = self._eval_image(raw_image)\n return image\n\n def minibatch(self, dataset, subset, use_datasets, cache_data,\n shift_ratio=-1):\n # TODO(jsimsa): Implement datasets code path\n del use_datasets, cache_data, shift_ratio\n with tf.name_scope('batch_processing'):\n all_images, all_labels = dataset.read_data_files(subset)\n all_images = tf.constant(all_images)\n all_labels = tf.constant(all_labels)\n input_image, input_label = tf.train.slice_input_producer(\n [all_images, all_labels])\n input_image = tf.cast(input_image, self.dtype)\n input_label = tf.cast(input_label, tf.int32)\n # Ensure that the random shuffling has good mixing properties.\n min_fraction_of_examples_in_queue = 0.4\n min_queue_examples = int(dataset.num_examples_per_epoch(subset) *\n min_fraction_of_examples_in_queue)\n raw_images, raw_labels = tf.train.shuffle_batch(\n [input_image, input_label], batch_size=self.batch_size,\n capacity=min_queue_examples + 3 * self.batch_size,\n min_after_dequeue=min_queue_examples)\n\n images = [[] for i in range(self.num_splits)]\n labels = [[] for i in range(self.num_splits)]\n\n # Create a list of size batch_size, each containing one image of the\n # batch. Without the unstack call, raw_images[i] would still access the\n # same image via a strided_slice op, but would be slower.\n raw_images = tf.unstack(raw_images, axis=0)\n raw_labels = tf.unstack(raw_labels, axis=0)\n for i in xrange(self.batch_size):\n split_index = i % self.num_splits\n # The raw image read from data has the format [depth, height, width]\n # reshape to the format returned by minibatch.\n raw_image = tf.reshape(raw_images[i],\n [dataset.depth, dataset.height, dataset.width])\n raw_image = tf.transpose(raw_image, [1, 2, 0])\n image = self.preprocess(raw_image)\n images[split_index].append(image)\n\n labels[split_index].append(raw_labels[i])\n\n for split_index in xrange(self.num_splits):\n images[split_index] = tf.parallel_stack(images[split_index])\n labels[split_index] = tf.parallel_stack(labels[split_index])\n return images, labels\n",
"# ==============================================================================\n# Copyright 2018 Paul Balanca. 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\"\"\"ImageNet pre-processing.\n\"\"\"\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nimport tensorflow as tf\n\n# from deploy import trainer_utils\n\nfrom tensorflow.contrib.data.python.ops import interleave_ops\nfrom tensorflow.contrib.data.python.ops import batching\nfrom tensorflow.python.ops import data_flow_ops\nfrom tensorflow.python.platform import gfile\n\nfrom .utils import parse_example_proto\nfrom .image import get_image_resize_method, distort_color\n\n\ndef eval_image_vgg(image,\n height,\n width,\n batch_position,\n resize_method,\n summary_verbosity=0):\n \"\"\"Get the image for model evaluation.\n\n We preprocess the image simiarly to VGG Slim, see\n https://github.com/tensorflow/models/blob/master/slim/preprocessing/vgg_preprocessing.py\n Validation images do not have bounding boxes, so to crop the image, we first\n resize the image such that the aspect ratio is maintained and the resized\n height and width are both at least 1.15 times `height` and `width`\n respectively. Then, we do a central crop to size (`height`, `width`).\n\n TODO(b/64579165): Determine if we should use different evaluation\n prepossessing steps.\n\n Args:\n image: 3-D float Tensor representing the image.\n height: The height of the image that will be returned.\n width: The width of the image that will be returned.\n batch_position: position of the image in a batch, which affects how images\n are distorted and resized. NOTE: this argument can be an integer or a\n tensor\n resize_method: one of the strings 'round_robin', 'nearest', 'bilinear',\n 'bicubic', or 'area'.\n summary_verbosity: Verbosity level for summary ops. Pass 0 to disable both\n summaries and checkpoints.\n Returns:\n An image of size (output_height, output_width, 3) that is resized and\n cropped as described above.\n \"\"\"\n # TODO(reedwm): Currently we resize then crop. Investigate if it's faster to\n # crop then resize.\n with tf.name_scope('eval_image'):\n if summary_verbosity >= 3:\n tf.summary.image(\n 'original_image', tf.expand_dims(image, 0))\n\n shape = tf.shape(image)\n image_height = shape[0]\n image_width = shape[1]\n image_height_float = tf.cast(image_height, tf.float32)\n image_width_float = tf.cast(image_width, tf.float32)\n\n scale_factor = 1.15\n\n # Compute resize_height and resize_width to be the minimum values such that\n # 1. The aspect ratio is maintained (i.e. resize_height / resize_width is\n # image_height / image_width), and\n # 2. resize_height >= height * `scale_factor`, and\n # 3. resize_width >= width * `scale_factor`\n max_ratio = tf.maximum(height / image_height_float,\n width / image_width_float)\n resize_height = tf.cast(image_height_float * max_ratio * scale_factor,\n tf.int32)\n resize_width = tf.cast(image_width_float * max_ratio * scale_factor,\n tf.int32)\n\n # Resize the image to shape (`resize_height`, `resize_width`)\n image_resize_method = get_image_resize_method(resize_method, batch_position)\n distorted_image = tf.image.resize_images(image,\n [resize_height, resize_width],\n image_resize_method,\n align_corners=False)\n\n # Do a central crop of the image to size (height, width).\n total_crop_height = (resize_height - height)\n crop_top = total_crop_height // 2\n total_crop_width = (resize_width - width)\n crop_left = total_crop_width // 2\n distorted_image = tf.slice(distorted_image, [crop_top, crop_left, 0],\n [height, width, 3])\n\n distorted_image.set_shape([height, width, 3])\n if summary_verbosity >= 3:\n tf.summary.image(\n 'cropped_resized_image', tf.expand_dims(distorted_image, 0))\n image = distorted_image\n return image\n\n\ndef eval_image_inception(image,\n height,\n width,\n batch_position,\n resize_method,\n summary_verbosity=0):\n \"\"\"Get the image for model evaluation.\n\n We preprocess the image similarly to Inception Slim, see\n https://github.com/tensorflow/models/blob/master/research/slim/preprocessing/inception_preprocessing.py\n\n The procedure is simpler than the VGG cropping: simply extract the center\n part of the image and then resize it to the expected output shape (which may\n induce some distortions).\n\n Args:\n image: 3-D float Tensor representing the image.\n height: The height of the image that will be returned.\n width: The width of the image that will be returned.\n batch_position: position of the image in a batch, which affects how images\n are distorted and resized. NOTE: this argument can be an integer or a\n tensor\n resize_method: one of the strings 'round_robin', 'nearest', 'bilinear',\n 'bicubic', or 'area'.\n summary_verbosity: Verbosity level for summary ops. Pass 0 to disable both\n summaries and checkpoints.\n Returns:\n An image of size (output_height, output_width, 3) that is resized and\n cropped as described above.\n \"\"\"\n with tf.name_scope('eval_image'):\n if summary_verbosity >= 3:\n tf.summary.image(\n 'original_image', tf.expand_dims(image, 0))\n # shape = tf.shape(image)\n # image_height = shape[0]\n # image_width = shape[1]\n\n # Crop the central region of the image with an area containing 87.5% of the original.\n central_fraction=0.875\n if central_fraction:\n image = tf.image.central_crop(image, central_fraction=central_fraction)\n\n # Resize the image to shape (`height`, `width`)\n image_resize_method = get_image_resize_method(resize_method, batch_position)\n image = tf.image.resize_images(image, [height, width],\n image_resize_method,\n align_corners=False)\n # image.set_shape([height, width, 3])\n if summary_verbosity >= 3:\n tf.summary.image('cropped_resized_image', tf.expand_dims(image, 0))\n return image\n\n\ndef train_image(image_buffer,\n height,\n width,\n bbox,\n batch_position,\n resize_method,\n distortions,\n scope=None,\n summary_verbosity=0,\n distort_color_in_yiq=False,\n fuse_decode_and_crop=False):\n \"\"\"Distort one image for training a network.\n\n Distorting images provides a useful technique for augmenting the data\n set during training in order to make the network invariant to aspects\n of the image that do not effect the label.\n\n Args:\n image_buffer: scalar string Tensor representing the raw JPEG image buffer.\n height: integer\n width: integer\n bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]\n where each coordinate is [0, 1) and the coordinates are arranged\n as [ymin, xmin, ymax, xmax].\n batch_position: position of the image in a batch, which affects how images\n are distorted and resized. NOTE: this argument can be an integer or a\n tensor\n resize_method: round_robin, nearest, bilinear, bicubic, or area.\n distortions: If true, apply full distortions for image colors.\n scope: Optional scope for op_scope.\n summary_verbosity: Verbosity level for summary ops. Pass 0 to disable both\n summaries and checkpoints.\n distort_color_in_yiq: distort color of input images in YIQ space.\n fuse_decode_and_crop: fuse the decode/crop operation.\n Returns:\n 3-D float Tensor of distorted image used for training.\n \"\"\"\n # with tf.op_scope([image, height, width, bbox], scope, 'distort_image'):\n # with tf.name_scope(scope, 'distort_image', [image, height, width, bbox]):\n with tf.name_scope(scope or 'distort_image'):\n # A large fraction of image datasets contain a human-annotated bounding box\n # delineating the region of the image containing the object of interest. We\n # choose to create a new bounding box for the object which is a randomly\n # distorted version of the human-annotated bounding box that obeys an\n # allowed range of aspect ratios, sizes and overlap with the human-annotated\n # bounding box. If no box is supplied, then we assume the bounding box is\n # the entire image.\n sample_distorted_bounding_box = tf.image.sample_distorted_bounding_box(\n tf.image.extract_jpeg_shape(image_buffer),\n bounding_boxes=bbox,\n min_object_covered=0.1,\n aspect_ratio_range=[0.75, 1.33],\n area_range=[0.05, 1.0],\n max_attempts=100,\n use_image_if_no_bounding_boxes=True)\n bbox_begin, bbox_size, distort_bbox = sample_distorted_bounding_box\n if summary_verbosity >= 4:\n image = tf.image.decode_jpeg(image_buffer, channels=3,\n dct_method='INTEGER_FAST')\n image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n image_with_distorted_box = tf.image.draw_bounding_boxes(\n tf.expand_dims(image, 0), distort_bbox)\n tf.summary.image(\n 'images_with_distorted_bounding_box',\n image_with_distorted_box)\n\n # Crop the image to the specified bounding box.\n if fuse_decode_and_crop:\n offset_y, offset_x, _ = tf.unstack(bbox_begin)\n target_height, target_width, _ = tf.unstack(bbox_size)\n crop_window = tf.stack([offset_y, offset_x, target_height, target_width])\n image = tf.image.decode_and_crop_jpeg(\n image_buffer, crop_window, channels=3)\n else:\n image = tf.image.decode_jpeg(image_buffer, channels=3,\n dct_method='INTEGER_FAST')\n image = tf.slice(image, bbox_begin, bbox_size)\n\n if distortions:\n # After this point, all image pixels reside in [0,1]. Before, they were\n # uint8s in the range [0, 255].\n image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n\n # This resizing operation may distort the images because the aspect\n # ratio is not respected.\n image_resize_method = get_image_resize_method(resize_method, batch_position)\n distorted_image = tf.image.resize_images(\n image, [height, width],\n image_resize_method,\n align_corners=False)\n\n # Restore the shape since the dynamic slice based upon the bbox_size loses\n # the third dimension.\n distorted_image.set_shape([height, width, 3])\n if summary_verbosity >= 4:\n tf.summary.image(\n 'cropped_resized_image',\n tf.expand_dims(distorted_image, 0))\n\n # Randomly flip the image horizontally.\n distorted_image = tf.image.random_flip_left_right(distorted_image)\n\n if distortions:\n # Randomly distort the colors.\n distorted_image = distort_color(distorted_image, batch_position,\n distort_color_in_yiq=distort_color_in_yiq)\n\n # Note: This ensures the scaling matches the output of eval_image\n distorted_image *= 255\n\n if summary_verbosity >= 4:\n tf.summary.image(\n 'final_distorted_image',\n tf.expand_dims(distorted_image, 0))\n return distorted_image\n\n\nclass RecordInputImagePreprocessor(object):\n \"\"\"Preprocessor for images with RecordInput format.\n \"\"\"\n def __init__(self,\n height,\n width,\n batch_size,\n num_splits,\n dtype,\n train,\n distortions,\n resize_method,\n eval_method,\n shift_ratio,\n summary_verbosity,\n distort_color_in_yiq,\n fuse_decode_and_crop):\n self.height = height\n self.width = width\n self.batch_size = batch_size\n self.num_splits = num_splits\n self.dtype = dtype\n self.train = train\n self.resize_method = resize_method\n self.eval_method = eval_method\n self.shift_ratio = shift_ratio\n self.distortions = distortions\n self.distort_color_in_yiq = distort_color_in_yiq\n self.fuse_decode_and_crop = fuse_decode_and_crop\n if self.batch_size % self.num_splits != 0:\n raise ValueError(\n ('batch_size must be a multiple of num_splits: '\n 'batch_size %d, num_splits: %d') %\n (self.batch_size, self.num_splits))\n self.batch_size_per_split = self.batch_size // self.num_splits\n self.summary_verbosity = summary_verbosity\n\n def preprocess(self, image_buffer, bbox, batch_position):\n \"\"\"Preprocessing image_buffer as a function of its batch position.\"\"\"\n if self.train:\n image = train_image(image_buffer, self.height, self.width, bbox,\n batch_position, self.resize_method, self.distortions,\n None, summary_verbosity=self.summary_verbosity,\n distort_color_in_yiq=self.distort_color_in_yiq,\n fuse_decode_and_crop=self.fuse_decode_and_crop)\n else:\n # Evaluation method (default=VGG).\n eval_methods = {\n 'vgg': eval_image_vgg,\n 'inception': eval_image_inception,\n }\n eval_image = eval_methods.get(self.eval_method, eval_image_vgg)\n image = tf.image.decode_jpeg(\n image_buffer, channels=3, dct_method='INTEGER_FAST')\n image = eval_image(image, self.height, self.width, batch_position,\n self.resize_method,\n summary_verbosity=self.summary_verbosity)\n # Note: image is now float32 [height,width,3] with range [0, 255]\n\n # image = tf.cast(image, tf.uint8) # HACK TESTING\n\n return image\n\n def parse_and_preprocess(self, value, batch_position):\n image_buffer, label_index, bbox, _ = parse_example_proto(value)\n image = self.preprocess(image_buffer, bbox, batch_position)\n return (label_index, image)\n\n def minibatch(self, dataset, subset, use_datasets, cache_data,\n shift_ratio=-1):\n if shift_ratio < 0:\n shift_ratio = self.shift_ratio\n with tf.name_scope('batch_processing'):\n # Build final results per split.\n images = [[] for _ in range(self.num_splits)]\n labels = [[] for _ in range(self.num_splits)]\n if use_datasets:\n glob_pattern = dataset.tf_record_pattern(subset)\n file_names = gfile.Glob(glob_pattern)\n if not file_names:\n raise ValueError('Found no files in --data_dir matching: {}'\n .format(glob_pattern))\n ds = tf.data.TFRecordDataset.list_files(file_names)\n ds = ds.apply(\n interleave_ops.parallel_interleave(\n tf.data.TFRecordDataset, cycle_length=10))\n if cache_data:\n ds = ds.take(1).cache().repeat()\n counter = tf.data.Dataset.range(self.batch_size)\n counter = counter.repeat()\n ds = tf.data.Dataset.zip((ds, counter))\n ds = ds.prefetch(buffer_size=self.batch_size)\n ds = ds.shuffle(buffer_size=10000)\n ds = ds.repeat()\n ds = ds.apply(\n batching.map_and_batch(\n map_func=self.parse_and_preprocess,\n batch_size=self.batch_size_per_split,\n num_parallel_batches=self.num_splits))\n ds = ds.prefetch(buffer_size=self.num_splits)\n ds_iterator = ds.make_one_shot_iterator()\n for d in xrange(self.num_splits):\n labels[d], images[d] = ds_iterator.get_next()\n\n else:\n record_input = data_flow_ops.RecordInput(\n file_pattern=dataset.tf_record_pattern(subset),\n seed=301,\n parallelism=64,\n buffer_size=10000,\n batch_size=self.batch_size,\n shift_ratio=shift_ratio,\n name='record_input')\n records = record_input.get_yield_op()\n records = tf.split(records, self.batch_size, 0)\n records = [tf.reshape(record, []) for record in records]\n for idx in xrange(self.batch_size):\n value = records[idx]\n (label, image) = self.parse_and_preprocess(value, idx)\n split_index = idx % self.num_splits\n labels[split_index].append(label)\n images[split_index].append(image)\n\n for split_index in xrange(self.num_splits):\n if not use_datasets:\n images[split_index] = tf.parallel_stack(images[split_index])\n labels[split_index] = tf.concat(labels[split_index], 0)\n images[split_index] = tf.cast(images[split_index], self.dtype)\n depth = 3\n images[split_index] = tf.reshape(\n images[split_index],\n shape=[self.batch_size_per_split, self.height, self.width, depth])\n labels[split_index] = tf.reshape(labels[split_index],\n [self.batch_size_per_split])\n return images, labels\n"
] | [
[
"tensorflow.image.resize_image_with_crop_or_pad",
"tensorflow.constant",
"tensorflow.image.random_flip_left_right",
"tensorflow.unstack",
"tensorflow.transpose",
"tensorflow.cast",
"tensorflow.reshape",
"tensorflow.expand_dims",
"tensorflow.random_crop",
"tensorflow.name_scope",
"tensorflow.train.slice_input_producer",
"tensorflow.train.shuffle_batch",
"tensorflow.parallel_stack"
],
[
"tensorflow.contrib.data.python.ops.batching.map_and_batch",
"tensorflow.concat",
"tensorflow.stack",
"tensorflow.cast",
"tensorflow.image.decode_and_crop_jpeg",
"tensorflow.image.central_crop",
"tensorflow.image.random_flip_left_right",
"tensorflow.summary.image",
"tensorflow.data.Dataset.zip",
"tensorflow.name_scope",
"tensorflow.image.decode_jpeg",
"tensorflow.unstack",
"tensorflow.shape",
"tensorflow.image.resize_images",
"tensorflow.image.extract_jpeg_shape",
"tensorflow.data.Dataset.range",
"tensorflow.split",
"tensorflow.parallel_stack",
"tensorflow.slice",
"tensorflow.maximum",
"tensorflow.reshape",
"tensorflow.python.platform.gfile.Glob",
"tensorflow.expand_dims",
"tensorflow.data.TFRecordDataset.list_files",
"tensorflow.image.convert_image_dtype",
"tensorflow.contrib.data.python.ops.interleave_ops.parallel_interleave"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
dchaves/audioshow | [
"2016378ed83b56f4934cc7854cbd6275adf84675"
] | [
"input.py"
] | [
"#!/usr/bin/env python\nimport struct\nimport numpy as np\nimport time\nimport matplotlib\nmatplotlib.use('GTKAgg')\nfrom matplotlib import pyplot as plt\n\n\nclass dynaplot:\n def __init__(self, max_x = 4096, window_size = 512):\n self.y_values = []\n self.x_values = []\n self.max_x = max_x\n self.window_size = window_size\n self.counter = 0\n self.fig, self.ax = plt.subplots(1, 1)\n self.ax.set_xlim(0, max_x)\n # self.ax.hold(True)\n plt.show(False)\n plt.draw()\n self.points = plt.plot(self.x_values,self.y_values)[0]\n self.background = self.fig.canvas.copy_from_bbox(self.ax.bbox)\n\n \"\"\"\n Display using matplotlib\n \"\"\"\n def plot(self, x_value, y_value):\n self.x_values.append(x_value)\n self.y_values.append(y_value)\n # self.ax.set_xlim(min(self.x_values), max(self.x_values))\n # self.ax.set_ylim(min(self.y_values), max(self.y_values))\n if (len(self.x_values) > self.max_x):\n self.x_values.pop(0)\n self.y_values.pop(0)\n self.counter = (self.counter + 1) % self.window_size\n if (self.counter == 0):\n self.points.set_data(np.fft.fft(self.y_values))\n self.fig.canvas.restore_region(self.background)\n self.ax.draw_artist(self.points)\n self.fig.canvas.blit(self.ax.bbox)\n plt.pause(0.00001)\n\n\nif __name__ == '__main__':\n audiofile = open(\"/tmp/audioout\")\n plotter = dynaplot()\n x = 0\n while True:\n value = struct.unpack(\"<h\", audiofile.read(2))\n plotter.plot(x, value)\n x += 1\n #print value\n"
] | [
[
"numpy.fft.fft",
"matplotlib.use",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.pause"
]
] | [
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.13",
"1.16",
"1.9",
"1.18",
"1.21",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Alive12321/Maze-PyQt5 | [
"7516a83f11c1dfef662fef5c1f5d294bf60c7bf2"
] | [
"Maze1.2.py"
] | [
"# -*- coding: utf-8 -*-\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\nimport sys,random\r\nfrom PyQt5.QtWidgets import QApplication,QMainWindow,QGraphicsItem\r\nfrom PyQt5.QtCore import Qt,QRectF\r\nimport numpy as np\r\nfrom queue import Queue,PriorityQueue\r\n\r\nWIDTH,HEIGHT=800,800 #Graphicsview的尺寸\r\nCOL_INTERVAL,ROW_INTERVAL = 3,3 #格子间的间距\r\nCOL_LEN,ROW_LEN = 20,20 #格子的长度\r\nCOL_NUM,ROW_NUM = 35,35 #格子的数量\r\nFIND,GENERATE,SPEED=0,0,0 #生成方式,走迷宫方式,刷新速度\r\nmaz=np.ones((ROW_NUM,COL_NUM)) #迷宫矩阵\r\ndx,dy=ROW_NUM - 2,COL_NUM - 1 #终点\r\nrecord,ans,process= [],[],[] #记录答案\r\n\r\nclass DFSg(object):\r\n def __init__(self, width=11, height=11):\r\n # 迷宫最小长宽为5\r\n assert width >= 5 and height >= 5, \"Length of width or height must be larger than 5.\"\r\n\r\n # 确保迷宫的长和宽均为奇数\r\n self.width = (width // 2) * 2 + 1\r\n self.height = (height // 2) * 2 + 1\r\n self.start = [1, 0]\r\n self.destination = [self.height - 2, self.width - 1]\r\n self.matrix = None\r\n\r\n def generate_matrix_dfs(self):\r\n # 地图初始化,并将出口和入口处的值设置为0\r\n self.matrix = -np.ones((self.height, self.width))\r\n self.matrix[self.start[0], self.start[1]] = 0\r\n self.matrix[self.destination[0], self.destination[1]] = 0\r\n\r\n visit_flag = [[0 for i in range(self.width)] for j in range(self.height)]\r\n\r\n def check(row, col, row_, col_):\r\n temp_sum = 0\r\n for d in [[0, 1], [0, -1], [1, 0], [-1, 0]]:\r\n temp_sum += self.matrix[row_ + d[0]][col_ + d[1]]\r\n return temp_sum <= -3\r\n\r\n def dfs(row, col):\r\n visit_flag[row][col] = 1\r\n self.matrix[row][col] = 0\r\n if row == self.start[0] and col == self.start[1] + 1:\r\n return\r\n\r\n directions = [[0, 2], [0, -2], [2, 0], [-2, 0]]\r\n random.shuffle(directions)\r\n for d in directions:\r\n row_, col_ = row + d[0], col + d[1]\r\n if row_ > 0 and row_ < self.height - 1 and col_ > 0 and col_ < self.width - 1 and visit_flag[row_][\r\n col_] == 0 and check(row, col, row_, col_):\r\n if row == row_:\r\n visit_flag[row][min(col, col_) + 1] = 1\r\n self.matrix[row][min(col, col_) + 1] = 0\r\n else:\r\n visit_flag[min(row, row_) + 1][col] = 1\r\n self.matrix[min(row, row_) + 1][col] = 0\r\n dfs(row_, col_)\r\n\r\n dfs(self.destination[0], self.destination[1] - 1)\r\n self.matrix[self.start[0], self.start[1] + 1] = 0\r\nclass PRIMg(object):\r\n def __init__(self, width=11, height=11):\r\n assert width >= 5 and height >= 5, \"Length of width or height must be larger than 5.\"\r\n\r\n self.width = (width // 2) * 2 + 1\r\n self.height = (height // 2) * 2 + 1\r\n self.start = [1, 0]\r\n self.destination = [self.height - 2, self.width - 1]\r\n self.matrix = None\r\n # 虽然说是prim算法,但是我感觉更像随机广度优先算法\r\n def generate_matrix_prim(self):\r\n # 地图初始化,并将出口和入口处的值设置为0\r\n self.matrix = -np.ones((self.height, self.width))\r\n\r\n def check(row, col):\r\n temp_sum = 0\r\n for d in [[0, 1], [0, -1], [1, 0], [-1, 0]]:\r\n temp_sum += self.matrix[row + d[0]][col + d[1]]\r\n return temp_sum < -3\r\n\r\n queue = []\r\n row, col = (np.random.randint(1, self.height - 1) // 2) * 2 + 1, (\r\n np.random.randint(1, self.width - 1) // 2) * 2 + 1\r\n queue.append((row, col, -1, -1))\r\n while len(queue) != 0:\r\n row, col, r_, c_ = queue.pop(np.random.randint(0, len(queue)))\r\n if check(row, col):\r\n self.matrix[row, col] = 0\r\n if r_ != -1 and row == r_:\r\n self.matrix[row][min(col, c_) + 1] = 0\r\n elif r_ != -1 and col == c_:\r\n self.matrix[min(row, r_) + 1][col] = 0\r\n for d in [[0, 2], [0, -2], [2, 0], [-2, 0]]:\r\n row_, col_ = row + d[0], col + d[1]\r\n if row_ > 0 and row_ < self.height - 1 and col_ > 0 and col_ < self.width - 1 and self.matrix[row_][\r\n col_] == -1:\r\n queue.append((row_, col_, row, col))\r\n\r\n self.matrix[self.start[0], self.start[1]] = 0\r\n self.matrix[self.destination[0], self.destination[1]] = 0\r\nclass UnionSet(object):\r\n\tdef __init__(self, arr):\r\n\t\tself.parent = {pos: pos for pos in arr}\r\n\t\tself.count = len(arr)\r\n\tdef find(self, root):\r\n\t\tif root == self.parent[root]:\r\n\t\t\treturn root\r\n\t\treturn self.find(self.parent[root])\r\n\tdef union(self, root1, root2):\r\n\t\tself.parent[self.find(root1)] = self.find(root2)\r\nclass KRUSKALg(object):\r\n\tdef __init__(self, width = 11, height = 11):\r\n\t\tassert width >= 5 and height >= 5, \"Length of width or height must be larger than 5.\"\r\n\r\n\t\tself.width = (width // 2) * 2 + 1\r\n\t\tself.height = (height // 2) * 2 + 1\r\n\t\tself.start = [1, 0]\r\n\t\tself.destination = [self.height - 2, self.width - 1]\r\n\t\tself.matrix = None\r\n\r\n\t# 最小生成树算法-kruskal(选边法)思想生成迷宫地图,这种实现方法最复杂。\r\n\tdef generate_matrix_kruskal(self):\r\n\t\t# 地图初始化,并将出口和入口处的值设置为0\r\n\t\tself.matrix = -np.ones((self.height, self.width))\r\n\r\n\t\tdef check(row, col):\r\n\t\t\tans, counter = [], 0\r\n\t\t\tfor d in [[0, 1], [0, -1], [1, 0], [-1, 0]]:\r\n\t\t\t\trow_, col_ = row + d[0], col + d[1]\r\n\t\t\t\tif row_ > 0 and row_ < self.height - 1 and col_ > 0 and col_ < self.width - 1 and self.matrix[row_, col_] == -1:\r\n\t\t\t\t\tans.append([d[0] * 2, d[1] * 2])\r\n\t\t\t\t\tcounter += 1\r\n\t\t\tif counter <= 1:\r\n\t\t\t\treturn []\r\n\t\t\treturn ans\r\n\r\n\t\tnodes = set()\r\n\t\trow = 1\r\n\t\twhile row < self.height:\r\n\t\t\tcol = 1\r\n\t\t\twhile col < self.width:\r\n\t\t\t\tself.matrix[row, col] = 0\r\n\t\t\t\tnodes.add((row, col))\r\n\t\t\t\tcol += 2\r\n\t\t\trow += 2\r\n\r\n\t\tunionset = UnionSet(nodes)\r\n\t\twhile unionset.count > 1:\r\n\t\t\trow, col = nodes.pop()\r\n\t\t\tdirections = check(row, col)\r\n\t\t\tif len(directions):\r\n\t\t\t\trandom.shuffle(directions)\r\n\t\t\t\tfor d in directions:\r\n\t\t\t\t\trow_, col_ = row + d[0], col + d[1]\r\n\t\t\t\t\tif unionset.find((row, col)) == unionset.find((row_, col_)):\r\n\t\t\t\t\t\tcontinue\r\n\t\t\t\t\tnodes.add((row, col))\r\n\t\t\t\t\tunionset.count -= 1\r\n\t\t\t\t\tunionset.union((row, col), (row_, col_))\r\n\r\n\t\t\t\t\tif row == row_:\r\n\t\t\t\t\t\tself.matrix[row][min(col, col_) + 1] = 0\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tself.matrix[min(row, row_) + 1][col] = 0\r\n\t\t\t\t\tbreak\r\n\r\n\t\tself.matrix[self.start[0], self.start[1]] = 0\r\n\t\tself.matrix[self.destination[0], self.destination[1]] = 0\r\nclass Ui_MainWindow(object):\r\n def setupUi(self, MainWindow):\r\n MainWindow.setObjectName(\"MainWindow\")\r\n MainWindow.resize(1089, 850)\r\n font = QtGui.QFont()\r\n font.setFamily(\"Yu Gothic\")\r\n MainWindow.setFont(font)\r\n self.centralwidget = QtWidgets.QWidget(MainWindow)\r\n self.centralwidget.setObjectName(\"centralwidget\")\r\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton.setGeometry(QtCore.QRect(870, 420, 141, 41))\r\n font = QtGui.QFont()\r\n font.setFamily(\"华文行楷\")\r\n font.setPointSize(13)\r\n self.pushButton.setFont(font)\r\n self.pushButton.setObjectName(\"pushButton\")\r\n self.label_4 = QtWidgets.QLabel(self.centralwidget)\r\n self.label_4.setGeometry(QtCore.QRect(880, 210, 151, 51))\r\n font = QtGui.QFont()\r\n font.setFamily(\"华文行楷\")\r\n font.setPointSize(20)\r\n self.label_4.setFont(font)\r\n self.label_4.setObjectName(\"label_4\")\r\n self.label_5 = QtWidgets.QLabel(self.centralwidget)\r\n self.label_5.setGeometry(QtCore.QRect(900, 550, 111, 41))\r\n font = QtGui.QFont()\r\n font.setFamily(\"华文行楷\")\r\n font.setPointSize(20)\r\n self.label_5.setFont(font)\r\n self.label_5.setObjectName(\"label_5\")\r\n self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton_2.setGeometry(QtCore.QRect(870, 720, 141, 41))\r\n font = QtGui.QFont()\r\n font.setFamily(\"华文行楷\")\r\n font.setPointSize(13)\r\n self.pushButton_2.setFont(font)\r\n self.pushButton_2.setObjectName(\"pushButton_2\")\r\n self.layoutWidget = QtWidgets.QWidget(self.centralwidget)\r\n self.layoutWidget.setGeometry(QtCore.QRect(820, 670, 245, 28))\r\n self.layoutWidget.setObjectName(\"layoutWidget\")\r\n self.horizontalLayout_5 = QtWidgets.QHBoxLayout(self.layoutWidget)\r\n self.horizontalLayout_5.setContentsMargins(0, 0, 0, 0)\r\n self.horizontalLayout_5.setObjectName(\"horizontalLayout_5\")\r\n self.label_7 = QtWidgets.QLabel(self.layoutWidget)\r\n font = QtGui.QFont()\r\n font.setFamily(\"幼圆\")\r\n font.setPointSize(14)\r\n self.label_7.setFont(font)\r\n self.label_7.setObjectName(\"label_7\")\r\n self.horizontalLayout_5.addWidget(self.label_7)\r\n self.comboBox_2 = QtWidgets.QComboBox(self.layoutWidget)\r\n self.comboBox_2.setObjectName(\"comboBox_2\")\r\n self.comboBox_2.addItem(\"\")\r\n self.comboBox_2.addItem(\"\")\r\n self.comboBox_2.addItem(\"\")\r\n self.horizontalLayout_5.addWidget(self.comboBox_2)\r\n self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)\r\n self.graphicsView.setGeometry(QtCore.QRect(0, 0, 805, 805))\r\n self.graphicsView.setStyleSheet(\"\")\r\n brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))\r\n brush.setStyle(QtCore.Qt.SolidPattern)\r\n self.graphicsView.setBackgroundBrush(brush)\r\n self.graphicsView.setObjectName(\"graphicsView\")\r\n self.label_8 = QtWidgets.QLabel(self.centralwidget)\r\n self.label_8.setGeometry(QtCore.QRect(800, 40, 301, 151))\r\n font = QtGui.QFont()\r\n font.setFamily(\"Lucida Calligraphy\")\r\n font.setPointSize(56)\r\n self.label_8.setFont(font)\r\n self.label_8.setObjectName(\"label_8\")\r\n self.widget = QtWidgets.QWidget(self.centralwidget)\r\n self.widget.setGeometry(QtCore.QRect(820, 260, 255, 31))\r\n self.widget.setObjectName(\"widget\")\r\n self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)\r\n self.horizontalLayout.setContentsMargins(0, 0, 0, 0)\r\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\r\n self.label = QtWidgets.QLabel(self.widget)\r\n font = QtGui.QFont()\r\n font.setFamily(\"幼圆\")\r\n font.setPointSize(15)\r\n self.label.setFont(font)\r\n self.label.setObjectName(\"label\")\r\n self.horizontalLayout.addWidget(self.label)\r\n self.lineEdit = QtWidgets.QLineEdit(self.widget)\r\n self.lineEdit.setObjectName(\"lineEdit\")\r\n self.horizontalLayout.addWidget(self.lineEdit)\r\n self.widget1 = QtWidgets.QWidget(self.centralwidget)\r\n self.widget1.setGeometry(QtCore.QRect(820, 310, 255, 31))\r\n self.widget1.setObjectName(\"widget1\")\r\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.widget1)\r\n self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)\r\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\r\n self.label_2 = QtWidgets.QLabel(self.widget1)\r\n font = QtGui.QFont()\r\n font.setFamily(\"幼圆\")\r\n font.setPointSize(15)\r\n font.setBold(False)\r\n font.setWeight(50)\r\n self.label_2.setFont(font)\r\n self.label_2.setObjectName(\"label_2\")\r\n self.horizontalLayout_2.addWidget(self.label_2)\r\n self.lineEdit_2 = QtWidgets.QLineEdit(self.widget1)\r\n self.lineEdit_2.setObjectName(\"lineEdit_2\")\r\n self.horizontalLayout_2.addWidget(self.lineEdit_2)\r\n self.widget2 = QtWidgets.QWidget(self.centralwidget)\r\n self.widget2.setGeometry(QtCore.QRect(820, 370, 240, 28))\r\n self.widget2.setObjectName(\"widget2\")\r\n self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.widget2)\r\n self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0)\r\n self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\")\r\n self.label_3 = QtWidgets.QLabel(self.widget2)\r\n font = QtGui.QFont()\r\n font.setFamily(\"幼圆\")\r\n font.setPointSize(14)\r\n self.label_3.setFont(font)\r\n self.label_3.setObjectName(\"label_3\")\r\n self.horizontalLayout_3.addWidget(self.label_3)\r\n self.comboBox = QtWidgets.QComboBox(self.widget2)\r\n self.comboBox.setObjectName(\"comboBox\")\r\n self.comboBox.addItem(\"\")\r\n self.comboBox.addItem(\"\")\r\n self.comboBox.addItem(\"\")\r\n self.horizontalLayout_3.addWidget(self.comboBox)\r\n self.widget3 = QtWidgets.QWidget(self.centralwidget)\r\n self.widget3.setGeometry(QtCore.QRect(820, 610, 241, 27))\r\n self.widget3.setObjectName(\"widget3\")\r\n self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.widget3)\r\n self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0)\r\n self.horizontalLayout_4.setObjectName(\"horizontalLayout_4\")\r\n self.label_6 = QtWidgets.QLabel(self.widget3)\r\n font = QtGui.QFont()\r\n font.setFamily(\"幼圆\")\r\n font.setPointSize(15)\r\n self.label_6.setFont(font)\r\n self.label_6.setObjectName(\"label_6\")\r\n self.horizontalLayout_4.addWidget(self.label_6)\r\n self.horizontalSlider = QtWidgets.QSlider(self.widget3)\r\n self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal)\r\n self.horizontalSlider.setObjectName(\"horizontalSlider\")\r\n self.horizontalLayout_4.addWidget(self.horizontalSlider)\r\n MainWindow.setCentralWidget(self.centralwidget)\r\n self.menubar = QtWidgets.QMenuBar(MainWindow)\r\n self.menubar.setGeometry(QtCore.QRect(0, 0, 1089, 26))\r\n self.menubar.setObjectName(\"menubar\")\r\n MainWindow.setMenuBar(self.menubar)\r\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\r\n self.statusbar.setObjectName(\"statusbar\")\r\n MainWindow.setStatusBar(self.statusbar)\r\n\r\n self.retranslateUi(MainWindow)\r\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\r\n def retranslateUi(self, MainWindow):\r\n _translate = QtCore.QCoreApplication.translate\r\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"Maze\"))\r\n self.pushButton.setText(_translate(\"MainWindow\", \"一键生成迷宫\"))\r\n self.label_4.setText(_translate(\"MainWindow\", \"迷宫生成\"))\r\n self.label_5.setText(_translate(\"MainWindow\", \"走迷宫\"))\r\n self.pushButton_2.setText(_translate(\"MainWindow\", \"开始迷宫\"))\r\n self.label_7.setText(_translate(\"MainWindow\", \"走迷宫算法\"))\r\n self.comboBox_2.setItemText(0, _translate(\"MainWindow\", \"DFS\"))\r\n self.comboBox_2.setItemText(1, _translate(\"MainWindow\", \"BFS\"))\r\n self.comboBox_2.setItemText(2, _translate(\"MainWindow\", \"A*\"))\r\n self.label_8.setText(_translate(\"MainWindow\", \"Maze\"))\r\n self.label.setText(_translate(\"MainWindow\", \"迷宫行数目\"))\r\n self.label_2.setText(_translate(\"MainWindow\", \"迷宫列数目\"))\r\n self.label_3.setText(_translate(\"MainWindow\", \"迷宫生成算法\"))\r\n self.comboBox.setItemText(0, _translate(\"MainWindow\", \"深度优先\"))\r\n self.comboBox.setItemText(1, _translate(\"MainWindow\", \"Prim算法\"))\r\n self.comboBox.setItemText(2, _translate(\"MainWindow\", \"Kruskal算法\"))\r\n self.label_6.setText(_translate(\"MainWindow\", \"速度\"))\r\nclass Board(QMainWindow, Ui_MainWindow):\r\n def __init__(self):\r\n super(Board, self).__init__()\r\n self.setupUi(self)\r\n self.graphicsView.scene=QtWidgets.QGraphicsScene(0,0,WIDTH,HEIGHT)\r\n maze=Maze()\r\n maze.setPos(0,0)\r\n self.graphicsView.scene.addItem(maze)\r\n self.graphicsView.setScene(self.graphicsView.scene)\r\n self.connecter()\r\n self.show()\r\n def connecter(self):\r\n self.pushButton.clicked.connect(self.draw)\r\n self.pushButton_2.clicked.connect(self.start)\r\n def start(self):\r\n global SPEED,FIND,ROUTE,ans,record\r\n ans=[]\r\n record=[]\r\n SPEED= int(self.horizontalSlider.value())\r\n FIND= int(self.comboBox_2.currentIndex())\r\n self.search()\r\n maze = Maze()\r\n maze.setPos(0, 0)\r\n self.update(maze)\r\n def draw(self):\r\n global COL_INTERVAL,ROW_INTERVAL,WIDTH,record\r\n global COL_NUM,ROW_NUM,COL_LEN,ROW_LEN,GENERATE,maz,ans\r\n ans=[]\r\n record=[]\r\n COL_NUM=int(self.lineEdit_2.text())\r\n ROW_NUM=int(self.lineEdit.text())\r\n if COL_NUM>=5 and ROW_NUM>=5:\r\n GENERATE = int(self.comboBox.currentIndex())\r\n self.updateParameter()\r\n maze = Maze()\r\n maze.setPos(0, 0)\r\n self.update(maze)\r\n else:\r\n print(\"长宽必须大于等于五\")\r\n def generate(self):\r\n global maz\r\n gen=Gen()\r\n maz=np.ones((ROW_NUM+2,COL_NUM+2))\r\n if(GENERATE==0):\r\n gen.dfsg()\r\n if(GENERATE == 1):\r\n gen.primg()\r\n if (GENERATE == 2):\r\n gen.todog()\r\n def updateParameter(self):\r\n global COL_INTERVAL, ROW_INTERVAL, WIDTH,dx,dy\r\n global COL_NUM, ROW_NUM, COL_LEN, ROW_LEN\r\n self.generate()\r\n ROW_NUM,COL_NUM=maz.shape\r\n COL_INTERVAL = int(0.1 * WIDTH / (COL_NUM-1))\r\n ROW_INTERVAL = int(0.1 * HEIGHT / (ROW_NUM-1))\r\n COL_LEN = int(0.9 * WIDTH / COL_NUM)\r\n ROW_LEN = int(0.9 * HEIGHT / ROW_NUM)\r\n dx = ROW_NUM - 2\r\n dy = COL_NUM - 1\r\n def search(self):\r\n global FIND,record,ans\r\n if (FIND== 0):\r\n record.append((1,0))\r\n dfs(1,0)\r\n ans=list(ans)\r\n if (FIND == 1):\r\n bfs((1,0))\r\n if (FIND == 2):\r\n Astar()\r\n def update(self,maze):\r\n self.graphicsView.scene.addItem(maze)\r\n self.graphicsView.setScene(self.graphicsView.scene)\r\n self.show()\r\nclass Gen():\r\n def dfsg(self):\r\n global maz\r\n k=DFSg(ROW_NUM,COL_NUM)\r\n k.generate_matrix_dfs()\r\n maz=k.matrix\r\n def primg(self):\r\n global maz\r\n k =PRIMg(ROW_NUM, COL_NUM)\r\n k.generate_matrix_prim()\r\n maz = k.matrix\r\n\r\n def todog(self):\r\n global maz\r\n k = KRUSKALg(ROW_NUM, COL_NUM)\r\n k.generate_matrix_kruskal()\r\n maz = k.matrix\r\n\r\n def check(self,temp):\r\n pass\r\n\r\n def get_next(self,temp):\r\n global stack\r\n dir = [(1, 0), (0, 1), (-1, 0), (0, -1)]\r\n np.random.shuffle(dir)\r\n (x,y)=temp\r\n for (dx,dy) in dir:\r\n if((dx+x)>0 and (dx+x)<ROW_NUM-1 and (dy+y)<COL_NUM-1 and (dy+y)>0):\r\n if((x+dx,y+dy) not in stack):\r\n print(dx+x,dy+y)\r\n return (dx+x,dy+y)\r\n return None\r\ndef Keep(temp):\r\n global ans,record\r\n ans=tuple(temp)\r\ndef Save(temp):\r\n global process, record\r\n process = tuple(temp)\r\ndef dfs(x,y):\r\n global dx, dy,record,w\r\n # Save(record)\r\n # pp = processPaint()\r\n # pp.setPos(0, 0)\r\n # w.update(pp)\r\n\r\n # time.sleep(0.1)\r\n if x == dx and y == dy:\r\n Keep(record)\r\n return\r\n for (kx, ky) in [[1, 0], [-1, 0], [0, 1], [0, -1]]:\r\n if (check(kx + x, ky + y)):\r\n record.append((kx + x, ky + y))\r\n dfs(kx + x, ky + y)\r\n record.pop()\r\ndef bfs(t):\r\n global que,dx,dy,record\r\n lis={}\r\n visited=[(1,0)]\r\n que=Queue()\r\n que.put(t)\r\n while que:\r\n temp=que.get()\r\n if temp[0]==dx and temp[1]==dy:\r\n break\r\n for (kx, ky) in [[1, 0], [-1, 0], [0, 1], [0, -1]]:\r\n x=kx + temp[0]\r\n y=ky + temp[1]\r\n if (x > 0 and y > 0 and x < ROW_NUM and y < COL_NUM and maz[x][y] == 0 and (x,y) not in visited):\r\n que.put((x, y))\r\n visited.append((x, y))\r\n lis[(x,y)]=(temp[0],temp[1])\r\n if (x==dx and y==dy):\r\n break\r\n record.append((dx,dy))\r\n (x,y)=lis[(dx,dy)]\r\n record.append((x, y))\r\n while (x,y)!=(1,0):\r\n (x,y)=lis[x,y]\r\n record.append((x, y))\r\n Keep(record)\r\ndef Astar():\r\n start = (1, 0)\r\n final = (ROW_NUM - 2, COL_NUM - 1)\r\n front = PriorityQueue()\r\n front.put(start)\r\n father = {}\r\n father[start] = None\r\n sum_cost = {}\r\n sum_cost[start] = 0\r\n while front:\r\n current = front.get()\r\n if current == final:\r\n break\r\n for (dx, dy) in [[1, 0], [-1, 0], [0, 1], [0, -1]]:\r\n x = current[0] + dx\r\n y = current[1] + dy\r\n if isOK((x, y)):\r\n cost = sum_cost[current] + calcuCost(current, (x, y))\r\n if (x, y) not in sum_cost or cost < sum_cost[(x, y)]:\r\n sum_cost[(x, y)] = cost\r\n priority = cost + heuristic(start, (x, y))\r\n front.put((x, y), priority)\r\n father[(x, y)] = current\r\n if (x, y) == final:\r\n break\r\n temp=final\r\n while temp:\r\n record.append(temp)\r\n temp=father[temp]\r\n Keep(record)\r\ndef check(x, y):\r\n global maz,record,ROW_NUM,COL_NUM\r\n if (x >= 0 and y >= 0 and x < ROW_NUM and y < COL_NUM and maz[x][y] == 0 and (x, y) not in record):\r\n return True\r\n return False\r\ndef heuristic(a,b):\r\n return abs(a[0]-b[0])+abs(a[1]-b[1])\r\ndef isOK(a):\r\n return (a[0]>0 and a[1]>0 and a[0]<ROW_NUM and a[1]<COL_NUM and maz[a[0]][a[1]]==0)\r\ndef calcuCost(a,b):\r\n return abs(a[0]-b[0])+abs(a[1]-b[1])\r\nclass Maze(QGraphicsItem):\r\n def __init__(self):\r\n super(Maze, self).__init__()\r\n def boundingRect(self):\r\n return QRectF(0, 0, 800, 800)\r\n def paint(self, painter, option, widget):\r\n global COL_INTERVAL, ROW_INTERVAL\r\n global WIDTH, COL_NUM, ROW_NUM\r\n global COL_LEN, ROW_LEN, maz,ROUTE\r\n for i in range(COL_NUM):\r\n for j in range(ROW_NUM):\r\n if(maz[i][j]!=0):\r\n painter.setPen(Qt.green)\r\n painter.setBrush(Qt.white)\r\n painter.drawRect(i*(COL_LEN+COL_INTERVAL),j*(ROW_LEN+ROW_INTERVAL),COL_LEN,ROW_LEN)\r\n if((i,j) in ans):\r\n painter.setPen(Qt.yellow)\r\n painter.setBrush(Qt.red)\r\n painter.drawEllipse(i * (COL_LEN + COL_INTERVAL)+COL_LEN/4, j * (ROW_LEN + ROW_INTERVAL)+ROW_LEN/4, COL_LEN/2, ROW_LEN/2)\r\nclass processPaint(QGraphicsItem):\r\n def __init__(self):\r\n super(processPaint, self).__init__()\r\n def boundingRect(self):\r\n return QRectF(0, 0, 800, 800)\r\n def paint(self, painter, option, widget):\r\n global COL_INTERVAL, ROW_INTERVAL\r\n global WIDTH, COL_NUM, ROW_NUM\r\n global COL_LEN, ROW_LEN, maz,process\r\n for i in range(COL_NUM):\r\n for j in range(ROW_NUM):\r\n if(maz[i][j]!=0):\r\n painter.setPen(Qt.green)\r\n painter.setBrush(Qt.white)\r\n painter.drawRect(i*(COL_LEN+COL_INTERVAL),j*(ROW_LEN+ROW_INTERVAL),COL_LEN,ROW_LEN)\r\n if((i,j) in record):\r\n painter.setPen(Qt.yellow)\r\n painter.setBrush(Qt.red)\r\n painter.drawEllipse(i * (COL_LEN + COL_INTERVAL)+COL_LEN/4, j * (ROW_LEN + ROW_INTERVAL)+ROW_LEN/4, COL_LEN/2, ROW_LEN/2)\r\ndef main():\r\n global w\r\n app = QApplication(sys.argv)\r\n w=Board()\r\n w.show()\r\n sys.exit(app.exec_())\r\nmain()"
] | [
[
"numpy.random.randint",
"numpy.random.shuffle",
"numpy.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cltl/robustness-albert | [
"47029cbac0c770e2e4fbad44534097305b0b609e"
] | [
"robustness_albert/train.py"
] | [
"# Code modified from:\n# https://github.com/huggingface/transformers/blob/master/examples/pytorch/text-classification/run_glue_no_trainer.py\n# Changed structure of the file, removed unnecessary code (e.g. creating new functions and removing non SST-2\n# related code), added comments, and added other necessary code for this research (e.g. incorporating BestEpoch or SWA).\n# coding=utf-8\n# Copyright 2021 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nimport random\nfrom typing import Callable, Tuple, Any\n\nimport click\nimport numpy as np\nimport torch\nimport wandb\nfrom datasets import load_metric, Metric\nfrom torch.optim import Optimizer\nfrom torch.optim.lr_scheduler import _LRScheduler, CyclicLR\nfrom torch.optim.swa_utils import AveragedModel\nfrom torch.utils.data import DataLoader, Dataset\nfrom tqdm import tqdm\nfrom transformers import AdamW\nfrom transformers import AlbertForSequenceClassification, set_seed, default_data_collator, \\\n DataCollatorWithPadding, get_scheduler\n\nfrom robustness_albert.lr_schedulers import SWALR\nfrom robustness_albert.utils import get_dataset, load_config, save_model, load_model\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(\"root\")\n\n\nclass BestEpoch:\n \"\"\"Class to keep track of the best epoch while training.\n\n Keeps track by comparing the evaluation loss of each epoch. If it is lower than the current best loss, this epoch\n will be considered the best until now, and its evaluation loss will replace the previous best loss.\n\n Attributes:\n best_epoch (int): Integer indicating the best epoch until now.\n best_loss (float): Float indicating the best loss until now.\n best_accuracy (float): Float indicating the best accuracy until now.\n\n \"\"\"\n def __init__(self):\n \"\"\"Initialize the tracker of the best epoch.\"\"\"\n self.best_epoch: int = 0\n self.best_loss: float = float(\"inf\")\n self.best_accuracy: float = 0.0\n\n def update(self, current_loss: float, current_accuracy: float, epoch: int) -> None:\n \"\"\"Updates the best epoch tracker.\n\n Takes the evaluation loss and accuracy of the current epoch and compares it with the current best loss.\n If it is lower, updates the current loss, accuracy, and epoch to be the best until now.\n\n Args:\n current_loss (float): loss of the current epoch.\n current_accuracy (float): accuracy of the current epoch.\n epoch (int): which epoch.\n \"\"\"\n if current_loss < self.best_loss:\n self.best_loss = current_loss\n self.best_accuracy = current_accuracy\n self.best_epoch = epoch\n\n\ndef get_optimizer(model: Any, learning_rate: float, weight_decay: float) -> Optimizer:\n \"\"\"Function that returns the optimizer for training.\n\n Given the model, learning rate, and weight decay, this function returns the optimizer that can be used while\n training. The model parameters are split into two groups: weight decay and non-weight decay groups, as done in the\n BERT paper.\n\n Args:\n model (torch.nn.module): Model used for training.\n learning_rate (float): Float that indicates the learning rate.\n weight_decay (float): Float that indicates the weight decay.\n\n Returns:\n optimizer (Optimizer): optimizer for the training.\n \"\"\"\n # Split weights in two groups, one with weight decay and the other not.\n no_decay = [\"bias\", \"LayerNorm.weight\"]\n optimizer_grouped_parameters = [\n {\n \"params\": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],\n \"weight_decay\": weight_decay,\n },\n {\n \"params\": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)],\n \"weight_decay\": 0.0,\n },\n ]\n optimizer = AdamW(optimizer_grouped_parameters, lr=learning_rate)\n\n return optimizer\n\n\ndef get_dataloader(\n dataset: Dataset, tokenizer: Callable, batch_size: int, padded: bool = False, shuffle: bool = False\n) -> DataLoader:\n \"\"\"Function that returns a dataloader.\n\n Given a dataset, tokenizer, batch size, and if padding has been applied already or not, a dataloader is returned\n with the appropriate data collator.\n\n Args:\n dataset (Dataset): Dataset that will be loaded.\n tokenizer (Tokenizer): Tokenizer that will be used if padding has not been applied before.\n batch_size (int): Batch size of the loader.\n padded (bool): Boolean that implies if the data has already been padded or not.\n shuffle (bool): Boolean to indicate if data should be shuffled by dataloader.\n\n Returns:\n dataloader (DataLoader): Dataloader that loads the dataset.\n \"\"\"\n # If dataset has been padded already, use default data collator. Else, use collator with padding.\n if padded:\n data_collator = default_data_collator\n else:\n data_collator = DataCollatorWithPadding(tokenizer)\n\n dataloader = DataLoader(dataset, shuffle=shuffle, collate_fn=data_collator, batch_size=batch_size)\n return dataloader\n\n\ndef train(\n model: Any,\n epoch: int,\n dataloader: DataLoader,\n optimizer: Optimizer,\n lr_scheduler: _LRScheduler,\n metric: Metric,\n logging_freq: int,\n max_steps: int,\n device: str,\n enable_swa: bool = False,\n swa_model: AveragedModel = None,\n swa_scheduler: SWALR = None,\n) -> None:\n \"\"\"Function that performs all the steps during the training phase.\n\n In this function, the entire training phase of an epoch is run. Looping over the dataloader, each batch is fed\n to the model, the loss and metric are tracked/calculated, and the forward and backward pass are done.\n\n Args:\n model (Model): Model that is being trained.\n epoch (int): Current epoch of experiment.\n dataloader (DataLoader): Object that will load the training data.\n optimizer (Optimizer): Optimizer for training.\n lr_scheduler (_LRScheduler): Learning rate scheduler for the optimizer.\n metric (Metric): Metric that is being tracked.\n logging_freq (int): Frequency of logging the training metrics.\n max_steps (int): Maximum amount of steps to be taken during this epoch.\n device (str): Device on which training will be done.\n enable_swa (bool): Boolean that indicates if Stochastic Weight Averaging should be applied during this epoch.\n swa_model (AveragedModel): Model that does Stochastic Weight Averaging.\n swa_scheduler (SWALR): Learning rate scheduler for Stochastic Weight Averaging.\n \"\"\"\n model.train()\n logging.info(f\" Start training epoch {epoch}\")\n\n if enable_swa:\n logging.info(\" SWA is enabled this epoch.\")\n\n accuracies = []\n losses = []\n for step, batch in enumerate(tqdm(dataloader)):\n\n input_ids = batch[\"input_ids\"].to(device)\n attention_mask = batch[\"attention_mask\"].to(device)\n labels = batch[\"labels\"].to(device)\n\n if step < 5:\n print(batch[\"input_ids\"][0])\n print(dataloader.collate_fn.tokenizer.batch_decode(batch[\"input_ids\"])[0])\n\n outputs = model(input_ids, attention_mask=attention_mask, labels=labels)\n loss = outputs.loss\n loss.backward()\n\n optimizer.step()\n optimizer.zero_grad()\n\n # TODO: Fix for tracking both learning rates necessary?\n if enable_swa and swa_scheduler:\n if isinstance(swa_scheduler, CyclicLR):\n swa_scheduler.step()\n current_lr = swa_scheduler.get_last_lr()[0]\n else:\n lr_scheduler.step()\n current_lr = lr_scheduler.get_last_lr()[0]\n\n predictions = outputs.logits.argmax(dim=-1)\n metric.add_batch(predictions=predictions, references=batch[\"labels\"])\n accuracy = metric.compute()[\"accuracy\"]\n current_step = (epoch * len(dataloader)) + step\n wandb.log(\n {\"epoch\": epoch, \"train_loss\": loss, \"train_accuracy\": accuracy, \"learning_rate\": current_lr},\n step=current_step\n )\n\n accuracies.append(accuracy)\n losses.append(loss.detach().cpu().numpy())\n\n if step % logging_freq == 0:\n logger.info(f\" Epoch {epoch}, Step {step}: Loss: {loss}, Accuracy: {accuracy}\")\n\n if current_step == max_steps - 1:\n break\n\n average_loss = np.mean(losses)\n average_accuracy = np.mean(accuracies)\n wandb.log({\"average_train_loss\": average_loss, \"average_train_accuracy\": average_accuracy})\n logger.info(f\" Epoch {epoch} average training loss: {average_loss}, accuracy: {average_accuracy}\")\n\n if enable_swa and swa_model and swa_scheduler:\n swa_model.update_parameters(model)\n if isinstance(swa_scheduler, SWALR):\n swa_scheduler.step()\n torch.optim.swa_utils.update_bn(dataloader, swa_model, device=torch.device(device))\n\n\ndef validate(\n model: Any,\n epoch: int,\n dataloader: DataLoader,\n metric: Metric,\n max_steps: int,\n device: str,\n enable_swa: bool = False,\n swa_model: AveragedModel = None,\n) -> Tuple[np.float_, float]:\n \"\"\"Function that performs all the steps during the validation/evaluation phase.\n\n In this function, the entire evaluation phase of an epoch is run. Looping over the dataloader, each batch is fed\n to the model and the loss and accuracy are tracked.\n\n Args:\n model (Model): Model that is being trained.:\n epoch (int): Current epoch of experiment.\n dataloader (DataLoader): Object that will load the training data.\n metric (Metric): Metric that is being tracked.\n max_steps (int): Maximum amount of steps to be taken during this epoch.\n device (str): Device on which training will be done.\n enable_swa (bool): Boolean that indicates if SWA should be enabled while evaluating, i.e. the SWA model is used.\n swa_model (AveragedModel): Stochastic Weight Averaging model.\n\n Returns:\n eval_loss (float): Average loss over the whole validation set.\n eval_accuracy (float): Average accuracy over the whole validation set.\n \"\"\"\n model.eval()\n\n if enable_swa and swa_model:\n swa_model.eval()\n\n with torch.no_grad():\n logger.info(\" Starting Evaluation\")\n losses = []\n for step, batch in enumerate(tqdm(dataloader)):\n input_ids = batch[\"input_ids\"].to(device)\n attention_mask = batch[\"attention_mask\"].to(device)\n labels = batch[\"labels\"].to(device)\n\n if step < 5:\n print(batch[\"input_ids\"][0])\n print(dataloader.collate_fn.tokenizer.batch_decode(batch[\"input_ids\"])[0])\n\n if enable_swa and swa_model:\n outputs = swa_model(input_ids, attention_mask, labels=labels)\n else:\n outputs = model(input_ids, attention_mask=attention_mask, labels=labels)\n predictions = outputs.logits.argmax(dim=-1)\n metric.add_batch(\n predictions=predictions,\n references=batch[\"labels\"],\n )\n losses.append(outputs.loss.detach().cpu().numpy())\n current_step = (epoch * len(dataloader)) + step\n\n if current_step == max_steps - 1:\n break\n\n eval_loss = np.mean(losses)\n eval_accuracy = metric.compute()[\"accuracy\"]\n logger.info(f\" Evaluation {epoch}: Average Loss: {eval_loss}, Average Accuracy: {eval_accuracy}\")\n wandb.log({\"epoch\": epoch, \"eval_loss\": eval_loss, \"eval_accuracy\": eval_accuracy})\n\n return eval_loss, eval_accuracy\n\n\[email protected]()\[email protected](\"-c\", \"--config-path\", \"config_path\", required=True, type=str)\ndef main(config_path):\n \"\"\"Function that executes the entire training pipeline.\n\n This function takes care of loading and processing the config file, initializing the model, dataset, optimizer, and\n other utilities for the entire training job.\n\n Args:\n config_path (str): path to the config file for the training experiment.\n \"\"\"\n config = load_config(config_path)\n\n # Initialize Weights & Biases.\n wandb.init(config=config, project=config[\"wandb\"][\"project_name\"], name=config[\"wandb\"][\"run_name\"])\n # Set seeds for reproducibility.\n set_seed(config[\"pipeline\"][\"seed\"])\n # torch.backends.cudnn.benchmark = False\n # os.environ['PYTHONHASHSEED'] = str(config[\"pipeline\"][\"seed\"])\n torch.backends.cudnn.deterministic = True\n\n # Get values from config.\n model_name = config[\"task\"][\"model_name\"]\n task_name = config[\"task\"][\"task_name\"]\n sub_task_name = config[\"task\"][\"sub_task_name\"]\n device = config[\"pipeline\"][\"device\"]\n swa = \"swa\" in config\n\n # Load dataset and dataloaders.\n dataset, tokenizer = get_dataset(\n task_name,\n model_name,\n sub_task=sub_task_name,\n padding=config[\"processing\"][\"padding\"],\n tokenize=True,\n batched=True,\n return_tokenizer=True\n )\n train_dataset = dataset[\"train\"]\n validation_dataset = dataset[\"validation\"]\n padding = config[\"processing\"][\"padding\"]\n train_batch_size = config[\"pipeline\"][\"train_batch_size\"]\n validation_batch_size = config[\"pipeline\"][\"validation_batch_size\"]\n train_dataloader = get_dataloader(train_dataset, tokenizer, train_batch_size, padding, shuffle=True)\n validation_dataloader = get_dataloader(validation_dataset, tokenizer, validation_batch_size, padding)\n\n # Set amount of training steps.\n num_update_steps_per_epoch = len(train_dataloader)\n n_epochs = config[\"pipeline\"][\"n_epochs\"]\n max_train_steps = n_epochs * num_update_steps_per_epoch\n # If a maximum amount of steps is specified, change the amount of epochs accordingly.\n if \"max_train_steps\" in config[\"pipeline\"]:\n max_train_steps = config[\"pipeline\"][\"max_train_steps\"]\n n_epochs = int(np.ceil(max_train_steps / num_update_steps_per_epoch))\n\n # Load metric, model, optimizer, and learning rate scheduler.\n metric = load_metric(task_name, sub_task_name)\n model = AlbertForSequenceClassification.from_pretrained(model_name)\n optimizer = get_optimizer(model, config[\"optimizer\"][\"learning_rate\"], config[\"optimizer\"][\"weight_decay\"])\n\n lr_scheduler = get_scheduler(\n name=config[\"optimizer\"][\"learning_rate_scheduler\"],\n optimizer=optimizer,\n num_warmup_steps=config[\"optimizer\"][\"num_warmup_steps\"],\n num_training_steps=max_train_steps,\n )\n\n swa_model = None\n swa_scheduler = None\n swa_start = None\n swa_schedule_type = None\n if swa:\n swa_model = AveragedModel(model, device=device)\n # Epoch from which SWA should start (count from 0)\n swa_start = config[\"swa\"][\"start\"]\n swa_schedule_type = config[\"swa\"].get(\"swa_schedule_type\", \"constant\")\n\n if swa_schedule_type == \"cyclic\":\n swa_learning_rate_max = config[\"swa\"][\"swa_learning_rate_max\"]\n swa_learning_rate_min = config[\"swa\"][\"swa_learning_rate_min\"]\n step_size_down = config[\"swa\"][\"step_size_down\"]\n step_size_up = config[\"swa\"][\"step_size_up\"]\n else:\n anneal_epochs = config[\"swa\"][\"anneal_epochs\"]\n anneal_strategy = config[\"swa\"][\"anneal_strategy\"]\n swa_learning_rate = config[\"swa\"][\"learning_rate\"]\n logging.info(f\" Stochastic Weight Averaging is turned on from Epoch {swa_start}\")\n\n # Set everything correctly according to resumption of training or not.\n start_epoch = 0\n if \"resume\" in config[\"pipeline\"]:\n model, optimizer, scheduler, epoch = load_model(config[\"pipeline\"][\"resume\"], model, optimizer, lr_scheduler)\n # Start from the next epoch.\n start_epoch = epoch + 1\n\n model = model.to(device)\n wandb.watch(model, optimizer, log=\"all\", log_freq=10)\n\n print(\"\\n\")\n logger.info(f\" Amount training examples: {len(train_dataset)}\")\n logger.info(f\" Amount validation examples: {len(validation_dataset)}\")\n logger.info(f\" Amount of epochs: {n_epochs}\")\n logger.info(f\" Amount optimization steps: {max_train_steps}\")\n logger.info(f\" Batch size train: {train_batch_size}, validation: {validation_batch_size}\")\n print(\"\\n\")\n\n # Log a few random samples from the training set:\n for index in random.sample(range(len(train_dataset)), 3):\n logger.info(f\" Sample {index} of the training set: {train_dataset[index]}.\")\n print(\"\\n\")\n\n # Setup best epoch tracker and early stopper if present in config.\n logging_freq = config[\"pipeline\"][\"logging_freq\"]\n tracker = BestEpoch()\n\n for epoch in range(start_epoch, n_epochs):\n enable_swa = False\n\n if swa and epoch == swa_start:\n if swa_schedule_type == \"cyclic\":\n swa_scheduler = CyclicLR(\n optimizer,\n swa_learning_rate_max,\n swa_learning_rate_min,\n step_size_down=step_size_down,\n step_size_up=step_size_up,\n cycle_momentum=False\n )\n else:\n swa_scheduler = SWALR(\n optimizer, swa_lr=swa_learning_rate, anneal_epochs=anneal_epochs, anneal_strategy=anneal_strategy\n )\n\n if swa and epoch >= swa_start:\n enable_swa = True\n\n train(\n model,\n epoch,\n train_dataloader,\n optimizer,\n lr_scheduler,\n metric,\n logging_freq,\n max_train_steps,\n device,\n enable_swa=enable_swa,\n swa_model=swa_model,\n swa_scheduler=swa_scheduler,\n )\n eval_loss, eval_accuracy = validate(\n model,\n epoch,\n validation_dataloader,\n metric,\n max_train_steps,\n device,\n enable_swa=enable_swa,\n swa_model=swa_model,\n )\n print(\"\\n\")\n\n model_to_save = model\n scheduler_to_save = lr_scheduler\n if enable_swa:\n model_to_save = swa_model\n scheduler_to_save = swa_scheduler\n save_model(\n model_to_save, optimizer, scheduler_to_save, epoch, config[\"pipeline\"][\"output_directory\"], model_name\n )\n tracker.update(eval_loss, eval_accuracy, epoch)\n\n logger.info(\n f\"Best performance was during epoch {tracker.best_epoch}, with a loss of {tracker.best_loss}, \"\n f\"and accuracy of {tracker.best_accuracy}\"\n )\n\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"torch.optim.lr_scheduler.CyclicLR",
"torch.utils.data.DataLoader",
"numpy.ceil",
"torch.no_grad",
"numpy.mean",
"torch.device",
"torch.optim.swa_utils.AveragedModel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dingcycle/depc | [
"5ff0a5322684daf715e1171a259b9c643925cf73"
] | [
"depc/sources/fake/__init__.py"
] | [
"import hashlib\nimport logging\n\nimport numpy as np\n\nfrom depc.sources import BaseSource, SourceRegister\nfrom depc.sources.exceptions import BadConfigurationException\nfrom depc.sources.fake.metrics import (\n generate_fake_db_connections,\n generate_fake_http_status,\n generate_fake_oco_status,\n generate_fake_ping_data,\n)\n\nlogger = logging.getLogger(__name__)\nfake_plugin = SourceRegister()\n\n\nSCHEMA = {\"type\": \"object\", \"properties\": {}}\nFORM = []\n\n\n@fake_plugin.source(schema=SCHEMA, form=FORM)\nclass Fake(BaseSource):\n \"\"\"\n Fake source used in the documentation tutorial.\n \"\"\"\n\n name = \"Fake\"\n\n @classmethod\n def create_random_state(cls, start, end, name):\n \"\"\"\n Give a unique seed based on parameters\n \"\"\"\n slug = \"{0}-{1}-{2}\".format(start, end, name)\n seed = int(hashlib.sha1(slug.encode(\"utf-8\")).hexdigest()[:7], 16)\n random_state = np.random.RandomState(seed)\n return random_state\n\n async def execute(self, parameters, name, start, end):\n metric = parameters[\"query\"]\n\n # Our fake database just provides 4 metrics\n random_metrics_dispatcher = {\n \"depc.tutorial.ping\": generate_fake_ping_data,\n \"depc.tutorial.oco\": generate_fake_oco_status,\n \"depc.tutorial.dbconnections\": generate_fake_db_connections,\n \"depc.tutorial.httpstatus\": generate_fake_http_status,\n }\n\n if metric not in random_metrics_dispatcher.keys():\n raise BadConfigurationException(\"Metric is not available for the tutorial\")\n\n # Generate datapoints\n random_state = self.create_random_state(start, end, name)\n timestamps = list(map(int, np.arange(start, end, 60, dtype=int)))\n values = random_metrics_dispatcher[metric](random_state, len(timestamps))\n dps = dict(zip(timestamps, values))\n\n return [{\"dps\": dps, \"metric\": metric, \"tags\": {\"name\": name}}]\n"
] | [
[
"numpy.arange",
"numpy.random.RandomState"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
palchicz/flytekit | [
"726762e1cbe39d216480374b7efb99c339ec63f5"
] | [
"tests/flytekit/unit/core/test_type_engine.py"
] | [
"import datetime\nimport os\nimport tempfile\nimport typing\nfrom dataclasses import asdict, dataclass\nfrom datetime import timedelta\nfrom enum import Enum\n\nimport pandas as pd\nimport pytest\nfrom dataclasses_json import DataClassJsonMixin, dataclass_json\nfrom flyteidl.core import errors_pb2\nfrom google.protobuf import json_format as _json_format\nfrom google.protobuf import struct_pb2 as _struct\nfrom marshmallow_enum import LoadDumpOptions\nfrom marshmallow_jsonschema import JSONSchema\n\nfrom flytekit import kwtypes\nfrom flytekit.common.exceptions import user as user_exceptions\nfrom flytekit.core.context_manager import FlyteContext, FlyteContextManager\nfrom flytekit.core.type_engine import (\n DataclassTransformer,\n DictTransformer,\n ListTransformer,\n LiteralsResolver,\n SimpleTransformer,\n TypeEngine,\n convert_json_schema_to_python_class,\n dataclass_from_dict,\n)\nfrom flytekit.models import types as model_types\nfrom flytekit.models.core.types import BlobType\nfrom flytekit.models.literals import Blob, BlobMetadata, Literal, LiteralCollection, LiteralMap, Primitive, Scalar\nfrom flytekit.models.types import LiteralType, SimpleType\nfrom flytekit.types.directory import TensorboardLogs\nfrom flytekit.types.directory.types import FlyteDirectory\nfrom flytekit.types.file import JPEGImageFile\nfrom flytekit.types.file.file import FlyteFile, FlyteFilePathTransformer, noop\nfrom flytekit.types.pickle import FlytePickle\nfrom flytekit.types.pickle.pickle import FlytePickleTransformer\nfrom flytekit.types.schema import FlyteSchema\n\n\ndef test_type_engine():\n t = int\n lt = TypeEngine.to_literal_type(t)\n assert lt.simple == model_types.SimpleType.INTEGER\n\n t = typing.Dict[str, typing.List[typing.Dict[str, timedelta]]]\n lt = TypeEngine.to_literal_type(t)\n assert lt.map_value_type.collection_type.map_value_type.simple == model_types.SimpleType.DURATION\n\n\ndef test_named_tuple():\n t = typing.NamedTuple(\"Outputs\", [(\"x_str\", str), (\"y_int\", int)])\n var_map = TypeEngine.named_tuple_to_variable_map(t)\n assert var_map.variables[\"x_str\"].type.simple == model_types.SimpleType.STRING\n assert var_map.variables[\"y_int\"].type.simple == model_types.SimpleType.INTEGER\n\n\ndef test_type_resolution():\n assert type(TypeEngine.get_transformer(typing.List[int])) == ListTransformer\n assert type(TypeEngine.get_transformer(typing.List)) == ListTransformer\n assert type(TypeEngine.get_transformer(list)) == ListTransformer\n\n assert type(TypeEngine.get_transformer(typing.Dict[str, int])) == DictTransformer\n assert type(TypeEngine.get_transformer(typing.Dict)) == DictTransformer\n assert type(TypeEngine.get_transformer(dict)) == DictTransformer\n\n assert type(TypeEngine.get_transformer(int)) == SimpleTransformer\n\n assert type(TypeEngine.get_transformer(os.PathLike)) == FlyteFilePathTransformer\n assert type(TypeEngine.get_transformer(FlytePickle)) == FlytePickleTransformer\n\n with pytest.raises(ValueError):\n TypeEngine.get_transformer(typing.Any)\n\n\ndef test_file_formats_getting_literal_type():\n transformer = TypeEngine.get_transformer(FlyteFile)\n\n lt = transformer.get_literal_type(FlyteFile)\n assert lt.blob.format == \"\"\n\n # Works with formats that we define\n lt = transformer.get_literal_type(FlyteFile[\"txt\"])\n assert lt.blob.format == \"txt\"\n\n lt = transformer.get_literal_type(FlyteFile[typing.TypeVar(\"jpg\")])\n assert lt.blob.format == \"jpg\"\n\n # Empty default to the default\n lt = transformer.get_literal_type(FlyteFile)\n assert lt.blob.format == \"\"\n\n lt = transformer.get_literal_type(FlyteFile[typing.TypeVar(\".png\")])\n assert lt.blob.format == \"png\"\n\n\ndef test_file_format_getting_python_value():\n transformer = TypeEngine.get_transformer(FlyteFile)\n\n ctx = FlyteContext.current_context()\n\n # This file probably won't exist, but it's okay. It won't be downloaded unless we try to read the thing returned\n lv = Literal(\n scalar=Scalar(\n blob=Blob(metadata=BlobMetadata(type=BlobType(format=\"txt\", dimensionality=0)), uri=\"file:///tmp/test\")\n )\n )\n\n pv = transformer.to_python_value(ctx, lv, expected_python_type=FlyteFile[\"txt\"])\n assert isinstance(pv, FlyteFile)\n assert pv.extension() == \"txt\"\n\n\ndef test_list_of_dict_getting_python_value():\n transformer = TypeEngine.get_transformer(typing.List)\n ctx = FlyteContext.current_context()\n lv = Literal(\n collection=LiteralCollection(\n literals=[Literal(map=LiteralMap({\"foo\": Literal(scalar=Scalar(primitive=Primitive(integer=1)))}))]\n )\n )\n\n pv = transformer.to_python_value(ctx, lv, expected_python_type=typing.List[typing.Dict[str, int]])\n assert isinstance(pv, list)\n\n\ndef test_list_of_dataclass_getting_python_value():\n @dataclass_json\n @dataclass()\n class Bar(object):\n w: typing.Optional[str]\n x: float\n y: str\n z: typing.Dict[str, bool]\n\n @dataclass_json\n @dataclass()\n class Foo(object):\n w: int\n x: typing.List[int]\n y: typing.Dict[str, str]\n z: Bar\n\n foo = Foo(w=1, x=[1], y={\"hello\": \"10\"}, z=Bar(w=None, x=1.0, y=\"hello\", z={\"world\": False}))\n generic = _json_format.Parse(typing.cast(DataClassJsonMixin, foo).to_json(), _struct.Struct())\n lv = Literal(collection=LiteralCollection(literals=[Literal(scalar=Scalar(generic=generic))]))\n\n transformer = TypeEngine.get_transformer(typing.List)\n ctx = FlyteContext.current_context()\n\n schema = JSONSchema().dump(typing.cast(DataClassJsonMixin, Foo).schema())\n foo_class = convert_json_schema_to_python_class(schema[\"definitions\"], \"FooSchema\")\n\n pv = transformer.to_python_value(ctx, lv, expected_python_type=typing.List[foo_class])\n assert isinstance(pv, list)\n assert pv[0].w == foo.w\n assert pv[0].x == foo.x\n assert pv[0].y == foo.y\n assert pv[0].z.x == foo.z.x\n assert type(pv[0].z.x) == float\n assert pv[0].z.y == foo.z.y\n assert pv[0].z.z == foo.z.z\n assert foo == dataclass_from_dict(Foo, asdict(pv[0]))\n\n\ndef test_file_no_downloader_default():\n # The idea of this test is to assert that if a FlyteFile is created with no download specified,\n # then it should return the set path itself. This matches if we use open method\n transformer = TypeEngine.get_transformer(FlyteFile)\n\n ctx = FlyteContext.current_context()\n local_file = \"/usr/local/bin/file\"\n\n lv = Literal(\n scalar=Scalar(blob=Blob(metadata=BlobMetadata(type=BlobType(format=\"\", dimensionality=0)), uri=local_file))\n )\n\n pv = transformer.to_python_value(ctx, lv, expected_python_type=FlyteFile)\n assert isinstance(pv, FlyteFile)\n assert pv.download() == local_file\n\n\ndef test_dir_no_downloader_default():\n # The idea of this test is to assert that if a FlyteFile is created with no download specified,\n # then it should return the set path itself. This matches if we use open method\n transformer = TypeEngine.get_transformer(FlyteDirectory)\n\n ctx = FlyteContext.current_context()\n\n local_dir = \"/usr/local/bin/\"\n lv = Literal(\n scalar=Scalar(blob=Blob(metadata=BlobMetadata(type=BlobType(format=\"\", dimensionality=1)), uri=local_dir))\n )\n\n pv = transformer.to_python_value(ctx, lv, expected_python_type=FlyteDirectory)\n assert isinstance(pv, FlyteDirectory)\n assert pv.download() == local_dir\n\n\ndef test_dict_transformer():\n d = DictTransformer()\n\n def assert_struct(lit: LiteralType):\n assert lit is not None\n assert lit.simple == SimpleType.STRUCT\n\n def recursive_assert(lit: LiteralType, expected: LiteralType, expected_depth: int = 1, curr_depth: int = 0):\n assert curr_depth <= expected_depth\n assert lit is not None\n if lit.map_value_type is None:\n assert lit == expected\n return\n recursive_assert(lit.map_value_type, expected, expected_depth, curr_depth + 1)\n\n # Type inference\n assert_struct(d.get_literal_type(dict))\n assert_struct(d.get_literal_type(typing.Dict[int, int]))\n recursive_assert(d.get_literal_type(typing.Dict[str, str]), LiteralType(simple=SimpleType.STRING))\n recursive_assert(d.get_literal_type(typing.Dict[str, int]), LiteralType(simple=SimpleType.INTEGER))\n recursive_assert(d.get_literal_type(typing.Dict[str, datetime.datetime]), LiteralType(simple=SimpleType.DATETIME))\n recursive_assert(d.get_literal_type(typing.Dict[str, datetime.timedelta]), LiteralType(simple=SimpleType.DURATION))\n recursive_assert(d.get_literal_type(typing.Dict[str, dict]), LiteralType(simple=SimpleType.STRUCT))\n recursive_assert(\n d.get_literal_type(typing.Dict[str, typing.Dict[str, str]]),\n LiteralType(simple=SimpleType.STRING),\n expected_depth=2,\n )\n recursive_assert(\n d.get_literal_type(typing.Dict[str, typing.Dict[int, str]]),\n LiteralType(simple=SimpleType.STRUCT),\n expected_depth=2,\n )\n recursive_assert(\n d.get_literal_type(typing.Dict[str, typing.Dict[str, typing.Dict[str, str]]]),\n LiteralType(simple=SimpleType.STRING),\n expected_depth=3,\n )\n recursive_assert(\n d.get_literal_type(typing.Dict[str, typing.Dict[str, typing.Dict[str, dict]]]),\n LiteralType(simple=SimpleType.STRUCT),\n expected_depth=3,\n )\n recursive_assert(\n d.get_literal_type(typing.Dict[str, typing.Dict[str, typing.Dict[int, dict]]]),\n LiteralType(simple=SimpleType.STRUCT),\n expected_depth=2,\n )\n\n ctx = FlyteContext.current_context()\n\n lit = d.to_literal(ctx, {}, typing.Dict, LiteralType(SimpleType.STRUCT))\n pv = d.to_python_value(ctx, lit, typing.Dict)\n assert pv == {}\n\n lit_empty = Literal(map=LiteralMap(literals={}))\n pv_empty = d.to_python_value(ctx, lit_empty, typing.Dict[str, str])\n assert pv_empty == {}\n\n # Literal to python\n with pytest.raises(TypeError):\n d.to_python_value(ctx, Literal(scalar=Scalar(primitive=Primitive(integer=10))), dict)\n with pytest.raises(TypeError):\n d.to_python_value(ctx, Literal(), dict)\n with pytest.raises(TypeError):\n d.to_python_value(ctx, Literal(map=LiteralMap(literals={\"x\": None})), dict)\n with pytest.raises(TypeError):\n d.to_python_value(ctx, Literal(map=LiteralMap(literals={\"x\": None})), typing.Dict[int, str])\n\n d.to_python_value(\n ctx,\n Literal(map=LiteralMap(literals={\"x\": Literal(scalar=Scalar(primitive=Primitive(integer=1)))})),\n typing.Dict[str, int],\n )\n\n\ndef test_convert_json_schema_to_python_class():\n @dataclass_json\n @dataclass\n class Foo(object):\n x: int\n y: str\n\n schema = JSONSchema().dump(typing.cast(DataClassJsonMixin, Foo).schema())\n foo_class = convert_json_schema_to_python_class(schema[\"definitions\"], \"FooSchema\")\n foo = foo_class(x=1, y=\"hello\")\n foo.x = 2\n assert foo.x == 2\n assert foo.y == \"hello\"\n with pytest.raises(AttributeError):\n _ = foo.c\n\n\ndef test_list_transformer():\n l0 = Literal(scalar=Scalar(primitive=Primitive(integer=3)))\n l1 = Literal(scalar=Scalar(primitive=Primitive(integer=4)))\n lc = LiteralCollection(literals=[l0, l1])\n lit = Literal(collection=lc)\n\n ctx = FlyteContext.current_context()\n xx = TypeEngine.to_python_value(ctx, lit, typing.List[int])\n assert xx == [3, 4]\n\n\ndef test_protos():\n ctx = FlyteContext.current_context()\n\n pb = errors_pb2.ContainerError(code=\"code\", message=\"message\")\n lt = TypeEngine.to_literal_type(errors_pb2.ContainerError)\n assert lt.simple == SimpleType.STRUCT\n assert lt.metadata[\"pb_type\"] == \"flyteidl.core.errors_pb2.ContainerError\"\n\n lit = TypeEngine.to_literal(ctx, pb, errors_pb2.ContainerError, lt)\n new_python_val = TypeEngine.to_python_value(ctx, lit, errors_pb2.ContainerError)\n assert new_python_val == pb\n\n # Test error\n l0 = Literal(scalar=Scalar(primitive=Primitive(integer=4)))\n with pytest.raises(AssertionError):\n TypeEngine.to_python_value(ctx, l0, errors_pb2.ContainerError)\n\n default_proto = errors_pb2.ContainerError()\n lit = TypeEngine.to_literal(ctx, default_proto, errors_pb2.ContainerError, lt)\n assert lit.scalar\n assert lit.scalar.generic is not None\n new_python_val = TypeEngine.to_python_value(ctx, lit, errors_pb2.ContainerError)\n assert new_python_val == default_proto\n\n\ndef test_guessing_basic():\n b = model_types.LiteralType(simple=model_types.SimpleType.BOOLEAN)\n pt = TypeEngine.guess_python_type(b)\n assert pt is bool\n\n lt = model_types.LiteralType(simple=model_types.SimpleType.INTEGER)\n pt = TypeEngine.guess_python_type(lt)\n assert pt is int\n\n lt = model_types.LiteralType(simple=model_types.SimpleType.STRING)\n pt = TypeEngine.guess_python_type(lt)\n assert pt is str\n\n lt = model_types.LiteralType(simple=model_types.SimpleType.DURATION)\n pt = TypeEngine.guess_python_type(lt)\n assert pt is timedelta\n\n lt = model_types.LiteralType(simple=model_types.SimpleType.DATETIME)\n pt = TypeEngine.guess_python_type(lt)\n assert pt is datetime.datetime\n\n lt = model_types.LiteralType(simple=model_types.SimpleType.FLOAT)\n pt = TypeEngine.guess_python_type(lt)\n assert pt is float\n\n lt = model_types.LiteralType(simple=model_types.SimpleType.NONE)\n pt = TypeEngine.guess_python_type(lt)\n assert pt is None\n\n lt = model_types.LiteralType(\n blob=BlobType(\n format=FlytePickleTransformer.PYTHON_PICKLE_FORMAT, dimensionality=BlobType.BlobDimensionality.SINGLE\n )\n )\n pt = TypeEngine.guess_python_type(lt)\n assert pt is FlytePickle\n\n\ndef test_guessing_containers():\n b = model_types.LiteralType(simple=model_types.SimpleType.BOOLEAN)\n lt = model_types.LiteralType(collection_type=b)\n pt = TypeEngine.guess_python_type(lt)\n assert pt == typing.List[bool]\n\n dur = model_types.LiteralType(simple=model_types.SimpleType.DURATION)\n lt = model_types.LiteralType(map_value_type=dur)\n pt = TypeEngine.guess_python_type(lt)\n assert pt == typing.Dict[str, timedelta]\n\n\ndef test_zero_floats():\n ctx = FlyteContext.current_context()\n\n l0 = Literal(scalar=Scalar(primitive=Primitive(integer=0)))\n l1 = Literal(scalar=Scalar(primitive=Primitive(float_value=0.0)))\n\n assert TypeEngine.to_python_value(ctx, l0, float) == 0\n assert TypeEngine.to_python_value(ctx, l1, float) == 0\n\n\n@dataclass_json\n@dataclass\nclass InnerStruct(object):\n a: int\n b: typing.Optional[str]\n c: typing.List[int]\n\n\n@dataclass_json\n@dataclass\nclass TestStruct(object):\n s: InnerStruct\n m: typing.Dict[str, str]\n\n\n@dataclass_json\n@dataclass\nclass TestStructB(object):\n s: InnerStruct\n m: typing.Dict[int, str]\n n: typing.List[typing.List[int]] = None\n o: typing.Dict[int, typing.Dict[int, int]] = None\n\n\n@dataclass_json\n@dataclass\nclass TestStructC(object):\n s: InnerStruct\n m: typing.Dict[str, int]\n\n\n@dataclass_json\n@dataclass\nclass TestStructD(object):\n s: InnerStruct\n m: typing.Dict[str, typing.List[int]]\n\n\nclass UnsupportedSchemaType:\n def __init__(self):\n self._a = \"Hello\"\n\n\n@dataclass_json\n@dataclass\nclass UnsupportedNestedStruct(object):\n a: int\n s: UnsupportedSchemaType\n\n\ndef test_dataclass_transformer():\n schema = {\n \"$ref\": \"#/definitions/TeststructSchema\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"definitions\": {\n \"InnerstructSchema\": {\n \"additionalProperties\": False,\n \"properties\": {\n \"a\": {\"title\": \"a\", \"type\": \"integer\"},\n \"b\": {\"default\": None, \"title\": \"b\", \"type\": [\"string\", \"null\"]},\n \"c\": {\n \"items\": {\"title\": \"c\", \"type\": \"integer\"},\n \"title\": \"c\",\n \"type\": \"array\",\n },\n },\n \"type\": \"object\",\n },\n \"TeststructSchema\": {\n \"additionalProperties\": False,\n \"properties\": {\n \"m\": {\"additionalProperties\": {\"title\": \"m\", \"type\": \"string\"}, \"title\": \"m\", \"type\": \"object\"},\n \"s\": {\"$ref\": \"#/definitions/InnerstructSchema\", \"field_many\": False, \"type\": \"object\"},\n },\n \"type\": \"object\",\n },\n },\n }\n tf = DataclassTransformer()\n t = tf.get_literal_type(TestStruct)\n assert t is not None\n assert t.simple is not None\n assert t.simple == SimpleType.STRUCT\n assert t.metadata is not None\n assert t.metadata == schema\n\n t = TypeEngine.to_literal_type(TestStruct)\n assert t is not None\n assert t.simple is not None\n assert t.simple == SimpleType.STRUCT\n assert t.metadata is not None\n assert t.metadata == schema\n\n t = tf.get_literal_type(UnsupportedNestedStruct)\n assert t is not None\n assert t.simple is not None\n assert t.simple == SimpleType.STRUCT\n assert t.metadata is None\n\n\ndef test_dataclass_int_preserving():\n ctx = FlyteContext.current_context()\n\n o = InnerStruct(a=5, b=None, c=[1, 2, 3])\n tf = DataclassTransformer()\n lv = tf.to_literal(ctx, o, InnerStruct, tf.get_literal_type(InnerStruct))\n ot = tf.to_python_value(ctx, lv=lv, expected_python_type=InnerStruct)\n assert ot == o\n\n o = TestStructB(\n s=InnerStruct(a=5, b=None, c=[1, 2, 3]), m={5: \"b\"}, n=[[1, 2, 3], [4, 5, 6]], o={1: {2: 3}, 4: {5: 6}}\n )\n lv = tf.to_literal(ctx, o, TestStructB, tf.get_literal_type(TestStructB))\n ot = tf.to_python_value(ctx, lv=lv, expected_python_type=TestStructB)\n assert ot == o\n\n o = TestStructC(s=InnerStruct(a=5, b=None, c=[1, 2, 3]), m={\"a\": 5})\n lv = tf.to_literal(ctx, o, TestStructC, tf.get_literal_type(TestStructC))\n ot = tf.to_python_value(ctx, lv=lv, expected_python_type=TestStructC)\n assert ot == o\n\n o = TestStructD(s=InnerStruct(a=5, b=None, c=[1, 2, 3]), m={\"a\": [5]})\n lv = tf.to_literal(ctx, o, TestStructD, tf.get_literal_type(TestStructD))\n ot = tf.to_python_value(ctx, lv=lv, expected_python_type=TestStructD)\n assert ot == o\n\n\ndef test_flyte_file_in_dataclass():\n @dataclass_json\n @dataclass\n class TestInnerFileStruct(object):\n a: JPEGImageFile\n b: typing.List[FlyteFile]\n c: typing.Dict[str, FlyteFile]\n\n @dataclass_json\n @dataclass\n class TestFileStruct(object):\n a: FlyteFile\n b: TestInnerFileStruct\n\n f = FlyteFile(\"s3://tmp/file\")\n o = TestFileStruct(a=f, b=TestInnerFileStruct(a=JPEGImageFile(\"s3://tmp/file.jpeg\"), b=[f], c={\"hello\": f}))\n\n ctx = FlyteContext.current_context()\n tf = DataclassTransformer()\n lt = tf.get_literal_type(TestFileStruct)\n lv = tf.to_literal(ctx, o, TestFileStruct, lt)\n ot = tf.to_python_value(ctx, lv=lv, expected_python_type=TestFileStruct)\n assert ot.a._downloader is not noop\n assert ot.b.a._downloader is not noop\n assert ot.b.b[0]._downloader is not noop\n assert ot.b.c[\"hello\"]._downloader is not noop\n\n assert o.a.path == ot.a.remote_source\n assert o.b.a.path == ot.b.a.remote_source\n assert o.b.b[0].path == ot.b.b[0].remote_source\n assert o.b.c[\"hello\"].path == ot.b.c[\"hello\"].remote_source\n\n\ndef test_flyte_directory_in_dataclass():\n @dataclass_json\n @dataclass\n class TestInnerFileStruct(object):\n a: TensorboardLogs\n b: typing.List[FlyteDirectory]\n c: typing.Dict[str, FlyteDirectory]\n\n @dataclass_json\n @dataclass\n class TestFileStruct(object):\n a: FlyteDirectory\n b: TestInnerFileStruct\n\n tempdir = tempfile.mkdtemp(prefix=\"flyte-\")\n f = FlyteDirectory(tempdir)\n o = TestFileStruct(a=f, b=TestInnerFileStruct(a=TensorboardLogs(\"s3://tensorboard\"), b=[f], c={\"hello\": f}))\n\n ctx = FlyteContext.current_context()\n tf = DataclassTransformer()\n lt = tf.get_literal_type(TestFileStruct)\n lv = tf.to_literal(ctx, o, TestFileStruct, lt)\n ot = tf.to_python_value(ctx, lv=lv, expected_python_type=TestFileStruct)\n\n assert ot.a._downloader is not noop\n assert ot.b.a._downloader is not noop\n assert ot.b.b[0]._downloader is not noop\n assert ot.b.c[\"hello\"]._downloader is not noop\n\n assert o.a.path == ot.a.path\n assert o.b.a.path == ot.b.a.remote_source\n assert o.b.b[0].path == ot.b.b[0].path\n assert o.b.c[\"hello\"].path == ot.b.c[\"hello\"].path\n\n\n# Enums should have string values\nclass Color(Enum):\n RED = \"red\"\n GREEN = \"green\"\n BLUE = \"blue\"\n\n\n# Enums with integer values are not supported\nclass UnsupportedEnumValues(Enum):\n RED = 1\n GREEN = 2\n BLUE = 3\n\n\ndef test_enum_type():\n t = TypeEngine.to_literal_type(Color)\n assert t is not None\n assert t.enum_type is not None\n assert t.enum_type.values\n assert t.enum_type.values == [c.value for c in Color]\n\n ctx = FlyteContextManager.current_context()\n lv = TypeEngine.to_literal(ctx, Color.RED, Color, TypeEngine.to_literal_type(Color))\n assert lv\n assert lv.scalar\n assert lv.scalar.primitive.string_value == \"red\"\n\n v = TypeEngine.to_python_value(ctx, lv, Color)\n assert v\n assert v == Color.RED\n\n v = TypeEngine.to_python_value(ctx, lv, str)\n assert v\n assert v == \"red\"\n\n with pytest.raises(ValueError):\n TypeEngine.to_python_value(ctx, Literal(scalar=Scalar(primitive=Primitive(string_value=str(Color.RED)))), Color)\n\n with pytest.raises(ValueError):\n TypeEngine.to_python_value(ctx, Literal(scalar=Scalar(primitive=Primitive(string_value=\"bad\"))), Color)\n\n with pytest.raises(AssertionError):\n TypeEngine.to_literal_type(UnsupportedEnumValues)\n\n\ndef test_pickle_type():\n class Foo(object):\n def __init__(self, number: int):\n self.number = number\n\n lt = TypeEngine.to_literal_type(FlytePickle)\n assert lt.blob.format == FlytePickleTransformer.PYTHON_PICKLE_FORMAT\n assert lt.blob.dimensionality == BlobType.BlobDimensionality.SINGLE\n\n ctx = FlyteContextManager.current_context()\n lv = TypeEngine.to_literal(ctx, Foo(1), FlytePickle, lt)\n assert \"/tmp/flyte/\" in lv.scalar.blob.uri\n\n transformer = FlytePickleTransformer()\n gt = transformer.guess_python_type(lt)\n pv = transformer.to_python_value(ctx, lv, expected_python_type=gt)\n assert Foo(1).number == pv.number\n\n\ndef test_enum_in_dataclass():\n @dataclass_json\n @dataclass\n class Datum(object):\n x: int\n y: Color\n\n lt = TypeEngine.to_literal_type(Datum)\n schema = Datum.schema()\n schema.fields[\"y\"].load_by = LoadDumpOptions.name\n assert lt.metadata == JSONSchema().dump(schema)\n\n transformer = DataclassTransformer()\n ctx = FlyteContext.current_context()\n datum = Datum(5, Color.RED)\n lv = transformer.to_literal(ctx, datum, Datum, lt)\n gt = transformer.guess_python_type(lt)\n pv = transformer.to_python_value(ctx, lv, expected_python_type=gt)\n assert datum.x == pv.x\n assert datum.y.value == pv.y\n\n\[email protected](\n \"python_value,python_types,expected_literal_map\",\n [\n (\n {\"a\": [1, 2, 3]},\n {\"a\": typing.List[int]},\n LiteralMap(\n literals={\n \"a\": Literal(\n collection=LiteralCollection(\n literals=[\n Literal(scalar=Scalar(primitive=Primitive(integer=1))),\n Literal(scalar=Scalar(primitive=Primitive(integer=2))),\n Literal(scalar=Scalar(primitive=Primitive(integer=3))),\n ]\n )\n )\n }\n ),\n ),\n (\n {\"p1\": {\"k1\": \"v1\", \"k2\": \"2\"}},\n {\"p1\": typing.Dict[str, str]},\n LiteralMap(\n literals={\n \"p1\": Literal(\n map=LiteralMap(\n literals={\n \"k1\": Literal(scalar=Scalar(primitive=Primitive(string_value=\"v1\"))),\n \"k2\": Literal(scalar=Scalar(primitive=Primitive(string_value=\"2\"))),\n },\n )\n )\n }\n ),\n ),\n (\n {\"p1\": TestStructD(s=InnerStruct(a=5, b=None, c=[1, 2, 3]), m={\"a\": [5]})},\n {\"p1\": TestStructD},\n LiteralMap(\n literals={\n \"p1\": Literal(\n scalar=Scalar(\n generic=_json_format.Parse(\n typing.cast(\n DataClassJsonMixin,\n TestStructD(s=InnerStruct(a=5, b=None, c=[1, 2, 3]), m={\"a\": [5]}),\n ).to_json(),\n _struct.Struct(),\n )\n )\n )\n }\n ),\n ),\n (\n {\"p1\": \"s3://tmp/file.jpeg\"},\n {\"p1\": JPEGImageFile},\n LiteralMap(\n literals={\n \"p1\": Literal(\n scalar=Scalar(\n blob=Blob(\n metadata=BlobMetadata(\n type=BlobType(format=\"jpeg\", dimensionality=BlobType.BlobDimensionality.SINGLE)\n ),\n uri=\"s3://tmp/file.jpeg\",\n )\n )\n )\n }\n ),\n ),\n ],\n)\ndef test_dict_to_literal_map(python_value, python_types, expected_literal_map):\n ctx = FlyteContext.current_context()\n\n assert TypeEngine.dict_to_literal_map(ctx, python_value, python_types) == expected_literal_map\n\n\ndef test_dict_to_literal_map_with_wrong_input_type():\n ctx = FlyteContext.current_context()\n input = {\"a\": 1}\n guessed_python_types = {\"a\": str}\n with pytest.raises(user_exceptions.FlyteTypeException):\n TypeEngine.dict_to_literal_map(ctx, input, guessed_python_types)\n\n\nTestSchema = FlyteSchema[kwtypes(some_str=str)]\n\n\n@dataclass_json\n@dataclass\nclass InnerResult:\n number: int\n schema: TestSchema\n\n\n@dataclass_json\n@dataclass\nclass Result:\n result: InnerResult\n schema: TestSchema\n\n\ndef test_schema_in_dataclass():\n schema = TestSchema()\n df = pd.DataFrame(data={\"some_str\": [\"a\", \"b\", \"c\"]})\n schema.open().write(df)\n o = Result(result=InnerResult(number=1, schema=schema), schema=schema)\n ctx = FlyteContext.current_context()\n tf = DataclassTransformer()\n lt = tf.get_literal_type(Result)\n lv = tf.to_literal(ctx, o, Result, lt)\n ot = tf.to_python_value(ctx, lv=lv, expected_python_type=Result)\n\n assert o == ot\n\n\[email protected](\n \"literal_value,python_type,expected_python_value\",\n [\n (\n Literal(\n collection=LiteralCollection(\n literals=[\n Literal(scalar=Scalar(primitive=Primitive(integer=1))),\n Literal(scalar=Scalar(primitive=Primitive(integer=2))),\n Literal(scalar=Scalar(primitive=Primitive(integer=3))),\n ]\n )\n ),\n typing.List[int],\n [1, 2, 3],\n ),\n (\n Literal(\n map=LiteralMap(\n literals={\n \"k1\": Literal(scalar=Scalar(primitive=Primitive(string_value=\"v1\"))),\n \"k2\": Literal(scalar=Scalar(primitive=Primitive(string_value=\"2\"))),\n },\n )\n ),\n typing.Dict[str, str],\n {\"k1\": \"v1\", \"k2\": \"2\"},\n ),\n ],\n)\ndef test_literals_resolver(literal_value, python_type, expected_python_value):\n lit_dict = {\"a\": literal_value}\n\n lr = LiteralsResolver(lit_dict)\n out = lr.get(\"a\", python_type)\n assert out == expected_python_value\n\n\ndef test_guess_of_dataclass():\n @dataclass_json\n @dataclass()\n class Foo(object):\n x: int\n y: str\n z: typing.Dict[str, int]\n\n def hello(self):\n ...\n\n lt = TypeEngine.to_literal_type(Foo)\n foo = Foo(1, \"hello\", {\"world\": 3})\n lv = TypeEngine.to_literal(FlyteContext.current_context(), foo, Foo, lt)\n lit_dict = {\"a\": lv}\n lr = LiteralsResolver(lit_dict)\n assert lr.get(\"a\", Foo) == foo\n assert hasattr(lr.get(\"a\", Foo), \"hello\") is True\n"
] | [
[
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
GuoxiaWang/InstanceLabelTool | [
"ece37a0dfe1467ad24d6d3472adb50b20b6abd24"
] | [
"lib/annotation.py"
] | [
"\"\"\"\nCopyright (c) 2018- Guoxia Wang\nmingzilaochongtu at gmail com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, subject to the following conditions: \n\nThe above copyright notice and this permission notice shall be included in \nall copies or substantial portions of the Software.\n\nThe Software is provided \"as is\", without warranty of any kind.\n\"\"\"\n\nfrom collections import namedtuple\nfrom abc import ABCMeta, abstractmethod\nimport json\nimport datetime\nimport os\nimport numpy as np\n\n\n# A point in a polygon\nPoint = namedtuple('Point', ['x', 'y'])\n\ndef enum(*args):\n enums = dict(zip(args, range(len(args))))\n return type('Enum', (), enums)\n\n# Type of an object\nAnnObjectType = enum('INSTANCE', 'OCCLUSION_BOUNDARY')\n\n# Abstract base class for annotation objects\nclass AnnObject:\n __metaclass__ = ABCMeta\n\n def __init__(self, objType):\n self.objectType = objType\n \n # If deleted or not\n self.deleted = 0\n # If verified or not\n self.verified = 0\n # The date string\n self.date = \"\"\n # The username\n self.user = \"\"\n # Draw the object\n # Not read from or written to JSON\n # Set to False if deleted object\n # Might be set to False by the application for other reasons\n self.draw = True\n\n @abstractmethod\n def __str__(self): pass\n\n @abstractmethod\n def fromJsonText(self, jsonText, objId=-1): pass\n\n @abstractmethod\n def toJsonText(self): pass\n\n def updateDate( self ):\n self.date = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n # Mark the object as deleted\n def delete(self):\n self.deleted = 1\n self.draw = False\n\n# Class that contains the information of a single annotated object as polygon\nclass AnnInstance(AnnObject):\n # Constructor\n def __init__(self):\n AnnObject.__init__(self, AnnObjectType.INSTANCE)\n # the polygon as list of points\n self.polygon = []\n # the object ID\n self.id = -1\n # the label\n self.label = \"\"\n # temporary color for draw label\n self.color = None\n\n def __str__(self):\n polyText = \"\"\n if self.polygon:\n # TODO\n pass\n else:\n polyText = \"none\"\n text = \"Object: {} - {}\".format( self.label , polyText )\n return text\n\n def fromJsonText(self, jsonText, objId):\n self.id = objId\n self.label = str(jsonText['label'])\n self.polygon = []\n for polygon in jsonText['polygon']:\n polygon = np.array(polygon).reshape((int(len(polygon)/2), 2))\n newPoly = []\n for i in range(polygon.shape[0]):\n newPoly.append(Point(polygon[i][0], polygon[i][1]))\n self.polygon.append(newPoly)\n if ('deleted' in jsonText.keys()):\n self.deleted = jsonText['deleted']\n else:\n self.deleted = 0\n if ('verified' in jsonText.keys()):\n self.verified = jsonText['verified']\n else:\n self.verified = 1\n if ('user' in jsonText.keys()):\n self.user = jsonText['user']\n else:\n self.user = ''\n if ('date' in jsonText.keys()):\n self.date = jsonText['date']\n else:\n self.date = ''\n if (self.deleted == 1):\n self.draw = False\n else:\n self.draw = True\n\n def toJsonText(self):\n objDict = {}\n objDict['label'] = self.label\n objDict['id'] = self.id\n objDict['deleted'] = self.deleted\n objDict['verified'] = self.verified\n objDict['user'] = self.user\n objDict['date'] = self.date\n objDict['polygon'] = []\n for poly in self.polygon:\n newPoly = []\n for pt in poly:\n newPoly.append(pt.x)\n newPoly.append(pt.y)\n objDict['polygon'].append(newPoly)\n\n return objDict\n\n# Class that contains the information of a single annotated object as polygon\nclass AnnBoundary(AnnObject):\n # Constructor\n def __init__(self):\n AnnObject.__init__(self, AnnObjectType.OCCLUSION_BOUNDARY)\n # the polygon as list of points\n self.polygon = []\n\n def __str__(self):\n polyText = \"\"\n if self.polygon:\n # TODO\n pass\n else:\n polyText = \"none\"\n text = \"Boundary: {}\".format(polyText )\n return text\n\n def fromJsonText(self, jsonText, objId = -1):\n self.polygon = []\n for polygon in jsonText['polygon']:\n polygon = np.array(polygon).reshape((int(len(polygon)/2), 2))\n newPoly = []\n for i in range(polygon.shape[0]):\n newPoly.append(Point(polygon[i][0], polygon[i][1]))\n self.polygon.append(newPoly)\n if ('deleted' in jsonText.keys()):\n self.deleted = jsonText['deleted']\n else:\n self.deleted = 0\n if ('verified' in jsonText.keys()):\n self.verified = jsonText['verified']\n else:\n self.verified = 1\n if ('user' in jsonText.keys()):\n self.user = jsonText['user']\n else:\n self.user = ''\n if ('date' in jsonText.keys()):\n self.date = jsonText['date']\n else:\n self.date = ''\n if (self.deleted == 1):\n self.draw = False\n else:\n self.draw = True\n\n def toJsonText(self):\n objDict = {}\n objDict['deleted'] = self.deleted\n objDict['verified'] = self.verified\n objDict['user'] = self.user\n objDict['date'] = self.date\n objDict['polygon'] = []\n for poly in self.polygon:\n newPoly = []\n for pt in poly:\n newPoly.append(pt.x)\n newPoly.append(pt.y)\n objDict['polygon'].append(newPoly)\n\n return objDict\n\n# The annotation of a whole image (doesn't support mixed annotations)\nclass Annotation:\n # Constructor\n def __init__(self, objType=AnnObjectType.INSTANCE):\n # the width of that image and thus of the label image\n self.imgWidth = 0\n # the height of that image and thus of the label image\n self.imgHeight = 0\n # the list of objects\n self.objects = []\n # the boundaries\n self.boundaries = None\n assert objType in AnnObjectType.__dict__.values()\n self.objectType = objType\n\n def fromJsonText(self, jsonText):\n jsonDict = json.loads(jsonText)\n self.imgWidth = int(jsonDict['imgWidth'])\n self.imgHeight = int(jsonDict['imgHeight'])\n self.objects = []\n for objId, objIn in enumerate(jsonDict['objects']):\n if (self.objectType == AnnObjectType.INSTANCE):\n obj = AnnInstance()\n obj.fromJsonText(objIn, objId)\n self.objects.append(obj)\n self.boundaries = None\n if ('boundaries' in jsonDict.keys()):\n self.boundaries = AnnBoundary()\n self.boundaries.fromJsonText(jsonDict['boundaries'])\n\n def toJsonText(self):\n jsonDict = {}\n jsonDict['imgWidth'] = self.imgWidth\n jsonDict['imgHeight'] = self.imgHeight\n jsonDict['objects'] = []\n for obj in self.objects:\n objDict = obj.toJsonText()\n jsonDict['objects'].append(objDict)\n if (self.boundaries):\n jsonDict['boundaries'] = self.boundaries.toJsonText()\n \n jsonText = json.dumps(jsonDict, default=lambda o: o.__dict__, sort_keys=True, indent=4)\n return jsonText\n\n # Read a json formatted polygon file and return the annotation\n def fromJsonFile(self, jsonFile):\n if not os.path.isfile(jsonFile):\n print('Given json file not found: {}'.format(jsonFile))\n return\n with open(jsonFile, 'r') as f:\n jsonText = f.read()\n self.fromJsonText(jsonText)\n\n def toJsonFile(self, jsonFile):\n with open(jsonFile, 'w') as f:\n f.write(self.toJsonText())\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
diegowendel/TSAP | [
"b7f00dabd924b824ffb16fb612306f84f6a8e4ca"
] | [
"src/analyzer/main.py"
] | [
"from random import random, shuffle\n\nfrom src.analyzer.classifier import Classifier\nfrom src.analyzer.preprocessor import PreProcessor\nfrom src.analyzer.sentilex import Sentilex\nfrom src.database.database_mongo import DatabaseMongo\nfrom src.utils.logger import Logger\nfrom src.utils.utils import Tweet\nfrom src.twitter.streamer import TweetStreamer\nfrom src.twitter.twitter_client import TwitterClient\n\nimport pandas as pd\n\nclassificador = Classifier()\nmongo = DatabaseMongo()\npreprocessor = PreProcessor()\nsentilex = Sentilex()\n\n'''\n******************************************************************************\n********************************** STREAMER **********************************\n******************************************************************************\n'''\ndef stream():\n # Criando o objeto TwitterClient que embala a api\n api = TwitterClient()\n # Criando o streamer\n streamer = TweetStreamer()\n streamer.stream(api.get_auth(), api.get_queries())\n\n'''\n******************************************************************************\n**************************** CLASSIFICADOR MANUAL ****************************\n******************************************************************************\n'''\ndef classificar_manualmente():\n inicio = 1\n fim = 11\n j = 1\n for i in range(inicio, fim):\n tweets = mongo.find_paginated(100, i)\n\n for tweet in tweets:\n Logger.ok('\\n\\n----- Classifique: ' + str(j) + ' -----')\n j = j + 1\n # Verifica se é um tweet com texto estendido\n if 'extended_tweet' in tweet:\n print(tweet['extended_tweet']['full_text'])\n classificacao = input(\"Classificação: \")\n tweet['classificacao'] = classificacao\n else:\n print(tweet['text'])\n classificacao = input(\"Classificação: \")\n tweet['classificacao'] = classificacao\n mongo.persist_classified(tweet)\n\ndef migrar():\n inicio = 1\n fim = 6\n j = 1\n for i in range(inicio, fim):\n tweets = mongo.find_paginated_csv(100, i)\n\n for tweet in tweets:\n j = j + 1\n print(j)\n classification = tweet['classificacao']\n if classification == 'N':\n tweet['classificacao'] = 'Negativo'\n elif classification == 'P':\n tweet['classificacao'] = 'Positivo'\n else:\n tweet['classificacao'] = 'Neutro'\n mongo.persist_classified(tweet)\n\ndef salvar_csv():\n dataset = pd.read_csv('tweets_mg.csv')\n for index, row in dataset.iterrows():\n tweet = {}\n tweet['text'] = row['Text']\n tweet['preprocessado'] = preprocessor.process(row['Text'])\n tweet['classificacao'] = row['Classificacao']\n mongo.persist_classified(tweet)\n\n'''\n******************************************************************************\n*************************** CLASSIFICAÇÃO SENTILEX ***************************\n******************************************************************************\n\n Classificação de 3000 tweets com base no dicionário SentiLex:\n \n - 1000 positivos\n - 1000 negativos\n - 1000 neutros\n'''\ndef classificar_sentilex():\n dicionario = sentilex.get_sentilex_dictionary()\n inicio = 1\n fim = 201\n j = 1\n positivo = 0\n negativo = 0\n neutro = 0\n for i in range(inicio, fim):\n tweets = mongo.find_paginated(100, i)\n\n for tweet in tweets:\n print(j)\n j = j + 1\n # Verifica se é um tweet com texto estendido\n if 'extended_tweet' in tweet:\n tweet['preprocessado'] = preprocessor.process(tweet['extended_tweet']['full_text'])\n else:\n tweet['preprocessado'] = preprocessor.process(tweet['text'])\n tweet['classificacao'] = sentilex.get_score_phrase(frase=tweet['preprocessado'], dicionario_palavra_polaridade=dicionario)\n if tweet['classificacao'] == 'Positivo':\n if positivo < 1000:\n positivo = positivo + 1\n mongo.persist_classified_sentilex(tweet)\n elif tweet['classificacao'] == 'Negativo':\n if negativo < 1000:\n negativo = negativo + 1\n mongo.persist_classified_sentilex(tweet)\n else:\n if neutro < 1000:\n neutro = neutro + 1\n mongo.persist_classified_sentilex(tweet)\n\ndef classificar_manualmente_1000():\n j = 1\n positivo = 0\n negativo = 0\n neutro = 0\n tweets = mongo.find_all_classificados()\n\n tweets_shuffle = []\n for tweet in tweets:\n tweets_shuffle.append(tweet)\n\n shuffle(tweets_shuffle, random)\n\n for tweet in tweets_shuffle:\n print(j)\n j = j + 1\n if tweet['classificacao'] == 'Positivo':\n if positivo < 1000:\n positivo = positivo + 1\n mongo.persist_classified_manualmente(tweet)\n elif tweet['classificacao'] == 'Negativo':\n if negativo < 1000:\n negativo = negativo + 1\n mongo.persist_classified_manualmente(tweet)\n else:\n if neutro < 1000:\n neutro = neutro + 1\n mongo.persist_classified_manualmente(tweet)\n\n'''\n******************************************************************************\n************************* PRÉ-PROCESSAMENTO DE TWEETS ************************\n******************************************************************************\n'''\ndef preprocessar():\n inicio = 1\n fim = 101\n j = 1\n for i in range(inicio, fim):\n tweets = mongo.find_paginated_classified(100, i)\n\n for tweet in tweets:\n print(j)\n j = j + 1\n # Verifica se é um tweet com texto estendido\n if 'extended_tweet' in tweet:\n tweet['preprocessado'] = preprocessor.process(tweet['extended_tweet']['full_text'])\n else:\n tweet['preprocessado'] = preprocessor.process(tweet['text'])\n mongo.persist_classified(tweet)\n\n'''\n******************************************************************************\n*************************** ANÁLISE DE SENTIMENTOS ***************************\n******************************************************************************\n'''\ndef treinar_classificador_MultinomialNB(mostrarAcuracia):\n dataset = mongo.find_all_classificados_manualmente()\n tweets = Tweet.get_tweets_processed_texts_from_dataset(dataset)\n # RESET CURSOR\n dataset = mongo.find_all_classificados_manualmente()\n classes = Tweet.get_tweets_classifications(dataset)\n # Treino do classificador\n classificador.treinar_multinomialNB(tweets=tweets, classificacoes=classes, mostrarLogs=mostrarAcuracia)\n\ndef treinar_classificador_random_forest(mostrarAcuracia):\n dataset = mongo.find_all_classificados()\n tweets = Tweet.get_tweets_processed_texts_from_dataset(dataset)\n # RESET CURSOR\n dataset = mongo.find_all_classificados()\n classes = Tweet.get_tweets_classifications_as_number(dataset)\n # Treino do classificador\n # classificador.treinar_random_forest(tweets=tweets, classificacoes=classes, mostrarLogs=mostrarAcuracia)\n classificador.preparar_random_forest(tweets=tweets, classificacoes=classes)\n\ndef treinar_classificador_svc(mostrarAcuracia):\n dataset = mongo.find_all_classificados()\n tweets = Tweet.get_tweets_processed_texts_from_dataset(dataset)\n # RESET CURSOR\n dataset = mongo.find_all_classificados()\n classes = Tweet.get_tweets_classifications_as_number(dataset)\n # Treino do classificador\n #classificador.treinar_SVC(tweets=tweets, classificacoes=classes, mostrarLogs=mostrarAcuracia)\n classificador.preparar_svc(tweets=tweets, classificacoes=classes)\n\ndef analisar_sentimentos():\n treinar_classificador_svc(mostrarAcuracia=True)\n # treinar_classificador_random_forest(mostrarAcuracia=True)\n\n inicio = 1\n fim = 300000\n j = 1\n for i in range(inicio, fim):\n print(j)\n j = j + 1\n tweets = mongo.find_paginated(100, i)\n tweets_texts = Tweet.get_tweets_texts_from_dataset(tweets)\n resultados = classificador.predict(tweets_texts)\n\n # RESET CURSOR\n tweets = mongo.find_paginated(100, i)\n for index, tweet in enumerate(tweets):\n if resultados[index] == 1:\n tweet['classificacao'] = 'Positivo'\n elif resultados[index] == -1:\n tweet['classificacao'] = 'Negativo'\n else:\n tweet['classificacao'] = 'Neutro'\n mongo.update(tweet)\n\n'''\n******************************************************************************\n************************************ MAIN ************************************\n******************************************************************************\n'''\ndef main():\n # stream() # Download de tweets\n # classificar_manualmente() # Classificação manual de tweets\n # salvar_csv()\n # migrar()\n\n # classificar_sentilex() # Classificação de tweets com SentiLex\n # classificar_manualmente_1000()\n # preprocessar() # Pré-processa os tweets\n analisar_sentimentos() # Analisa os sentimentos dos tweets\n\n # treinar_classificador_MultinomialNB(mostrarAcuracia=True)\n # treinar_classificador_random_forest(mostrarAcuracia=True)\n # treinar_classificador_svc(mostrarAcuracia=True)\n\n #grid_search()\n\nif __name__ == \"__main__\":\n # Calling main function\n main()\n"
] | [
[
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
Hamzeluie/tensortrade | [
"e81c94c7048d4a57e2a2d5c76f5d6005f96406fc"
] | [
"tensortrade/data/cdd.py"
] | [
"\"\"\"Contains methods and classes to collect data from\nhttps://www.cryptodatadownload.com.\n\"\"\"\n\nimport ssl\n\nimport pandas as pd\n\n\nssl._create_default_https_context = ssl._create_unverified_context\n\n\nclass CryptoDataDownload:\n \"\"\"Provides methods for retrieving data on different cryptocurrencies from\n https://www.cryptodatadownload.com/cdd/.\n\n Attributes\n ----------\n url : str\n The url for collecting data from CryptoDataDownload.\n\n Methods\n -------\n fetch(exchange_name,base_symbol,quote_symbol,timeframe,include_all_volumes=False)\n Fetches data for different exchanges and cryptocurrency pairs.\n\n \"\"\"\n\n def __init__(self) -> None:\n self.url = \"https://www.cryptodatadownload.com/cdd/\"\n\n def fetch_default(self,\n exchange_name: str,\n base_symbol: str,\n quote_symbol: str,\n timeframe: str,\n include_all_volumes: bool = False) -> pd.DataFrame:\n \"\"\"Fetches data from all exchanges that match the evaluation structure.\n\n Parameters\n ----------\n exchange_name : str\n The name of the exchange.\n base_symbol : str\n The base symbol fo the cryptocurrency pair.\n quote_symbol : str\n The quote symbol fo the cryptocurrency pair.\n timeframe : {\"d\", \"h\", \"m\"}\n The timeframe to collect data from.\n include_all_volumes : bool, optional\n Whether or not to include both base and quote volume.\n\n Returns\n -------\n `pd.DataFrame`\n A open, high, low, close and volume for the specified exchange and\n cryptocurrency pair.\n \"\"\"\n\n filename = \"{}_{}{}_{}.csv\".format(exchange_name, quote_symbol, base_symbol, timeframe)\n base_vc = \"Volume {}\".format(base_symbol)\n new_base_vc = \"volume_base\"\n quote_vc = \"Volume {}\".format(quote_symbol)\n new_quote_vc = \"volume_quote\"\n\n df = pd.read_csv(self.url + filename, skiprows=1)\n df = df[::-1]\n df = df.drop([\"symbol\"], axis=1)\n df = df.rename({base_vc: new_base_vc, quote_vc: new_quote_vc, \"Date\": \"date\"}, axis=1)\n\n df[\"unix\"] = df[\"unix\"].astype(int)\n df[\"unix\"] = df[\"unix\"].apply(\n lambda x: int(x / 1000) if len(str(x)) == 13 else x\n )\n df[\"date\"] = pd.to_datetime(df[\"unix\"], unit=\"s\")\n\n df = df.set_index(\"date\")\n df.columns = [name.lower() for name in df.columns]\n df = df.reset_index()\n if not include_all_volumes:\n df = df.drop([new_quote_vc], axis=1)\n df = df.rename({new_base_vc: \"volume\"}, axis=1)\n return df\n return df\n\n def fetch_gemini(self,\n base_symbol: str,\n quote_symbol: str,\n timeframe: str) -> pd.DataFrame:\n \"\"\"\n Fetches data from the gemini exchange.\n\n Parameters\n ----------\n base_symbol : str\n The base symbol fo the cryptocurrency pair.\n quote_symbol : str\n The quote symbol fo the cryptocurrency pair.\n timeframe : {\"d\", \"h\", \"m\"}\n The timeframe to collect data from.\n\n Returns\n -------\n `pd.DataFrame`\n A open, high, low, close and volume for the specified\n cryptocurrency pair.\n \"\"\"\n if timeframe.endswith(\"h\"):\n timeframe = timeframe[:-1] + \"hr\"\n filename = \"{}_{}{}_{}.csv\".format(\"gemini\", quote_symbol, base_symbol, timeframe)\n df = pd.read_csv(self.url + filename, skiprows=1)\n df = df[::-1]\n df = df.drop([\"Symbol\", \"Unix Timestamp\"], axis=1)\n df.columns = [name.lower() for name in df.columns]\n df = df.set_index(\"date\")\n df = df.reset_index()\n return df\n\n def fetch(self,\n exchange_name: str,\n base_symbol: str,\n quote_symbol: str,\n timeframe: str,\n include_all_volumes: bool = False) -> pd.DataFrame:\n \"\"\"Fetches data for different exchanges and cryptocurrency pairs.\n\n Parameters\n ----------\n exchange_name : str\n The name of the exchange.\n base_symbol : str\n The base symbol fo the cryptocurrency pair.\n quote_symbol : str\n The quote symbol fo the cryptocurrency pair.\n timeframe : {\"d\", \"h\", \"m\"}\n The timeframe to collect data from.\n include_all_volumes : bool, optional\n Whether or not to include both base and quote volume.\n\n Returns\n -------\n `pd.DataFrame`\n A open, high, low, close and volume for the specified exchange and\n cryptocurrency pair.\n \"\"\"\n if exchange_name.lower() == \"gemini\":\n return self.fetch_gemini(base_symbol, quote_symbol, timeframe)\n return self.fetch_default(exchange_name,\n base_symbol,\n quote_symbol,\n timeframe,\n include_all_volumes=include_all_volumes)\n"
] | [
[
"pandas.read_csv",
"pandas.to_datetime"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
sohailhabib/SecurityMetrics | [
"7de3f462e89d97592e0c28a623bd6f7112b9a3b1",
"7de3f462e89d97592e0c28a623bd6f7112b9a3b1"
] | [
"source_code/dataset/dim_red_pca_operation.py",
"source_code/adversaries/mk_attack.py"
] | [
"\"\"\"\nMIT License\n\nCopyright (c) 2021, Sohail Habib\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\nrights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the\nSoftware.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\nWARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n------------------------------------------------------------------------------------------------------------------------\n\nPrinciple Component Analysis (PCA) dimensionality reduction\n=====================\nThis class implements dimension reduction using Principle Component Analysis (PCA)\n\n\"\"\"\nfrom dataset.dataset_operation import DatasetOperation\nimport pandas as pd\nfrom sklearn.decomposition import PCA\n\n\nclass PcaDimRed(DatasetOperation):\n\n def __init__(self):\n \"\"\"\n Initializes the class object\n\n\n \"\"\"\n self.red_df = pd.DataFrame()\n return\n\n def operate(self, data, n_components=None, copy=True, whiten=False, output_path=None):\n self.red_df = data\n reduction_data = data\n pca = PCA(n_components=n_components, copy=copy, whiten=whiten)\n labels = None\n if 'labels' in self.red_df:\n labels = self.red_df['labels']\n reduction_data = self.red_df.drop(columns='labels')\n users = self.red_df['user']\n reduction_data = reduction_data.drop(columns='user')\n\n reduction_data = pca.fit_transform(reduction_data)\n self.red_df = pd.DataFrame(reduction_data)\n if labels is not None:\n self.red_df.insert(len(self.red_df.columns), \"labels\", labels)\n self.red_df.insert(0, \"user\", users)\n\n if output_path is not None:\n self.red_df.to_csv(output_path, index=False, mode='w+')\n\n return self.red_df\n",
"\"\"\"\nMIT License\n\nCopyright (c) 2021, Sohail Habib\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\nrights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the\nSoftware.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\nWARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n------------------------------------------------------------------------------------------------------------------------\n\nMasterkey attack\n=====================\nThis class implements masterkey attack from paper Using global knowledge of users' typing traits to attack\nkeystroke biometrics templates\n\n@inproceedings{serwadda2011using,\n title={Using global knowledge of users' typing traits to attack keystroke biometrics templates},\n author={Serwadda, Abdul and Phoha, Vir V and Kiremire, Ankunda},\n booktitle={Proceedings of the Thirteenth ACM Multimedia Workshop on Multimedia and Security},\n pages={51--60},\n year={2011}\n}\n\n\"\"\"\nfrom source_code.adversaries.adversarial_attacks import Attacks\nimport pandas as pd\nimport numpy as np\n\n\nclass MkAttack(Attacks):\n\n def __init__(self, data, required_attack_samples):\n \"\"\"\n\n @param required_attack_samples: Expects an integer for number of attack samples to generate\n @param data: Expects a Pandas dataframe\n \"\"\"\n self.attack_df = data\n self.attack_samples = required_attack_samples\n self.attack_df_mk = None\n\n def generate_attack(self):\n if 'user' in self.attack_df.columns:\n centroid = self.attack_df.drop('user', axis=1).mean().values.reshape(1, -1)\n # Using numpy arrays for more efficient usage\n feat_list = self.attack_df.columns.drop('user').to_list()\n else:\n centroid = self.attack_df.mean()\n # Using numpy arrays for more efficient usage\n feat_list = self.attack_df.columns.drop('user').to_list()\n\n # Generating attack set\n pos_list = np.round(np.arange(0, 5, (5 / (self.attack_samples / 2))), 3)\n neg_list = np.round(pos_list * -1, 3)\n std_list = list()\n for idx in range(len(pos_list)):\n std_list.append(pos_list[idx])\n std_list.append(neg_list[idx])\n\n self.attack_df_mk = pd.DataFrame(columns=feat_list)\n\n for row_num, std in zip(range(len(std_list)), std_list):\n self.attack_df_mk.loc[row_num, :] = \\\n centroid + (std * centroid.reshape(1, -1))\n\n return self.attack_df_mk\n"
] | [
[
"sklearn.decomposition.PCA",
"pandas.DataFrame"
],
[
"numpy.round",
"numpy.arange",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
ichaelm/MusicPrediction | [
"df495410d5f956eb7656045363479ad378ef71f6"
] | [
"src/TensionModule.py"
] | [
"# Tension Module (numpy)\n# Zicheng Gao\n\nimport numpy as np\n\nv_basis = np.r_[:12]\n\nvalToNote = ['A','Bb','B','C','C#','D','Eb','E','F','F#','G','G#']\n\n# from Robert Rowe's \"Machine Musicianship\" p 48\nclass metric:\n\tdissonance = [1, 6, 5, 4, 3, 2, 7, 2, 3, 4, 5, 6]\n\twestern = [1, 8, 6, 2.1, 2, 4.5, 5, 1.5, 4.6, 4.7, 4, 7]\n\nclass TensionModule:\n\n\tdef __init__(self, metric = metric.dissonance, kertosis = 1):\n\t\tself.metric = metric\n\t\tself.kertosis = kertosis\n\n\tdef mut_tens(self, intvs):\n\t\t# change to tensions\n\t\ttens = np.tile(intvs, (1,1))\n\t\tfor i in np.r_[:12]:\n\t\t\ttens[intvs == (12 - i) % 12] = self.metric[i]\n\t\treturn 3 ** tens\n\n\t@staticmethod\n\tdef __intervals(bases, quanta):\n\t\t# Generate intervals between bases and quanta\n\t\tdiffs = np.tile(bases, (len(quanta), 1)) + 12\n\t\tdiffs -= np.tile(quanta, (len(bases), 1)).T\n\t\tdiffs %= 12\n\t\treturn diffs\n\n\t@staticmethod\n\tdef __prepare_quanta(quanta):\n\t\t# Extract Pairs of Notes and Weights into numpy arrays.\n\t\t# Return (notes, weights). With no weights, weights returns None.\n\t\tif type(quanta) is not np.ndarray:\n\t\t\tquanta = np.array(quanta)\n\n\t\tif quanta.ndim > 1:\n\t\t\treturn (quanta[:,0].astype(int), quanta[:,1])\n\t\telse:\n\t\t\treturn (quanta.astype(int), None)\n\n\tdef selfTension(self, notes_a):\n\t\t# evaluate sum of tensions between each self-note\n\t\tquanta, weights = self.__prepare_quanta(notes_a)\n\t\tdiffs = self.__intervals(quanta, quanta)\n\t\ttens = self.mut_tens(diffs)\n\t\tnoteamt = len(quanta)\n\t\tif weights is not None:\n\t\t\ttens = (tens.T * weights).T * weights\n\t\t\tnoteamt = np.sum(weights)\n\t\treturn np.sum(tens) / ((noteamt**2 - noteamt) * 3**4)\n\n\tdef inversionIntervals(quanta):\n\t\t# return intervals of the inversions of this note group\n\t\tqlen = len(quanta)\n\t\tintervals = np.tile(np.diff(quanta[np.r_[:qlen,0]])%12,qlen+1)\n\t\treturn intervals.reshape(qlen,qlen+1)[:-1][:,:-1]\n\n\tdef inversionTensions(self, quanta):\n\t\t# return tensions of inversions based on internal intervals\n\t\tintervals = self.inversionIntervals(quanta)\n\t\tinvTensions = np.sum(self.mut_tens(intervals), 0)\n\t\treturn np.vstack((quanta, invTensions)).T\n\n\tdef basis_likelihood(self, notes):\n\t\t# return likelihood based off minimal energy for each basis note\n\t\t# probably shouldn't be used to actually determine basis\n\t\tquanta, weights = self.__prepare_quanta(notes)\n\t\tif np.all(quanta == 0):\n\t\t\treturn np.zeros(12) + 1/12\n\t\tdiffs = self.__intervals(v_basis, quanta)\n\t\ttens = self.mut_tens(diffs)\n\t\tnoteamt = len(quanta)\n\t\tif weights is not None:\n\t\t\ttens = tens * weights.T[:, np.newaxis]\n\t\t\tnoteamt = np.sum(weights)\n\t\ttensionList = np.sum(tens, 0)\n\t\treturn self.flipmax(tensionList)\n\n\tdef determineBasis(self, notes, tolerance=0, verbose=False):\n\t\t# print out as well - has internal trim\n\t\tif verbose:\n\t\t\tprint('for', notes)\n\t\tbTensions = np.vstack((v_basis, self.basis_likelihood(notes))).T\n\t\tbase = np.max(bTensions[:,1])\n\t\tbest = bTensions[bTensions[:,1] >= base * (1 - tolerance)]\n\t\tif verbose:\n\t\t\tfor pair in best:\n\t\t\t\tprint(valToNote[int(pair[0])] + ':', pair[1])\n\t\t\tprint()\n\t\treturn best\n\n\t# the recently made-up cousin of softmax\n\tdef flipmax(self, x):\n\t\treturn (1 / (x ** self.kertosis)) / np.sum(1 / (x ** self.kertosis))\n\n\n#################################################################\n# Thoughts & possible future additions\n# Maybe add some preference for lowest note in quanta as basis?\n# Sort notes and then apply a scaling factor for notes that have many notes between them?\n\nif __name__ == '__main__':\n\n\ttensmod = TensionModule()\n\n\tif 1:\n\t\t# 'byInterval' can give a canonical answer but does not return other good candidates accurately (?)\n\t\t# Is simpler better sometimes?\n\t\ttensmod.determineBasis([3, 7], verbose = True) # C major third => C / E\n\t\ttensmod.determineBasis([3, 7, 10], verbose = True) # C MAJ => C w/o interval, G with\n\t\ttensmod.determineBasis([3, 31, 34], verbose = True) # C MAJ across octaves => C\n\t\ttensmod.determineBasis([27, 31, 34], verbose = True) # C MAJ one octave up => C\n\t\ttensmod.determineBasis([3, 6, 9, 12], verbose = True) # C dim 7 = everything is bad\n\t\ttensmod.determineBasis([3, 6, 10, 13], verbose = True) # C minor minor 7 => G / Eb\n\t\ttensmod.determineBasis([3, 7, 10, 13], verbose = True) # C major minor 7 => G\n\t\ttensmod.determineBasis([3, 6, 10, 14], verbose = True) # C major major 7 => G (!)\n\n\tif 0:\n\t\tprint(\"==Tensions==\\n\")\n\n\t\t# Thirds\n\t\tprint('Major Third', selfTension([0, 4]))\n\t\t# print(selfTension([2, 6]))\n\n\t\t# Fifths\n\t\tprint('Perfc Fifth', selfTension([2, 9]), '\\n')\n\t\t# print(selfTension([2, 9, 2, 9]))\n\n\t\tprint('Augmented Triad', selfTension([0, 4, 8]))\n\t\tprint('Major Triad', selfTension([0, 4, 7]))\n\t\tprint('Minor Triad', selfTension([0, 3, 7]))\n\t\tprint('Diminished Triad', selfTension([3, 7, 9]), '\\n')\n\n\t\tprint('Fully Dimin 7', selfTension([0, 3, 6, 9])) # should be very high\n\t\tprint('Minor Minor 7', selfTension([0, 3, 7, 10])) # should be ok\n\t\tprint('Minor Major 7', selfTension([0, 3, 7, 11])) # should be high\n\t\tprint('Dominant 7', selfTension([0, 4, 7, 10])) # should be low, but the tritone between the 3 and the 7- makes this bad\n\t\tprint('Major Major 7', selfTension([0, 4, 7, 11])) # should be ok\n\n\t\tprint()\n\t\tprint('Cluster', selfTension([0, 1, 2, 3]))\n\t\tprint('Cluster', selfTension([0, 1, 2]))\n\t\t\n\tkeys = np.r_[:88]\n\tm_state = np.zeros(88)\n\tm_state[0] = 1.0\n\tm_state[12] = 1.0\n\tm_state[12 + 3] = 1.0\n\tm_state[12 + 7] = 1.0\n\tm_state[24 + 3] = 1.0\n\t# m_state[7 + 24] = 1.0\n\t# m_state[0:88] = 1.0\n\t# length = 1+1*6\n\t# m_state[0:length:6] = 1.0\n\n\tactives = keys[m_state > 0]\n\tweights = m_state[m_state > 0]\n\n\tpairs = np.vstack((actives, weights)).T\n\t# print(mut_tens(np.array(v_basis)))\n\tprint(\"Pairs\")\n\tprint(pairs)\n\t# print(selfTension(pairs))\n\t# print(determineBasis(np.array([0, 4, 7, 5]) + 3, tolerance = 1, verbose = True))\n\n\tprint(\"Basis Likelihood\")\n\tprint(tensmod.basis_likelihood(pairs))\n\t# determineBasis(pairs, verbose = True, tolerance = 1)\n\n"
] | [
[
"numpy.tile",
"numpy.all",
"numpy.max",
"numpy.diff",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ash22194/stable-baselines3 | [
"b2729e0b2df2f9026d7587c5506ea3b60e316fed"
] | [
"examples/testCartPole.py"
] | [
"\nimport torch\nfrom torch import nn\nimport os\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom ipdb import set_trace\nfrom scipy.linalg import solve_continuous_are\nfrom scipy.io import loadmat\nfrom scipy.interpolate import interpn\n\nfrom systems.cartpole import CartPole\nfrom stable_baselines3 import A2C, PPO, DDPG\nfrom stable_baselines3.common.env_checker import check_env\nfrom stable_baselines3.common.sb2_compat.rmsprop_tf_like import RMSpropTFLike\n\nsys = {'mc': 5, 'mp': 1, 'l': 0.9, 'g': 9.81, 'Q': np.diag([25, 0.02, 25, 0.02]), 'R': np.diag([0.001, 0.001]),\\\n\t 'goal': np.array([[0], [0], [np.pi], [0]]), 'u0': np.zeros((2,1)), 'T': 4, 'dt': 2.5e-3, 'gamma_': 0.997, 'X_DIMS': 4, 'U_DIMS': 2,\\\n\t 'x_limits': np.array([[-1.5, 1.5], [-3, 3], [0, 2*np.pi], [-3, 3]]), 'u_limits': np.array([[-9, 9], [-9, 9]])}\n# sys = {'mc': 5, 'mp': 1, 'l': 0.9, 'g': 9.81, 'Q': np.diag([25, 0.02, 25, 0.02]), 'R': np.diag([0.001, 0.001]),\\\n# \t 'goal': np.array([[0], [0], [np.pi], [0]]), 'u0': np.zeros((2,1)), 'T': 4, 'dt': 1e-3, 'gamma_': 0.997, 'X_DIMS': 4, 'U_DIMS': 2,\\\n# \t 'x_limits': np.array([[-1, 1], [-1, 1], [3*np.pi/4, 5*np.pi/4], [-1, 1]]), 'u_limits': np.array([[-9, 9], [-9, 9]])}\nfixed_start = False\nnormalized_actions = True\nenv = CartPole(sys, fixed_start=fixed_start, normalized_actions=normalized_actions)\ncheck_env(env)\n\n# Load DP solution to compare\n# filename = '~/Documents/MATLAB/iLQG/DP/data/cartpole/decomp0/final.mat'\n# policy_analytical = loadmat(filename)\n\nenv_dummy = CartPole(sys, fixed_start=fixed_start, normalized_actions=normalized_actions)\ncheck_env(env_dummy)\ngoal = sys['goal']\nu0 = sys['u0']\nA = np.zeros((sys['X_DIMS'], sys['X_DIMS']))\nB = np.zeros((sys['X_DIMS'], sys['U_DIMS']))\nfor xx in range(sys['X_DIMS']):\n\tperturb_p = np.zeros(goal.shape)\n\tperturb_p[xx] = 1e-4\n\tperturb_m = np.zeros(goal.shape)\n\tperturb_m[xx] = -1e-4\n\tdyn_p = env_dummy.dyn(goal + perturb_p, u0)\n\tdyn_m = env_dummy.dyn(goal + perturb_m, u0)\n\tA[:, xx:(xx+1)] = (dyn_p - dyn_m) / (2e-4)\n\nfor uu in range(sys['U_DIMS']):\n\tperturb_p = np.zeros(u0.shape)\n\tperturb_p[uu] = 1e-4\n\tperturb_m = np.zeros(u0.shape)\n\tperturb_m[uu] = -1e-4\n\tdyn_p = env_dummy.dyn(goal, u0 + perturb_p)\n\tdyn_m = env_dummy.dyn(goal, u0 + perturb_m)\n\tB[:, uu:(uu+1)] = (dyn_p - dyn_m) / (2e-4)\n\nQ = sys['Q']\nR = sys['R']\nlambda_ = (1 - sys['gamma_']) / sys['dt']\nP = solve_continuous_are(A - lambda_/2*np.eye(sys['X_DIMS']), B, Q, R)\nK = np.matmul(np.linalg.inv(R), np.matmul(B.T, P))\n\n# Test the policy\nobs = env_dummy.reset()\nstart = obs\nu_limits = sys['u_limits']\nvalue = 0\nfor i in range(int(3*sys['T']/sys['dt'])):\n\taction = np.matmul(-K, obs[:,np.newaxis] - goal)[:,0]\n\taction = np.maximum(u_limits[:,0], np.minimum(u_limits[:,1], action))\n\tif (normalized_actions):\n\t\taction = (2*action - (u_limits[:,1] + u_limits[:,0])) / (u_limits[:,1] - u_limits[:,0])\n\n\tobs, reward, done, info = env_dummy.step(action)\n\tvalue *= sys['gamma_']\n\tvalue += reward\n\tif done:\n\t\tprint('Start state :', start, ', Final state :', obs, 'Value :', value)\n\t\tobs = env_dummy.reset()\n\t\tstart = obs\n\t\tvalue = 0\n\nset_trace()\n# Compute Policy and Value function numerically\nalgorithm = 'A2C'\nif (fixed_start):\n\tsave_path = os.path.join('examples/data/cartpole_fixedstart', algorithm)\nelse:\n\tsave_path = os.path.join('examples/data/cartpole', algorithm)\nlog_path = os.path.join(save_path, 'tb_log')\nfiles = [f for f in os.listdir(save_path) if os.path.isfile(os.path.join(save_path, f))]\nsave_timestep = 0\nff_latest = ''\nfor ff in files:\n\tif 'model' not in ff:\n\t\tcontinue \n\ttt = ff.split('_')[-1]\n\ttt = int(tt.split('.')[0])\n\tif (tt > save_timestep):\n\t\tsave_timestep = tt\n\t\tff_latest = ff\n\ntotal_timesteps = 10000000\nif ((save_timestep <= total_timesteps) and (save_timestep > 0)):\n\tif (algorithm == 'A2C'):\n\t\tmodel = A2C.load(os.path.join(save_path, 'model_'+str(save_timestep)))\n\telif (algorithm == 'PPO'):\n\t\tmodel = PPO.load(os.path.join(save_path, 'model_'+str(save_timestep)))\n\telif (algorithm == 'DDPG'):\n\t\tmodel = DDPG.load(os.path.join(save_path, 'model_'+str(save_timestep)))\nelse:\n\tif (normalized_actions):\n\t\tpolicy_std = 0.1\n\telse:\n\t\tpolicy_std = 0.1 * sys['u_limits'][:,1]\n\t\t\n\tif (algorithm == 'A2C'):\n\t\tpolicy_kwargs = dict(activation_fn=nn.ReLU, net_arch=[dict(pi=[32, 32], vf=[32, 32])], log_std_init=np.log(policy_std), optimizer_class=RMSpropTFLike, optimizer_kwargs=dict(eps=1e-5))\n\t\tmodel = A2C('MlpPolicy', env, gamma=sys['gamma_'], n_steps=50, tensorboard_log=log_path, verbose=1, policy_kwargs=policy_kwargs)\n\telif (algorithm == 'PPO'):\n\t\tpolicy_kwargs = dict(activation_fn=nn.ReLU, net_arch=[dict(pi=[32, 32], vf=[32, 32])])\n\t\tmodel = PPO('MlpPolicy', env, gamma=sys['gamma_'], n_steps=2048, clip_range_vf=None, clip_range=0.5, tensorboard_log=log_path, verbose=1, policy_kwargs=policy_kwargs)\n\telif (algorithm == 'DDPG'):\n\t\tpolicy_kwargs = dict(activation_fn=nn.ReLU, net_arch=dict(pi=[16, 16], qf=[16, 16]))\n\t\tmodel = DDPG('MlpPolicy', env, gamma=sys['gamma_'], tensorboard_log=log_path, verbose=1, policy_kwargs=policy_kwargs)\n\nsave_every = total_timesteps\n# save_every = 500000\ntimesteps = save_timestep\nlog_steps = 4000\nwhile timesteps < total_timesteps:\n\tmodel.learn(total_timesteps=save_every, log_interval=round(log_steps/model.n_steps))\n\ttimesteps = timesteps + save_every\n\tmodel.save(os.path.join(save_path, 'model_' + str(timesteps)))\n\n# Test the learned policy\nobs = env.reset()\nstart = obs\nfor i in range(24000):\n\taction, _state = model.predict(obs, deterministic=True)\n\tobs, reward, done, info = env.step(action)\n\t# if (i%100==0):\n\t# \tprint('State : ', obs, ', Action : ', action)\n\t\t# set_trace()\n\tif done:\n\t\tprint('Start state :', start, ', Final state :', obs)\n\t\tobs = env.reset()\n\t\tstart = obs\n\nset_trace()\n"
] | [
[
"numpy.diag",
"numpy.log",
"numpy.minimum",
"numpy.linalg.inv",
"numpy.eye",
"numpy.matmul",
"numpy.array",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
brandongk-ubco/ensembler | [
"9d4ab1a07f686eee8b5a4e721a6acc44da3ef94d"
] | [
"tests/test_sample_dataframe.py"
] | [
"from ensembler.datasets.helpers import sample_dataset\nimport pandas as pd\nimport uuid\nimport os\n\n\nclass TestSampleDataFrame:\n def test_sample_single_class(self):\n df = pd.DataFrame([{\n \"sample\": uuid.uuid4(),\n \"background\": 0.1,\n \"1\": 0.9\n }, {\n \"sample\": uuid.uuid4(),\n \"background\": 0.1,\n \"1\": 0.9\n }])\n\n result = sample_dataset(df)\n\n assert len(result) == 2\n assert result.iloc[0][\"sample\"] == df.iloc[0][\"sample\"]\n assert result.iloc[1][\"sample\"] == df.iloc[1][\"sample\"]\n\n def test_sample_single_class_one_sample(self):\n df = pd.DataFrame([{\n \"sample\": uuid.uuid4(),\n \"background\": 1,\n \"1\": 0\n }, {\n \"sample\": uuid.uuid4(),\n \"background\": 0.1,\n \"1\": 1\n }])\n\n result = sample_dataset(df)\n\n assert len(result) == 1\n assert result.iloc[0][\"sample\"] == df.iloc[1][\"sample\"]\n\n def test_sample_single_class_many_samples(self):\n df = pd.DataFrame()\n\n for i in range(100):\n df = df.append(pd.DataFrame([{\n \"sample\": uuid.uuid4(),\n \"background\": 0.5,\n \"1\": 0.5\n }]),\n ignore_index=True)\n\n result = sample_dataset(df)\n\n assert len(result) == 100\n\n def test_large_dataset(self):\n sample_file = os.path.join(os.path.dirname(__file__), \"fixtures\",\n \"class_samples.csv\")\n df = pd.read_csv(sample_file)\n\n result = sample_dataset(df)\n\n assert len(result) == len(df)\n assert len(df[~result.index.isin(df.index)]) == 0\n"
] | [
[
"pandas.read_csv",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
fotavio16/PycharmProjects | [
"f5be49db941de69159ec543e8a6dde61f9f94d86"
] | [
"OpenCV/bookIntroCV_008_binarizacao.py"
] | [
"'''\n\n Livro-Introdução-a-Visão-Computacional-com-Python-e-OpenCV-3\n\nRepositório de imagens\nhttps://github.com/opencv/opencv/tree/master/samples/data\n'''\n\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n#import mahotas\n\nVERMELHO = (0, 0, 255)\nVERDE = (0, 255, 0)\nAZUL = (255, 0, 0)\nAMARELO = (0, 255, 255)\nBRANCO = (255,255,255)\nCIANO = (255, 255, 0)\nPRETO = (0, 0, 0)\n\nimg = cv2.imread('ponte2.jpg') # Flag 1 = Color, 0 = Gray, -1 = Unchanged\nimg = img[::2,::2] # Diminui a imagem\n\n#Binarização com limiar\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\nsuave = cv2.GaussianBlur(img, (7, 7), 0) # aplica blur\n(T, bin) = cv2.threshold(suave, 160, 255, cv2.THRESH_BINARY)\n(T, binI) = cv2.threshold(suave, 160, 255, cv2.THRESH_BINARY_INV)\n\n'''\nresultado = np.vstack([\n np.hstack([suave, bin]),\n np.hstack([binI, cv2.bitwise_and(img, img, mask = binI)])\n ])\n'''\nresultado = np.vstack([\n np.hstack([img, suave]),\n np.hstack([bin, binI])\n ])\n\ncv2.imshow(\"Binarização da imagem\", resultado)\ncv2.waitKey(0)\n\n#Threshold adaptativo\n\nbin1 = cv2.adaptiveThreshold(suave, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 21, 5)\nbin2 = cv2.adaptiveThreshold(suave, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 21, 5)\n\nresultado = np.vstack([\n np.hstack([img, suave]),\n np.hstack([bin1, bin2])\n ])\ncv2.imshow(\"Binarização adaptativa da imagem\", resultado)\ncv2.waitKey(0)\n\n#Threshold com Otsu e Riddler-Calvard\n'''\nT = mahotas.thresholding.otsu(suave)\ntemp = img.copy()\ntemp[temp > T] = 255\ntemp[temp < 255] = 0\ntemp = cv2.bitwise_not(temp)\nT = mahotas.thresholding.rc(suave)\ntemp2 = img.copy()\ntemp2[temp2 > T] = 255\ntemp2[temp2 < 255] = 0\ntemp2 = cv2.bitwise_not(temp2)\nresultado = np.vstack([\n np.hstack([img, suave]),\n np.hstack([temp, temp2])\n ])\ncv2.imshow(\"Binarização com método Otsu e Riddler-Calvard\", resultado)\ncv2.waitKey(0)\n'''\n\n"
] | [
[
"numpy.hstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zedhed/PYNQ-DL | [
"c80b50bcaebe096ac1df4b635977620e90b263dd"
] | [
"darius/lib/darius_lib.py"
] | [
"# Copyright (c) 2018, Xilinx, Inc.\r\n# All rights reserved.\r\n#\r\n# Redistribution and use in source and binary forms, with or without\r\n# modification, are permitted provided that the following conditions are met:\r\n#\r\n# 1. Redistributions of source code must retain the above copyright notice,\r\n# this list of conditions and the following disclaimer.\r\n#\r\n# 2. Redistributions in binary form must reproduce the above copyright\r\n# notice, this list of conditions and the following disclaimer in the\r\n# documentation and/or other materials provided with the distribution.\r\n#\r\n# 3. Neither the name of the copyright holder nor the names of its\r\n# contributors may be used to endorse or promote products derived from\r\n# this software without specific prior written permission.\r\n#\r\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\r\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\r\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\r\n# OR BUSINESS INTERRUPTION). HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\r\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\r\n# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\r\n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\nimport numpy as np\r\nfrom math import *\r\nfrom random import *\r\n\r\n__author__ = \"Ehsan Ghasemi; Radhika Pokanati\"\r\n__copyright__ = \"Copyright 2016, Xilinx\"\r\n__email__ = \"[email protected]\"\r\n\r\n# CNNDataflow IP Constants\r\nC_MAX_ADDR_WIDTH = 12\r\nC_MAX_ITER_WIDTH = 6\r\nC_MAX_IMG_DIMENSION_WIDTH = 10\r\nC_MAX_INPUT_WIDTH = 16\r\nC_NUM_OF_ROWS = 8\r\nC_NUM_OF_COLS = 8\r\n\r\n\r\nclass Darius(object):\r\n def __init__(self, ifm_height, ifm_width, ifm_depth, kernel_height,\r\n kernel_width, pad, stride, channels,\r\n pool_kernel_height, pool_kernel_width, pool_stride,\r\n ifm_baseaddr, weights_baseaddr, ofm_baseaddr):\r\n \"\"\"Return a new Convolution with Maxpool object\"\"\"\r\n\r\n self.ifm_height = ifm_height\r\n self.ifm_width = ifm_width\r\n self.ifm_depth = ifm_depth\r\n self.kernel_height = kernel_height\r\n self.kernel_width = kernel_width\r\n self.pad = pad\r\n self.stride = stride\r\n self.channels = channels\r\n self.pool_kernel_height = pool_kernel_height\r\n self.pool_kernel_width = pool_kernel_width\r\n self.pool_stride = pool_stride\r\n self.ifm_baseaddr = ifm_baseaddr\r\n self.weights_baseaddr = weights_baseaddr\r\n self.ofm_baseaddr = ofm_baseaddr\r\n\r\n def derive_attributes():\r\n self.ofm_height = ceil((self.ifm_height + 2 * self.pad - self.kernel_height) / self.stride + 1)\r\n self.ofm_width = ceil((self.ifm_width + 2 * self.pad - self.kernel_width) / self.stride + 1)\r\n self.ofm_depth = self.channels\r\n self.ifm_slices = ceil(self.ifm_depth / C_NUM_OF_ROWS)\r\n self.ofm_slices = ceil(self.channels / C_NUM_OF_COLS)\r\n self.ofm_fragments = 1\r\n self.ifm_mem_fragments = 1\r\n \r\n self.ifm_packet_length = self.ifm_width * self.ifm_height * self.ifm_slices\r\n self.ifm_depth_offset = self.ifm_width * self.ifm_height * self.ifm_depth\r\n self.ifm_height_offset = 0\r\n \r\n self.ofm_offset = self.ofm_height * self.ofm_width * self.ofm_depth\r\n\r\n self.weights_packet_length = self.kernel_height * self.kernel_width * self.ifm_depth\r\n self.weight_depth_offset = self.kernel_height * self.kernel_width * self.ifm_depth * \\\r\n C_NUM_OF_COLS\r\n self.weight_offset = self.kernel_height * self.kernel_width * self.ifm_depth\r\n self.weight_pkt_offset = C_NUM_OF_ROWS * self.kernel_height * self.kernel_width\r\n \r\n self.reserved = 0\r\n \r\n self.pool_input_height = self.ofm_height\r\n self.pool_input_width = self.ofm_width\r\n # divid by one so to make it float calculation\r\n try:\r\n self.pool_output_height = ceil(((self.pool_input_height - self.pool_kernel_height) / 1.0) / self.pool_stride / 1.0 + 1)\r\n self.pool_output_width = ceil(((self.pool_input_width - self.pool_kernel_width) / 1.0) / self.pool_stride / 1.0 + 1)\r\n except ZeroDivisionError:\r\n self.pool_output_height = 0\r\n self.pool_output_width = 0\r\n print(\"INFO: POOL STRIDE OF 0 DISABLES MAXPOOLING; ONLY CONVOLUTION WOULD HAPPEN!\")\r\n\r\n # pool_stride has to be a multiple of 2\r\n if (self.pool_stride != 0 \\\r\n and self.pool_output_height > 5 and self.pool_output_width > 5 \\\r\n and self.pool_output_width * self.pool_kernel_width < 1 << 9 \\\r\n and self.pool_output_width < 1 << 8):\r\n\r\n # WHEN MAXPOOL IS ENABLED, THE OUTPUT SIZE WILL BE SMALLER\r\n # THERFORE, THE OFM_PACKET_LENGTH HAS TO BE ADJUSTED ACCORDINGLY\r\n self.ofm_packet_length = self.pool_output_height * self.pool_output_width * self.ofm_slices\r\n else:\r\n self.pool_output_height = 0\r\n self.pool_output_width = 0\r\n self.pool_kernel_height = 0\r\n self.pool_kernel_width = 0\r\n self.pool_stride = 0\r\n self.ofm_packet_length = self.ofm_height * self.ofm_width * self.ofm_slices \r\n \r\n derive_attributes()\r\n\r\n def IP_cmd(self): \r\n \"\"\" Construct convolution command for CNNDataflow IP if the arguments\r\n inputed are in supported range of Convolution Overlay \"\"\"\r\n\r\n # The IFM demensions to be in range (6,32)\r\n if (self.ifm_height < 6 or self.ifm_width < 6 or self.ifm_height > 32 or self.ifm_width > 32):\r\n print(\"ERROR: THE IFM VOLUME IS EITHER SMALLER/LARGER THAN SUPPORTED\")\r\n print(\"TIP: Make sure IFM height and width are in range from 6 to 32\")\r\n return False\r\n\r\n # The IFM depth to be multiples of 8 and are in range (8,1024)\r\n if (self.ifm_depth <= 512 or self.ifm_depth >= 8):\r\n if (self.ifm_depth % 8 != 0):\r\n print(\"ERROR: THE IFM DEPTH NEEDS TO BE IN MULTIPLES OF 8 IN THE RANGE 8 TO 512\")\r\n return False\r\n else:\r\n print(\"ERROR: THE IFM DEPTH NEEDS TO BE IN MULTIPLES OF 8 IN THE RANGE 8 TO 512\")\r\n return False\r\n\r\n # The Kernel demensions to be in range (1,16)\r\n if (self.kernel_height < 1 or self.kernel_width < 1 or self.kernel_height > 16 or self.kernel_width > 16):\r\n print(\"ERROR: THE KERNEL DIMENSIONS ARE EITHER SMALLER/LARGER THAN SUPPORTED\")\r\n print(\"TIP: Make sure Kernel height and width are in range from 1 to 16\")\r\n return False\r\n\r\n if (self.stride > 4 or self.stride == 0 or (self.stride != 1 and self.stride % 2 != 0)):\r\n print(\"ERROR: THIS STRIDE FOR CONVOLUTION IS NOT RECOMMENDED\")\r\n print(\"TIP: Make sure stride is either 1, 2 and 4\")\r\n return False\r\n\r\n # The Number of Pad bits to be in range (0,16)\r\n if (self.pad < 0 or self.pad > 16):\r\n print(\"ERROR: THE PADDED BITS ARE EITHER SMALLER/LARGER THAN SUPPORTED\")\r\n print(\"TIP: Make sure Pad is in range from 0 to 16\")\r\n return False\r\n\r\n # The OFM Channels to be multiples of 8 and are in range (8,1024)\r\n if (self.ofm_depth <= 512 or self.ofm_depth >= 8):\r\n if (self.ofm_depth % 8 != 0):\r\n print(\"ERROR: THE NUMBER OF CHANNELS NEEDS TO BE IN MULTIPLES OF 8 IN THE RANGE 8 TO 512\")\r\n return False\r\n else:\r\n print(\"ERROR: THE NUMBER OF CHANNELS NEEDS TO BE IN MULTIPLES OF 8 IN THE RANGE 8 TO 512\")\r\n return False\r\n\r\n # The accumulation loopback has 10 cycle delay\r\n if (self.ofm_height * self.ofm_width < 10):\r\n print(\"ERROR: THE OFM VOLUME IS SMALLER THAN SUPPORTED\")\r\n print(\"TIP: Manage the IFM dimensions, kernel dimensions and other \"\r\n \"arguments such that ofm volume is of moderate size \")\r\n return False\r\n\r\n # The 2D dimensions are limited by BRAM chosen\r\n if (self.ifm_height * self.ifm_width > (1 << C_MAX_ADDR_WIDTH) or self.ofm_height * self.ofm_width > (1 << C_MAX_ADDR_WIDTH)):\r\n print(\"ERROR: THE IFM/OFM PLANE DOES NOT FIT IN THE LINE BUFFER\")\r\n return False\r\n\r\n # The max allowable block read (BTT) by the datamover is limited by\r\n # 2^23. The num of channels is currently limited by this number\r\n if (self.ofm_height * self.ofm_width * self.channels * (C_MAX_INPUT_WIDTH / 8) > 1 << 23):\r\n print(\"ERROR: THE NUMBER OF CHANNELS IS LARGER THAN THE MAXIMUM \"\r\n \"ALLOWABLE BYTES-TO-TRANSFER(BTT) OF DATAMOVER\")\r\n print(\"TIP: Decrease the number of channels\")\r\n return False\r\n\r\n while True:\r\n print(\"All IP arguments are in supported range\")\r\n cmd_conv = np.array([self.ifm_height, self.ifm_width, self.kernel_height,\r\n self.kernel_width, self.stride, self.pad, self.ofm_height,\r\n self.ofm_width, self.ifm_slices, self.ofm_slices,\r\n self.ofm_fragments, self.ifm_mem_fragments],\r\n dtype='uint16')\r\n\r\n cmd_addr = np.array([self.ifm_baseaddr, self.ifm_packet_length,\r\n self.ifm_depth_offset, self.ifm_height_offset,\r\n self.ofm_baseaddr, self.ofm_packet_length,\r\n self.weights_baseaddr, self.weights_packet_length,\r\n self.weight_depth_offset],\r\n dtype='uint32')\r\n\r\n cmd_mode = np.array([0, 0], dtype='uint16')\r\n\r\n cmd_pool = np.array([self.pool_input_height, self.pool_input_width,\r\n self.pool_kernel_height, self.pool_kernel_width,\r\n self.pool_output_height, self.pool_output_width,\r\n self.pool_stride, 0],\r\n dtype='uint16')\r\n\r\n cmd_rsvd = np.zeros((12,), dtype='uint32')\r\n\r\n IP_cmd = cmd_conv.tobytes() + \\\r\n cmd_addr.tobytes() + \\\r\n cmd_mode.tobytes() + \\\r\n cmd_pool.tobytes() + \\\r\n cmd_rsvd.tobytes()\r\n return IP_cmd\r\n break\r\n\r\n def reshape_and_copy_ifm(self, ifm_sw, ifm):\r\n \"\"\" Reshape the IFM Volume as per IP requirement and copy to physical\r\n memory with ifm pointer \"\"\"\r\n hw_index = 0\r\n for i in range(0, self.ifm_slices):\r\n for j in range(0, self.ifm_height * self.ifm_width):\r\n for k in range(0, C_NUM_OF_ROWS):\r\n index = i * (self.ifm_height * self.ifm_width) * C_NUM_OF_ROWS + \\\r\n k * (self.ifm_height * self.ifm_width) + j\r\n ifm[hw_index] = ifm_sw[index]\r\n hw_index = hw_index + 1\r\n\r\n def reshape_and_copy_weights(self, weights_sw, weights):\r\n \"\"\" Reshape the Weights as per IP requirement and copy to physical\r\n memory with weights pointer \"\"\"\r\n weights_index = 0\r\n for i in range(0, self.ofm_slices):\r\n for j in range(0, self.ifm_slices):\r\n for k in range(0, self.kernel_height * self.kernel_width):\r\n for r in range(0, C_NUM_OF_ROWS):\r\n for c in range(0, C_NUM_OF_COLS):\r\n addr = i * C_NUM_OF_COLS * self.weight_offset + \\\r\n c * self.weight_offset + \\\r\n j * self.weight_pkt_offset + \\\r\n r * self.kernel_height * self.kernel_width + \\\r\n k\r\n weights[weights_index] = weights_sw[addr]\r\n weights_index = weights_index + 1\r\n\r\n def calc_efficiency(self, hw_cycles):\r\n \"\"\" Gives efficiency of IP \"\"\"\r\n num_of_calc = self.ofm_height * self.ofm_width * \\\r\n self.ofm_depth * self.kernel_height * self.kernel_width * self.ifm_depth\r\n theoretical_cycles = num_of_calc / (C_NUM_OF_COLS * C_NUM_OF_ROWS)\r\n efficiency = (theoretical_cycles / hw_cycles) * 100\r\n return float(efficiency)\r\n "
] | [
[
"numpy.array",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
SethKitchen/open_spiel | [
"d38c935020c625438b62278523bf692b964cabc7"
] | [
"open_spiel/python/algorithms/tabular_qlearner.py"
] | [
"# Copyright 2019 DeepMind Technologies Ltd. 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\"\"\"Tabular Q-learning agent.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport numpy as np\n\nfrom open_spiel.python import rl_agent\nfrom open_spiel.python import rl_tools\n\n\nclass QLearner(rl_agent.AbstractAgent):\n \"\"\"Tabular Q-Learning agent.\n\n See open_spiel/python/examples/tic_tac_toe_qlearner.py for an usage example.\n \"\"\"\n\n def __init__(self,\n player_id,\n num_actions,\n step_size=0.1,\n epsilon_schedule=rl_tools.ConstantSchedule(0.2),\n discount_factor=1.0):\n \"\"\"Initialize the Q-Learning agent.\"\"\"\n self._player_id = player_id\n self._num_actions = num_actions\n self._step_size = step_size\n self._epsilon_schedule = epsilon_schedule\n self._epsilon = epsilon_schedule.value\n self._discount_factor = discount_factor\n self._q_values = collections.defaultdict(\n lambda: collections.defaultdict(float))\n self._prev_info_state = None\n self._last_loss_value = None\n\n def _epsilon_greedy(self, info_state, legal_actions, epsilon):\n \"\"\"Returns a valid epsilon-greedy action and valid action probs.\n\n If the agent has not been to `info_state`, a valid random action is chosen.\n\n Args:\n info_state: hashable representation of the information state.\n legal_actions: list of actions at `info_state`.\n epsilon: float, prob of taking an exploratory action.\n\n Returns:\n A valid epsilon-greedy action and valid action probabilities.\n \"\"\"\n probs = np.zeros(self._num_actions)\n greedy_q = max([self._q_values[info_state][a] for a in legal_actions])\n greedy_actions = [\n a for a in legal_actions if self._q_values[info_state][a] == greedy_q\n ]\n probs[legal_actions] = epsilon / len(legal_actions)\n probs[greedy_actions] += (1 - epsilon) / len(greedy_actions)\n action = np.random.choice(range(self._num_actions), p=probs)\n return action, probs\n\n def step(self, time_step, is_evaluation=False):\n \"\"\"Returns the action to be taken and updates the Q-values if needed.\n\n Args:\n time_step: an instance of rl_environment.TimeStep.\n is_evaluation: bool, whether this is a training or evaluation call.\n\n Returns:\n A `rl_agent.StepOutput` containing the action probs and chosen action.\n \"\"\"\n info_state = str(time_step.observations[\"info_state\"][self._player_id])\n legal_actions = time_step.observations[\"legal_actions\"][self._player_id]\n\n # Prevent undefined errors if this agent never plays until terminal step\n action, probs = None, None\n\n # Act step: don't act at terminal states.\n if not time_step.last():\n epsilon = 0.0 if is_evaluation else self._epsilon\n action, probs = self._epsilon_greedy(\n info_state, legal_actions, epsilon=epsilon)\n\n # Learn step: don't learn during evaluation or at first agent steps.\n if self._prev_info_state and not is_evaluation:\n target = time_step.rewards[self._player_id]\n if not time_step.last(): # Q values are zero for terminal.\n target += self._discount_factor * max(\n [self._q_values[info_state][a] for a in legal_actions])\n\n prev_q_value = self._q_values[self._prev_info_state][self._prev_action]\n self._last_loss_value = target - prev_q_value\n self._q_values[self._prev_info_state][self._prev_action] += (\n self._step_size * self._last_loss_value)\n\n # Decay epsilon, if necessary.\n self._epsilon = self._epsilon_schedule.step()\n\n if time_step.last(): # prepare for the next episode.\n self._prev_info_state = None\n return\n\n # Don't mess up with the state during evaluation.\n if not is_evaluation:\n self._prev_info_state = info_state\n self._prev_action = action\n return rl_agent.StepOutput(action=action, probs=probs)\n\n @property\n def loss(self):\n return self._last_loss_value\n"
] | [
[
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jialin-wu-02/skyportal | [
"29d606ad8567b2230fb0553b18dd3cb9d3ab2d84"
] | [
"skyportal/handlers/api/photometry.py"
] | [
"import numpy as np\nimport arrow\nfrom astropy.time import Time\nfrom astropy.table import Table\nimport pandas as pd\nfrom marshmallow.exceptions import ValidationError\nfrom baselayer.app.access import permissions, auth_or_token\nfrom ..base import BaseHandler\nfrom ...models import (\n DBSession, Photometry, Instrument, Source, Obj,\n PHOT_ZP, PHOT_SYS, Thumbnail\n)\n\nfrom ...schema import (PhotometryMag, PhotometryFlux)\nfrom ...phot_enum import ALLOWED_MAGSYSTEMS\nimport sncosmo\n\ndef nan_to_none(value):\n \"\"\"Coerce a value to None if it is nan, else return value.\"\"\"\n try:\n return None if np.isnan(value) else value\n except TypeError:\n return value\n\ndef allscalar(d):\n return all(np.isscalar(v) or v is None for v in d.values())\n\n\ndef serialize(phot, outsys, format):\n\n retval = {\n 'obj_id': phot.obj_id,\n 'ra': phot.ra,\n 'dec': phot.dec,\n 'filter': phot.filter,\n 'mjd': phot.mjd,\n 'instrument_id': phot.instrument_id,\n 'ra_unc': phot.ra_unc,\n 'dec_unc': phot.dec_unc\n }\n\n filter = phot.filter\n\n magsys_db = sncosmo.get_magsystem('ab')\n outsys = sncosmo.get_magsystem(outsys)\n\n relzp_out = 2.5 * np.log10(outsys.zpbandflux(filter))\n\n # note: these are not the actual zeropoints for magnitudes in the db or\n # packet, just ones that can be used to derive corrections when\n # compared to relzp_out\n\n relzp_db = 2.5 * np.log10(magsys_db.zpbandflux(filter))\n db_correction = relzp_out - relzp_db\n\n # this is the zeropoint for fluxes in the database that is tied\n # to the new magnitude system\n corrected_db_zp = PHOT_ZP + db_correction\n\n if format == 'mag':\n if phot.original_user_data is not None and 'limiting_mag' in phot.original_user_data:\n magsys_packet = sncosmo.get_magsystem(phot.original_user_data['magsys'])\n relzp_packet = 2.5 * np.log10(magsys_packet.zpbandflux(filter))\n packet_correction = relzp_out - relzp_packet\n maglimit = phot.original_user_data['limiting_mag']\n maglimit_out = maglimit + packet_correction\n else:\n # calculate the limiting mag\n fluxerr = phot.fluxerr\n fivesigma = 5 * fluxerr\n maglimit_out = -2.5 * np.log10(fivesigma) + corrected_db_zp\n\n retval.update({\n 'mag': phot.mag + db_correction,\n 'magerr': phot.e_mag,\n 'magsys': 'ab',\n 'limiting_mag': maglimit_out\n })\n elif format == 'flux':\n retval.update({\n 'flux': phot.flux,\n 'magsys': 'ab',\n 'zp': corrected_db_zp,\n 'fluxerr': phot.fluxerr\n })\n else:\n raise ValueError('Invalid output format specified. Must be one of '\n f\"['flux', 'mag'], got '{format}'.\")\n return retval\n\n\nclass PhotometryHandler(BaseHandler):\n @permissions(['Upload data'])\n def post(self):\n \"\"\"\n ---\n description: Upload photometry\n requestBody:\n content:\n application/json:\n schema:\n oneOf:\n - $ref: \"#/components/schemas/PhotMagFlexible\"\n - $ref: \"#/components/schemas/PhotFluxFlexible\"\n responses:\n 200:\n content:\n application/json:\n schema:\n allOf:\n - $ref: '#/components/schemas/Success'\n - type: object\n properties:\n data:\n type: object\n properties:\n ids:\n type: array\n items:\n type: integer\n description: List of new photometry IDs\n \"\"\"\n\n data = self.get_json()\n\n if not isinstance(data, dict):\n return self.error('Top level JSON must be an instance of `dict`, got '\n f'{type(data)}.')\n\n if allscalar(data):\n data = [data]\n\n try:\n df = pd.DataFrame(data)\n except ValueError as e:\n return self.error('Unable to coerce passed JSON to a series of packets. '\n f'Error was: \"{e}\"')\n\n # pop out thumbnails and process what's left using schemas\n\n ids = []\n for i, row in df.iterrows():\n packet = row.to_dict()\n\n # coerce nans to nones\n for key in packet:\n packet[key] = nan_to_none(packet[key])\n\n try:\n phot = PhotometryFlux.load(packet)\n except ValidationError as e1:\n try:\n phot = PhotometryMag.load(packet)\n except ValidationError as e2:\n return self.error('Invalid input format: Tried to parse '\n f'{packet} as PhotometryFlux, got: '\n f'\"{e1.normalized_messages()}.\" Tried '\n f'to parse {packet} as PhotometryMag, got:'\n f' \"{e2.normalized_messages()}.\"')\n\n phot.original_user_data = packet\n DBSession().add(phot)\n\n # to set up obj link\n DBSession().flush()\n\n time = arrow.get(Time(phot.mjd, format='mjd').iso)\n phot.obj.last_detected = max(\n time,\n phot.obj.last_detected\n if phot.obj.last_detected is not None\n else arrow.get(\"1000-01-01\")\n )\n ids.append(phot.id)\n\n DBSession().commit()\n return self.success(data={\"ids\": ids})\n\n @auth_or_token\n def get(self, photometry_id):\n # The full docstring/API spec is below as an f-string\n\n phot = Photometry.query.get(photometry_id)\n if phot is None:\n return self.error('Invalid photometry ID')\n # Ensure user/token has access to parent source\n _ = Source.get_if_owned_by(phot.obj_id, self.current_user)\n\n # get the desired output format\n format = self.get_query_argument('format', 'mag')\n outsys = self.get_query_argument('magsys', 'ab')\n output = serialize(phot, outsys, format)\n return self.success(data=output)\n\n @permissions(['Manage sources'])\n def put(self, photometry_id):\n \"\"\"\n ---\n description: Update photometry\n parameters:\n - in: path\n name: photometry_id\n required: true\n schema:\n type: integer\n requestBody:\n content:\n application/json:\n schema:\n oneOf:\n - $ref: \"#/components/schemas/PhotometryMag\"\n - $ref: \"#/components/schemas/PhotometryFlux\"\n responses:\n 200:\n content:\n application/json:\n schema: Success\n 400:\n content:\n application/json:\n schema: Error\n \"\"\"\n # Ensure user/token has access to parent source\n s = Source.get_if_owned_by(Photometry.query.get(photometry_id).obj_id,\n self.current_user)\n packet = self.get_json()\n\n try:\n phot = PhotometryFlux.load(packet)\n except ValidationError as e1:\n try:\n phot = PhotometryMag.load(packet)\n except ValidationError as e2:\n return self.error('Invalid input format: Tried to parse '\n f'{packet} as PhotometryFlux, got: '\n f'\"{e1.normalized_messages()}.\" Tried '\n f'to parse {packet} as PhotometryMag, got:'\n f' \"{e2.normalized_messages()}.\"')\n \n phot.original_user_data = packet\n phot.id = photometry_id\n DBSession().merge(phot)\n DBSession().commit()\n return self.success()\n\n @permissions(['Manage sources'])\n def delete(self, photometry_id):\n \"\"\"\n ---\n description: Delete photometry\n parameters:\n - in: path\n name: photometry_id\n required: true\n schema:\n type: integer\n responses:\n 200:\n content:\n application/json:\n schema: Success\n 400:\n content:\n application/json:\n schema: Error\n \"\"\"\n # Ensure user/token has access to parent source\n s = Source.get_if_owned_by(Photometry.query.get(photometry_id).obj_id,\n self.current_user)\n DBSession.query(Photometry).filter(Photometry.id == int(photometry_id)).delete()\n DBSession().commit()\n\n return self.success()\n\n\nclass SourcePhotometryHandler(BaseHandler):\n @auth_or_token\n def get(self, obj_id):\n source = Source.get_if_owned_by(obj_id, self.current_user)\n format = self.get_query_argument('format', 'mag')\n outsys = self.get_query_argument('magsys', 'ab')\n return self.success(\n data=[serialize(phot, outsys, format) for phot in source.photometry]\n )\n\n\nPhotometryHandler.get.__doc__ = f\"\"\"\n ---\n description: Retrieve photometry\n parameters:\n - in: path\n name: photometry_id\n required: true\n schema:\n type: integer\n - in: query\n name: format\n required: false\n description: >-\n Return the photometry in flux or magnitude space?\n If a value for this query parameter is not provided, the\n result will be returned in magnitude space.\n schema:\n type: string\n enum:\n - mag\n - flux\n - in: query\n name: magsys\n required: false\n description: >- \n The magnitude or zeropoint system of the output. (Default AB) \n schema:\n type: string\n enum: {list(ALLOWED_MAGSYSTEMS)}\n \n responses:\n 200:\n content:\n application/json:\n schema:\n oneOf:\n - $ref: \"#/components/schemas/SinglePhotometryFlux\"\n - $ref: \"#/components/schemas/SinglePhotometryMag\"\n 400:\n content:\n application/json:\n schema: Error\n \"\"\"\n\nSourcePhotometryHandler.get.__doc__ = f\"\"\" \n ---\n description: Retrieve photometry\n parameters:\n - in: path\n name: source_id\n required: true\n schema:\n type: integer\n description: ID of the source to retrieve photometry for\n - in: query\n name: format\n required: false\n description: >-\n Return the photometry in flux or magnitude space?\n If a value for this query parameter is not provided, the\n result will be returned in magnitude space.\n schema:\n type: string\n enum:\n - mag\n - flux\n - in: query\n name: magsys\n required: false\n description: >- \n The magnitude or zeropoint system of the output. (Default AB) \n schema:\n type: string\n enum: {list(ALLOWED_MAGSYSTEMS)}\n \n responses:\n 200:\n content:\n application/json:\n schema:\n oneOf:\n - $ref: \"#/components/schemas/ArrayOfPhotometryFluxs\"\n - $ref: \"#/components/schemas/ArrayOfPhotometryMags\"\n 400:\n content:\n application/json:\n schema: Error\n \"\"\"\n\n"
] | [
[
"numpy.isnan",
"numpy.isscalar",
"numpy.log10",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
0gubanov/robinbot | [
"59c9520cf47165c62fc87fd7d5587c3105290f05"
] | [
"robinhoodbot/misc.py"
] | [
"import robin_stocks as r\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as plticker\n\ndef show_plot(price, firstIndicator, secondIndicator, dates, label1=\"\", label2=\"\"):\n \"\"\"Displays a chart of the price and indicators for a stock\n\n Args:\n price(Pandas series): Series containing a stock's prices\n firstIndicator(Pandas series): Series containing a technical indicator, such as 50-day moving average\n secondIndicator(Pandas series): Series containing a technical indicator, such as 200-day moving average\n dates(Pandas series): Series containing the dates that correspond to the prices and indicators\n label1(str): Chart label of the first technical indicator\n label2(str): Chart label of the first technical indicator\n\n Returns:\n True if the stock's current price is higher than it was five years ago, or the stock IPO'd within the last five years\n False otherwise\n \"\"\"\n plt.figure(figsize=(10,5))\n plt.title(symbol)\n plt.plot(dates, price, label=\"Closing prices\")\n plt.plot(dates, firstIndicator, label=label1)\n plt.plot(dates, secondIndicator, label=label2)\n plt.yticks(np.arange(price.min(), price.max(), step=((price.max()-price.min())/15.0)))\n plt.legend()\n plt.show()\n\ndef get_equity_data():\n \"\"\"Displays a pie chart of your portfolio holdings\n \"\"\"\n holdings_data = r.build_holdings()\n equity_data = {}\n for key, value in holdings_data.items():\n equity_data[key] = {}\n equity_data[key][name] = value.get('name')\n equity_data[key][percentage] = value.get(\"percentage\")\n equity_data[key][type]\n fig1, ax1 = plt.subplots()\n ax1.pie(equities, labels=labels, autopct='%1.1f%%',\n shadow=True, startangle=90)\n ax1.axis('equal')\n plt.show()\n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rdbch/COVID-19-Forecast | [
"3aa9730ce07e935a87565d00052868dffdb430d9"
] | [
"core/nn/loss.py"
] | [
"import numpy as np\n\nimport torch\nfrom torch import nn\n\n# =============================================== L1 NORM =====================================================\ndef l1_norm_error(source, candidate):\n\n error = np.abs(source - candidate)\n source[source == 0] = 1e-30 # add for numerical stability\n error = error / source # compute the percentage\n error = error.mean()\n return error\n\n# =============================================== RMSLE =====================================================\ndef rmsle_error(source, candidate):\n candidate += 1e-30\n error = np.log10((source + 1) / (candidate + 1))\n error = error * error\n error = error.mean()\n error = np.sqrt(error)\n\n return error\n\n# =============================================== GRADIENT SMOOTH =====================================================\nclass GradientSmoothLoss(nn.Module):\n def __init__(self, refGrad, future, decayFunc = None):\n '''\n Function that minimizes the rate of change of a time series prediction,\n as the times evolves. It tries to give a desired \"shape\".\n\n :param refGrad: the maximum gradient that is used for scaling\n :param future: number of future predictions in the timeseries\n :param decayFunc: decay function for weights (the weights decrease as time increases, such that the last\n timestamps will have a smoother rate of change)\n '''\n\n super().__init__()\n self.future = future\n self.refGrad = refGrad\n\n # compute decay weights\n decay = np.linspace(0, 1, future)\n decay = self.__linear_decay(decay) if decayFunc is None \\\n else decayFunc(decay)\n decay = torch.from_numpy(decay)\n\n self.decay = decay * refGrad\n\n # =============================================== LINEAR DECAY =====================================================\n def __linear_decay(self, linSpace):\n return 0.8 - linSpace * 0.5\n\n # =============================================== FORWARD ==========================================================\n def forward(self, inTensor, clampVal = 0.25):\n '''\n :param inTensor: input tensor on which to apply the loss\n :param clampVal: clamp errors before averaging for better stability\n :return:\n '''\n\n self.decay = self.decay.to(inTensor.device)\n\n gradOut = inTensor[:, 1:] - inTensor[:, :-1]\n gradOut = gradOut.abs() - self.decay\n gradOut = torch.clamp(gradOut, min=0, max=clampVal)\n gradOut = gradOut.mean()\n\n return gradOut\n\n\n"
] | [
[
"numpy.sqrt",
"numpy.abs",
"numpy.linspace",
"torch.from_numpy",
"numpy.log10",
"torch.clamp"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Unity-Technologies/datasetinsights | [
"0c6e2407f3b6ceb7a38cb82e3bbcf41a6c2d4672"
] | [
"datasetinsights/datasets/unity_perception/references.py"
] | [
"\"\"\" Load Synthetic dataset references tables\n\"\"\"\nimport pandas as pd\n\nfrom .tables import DATASET_TABLES, SCHEMA_VERSION, glob, load_table\nfrom .validation import DuplicateRecordError, NoRecordError\n\n\nclass AnnotationDefinitions:\n \"\"\"Load annotation_definitions table\n\n For more detail, see schema design here:\n :ref:`annotation_definitions.json`\n\n Attributes:\n table (pd): a collection of annotation_definitions records\n \"\"\"\n\n TABLE_NAME = \"annotation_definitions\"\n FILE_PATTERN = DATASET_TABLES[TABLE_NAME].file\n\n def __init__(self, data_root, version=SCHEMA_VERSION):\n \"\"\" Initialize AnnotationDefinitions\n\n Args:\n data_root (str): the root directory of the dataset containing\n tables\n version (str): desired schema version\n \"\"\"\n self.table = self.load_annotation_definitions(data_root, version)\n\n def load_annotation_definitions(self, data_root, version):\n \"\"\"Load annotation definition files.\n\n For more detail, see schema design here:\n :ref:`annotation_definitions.json`\n\n Args:\n data_root (str): the root directory of the dataset containing\n tables\n version (str): desired schema version\n\n Returns:\n A Pandas dataframe with annotation definition records.\n Columns: 'id' (annotation id), 'name' (annotation name),\n 'description' (string description), 'format'\n (string describing format), 'spec' ( Format-specific specification\n for the annotation values)\n \"\"\"\n definitions = []\n for def_file in glob(data_root, self.FILE_PATTERN):\n definition = load_table(def_file, self.TABLE_NAME, version)\n definitions.append(definition)\n\n if definitions:\n combined = pd.concat(definitions, axis=0).drop_duplicates(\n subset=\"id\"\n )\n else:\n combined = pd.DataFrame({})\n\n return combined\n\n def get_definition(self, def_id):\n \"\"\"Get the annotation definition for a given definition id\n\n Args:\n def_id (int): annotation definition id used to filter results\n\n Returns:\n dict: a dictionary containing the annotation definition\n\n Raises:\n NoRecordError: If no annotation are found for a given definition id\n \"\"\"\n mask = self.table.id == def_id\n definition = self.table[mask]\n if definition.empty:\n raise NoRecordError(\n f\"No records are found in the annotation_definitions file \"\n f\"that matches the specified definition id: {def_id}\"\n )\n definition = definition.to_dict(\"records\")[0]\n\n return definition\n\n def find_by_name(self, pattern):\n \"\"\" Get the annotation definition by matching patterns\n\n This method will try to match the pattern of the annotation definition\n by name to determine\n\n Args:\n pattern (srt): the regex pattern\n\n Returns:\n dict: a dictionary containing the annotation definition\n\n Raises:\n NoRecordError: If no annotation are found for a given definition id\n DuplicateRecordError: If more than one record is found by the given\n pattern\n \"\"\"\n mask = self.table.name.str.contains(pattern)\n definition = self.table[mask]\n if definition.empty:\n raise NoRecordError(\n \"No records are found in the annotation definition table\"\n f\"that matches the specified pattern: {pattern}\"\n )\n if definition.shape[0] > 1:\n raise DuplicateRecordError(\n \"Found more than one annodation definition that matches\"\n f\"the pattern {pattern}. The matched records are: \\n\"\n f\"{definition}\"\n )\n definition = definition.to_dict(\"records\")[0]\n\n return definition\n\n\nclass MetricDefinitions:\n \"\"\"Load metric_definitions table\n\n For more detail, see schema design here:\n\n :ref:`metric_definitions.json`\n\n Attributes:\n table (pd): a collection of metric_definitions records with columns: id\n (id for metric definition), name, description, spec (definition specific\n spec)\n \"\"\"\n\n TABLE_NAME = \"metric_definitions\"\n FILE_PATTERN = DATASET_TABLES[TABLE_NAME].file\n\n def __init__(self, data_root, version=SCHEMA_VERSION):\n \"\"\" Initialize MetricDefinitions\n Args:\n data_root (str): the root directory of the dataset containing\n tables\n version (str): desired schema version\n \"\"\"\n self.table = self.load_metric_definitions(data_root, version)\n\n def load_metric_definitions(self, data_root, version):\n \"\"\"Load metric definition files.\n\n :ref:`metric_definitions.json`\n\n Args:\n data_root (str): the root directory of the dataset containing tables\n version (str): desired schema version\n\n Returns:\n A Pandas dataframe with metric definition records.\n a collection of metric_definitions records with columns: id\n (id for metric definition), name, description, spec (definition specific\n spec)\n \"\"\"\n definitions = []\n for def_file in glob(data_root, self.FILE_PATTERN):\n definition = load_table(def_file, self.TABLE_NAME, version)\n definitions.append(definition)\n\n combined = pd.concat(definitions, axis=0).drop_duplicates(subset=\"id\")\n\n return combined\n\n def get_definition(self, def_id):\n \"\"\"Get the metric definition for a given definition id\n\n Args:\n def_id (int): metric definition id used to filter results\n\n Returns:\n a dictionary containing metric definition\n \"\"\"\n mask = self.table.id == def_id\n definition = self.table[mask]\n if definition.empty:\n raise NoRecordError(\n f\"No records are found in the metric_definitions file \"\n f\"that matches the specified definition id: {def_id}\"\n )\n definition = definition.to_dict(\"records\")[0]\n\n return definition\n\n\nclass Egos:\n \"\"\"Load egos table\n\n For more detail, see schema design here:\n :ref:`egos.json`\n\n Attributes:\n table (pd): a collection of egos records\n \"\"\"\n\n TABLE_NAME = \"egos\"\n FILE_PATTERN = DATASET_TABLES[TABLE_NAME].file\n\n def __init__(self, data_root, version=SCHEMA_VERSION):\n \"\"\"Initialize `:ref:Egos`\n\n\n Args:\n data_root (str): the root directory of the dataset containing\n ego tables. Two columns: id (ego id) and description\n version (str): desired schema version\n \"\"\"\n self.table = self.load_egos(data_root, version)\n\n def load_egos(self, data_root, version):\n \"\"\"Load egos files.\n For more detail, see schema design here:\n\n :ref:`egos.json`\n\n Args:\n data_root (str): the root directory of the dataset containing\n ego tables\n version (str): desired schema version\n\n Returns:\n A pandas dataframe with all ego records with two columns: id\n (ego id) and description\n \"\"\"\n egos = []\n for ego_file in glob(data_root, self.FILE_PATTERN):\n ego = load_table(ego_file, self.TABLE_NAME, version)\n egos.append(ego)\n combined = pd.concat(egos, axis=0).drop_duplicates(subset=\"id\")\n\n return combined\n\n\nclass Sensors:\n \"\"\"Load sensors table\n\n For more detail, see schema design here:\n\n :ref:`sensors.json`\n\n Attributes:\n table (pd): a collection of sensors records with columns:\n 'id' (sensor id), 'ego_id', 'modality'\n ({camera, lidar, radar, sonar,...} -- Sensor modality), 'description'\n\n \"\"\"\n\n TABLE_NAME = \"sensors\"\n FILE_PATTERN = DATASET_TABLES[TABLE_NAME].file\n\n def __init__(self, data_root, version=SCHEMA_VERSION):\n \"\"\" Initialize Sensors\n\n Args:\n data_root (str): the root directory of the dataset containing\n tables\n version (str): desired schema version\n \"\"\"\n self.table = self.load_sensors(data_root, version)\n\n def load_sensors(self, data_root, version):\n \"\"\"Load sensors files.\n\n For more detail, see schema design here:\n\n :ref:`sensors.json`\n\n Args:\n data_root (str): the root directory of the dataset containing\n tables\n version (str): desired schema version\n\n Returns:\n A pandas dataframe with all sensors records with columns:\n 'id' (sensor id), 'ego_id', 'modality'\n ({camera, lidar, radar, sonar,...} -- Sensor modality), 'description'\n \"\"\"\n sensors = []\n for sensor_file in glob(data_root, self.FILE_PATTERN):\n sensor = load_table(sensor_file, self.TABLE_NAME, version)\n sensors.append(sensor)\n combined = pd.concat(sensors, axis=0).drop_duplicates(subset=\"id\")\n\n return combined\n"
] | [
[
"pandas.concat",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
Aniruddha120/qiskit-aqua | [
"9806a31819bbc7160568a5cb36b38b9e3dd1a78e"
] | [
"qiskit/aqua/operators/primitive_ops/pauli_op.py"
] | [
"# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2020.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\" PauliOp Class \"\"\"\n\nfrom typing import Union, Set, Dict, cast\nimport logging\nimport numpy as np\nfrom scipy.sparse import spmatrix\n\nfrom qiskit import QuantumCircuit\nfrom qiskit.circuit import ParameterExpression, Instruction\nfrom qiskit.quantum_info import Pauli\nfrom qiskit.circuit.library import RZGate, RYGate, RXGate, XGate, YGate, ZGate, IGate\n\nfrom ..operator_base import OperatorBase\nfrom .primitive_op import PrimitiveOp\nfrom ..list_ops.summed_op import SummedOp\nfrom ..list_ops.composed_op import ComposedOp\nfrom ..list_ops.tensored_op import TensoredOp\nfrom ..legacy.weighted_pauli_operator import WeightedPauliOperator\n\nlogger = logging.getLogger(__name__)\nPAULI_GATE_MAPPING = {'X': XGate(), 'Y': YGate(), 'Z': ZGate(), 'I': IGate()}\n\n\nclass PauliOp(PrimitiveOp):\n \"\"\" Class for Operators backed by Terra's ``Pauli`` module.\n\n \"\"\"\n\n def __init__(self,\n primitive: Union[Pauli] = None,\n coeff: Union[int, float, complex, ParameterExpression] = 1.0) -> None:\n \"\"\"\n Args:\n primitive: The Pauli which defines the behavior of the underlying function.\n coeff: A coefficient multiplying the primitive.\n\n Raises:\n TypeError: invalid parameters.\n \"\"\"\n if not isinstance(primitive, Pauli):\n raise TypeError(\n 'PauliOp can only be instantiated with Paulis, not {}'.format(type(primitive)))\n super().__init__(primitive, coeff=coeff)\n\n def primitive_strings(self) -> Set[str]:\n return {'Pauli'}\n\n @property\n def num_qubits(self) -> int:\n return len(self.primitive)\n\n def add(self, other: OperatorBase) -> OperatorBase:\n if not self.num_qubits == other.num_qubits:\n raise ValueError(\n 'Sum over operators with different numbers of qubits, {} and {}, is not well '\n 'defined'.format(self.num_qubits, other.num_qubits))\n\n if isinstance(other, PauliOp) and self.primitive == other.primitive:\n return PauliOp(self.primitive, coeff=self.coeff + other.coeff)\n\n return SummedOp([self, other])\n\n def adjoint(self) -> OperatorBase:\n return PauliOp(self.primitive, coeff=np.conj(self.coeff))\n\n def equals(self, other: OperatorBase) -> bool:\n if not isinstance(other, PauliOp) or not self.coeff == other.coeff:\n return False\n\n return self.primitive == other.primitive\n\n def tensor(self, other: OperatorBase) -> OperatorBase:\n # Both Paulis\n if isinstance(other, PauliOp):\n # Copying here because Terra's Pauli kron is in-place.\n op_copy = Pauli(x=other.primitive.x, z=other.primitive.z) # type: ignore\n # NOTE!!! REVERSING QISKIT ENDIANNESS HERE\n return PauliOp(op_copy.kron(self.primitive), coeff=self.coeff * other.coeff)\n\n # pylint: disable=cyclic-import,import-outside-toplevel\n from .circuit_op import CircuitOp\n if isinstance(other, CircuitOp):\n return self.to_circuit_op().tensor(other)\n\n return TensoredOp([self, other])\n\n def compose(self, other: OperatorBase) -> OperatorBase:\n other = self._check_zero_for_composition_and_expand(other)\n\n # If self is identity, just return other.\n if not any(self.primitive.x + self.primitive.z): # type: ignore\n return other * self.coeff # type: ignore\n\n # Both Paulis\n if isinstance(other, PauliOp):\n product, phase = Pauli.sgn_prod(self.primitive, other.primitive)\n return PrimitiveOp(product, coeff=self.coeff * other.coeff * phase)\n\n # pylint: disable=cyclic-import,import-outside-toplevel\n from .circuit_op import CircuitOp\n from ..state_fns.circuit_state_fn import CircuitStateFn\n if isinstance(other, (CircuitOp, CircuitStateFn)):\n return self.to_circuit_op().compose(other)\n\n return ComposedOp([self, other])\n\n def to_matrix(self, massive: bool = False) -> np.ndarray:\n if self.num_qubits > 16 and not massive:\n raise ValueError(\n 'to_matrix will return an exponentially large matrix, '\n 'in this case {0}x{0} elements.'\n ' Set massive=True if you want to proceed.'.format(2 ** self.num_qubits))\n\n return self.primitive.to_matrix() * self.coeff # type: ignore\n\n def to_spmatrix(self) -> spmatrix:\n \"\"\" Returns SciPy sparse matrix representation of the Operator.\n\n Returns:\n CSR sparse matrix representation of the Operator.\n\n Raises:\n ValueError: invalid parameters.\n \"\"\"\n return self.primitive.to_spmatrix() * self.coeff # type: ignore\n\n def __str__(self) -> str:\n prim_str = str(self.primitive)\n if self.coeff == 1.0:\n return prim_str\n else:\n return \"{} * {}\".format(self.coeff, prim_str)\n\n def eval(self,\n front: Union[str, dict, np.ndarray,\n OperatorBase] = None) -> Union[OperatorBase, float, complex]:\n if front is None:\n return self.to_matrix_op()\n\n # pylint: disable=import-outside-toplevel,cyclic-import\n from ..state_fns.state_fn import StateFn\n from ..state_fns.dict_state_fn import DictStateFn\n from ..state_fns.circuit_state_fn import CircuitStateFn\n from ..list_ops.list_op import ListOp\n from .circuit_op import CircuitOp\n\n new_front = None\n\n # For now, always do this. If it's not performant, we can be more granular.\n if not isinstance(front, OperatorBase):\n front = StateFn(front, is_measurement=False)\n\n if isinstance(front, ListOp) and front.distributive:\n new_front = front.combo_fn([self.eval(front.coeff * front_elem) # type: ignore\n for front_elem in front.oplist])\n\n else:\n\n if self.num_qubits != front.num_qubits:\n raise ValueError(\n 'eval does not support operands with differing numbers of qubits, '\n '{} and {}, respectively.'.format(\n self.num_qubits, front.num_qubits))\n\n if isinstance(front, DictStateFn):\n\n new_dict = {} # type: Dict\n corrected_x_bits = self.primitive.x[::-1] # type: ignore\n corrected_z_bits = self.primitive.z[::-1] # type: ignore\n\n for bstr, v in front.primitive.items():\n bitstr = np.asarray(list(bstr)).astype(np.int).astype(np.bool)\n new_b_str = np.logical_xor(bitstr, corrected_x_bits)\n new_str = ''.join(map(str, 1 * new_b_str))\n z_factor = np.product(1 - 2 * np.logical_and(bitstr, corrected_z_bits))\n y_factor = np.product(np.sqrt(1 - 2 * np.logical_and(corrected_x_bits,\n corrected_z_bits) + 0j))\n new_dict[new_str] = (v * z_factor * y_factor) + new_dict.get(new_str, 0)\n new_front = StateFn(new_dict, coeff=self.coeff * front.coeff)\n\n elif isinstance(front, StateFn) and front.is_measurement:\n raise ValueError('Operator composed with a measurement is undefined.')\n\n # Composable types with PauliOp\n elif isinstance(front, (PauliOp, CircuitOp, CircuitStateFn)):\n new_front = self.compose(front)\n\n # Covers VectorStateFn and OperatorStateFn\n elif isinstance(front, OperatorBase):\n new_front = self.to_matrix_op().eval(front.to_matrix_op()) # type: ignore\n\n return new_front\n\n def exp_i(self) -> OperatorBase:\n \"\"\" Return a ``CircuitOp`` equivalent to e^-iH for this operator H. \"\"\"\n # if only one qubit is significant, we can perform the evolution\n corrected_x = self.primitive.x[::-1] # type: ignore\n corrected_z = self.primitive.z[::-1] # type: ignore\n # pylint: disable=import-outside-toplevel,no-member\n sig_qubits = np.logical_or(corrected_x, corrected_z)\n if np.sum(sig_qubits) == 0:\n # e^I is just a global phase, but we can keep track of it! Should we?\n # For now, just return identity\n return PauliOp(self.primitive)\n if np.sum(sig_qubits) == 1:\n sig_qubit_index = sig_qubits.tolist().index(True)\n coeff = np.real(self.coeff) \\\n if not isinstance(self.coeff, ParameterExpression) \\\n else self.coeff\n # Y rotation\n if corrected_x[sig_qubit_index] and corrected_z[sig_qubit_index]:\n rot_op = PrimitiveOp(RYGate(coeff))\n # Z rotation\n elif corrected_z[sig_qubit_index]:\n rot_op = PrimitiveOp(RZGate(coeff))\n # X rotation\n elif corrected_x[sig_qubit_index]:\n rot_op = PrimitiveOp(RXGate(coeff))\n\n from ..operator_globals import I\n left_pad = I.tensorpower(sig_qubit_index)\n right_pad = I.tensorpower(self.num_qubits - sig_qubit_index - 1)\n # Need to use overloaded operators here in case left_pad == I^0\n return left_pad ^ rot_op ^ right_pad\n else:\n from ..evolutions.evolved_op import EvolvedOp\n return EvolvedOp(self)\n\n def commutes(self, other_op: OperatorBase) -> bool:\n \"\"\" Returns whether self commutes with other_op.\n\n Args:\n other_op: An ``OperatorBase`` with which to evaluate whether self commutes.\n\n Returns:\n A bool equaling whether self commutes with other_op\n\n \"\"\"\n if not isinstance(other_op, PauliOp):\n return False\n # Don't use compose because parameters will break this\n self_bits = self.primitive.z + 2 * self.primitive.x # type: ignore\n other_bits = other_op.primitive.z + 2 * other_op.primitive.x # type: ignore\n return all((self_bits * other_bits) * (self_bits - other_bits) == 0)\n\n def to_circuit(self) -> QuantumCircuit:\n # If Pauli equals identity, don't skip the IGates\n is_identity = sum(self.primitive.x + self.primitive.z) == 0 # type: ignore\n\n # Note: Reversing endianness!!\n qc = QuantumCircuit(len(self.primitive))\n for q, pauli_str in enumerate(reversed(self.primitive.to_label())): # type: ignore\n gate = PAULI_GATE_MAPPING[pauli_str]\n if not pauli_str == 'I' or is_identity:\n qc.append(gate, qargs=[q])\n return qc\n\n def to_instruction(self) -> Instruction:\n # TODO should we just do the following because performance of adding and deleting IGates\n # doesn't matter?\n # (Reduce removes extra IGates).\n # return PrimitiveOp(self.primitive.to_instruction(), coeff=self.coeff).reduce()\n\n return self.to_circuit().to_instruction()\n\n def to_pauli_op(self, massive: bool = False) -> OperatorBase:\n return self\n\n def to_legacy_op(self, massive: bool = False) -> WeightedPauliOperator:\n if isinstance(self.coeff, ParameterExpression):\n try:\n coeff = float(self.coeff)\n except TypeError:\n raise TypeError('Cannot convert Operator with unbound parameter {} to Legacy '\n 'Operator'.format(self.coeff))\n else:\n coeff = cast(float, self.coeff)\n return WeightedPauliOperator(paulis=[(coeff, self.primitive)]) # type: ignore\n"
] | [
[
"numpy.logical_xor",
"numpy.conj",
"numpy.logical_or",
"numpy.real",
"numpy.logical_and",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kiwicom/catboost-cxx | [
"7ae872fe9418215b6592e1a947d1cd4bc5b10b3d"
] | [
"unittest/testdata/gen_catboost_tests.py"
] | [
"#!/usr/bin/env python3\n\nimport catboost as cb\nimport numpy as np\nimport numpy.matlib as mlib\nimport json\nimport os, sys\n\ndef xor_dataset():\n x = np.array([ [0, 0], [0, 1], [1, 0], [1, 1] ])\n y = np.array([ 0, 1, 1, 0 ])\n return x, y\n\ndef or_dataset():\n x = np.array([ [0, 0], [0, 1], [1, 0], [1, 1] ])\n y = np.array([ 0, 1, 1, 1 ])\n return x, y\n\ndef and_dataset():\n x = np.array([ [0, 0], [0, 1], [1, 0], [1, 1] ])\n y = np.array([ 0, 0, 0, 1 ])\n return x, y\n\ndef regression_dataset():\n a = np.array( [ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0 ] )\n x = np.random.rand(100, 8)\n y = mlib.dot(x, a) + np.random.rand(100) / 10.0\n return x, y\n\ndef gen_test(fnm, dataset, iterations = 10, learning_rate = 0.1, loss = \"RMSE\"):\n features, labels = dataset()\n model = cb.CatBoost({\"learning_rate\": learning_rate, \"iterations\": iterations, \"loss_function\": loss })\n model.fit(features, y = labels)\n model.save_model(fnm + \"-model.json\", format = \"json\")\n width = features.shape[1]\n x = np.random.rand(10, width)\n y = model.predict(x)\n with open(fnm + \".json\", \"wt\") as f:\n json.dump({\"x\": x.tolist(), \"y\": y.tolist()}, f)\n\ndef main():\n gen_test(\"xor\", xor_dataset, iterations = 50, learning_rate = 0.2, loss = \"RMSE\")\n gen_test(\"or\", xor_dataset, iterations = 50, learning_rate = 0.2, loss = \"RMSE\")\n gen_test(\"and\", xor_dataset, iterations = 50, learning_rate = 0.2, loss = \"RMSE\")\n gen_test(\"regression\", regression_dataset, iterations = 100, learning_rate = 0.2, loss = \"RMSE\")\n\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"numpy.array",
"numpy.matlib.dot",
"numpy.random.rand"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
StanczakDominik/fbpic | [
"8b03d1f3182c1cd2b14c7add92cb6063c84f78a5"
] | [
"fbpic/openpmd_diag/data_dict.py"
] | [
"# Copyright 2016, FBPIC contributors\n# Authors: Remi Lehe, Manuel Kirchen\n# License: 3-Clause-BSD-LBNL\n\"\"\"\nThis file defines useful correspondance dictionaries\nwhich are used in the openPMD writer\n\"\"\"\nimport numpy as np\n\n# Correspondance between quantity and corresponding dimensions\n# As specified in the openPMD standard, the arrays represent the\n# 7 basis dimensions L, M, T, I, theta, N, J\nunit_dimension_dict = {\n \"rho\" : np.array([-3., 0., 1., 1., 0., 0., 0.]),\n \"J\" : np.array([-2., 0., 0., 1., 0., 0., 0.]),\n \"E\" : np.array([ 1., 1.,-3.,-1., 0., 0., 0.]),\n \"B\" : np.array([ 0., 1.,-2.,-1., 0., 0., 0.]),\n \"charge\" : np.array([0., 0., 1., 1., 0., 0., 0.]),\n \"mass\" : np.array([1., 0., 0., 0., 0., 0., 0.]),\n \"weighting\" : np.array([0., 0., 0., 0., 0., 0., 0.]),\n \"position\" : np.array([1., 0., 0., 0., 0., 0., 0.]),\n \"positionOffset\" : np.array([1., 0., 0., 0., 0., 0., 0.]),\n \"momentum\" : np.array([1., 1.,-1., 0., 0., 0., 0.]),\n \"id\" : np.array([0., 0., 0., 0., 0., 0., 0.]),\n \"gamma\" : np.array([0., 0., 0., 0., 0., 0., 0.]) }\n\n# Typical weighting of different particle properties\nmacro_weighted_dict = {\n \"charge\": np.uint32(0),\n \"mass\": np.uint32(0),\n \"weighting\": np.uint32(1),\n \"position\": np.uint32(0),\n \"positionOffset\": np.uint32(0),\n \"momentum\" : np.uint32(0),\n \"E\": np.uint32(0),\n \"B\": np.uint32(0),\n \"gamma\" : np.uint32(0),\n \"id\" : np.uint32(0) }\nweighting_power_dict = {\n \"charge\": 1.,\n \"mass\": 1.,\n \"weighting\": 1.,\n \"position\": 0.,\n \"positionOffset\": 0.,\n \"momentum\": 1.,\n \"E\": 0.,\n \"B\": 0.,\n \"gamma\": 0.,\n \"id\": 0. }\n"
] | [
[
"numpy.array",
"numpy.uint32"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ajabri/rlpyt | [
"a2e347153421e2d7b23a08ef6eec94f3c9f9ffa9"
] | [
"rlpyt/runners/minibatch_rl.py"
] | [
"\nimport psutil\nimport time\nimport torch\nimport math\nfrom collections import deque\n\nfrom rlpyt.runners.base import BaseRunner\nfrom rlpyt.utils.quick_args import save__init__args\nfrom rlpyt.utils.seed import set_seed, make_seed\nfrom rlpyt.utils.logging import logger\nfrom rlpyt.utils.prog_bar import ProgBarCounter\n\n\nclass MinibatchRlBase(BaseRunner):\n\n _eval = False\n\n def __init__(\n self,\n algo,\n agent,\n sampler,\n n_steps,\n seed=None,\n affinity=None,\n log_interval_steps=1e5,\n diag_fn=None,\n ):\n n_steps = int(n_steps)\n log_interval_steps = int(log_interval_steps)\n affinity = dict() if affinity is None else affinity\n save__init__args(locals())\n\n def startup(self):\n p = psutil.Process()\n try:\n if (self.affinity.get(\"master_cpus\", None) is not None and\n self.affinity.get(\"set_affinity\", True)):\n p.cpu_affinity(self.affinity[\"master_cpus\"])\n cpu_affin = p.cpu_affinity()\n except AttributeError:\n cpu_affin = \"UNAVAILABLE MacOS\"\n logger.log(f\"Runner {getattr(self, 'rank', '')} master CPU affinity: \"\n f\"{cpu_affin}.\")\n if self.affinity.get(\"master_torch_threads\", None) is not None:\n torch.set_num_threads(self.affinity[\"master_torch_threads\"])\n logger.log(f\"Runner {getattr(self, 'rank', '')} master Torch threads: \"\n f\"{torch.get_num_threads()}.\")\n if self.seed is None:\n self.seed = make_seed()\n set_seed(self.seed)\n self.rank = rank = getattr(self, \"rank\", 0)\n self.world_size = world_size = getattr(self, \"world_size\", 1)\n examples = self.sampler.initialize(\n agent=self.agent, # Agent gets intialized in sampler.\n affinity=self.affinity,\n seed=self.seed + 1,\n bootstrap_value=getattr(self.algo, \"bootstrap_value\", False),\n traj_info_kwargs=self.get_traj_info_kwargs(),\n rank=rank,\n world_size=world_size,\n )\n self.itr_batch_size = self.sampler.batch_spec.size * world_size\n n_itr = self.get_n_itr()\n self.agent.to_device(self.affinity.get(\"cuda_idx\", None))\n if world_size > 1:\n self.agent.data_parallel()\n self.algo.initialize(\n agent=self.agent,\n n_itr=n_itr,\n batch_spec=self.sampler.batch_spec,\n mid_batch_reset=self.sampler.mid_batch_reset,\n examples=examples,\n world_size=world_size,\n rank=rank,\n )\n self.initialize_logging()\n return n_itr\n\n def get_traj_info_kwargs(self):\n return dict(discount=getattr(self.algo, \"discount\", 1))\n\n def get_n_itr(self):\n log_interval_itrs = max(self.log_interval_steps //\n self.itr_batch_size, 1)\n n_itr = math.ceil(self.n_steps / self.log_interval_steps) * log_interval_itrs\n self.log_interval_itrs = log_interval_itrs\n self.n_itr = n_itr\n logger.log(f\"Running {n_itr} iterations of minibatch RL.\")\n return n_itr\n\n def initialize_logging(self):\n self._opt_infos = {k: list() for k in self.algo.opt_info_fields}\n self._start_time = self._last_time = time.time()\n self._cum_time = 0.\n self._cum_completed_trajs = 0\n self._last_update_counter = 0\n\n def shutdown(self):\n logger.log(\"Training complete.\")\n self.pbar.stop()\n self.sampler.shutdown()\n\n def get_itr_snapshot(self, itr):\n return dict(\n itr=itr,\n cum_steps=itr * self.sampler.batch_size * self.world_size,\n agent_state_dict=self.agent.state_dict(),\n optimizer_state_dict=self.algo.optim_state_dict(),\n )\n\n def save_itr_snapshot(self, itr):\n logger.log(\"saving snapshot...\")\n params = self.get_itr_snapshot(itr)\n logger.save_itr_params(itr, params)\n logger.log(\"saved\")\n\n def store_diagnostics(self, itr, traj_infos, opt_info):\n self._cum_completed_trajs += len(traj_infos)\n for k, v in self._opt_infos.items():\n new_v = getattr(opt_info, k, [])\n v.extend(new_v if isinstance(new_v, list) else [new_v])\n self.pbar.update((itr + 1) % self.log_interval_itrs)\n\n def log_diagnostics(self, itr, traj_infos=None, eval_time=0):\n if itr > 0:\n self.pbar.stop()\n self.save_itr_snapshot(itr)\n new_time = time.time()\n self._cum_time = new_time - self._start_time\n train_time_elapsed = new_time - self._last_time - eval_time\n new_updates = self.algo.update_counter - self._last_update_counter\n new_samples = (self.sampler.batch_size * self.world_size *\n self.log_interval_itrs)\n updates_per_second = (float('nan') if itr == 0 else\n new_updates / train_time_elapsed)\n samples_per_second = (float('nan') if itr == 0 else\n new_samples / train_time_elapsed)\n replay_ratio = (new_updates * self.algo.batch_size * self.world_size /\n new_samples)\n cum_replay_ratio = (self.algo.batch_size * self.algo.update_counter /\n ((itr + 1) * self.sampler.batch_size)) # world_size cancels.\n cum_steps = (itr + 1) * self.sampler.batch_size * self.world_size\n\n if self._eval:\n logger.record_tabular('CumTrainTime',\n self._cum_time - self._cum_eval_time) # Already added new eval_time.\n logger.record_tabular('Iteration', itr)\n logger.record_tabular('CumTime (s)', self._cum_time)\n logger.record_tabular('CumSteps', cum_steps)\n logger.record_tabular('CumCompletedTrajs', self._cum_completed_trajs)\n logger.record_tabular('CumUpdates', self.algo.update_counter)\n logger.record_tabular('StepsPerSecond', samples_per_second)\n logger.record_tabular('UpdatesPerSecond', updates_per_second)\n logger.record_tabular('ReplayRatio', replay_ratio)\n logger.record_tabular('CumReplayRatio', cum_replay_ratio)\n self._log_infos(traj_infos)\n logger.dump_tabular(with_prefix=False)\n\n self._last_time = new_time\n self._last_update_counter = self.algo.update_counter\n if itr < self.n_itr - 1:\n logger.log(f\"Optimizing over {self.log_interval_itrs} iterations.\")\n self.pbar = ProgBarCounter(self.log_interval_itrs)\n\n def _log_infos(self, traj_infos=None):\n if traj_infos is None:\n traj_infos = self._traj_infos\n if traj_infos:\n for k in traj_infos[0]:\n if not k.startswith(\"_\"):\n logger.record_tabular_misc_stat(k,\n [info[k] for info in traj_infos])\n\n if self._opt_infos:\n for k, v in self._opt_infos.items():\n logger.record_tabular_misc_stat(k, v)\n self._opt_infos = {k: list() for k in self._opt_infos} # (reset)\n\n\nclass MinibatchRl(MinibatchRlBase):\n \"\"\"Runs RL on minibatches; tracks performance online using learning\n trajectories.\"\"\"\n\n def __init__(self, log_traj_window=100, **kwargs):\n super().__init__(**kwargs)\n self.log_traj_window = int(log_traj_window)\n\n def train(self):\n n_itr = self.startup()\n for itr in range(n_itr):\n with logger.prefix(f\"itr #{itr} \"):\n self.agent.sample_mode(itr) # Might not be this agent sampling.\n samples, traj_infos = self.sampler.obtain_samples(itr)\n self.agent.train_mode(itr)\n opt_info = self.algo.optimize_agent(itr, samples)\n self.store_diagnostics(itr, traj_infos, opt_info)\n # import pdb; pdb.set_trace()\n if (itr + 1) % self.log_interval_itrs == 0:\n self.log_diagnostics(itr)\n if self.diag_fn is not None:\n self.diag_fn(samples, itr)\n\n self.shutdown()\n\n def initialize_logging(self):\n self._traj_infos = deque(maxlen=self.log_traj_window)\n self._new_completed_trajs = 0\n logger.log(f\"Optimizing over {self.log_interval_itrs} iterations.\")\n super().initialize_logging()\n self.pbar = ProgBarCounter(self.log_interval_itrs)\n\n def store_diagnostics(self, itr, traj_infos, opt_info):\n self._new_completed_trajs += len(traj_infos)\n self._traj_infos.extend(traj_infos)\n super().store_diagnostics(itr, traj_infos, opt_info)\n\n def log_diagnostics(self, itr):\n logger.record_tabular('NewCompletedTrajs', self._new_completed_trajs)\n logger.record_tabular('StepsInTrajWindow',\n sum(info[\"Length\"] for info in self._traj_infos))\n super().log_diagnostics(itr)\n self._new_completed_trajs = 0\n\n\nclass MinibatchRlEval(MinibatchRlBase):\n \"\"\"Runs RL on minibatches; tracks performance offline using evaluation\n trajectories.\"\"\"\n\n _eval = True\n\n def train(self):\n n_itr = self.startup()\n with logger.prefix(f\"itr #0 \"):\n eval_traj_infos, eval_time = self.evaluate_agent(0)\n self.log_diagnostics(0, eval_traj_infos, eval_time)\n for itr in range(n_itr):\n with logger.prefix(f\"itr #{itr} \"):\n self.agent.sample_mode(itr)\n samples, traj_infos = self.sampler.obtain_samples(itr)\n self.agent.train_mode(itr)\n opt_info = self.algo.optimize_agent(itr, samples)\n self.store_diagnostics(itr, traj_infos, opt_info)\n if (itr + 1) % self.log_interval_itrs == 0:\n eval_traj_infos, eval_time = self.evaluate_agent(itr)\n self.log_diagnostics(itr, eval_traj_infos, eval_time)\n # if (itr + 1) % self.viz_interval_itrs == 0:\n # # HACK make a new sampler?\n # eval_traj_infos, eval_time = self.evaluate_agent(itr)\n # self.log_diagnostics(itr, eval_traj_infos, eval_time)\n\n self.shutdown()\n\n def evaluate_agent(self, itr):\n if itr > 0:\n self.pbar.stop()\n logger.log(\"Evaluating agent...\")\n self.agent.eval_mode(itr) # Might be agent in sampler.\n eval_time = -time.time()\n traj_infos = self.sampler.evaluate_agent(itr)\n eval_time += time.time()\n logger.log(\"Evaluation runs complete.\")\n return traj_infos, eval_time\n\n def initialize_logging(self):\n super().initialize_logging()\n self._cum_eval_time = 0\n\n def log_diagnostics(self, itr, eval_traj_infos, eval_time):\n if not eval_traj_infos:\n logger.log(\"WARNING: had no complete trajectories in eval.\")\n steps_in_eval = sum([info[\"Length\"] for info in eval_traj_infos])\n logger.record_tabular('StepsInEval', steps_in_eval)\n logger.record_tabular('TrajsInEval', len(eval_traj_infos))\n self._cum_eval_time += eval_time\n logger.record_tabular('CumEvalTime', self._cum_eval_time)\n super().log_diagnostics(itr, eval_traj_infos, eval_time)\n"
] | [
[
"torch.get_num_threads",
"torch.set_num_threads"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
brandon-m-booth/2018_continuous_annotations | [
"f5621d5d7da56d62e06d8e40afa152cccb40930e"
] | [
"src/linear_segmented_regression/continuous_opt.py"
] | [
"#!/usr/bin/env python\n\nimport os\nimport sys\nimport pdb\nimport math\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'util')))\nimport util\n\n# For debugging\nshow_debug_plots = False\n\ndef ComputeOptimalFit(input_csv_path, num_segments):\n # Get the signal data\n signal_df = pd.read_csv(input_csv_path)\n time = signal_df.iloc[:,0]\n signal = signal_df.iloc[:,1]\n signal.index = time\n\n print(\"Computing optimal segmented linear fit with %d segments...\"%(num_segments))\n\n # Dynamic program to find the optimal linear segmented regression\n n = len(time)\n F = np.nan*np.zeros((n, num_segments))\n I = np.zeros((n, num_segments)).astype(int)\n A = np.nan*np.zeros((n,n))\n B = np.nan*np.zeros((n,n))\n X = np.nan*np.zeros((n, num_segments))\n for j in range(1,n+1):\n for t in range(j,num_segments+1):\n F[j-1,t-1] = np.inf\n I[j-1,t-1] = 0\n X[j-1,t-1] = 0\n (a,b,cost) = util.FitLineSegment(signal.iloc[0:j])\n A[j-1,0] = a\n B[j-1,0] = b\n X[j-1,0] = signal.index[0]\n F[j-1,0] = cost\n I[j-1,0] = 1\n for t in range(2,min(j,num_segments+1)):\n F[j-1,t-1] = np.inf\n I[j-1,t-1] = 0\n X[j-1,0] = 0\n for i in range(t,j):\n k = I[i-1,t-2]\n if k != 0 and A[k-1,i-1] != A[i-1,j-1]:\n (a, b, x, cost) = util.FitLineSegmentWithIntersection(signal, i, j-1, A[i-1,t-2], B[i-1,t-2], max(0,signal.index[i-1]), min(signal.index[n-1],signal.index[i]))\n\n if show_debug_plots and not np.isinf(cost):\n plt.figure()\n plt.plot(signal.index[0:j], signal.iloc[0:j], 'bo')\n new_line_x = np.array(signal.index[i-1:j])\n new_line_y = a*new_line_x + b\n plt.plot(new_line_x, new_line_y, 'g--')\n right_most_line_x = np.array(signal.index[0:i])\n right_most_line_y = A[i-1,t-2]*right_most_line_x + B[i-1,t-2]\n plt.plot(right_most_line_x, right_most_line_y, 'r-')\n plt.title(\"T=%d, i=%d, j=%d, Cost of new line: %f\"%(t, i, j, cost))\n plt.show()\n\n if F[j-1,t-1] > F[i-1,t-2] + cost:\n F[j-1,t-1] = F[i-1,t-2] + cost\n A[j-1,t-1] = a\n B[j-1,t-1] = b\n I[j-1,t-1] = i\n X[j-1,t-1] = x\n\n # Recover optimal approximation\n knots = [n]\n x = [signal.index[n-1]]\n i = n\n t = num_segments\n while t > 0:\n x.append(X[knots[-1]-1,t-1])\n knots.append(I[knots[-1]-1,t-1])\n t -= 1\n knots.reverse()\n x.reverse()\n y = [A[knots[1]-1,0]*x[0] + B[knots[1]-1,0]]\n t = 1\n for i in range(1,len(knots)-1):\n y.append(A[knots[i]-1,t-1]*x[i] + B[knots[i]-1,t-1])\n t += 1\n y.append(A[knots[-1]-1,t-1]*x[-1] + B[knots[-1]-1,t-1])\n\n print(\"Final approximation loss value: %f\"%(F[n-1, num_segments-1]))\n\n # Plot results\n plt.figure()\n plt.plot(time, signal, 'bo')\n plt.plot(x, y, 'r-o')\n plt.show()\n\n return\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--input', dest='input_csv', required=True, help='CSV-formatted input signal file with (first column: time, second: signal value)')\n parser.add_argument('--segments', dest='num_segments', required=True, help='Number of segments to use in the approximation')\n try:\n args = parser.parse_args()\n except:\n parser.print_help()\n sys.exit(0)\n input_csv_path = args.input_csv\n num_segments = int(args.num_segments)\n ComputeOptimalFit(input_csv_path, num_segments)\n"
] | [
[
"pandas.read_csv",
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.zeros",
"numpy.isinf",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
eddiejessup/spatious | [
"b7ae91bec029e85a45a7f303ee184076433723cd"
] | [
"spatious/distance.py"
] | [
"\"\"\"\nDistance finding functions inspired by scipy.spatial.distance.\n\"\"\"\n\nfrom __future__ import print_function, division\nimport numpy as np\nfrom spatious import vector\nfrom spatious.distance_numerics import pdist_angle\n\n\ndef csep(ra, rb):\n \"\"\"Return separation vectors between each pair of the two sets of points.\n\n Parameters\n ----------\n ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.\n Two sets of points.\n\n Returns\n -------\n csep: float array-like, shape (n, m, d)\n csep[i, j] is the separation vector from point j to point i.\n Note the un-intuitive vector direction.\n \"\"\"\n return ra[:, np.newaxis, :] - rb[np.newaxis, :, :]\n\n\ndef csep_close(ra, rb):\n \"\"\"Return the closest separation vector between each point in one set,\n and every point in a second set.\n\n Parameters\n ----------\n ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.\n Two sets of points. `ra` is the set of points from which the closest\n separation vectors to points `rb` are calculated.\n\n Returns\n -------\n csep_close: float array-like, shape (n, m, d)\n csep[i] is the closest separation vector from point ra[j]\n to any point rb[i].\n Note the un-intuitive vector direction.\n \"\"\"\n seps = csep(ra, rb)\n seps_sq = np.sum(np.square(seps), axis=-1)\n\n i_close = np.argmin(seps_sq, axis=-1)\n\n i_all = list(range(len(seps)))\n sep = seps[i_all, i_close]\n sep_sq = seps_sq[i_all, i_close]\n return sep, sep_sq\n\n\ndef csep_periodic(ra, rb, L):\n \"\"\"Return separation vectors between each pair of the two sets of points.\n\n Parameters\n ----------\n ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.\n Two sets of points.\n L: float array, shape (d,)\n System lengths.\n\n Returns\n -------\n csep: float array-like, shape (n, m, d)\n csep[i, j] is the separation vector from point j to point i.\n Note the un-intuitive vector direction.\n \"\"\"\n seps = ra[:, np.newaxis, :] - rb[np.newaxis, :, :]\n for i_dim in range(ra.shape[1]):\n seps_dim = seps[:, :, i_dim]\n seps_dim[seps_dim > L[i_dim] / 2.0] -= L[i_dim]\n seps_dim[seps_dim < -L[i_dim] / 2.0] += L[i_dim]\n return seps\n\n\ndef csep_periodic_close(ra, rb, L):\n \"\"\"Return the closest separation vector between each point in one set,\n and every point in a second set, in periodic space.\n\n Parameters\n ----------\n ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.\n Two sets of points. `ra` is the set of points from which the closest\n separation vectors to points `rb` are calculated.\n L: float array, shape (d,)\n System lengths.\n\n Returns\n -------\n csep_close: float array-like, shape (n, m, d)\n csep[i] is the closest separation vector from point ra[j]\n to any point rb[i].\n Note the un-intuitive vector direction.\n \"\"\"\n seps = csep_periodic(ra, rb, L)\n seps_sq = np.sum(np.square(seps), axis=-1)\n\n i_close = np.argmin(seps_sq, axis=-1)\n\n i_all = list(range(len(seps)))\n sep = seps[i_all, i_close]\n sep_sq = seps_sq[i_all, i_close]\n return sep, sep_sq\n\n\ndef cdist_sq_periodic(ra, rb, L):\n \"\"\"Return the squared distance between each point in on set,\n and every point in a second set, in periodic space.\n\n Parameters\n ----------\n ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.\n Two sets of points.\n L: float array, shape (d,)\n System lengths.\n\n Returns\n -------\n cdist_sq: float array-like, shape (n, m, d)\n cdist_sq[i, j] is the squared distance between point j and point i.\n \"\"\"\n return np.sum(np.square(csep_periodic(ra, rb, L)), axis=-1)\n\n\ndef pdist_sq_periodic(r, L):\n \"\"\"Return the squared distance between all combinations of\n a set of points, in periodic space.\n\n Parameters\n ----------\n r: shape (n, d) for n points in d dimensions.\n Set of points\n L: float array, shape (d,)\n System lengths.\n\n Returns\n -------\n d_sq: float array, shape (n, n, d)\n Squared distances\n \"\"\"\n d = csep_periodic(r, r, L)\n d[np.identity(len(r), dtype=np.bool)] = np.inf\n d_sq = np.sum(np.square(d), axis=-1)\n return d_sq\n\n\ndef angular_distance(n1, n2):\n \"\"\"Return the angular separation between two 3 dimensional vectors.\n\n Parameters\n ----------\n n1, n2: array-like, shape (3,)\n Coordinates of two vectors.\n Their magnitude does not matter.\n\n Returns\n -------\n d_sigma: float\n Angle between n1 and n2 in radians.\n \"\"\"\n return np.arctan2(vector.vector_mag(np.cross(n1, n2)), np.dot(n1, n2))\n"
] | [
[
"numpy.square",
"numpy.dot",
"numpy.argmin",
"numpy.cross"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
fhoeb/py-tmps | [
"b7eced582acb4042815a775090a59f569975e3be"
] | [
"tmps/star/itime/factory.py"
] | [
"\"\"\"\n Main interface factory functions for imaginary time evolution propagators (ITMPS, ITMPO, ITPMPS)\n\"\"\"\n\nfrom tmps.star.itime.itmps import StarITMPS\nfrom tmps.star.itime.itpmps import StarITPMPS\nfrom tmps.star.itime.itmpo import StarITMPO\nimport numpy as np\nfrom tmps.utils.shape import check_shape\n\n\ndef from_hamiltonian(psi_0, mpa_type, system_index, h_site, h_bond, tau=0.01, state_compression_kwargs=None,\n op_compression_kwargs=None, second_order_trotter=False, t0=0, psi_0_compression_kwargs=None,\n track_trace=False):\n \"\"\"\n Factory function for imaginary time TMP-objects (ITMPS, ITMPO, ITPMPS)\n :param psi_0: Initial state as MPArray. Need not be normalized, as it is normalized before propagation\n :param mpa_type: Type of MPArray to propagate, supported are mps, mpo, and pmps\n :param system_index: Index of the system site in the chain (place of the system site operator in the h_site list)\n :param h_site: Iterator over local site Hamiltonians. If a single numpy ndarray is passed\n this element is broadcast over all sites\n :param h_bond: Iterator over coupling Hamiltonians.\n Ordered like this:\n - Sites left of the system site (denoted by system index) couple (from left to right)\n the current site to the system site AS IF they were directly adjacent\n - Sites right of the system site (denoted by system index) couple (from left to right)\n the system site to the current site AS IF they were directly adjacent\n At system_index, the list/iterator may contain either None or the first coupling for the\n site immediately to the right of the system. If a a single numpy ndarray is passed\n this element is broadcast over all sites\n :param tau: Timestep for each invocation of evolve. Real timestep should be passed here. Default is .01\n :param state_compression_kwargs: Arguments for mpa compression after each dot product (see real time\n evolution factory function for details)\n :param op_compression_kwargs: Arguments for trotter step operator pre-compression (see real time evolution\n factory function for details)\n :param second_order_trotter: Switch to use second order instead of fourth order trotter if desired\n By default fourth order Trotter is used\n :param t0: Initial time of the propagation\n :param psi_0_compression_kwargs: Optional compresion kwargs for the initial state (see real time evolution\n factory function for details)\n :param track_trace: If the trace of the (effective) density matrix should be tracked during the\n imaginary time evolution\n :return: TMP object. If mpa_type is mps: ITMPS obj., if mpa_type is mpo: ITMPO obj.,\n if mpa_type is pmps: ITPMPS obj.\n \"\"\"\n if not check_shape(psi_0, mpa_type):\n raise AssertionError('MPA shape of the initial state is not compatible with the chosen mpa_type')\n assert np.imag(tau) == 0 and np.real(tau) != 0\n tau = 1j * tau\n if mpa_type == 'mps':\n return StarITMPS.from_hamiltonian(psi_0, False, False, system_index, h_site, h_bond, tau=tau,\n state_compression_kwargs=state_compression_kwargs,\n op_compression_kwargs=op_compression_kwargs,\n second_order_trotter=second_order_trotter, t0=t0,\n psi_0_compression_kwargs=psi_0_compression_kwargs,\n track_trace=track_trace)\n elif mpa_type == 'pmps':\n return StarITPMPS.from_hamiltonian(psi_0, True, False, system_index, h_site, h_bond, tau=tau,\n state_compression_kwargs=state_compression_kwargs,\n op_compression_kwargs=op_compression_kwargs,\n second_order_trotter=second_order_trotter, t0=t0,\n psi_0_compression_kwargs=psi_0_compression_kwargs,\n track_trace=track_trace)\n elif mpa_type == 'mpo':\n return StarITMPO.from_hamiltonian(psi_0, False, True, system_index, h_site, h_bond, tau=tau,\n state_compression_kwargs=state_compression_kwargs,\n op_compression_kwargs=op_compression_kwargs,\n second_order_trotter=second_order_trotter, t0=t0,\n psi_0_compression_kwargs=psi_0_compression_kwargs,\n track_trace=track_trace)\n else:\n raise AssertionError('Unsupported mpa_type')\n\n\ndef from_hi(psi_0, mpa_type, system_index, hi, tau=0.01, state_compression_kwargs=None,\n op_compression_kwargs=None, second_order_trotter=False, t0=0, psi_0_compression_kwargs=None,\n track_trace=False):\n \"\"\"\n Factory function for imaginary time TMP-objects (ITMPS, ITMPO, ITPMPS)\n :param psi_0: Initial state as MPArray. Need not be normalized, as it is normalized before propagation\n :param mpa_type: Type of MPArray to propagate, supported are mps, mpo, and pmps\n :param system_index: Index of the system site in the chain (place of the system site operator in the hi_list)\n :param hi: List/tuple for all terms in the Hamiltonian H = sum_i hi\n Ordered like this:\n - Sites left of the system site (denoted by system index) couple (from left to right)\n the current site to the system site (and contain the site local operators)\n - The term for the system site must be present and contains the local Hamiltonian only!\n May be None, in which case the local Hamiltonian for the site is assumed to be 0\n - Sites right of the system site (denoted by system index) couple (from left to right)\n the system site to the current site (and contain the site local operators)\n :param tau: Timestep for each invocation of evolve. Real timestep should be passed here. Default is .01\n :param state_compression_kwargs: Arguments for mpa compression after each dot product (see real time\n evolution factory function for details)\n :param op_compression_kwargs: Arguments for trotter step operator pre-compression (see real time evolution\n factory function for details)\n :param second_order_trotter: Switch to use second order instead of fourth order trotter if desired\n By default fourth order Trotter is used\n :param t0: Initial time of the propagation\n :param psi_0_compression_kwargs: Optional compresion kwargs for the initial state (see real time evolution\n factory function for details)\n :param track_trace: If the trace of the (effective) density matrix should be tracked during the\n imaginary time evolution\n :return: TMP object. If mpa_type is mps: ITMPS obj., if mpa_type is mpo: ITMPO obj., if mpa_type is pmps: ITPMPS obj.\n \"\"\"\n if not check_shape(psi_0, mpa_type):\n raise AssertionError('MPA shape of the initial state is not compatible with the chosen mpa_type')\n assert np.imag(tau) == 0 and np.real(tau) != 0\n tau = 1j * tau\n if mpa_type == 'mps':\n return StarITMPS.from_hi(psi_0, False, False, system_index, hi, tau=tau,\n state_compression_kwargs=state_compression_kwargs,\n op_compression_kwargs=op_compression_kwargs,\n second_order_trotter=second_order_trotter, t0=t0,\n psi_0_compression_kwargs=psi_0_compression_kwargs,\n track_trace=track_trace)\n elif mpa_type == 'pmps':\n return StarITPMPS.from_hi(psi_0, True, False, system_index, hi, tau=tau,\n state_compression_kwargs=state_compression_kwargs,\n op_compression_kwargs=op_compression_kwargs,\n second_order_trotter=second_order_trotter, t0=t0,\n psi_0_compression_kwargs=psi_0_compression_kwargs,\n track_trace=track_trace)\n elif mpa_type == 'mpo':\n return StarITMPO.from_hi(psi_0, False, True, system_index, hi, tau=tau,\n state_compression_kwargs=state_compression_kwargs,\n op_compression_kwargs=op_compression_kwargs,\n second_order_trotter=second_order_trotter, t0=t0,\n psi_0_compression_kwargs=psi_0_compression_kwargs,\n track_trace=track_trace)\n else:\n raise AssertionError('Unsupported mpa_type')\n"
] | [
[
"numpy.real",
"numpy.imag"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
willthefrog/models | [
"6b296d7319f27eee4437b7916dae8cf0d9e94970"
] | [
"PaddleCV/object_detection/ppdet/utils/visualizer.py"
] | [
"# Copyright (c) 2019 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\nfrom __future__ import unicode_literals\n\nimport numpy as np\nimport pycocotools.mask as mask_util\nfrom PIL import Image, ImageDraw\n\nfrom .colormap import colormap\n\n__all__ = ['visualize_results']\n\n\ndef visualize_results(image,\n catid2name,\n threshold=0.5,\n bbox_results=None,\n mask_results=None):\n \"\"\"\n Visualize bbox and mask results\n \"\"\"\n if mask_results:\n image = draw_mask(image, mask_results, threshold)\n if bbox_results:\n image = draw_bbox(image, catid2name, bbox_results, threshold)\n return image\n\n\ndef draw_mask(image, segms, threshold, alpha=0.7):\n \"\"\"\n Draw mask on image\n \"\"\"\n im_width, im_height = image.size\n mask_color_id = 0\n w_ratio = .4\n img_array = np.array(image).astype('float32')\n for dt in np.array(segms):\n segm, score = dt['segmentation'], dt['score']\n if score < threshold:\n continue\n mask = mask_util.decode(segm) * 255\n color_list = colormap(rgb=True)\n color_mask = color_list[mask_color_id % len(color_list), 0:3]\n mask_color_id += 1\n for c in range(3):\n color_mask[c] = color_mask[c] * (1 - w_ratio) + w_ratio * 255\n idx = np.nonzero(mask)\n img_array[idx[0], idx[1], :] *= 1.0 - alpha\n img_array[idx[0], idx[1], :] += alpha * color_mask\n return Image.fromarray(img_array.astype('uint8'))\n\n\ndef draw_bbox(image, catid2name, bboxes, threshold):\n \"\"\"\n Draw bbox on image\n \"\"\"\n draw = ImageDraw.Draw(image)\n im_width, im_height = image.size\n\n for dt in np.array(bboxes):\n catid, bbox, score = dt['category_id'], dt['bbox'], dt['score']\n if score < threshold:\n continue\n xmin, ymin, w, h = bbox\n xmax = xmin + w\n ymax = ymin + h\n draw.line(\n [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin),\n (xmin, ymin)],\n width=2,\n fill='red')\n if image.mode == 'RGB':\n draw.text((xmin, ymin), catid2name[catid], (255, 255, 0))\n\n return image\n"
] | [
[
"numpy.array",
"numpy.nonzero"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
davWilk/udemy_courses | [
"916f42eddd02400e4b8a1600e86514f28e7009b1"
] | [
"udemy Model Predictive Control/assignment3.py"
] | [
"from pyexpat.errors import XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING\nfrom re import X\nimport numpy as np\nfrom sim.sim2d import sim_run\n\n# Simulator options.\noptions = {}\noptions['FIG_SIZE'] = [8,8]\noptions['OBSTACLES'] = True\n\nclass Point:\n def __init__(self, r, theta):\n self.r = r\n self.theta = theta\n\nclass ModelPredictiveControl:\n def __init__(self):\n self.horizon = 2\n self.dt = 0.2\n\n self.pedal_upper_lim = 5\n self.pedal_lower_lim = -5\n\n self.steering_upper_lim = 0.8\n self.steering_lower_lim = -0.8\n\n # Reference or set point the controller will achieve.\n self.reference1 = [10, 0, 0]\n self.reference2 = [2, 4, 3.14/3]\n\n self.x_obs = 5\n self.y_obs = 0.1\n\n\n # Array of points around vehicle where distance\n # sensors would be placed.\n # Required for enhanced obstacle avoidance.\n # These points are all RELATIVE to the mid-rear of vehicle, and are\n # modelled as if the vehicle was facing to the right. \n # See below diagram:\n #\n # #-----1------#\n # | |\n # O (2.5x1) 2\n # | |\n # #-----3------#\n # The points are in (r,theta) form thus angles need to be added to current vehicle angle\n # to get ABSOLUTE points\n\n # 7 sensors behaves on par with having 4 sensors\n # self.sensor_points = [Point(0,0), Point(0.5, 1.571), Point(1.346, 0.381), Point(2.550, 0.197), \n # Point(2.5, 0), Point(2.550, -0.197), Point(1.346, -0.381), Point(0.5, -1.571)]\n\n self.sensor_points = [Point(0,0), Point(1.346, 0.381), \n Point(2.5, 0), Point(1.346, -0.381)]\n\n def plant_model(self,prev_state, dt, pedal, steering):\n x_t = prev_state[0]\n y_t = prev_state[1]\n psi_t = prev_state[2]\n v_t = prev_state[3]\n\n # Assumption of 1:1 relationship between pedal/acceleration and steering/wheel angle\n a_t = pedal\n beta = steering\n\n v_t = 0.96*v_t + a_t * dt\n x_t += (v_t * np.cos(psi_t)) * dt\n y_t += (v_t * np.sin(psi_t)) * dt\n\n psi_t += (v_t * np.tan(beta) / 2.5) * dt\n\n return [x_t, y_t, psi_t, v_t]\n\n def cost_function(self,u, *args):\n state = args[0]\n ref = args[1]\n cost = 0.0\n\n for k in range(self.horizon):\n v_t_init = state[2]\n\n state = self.plant_model(state, self.dt, u[2*k], u[2*k+1])\n\n phi_t = state[2]\n x_t = state[0]\n y_t = state[1]\n v_t = state[3]\n\n error_phi_abs = abs(ref[2] - state[2])\n error_x_abs = abs(ref[0] - state[0])\n error_y_abs = abs(ref[1] - state[1])\n # x/y costs\n cost += 0.5*error_x_abs ** 2 + 5*error_x_abs\n cost += 0.5*error_y_abs ** 2 + 5*error_y_abs\n\n # angle cost\n cost += 1.5*error_phi_abs**2# + error_phi_abs\n\n # Steering position cost - VERY large penalty for exceeding bounds of wheel\n # Steering wheel movement is constrained to +/- 0.8rad\n if u[2*k+1] > self.steering_upper_lim:\n cost += abs(u[2*k+1] - self.steering_upper_lim) * 10\n elif u[2*k+1] < self.steering_lower_lim:\n cost += abs(u[2*k+1] - self.steering_lower_lim) * 10\n\n # Pedal position cost\n if u[2*k] > self.pedal_upper_lim:\n cost += abs(u[2*k] - self.pedal_upper_lim) * 10\n if u[2*k] < self.pedal_lower_lim:\n cost += abs(u[2*k] - self.pedal_lower_lim) * 10\n\n\n # penalty for approaching obstacle \n # Cost is implemented such that cost increases much\n # faster as vehicle approaches the obstacle.\n # This should deter the optimizer from\n # solving to such position.\n dist = 0\n for point in self.sensor_points:\n _x = x_t + (point.r * np.cos(point.theta + phi_t))\n _y = y_t + (point.r * np.sin(point.theta + phi_t))\n\n x_dist = abs(self.x_obs - _x)\n y_dist = abs(self.y_obs - _y)\n dist += np.sqrt((x_dist**2)+(y_dist**2))\n\n # Protecting for div by zero\n if dist < 0.00001:\n dist = 0.00001\n cost += 20/(dist)\n \n # Speed limit penalty\n speed_kph = v_t * 3.6\n if abs(speed_kph) > 15:\n cost += (abs(speed_kph) - 15) * 1\n\n # Acceleration cost\n cost += (state[3] - v_t_init) ** 2 * 0.1\n \n\n return cost\n\nsim_run(options, ModelPredictiveControl)\n"
] | [
[
"numpy.tan",
"numpy.sqrt",
"numpy.cos",
"numpy.sin"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jungokasai/deep-shallow | [
"605cac3bd282d814f67774b394f722cbc064c69f"
] | [
"fairseq/models/nat/cmlm_at.py"
] | [
"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"\nThis file implements:\nFast Structured Decoding of Non-autoregressive Transformers\n\"\"\"\nimport torch\nimport torch.nn.functional as F\n\nfrom fairseq import utils\nfrom fairseq.models import (\nregister_model,\nregister_model_architecture,\n)\nfrom fairseq.models.nat import (\nNATransformerDecoder,\nCMLMNATransformerModel,\nensemble_decoder,\n)\nfrom fairseq.models.transformer import TransformerDecoder\nfrom fairseq.models.nat import NATransformerDecoder\nfrom fairseq.utils import new_arange\nfrom fairseq.iterative_refinement_generator import DecoderOut\nfrom fairseq.models.fairseq_encoder import EncoderOut\nfrom typing import Any, Dict, List, Optional, Tuple\nfrom torch import Tensor\nfrom fairseq.modules.transformer_sentence_encoder import init_bert_params\nfrom copy import deepcopy\n\n\n@register_model(\"cmlm_at\")\nclass CMLMATModel(CMLMNATransformerModel):\n @staticmethod\n def add_args(parser):\n CMLMNATransformerModel.add_args(parser)\n\n @classmethod\n def build_decoder(cls, args, tgt_dict, embed_tokens):\n decoder = CMLMATDecoder(args, tgt_dict, embed_tokens)\n if getattr(args, \"apply_bert_init\", False):\n decoder.apply(init_bert_params)\n return decoder\n\n def forward(\n self, src_tokens, src_lengths, prev_output_tokens, tgt_tokens, **kwargs\n ):\n # Because of torch jit, this is never called in inference. \n # We call encoder.forward and decoder.forward separately\n assert not self.decoder.bottom_nat.src_embedding_copy, \"do not support embedding copy.\"\n\n # encoding\n encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)\n\n # get rid of bos for AT consistency\n prev_output_tokens = prev_output_tokens[:, 1:]\n tgt_tokens = tgt_tokens[:, 1:]\n\n\n padded_tgt_lengths = (src_lengths*1.2+10).long() # [B]\n max_tgt_length = padded_tgt_lengths.max()\n bsz, seq_len = tgt_tokens.size()\n prev_output_tokens_new = prev_output_tokens.new_ones([bsz, max_tgt_length])*self.pad\n tgt_tokens_new = tgt_tokens.new_ones([bsz, max_tgt_length])*self.pad\n\n arange_mat = torch.arange(max_tgt_length, \n device=prev_output_tokens.device).squeeze(0).repeat([bsz, 1])\n # Fill in eos's\n prev_output_tokens_new = prev_output_tokens_new.masked_fill(\n arange_mat<padded_tgt_lengths.unsqueeze(1), self.eos)\n tgt_tokens_new = tgt_tokens_new.masked_fill(\n arange_mat<padded_tgt_lengths.unsqueeze(1), self.eos)\n # Fill in actual tokens\n non_pad_mask = prev_output_tokens.ne(self.pad)\n prev_output_tokens_new = prev_output_tokens_new.masked_scatter(\n arange_mat<non_pad_mask.sum(1, keepdim=True), prev_output_tokens[non_pad_mask])\n tgt_tokens_new = tgt_tokens_new.masked_scatter(\n arange_mat<non_pad_mask.sum(1, keepdim=True), tgt_tokens[non_pad_mask])\n\n\n if self.training:\n # mask eos from left\n nb_eos = prev_output_tokens_new.eq(self.eos).sum(1, keepdim=True)\n nb_masked_eos = (nb_eos.float().uniform_()*nb_eos).long() + 1\n eos_start_idxes = non_pad_mask.sum(1, keepdim=True) - 1\n # -1 for the original eos\n eos_masking = (eos_start_idxes <= arange_mat) & (arange_mat< eos_start_idxes + nb_masked_eos)\n prev_output_tokens_new = prev_output_tokens_new.masked_fill(\n eos_masking, self.unk) \n\n prev_output_tokens = prev_output_tokens_new\n tgt_tokens = tgt_tokens_new\n\n\n # decoding\n word_ins_out, word_ins_out_at, prev_output_tokens_at = self.decoder(\n prev_output_tokens=prev_output_tokens,\n encoder_out=encoder_out,\n tgt_tokens=tgt_tokens,\n normalize=False,\n )\n word_ins_mask = prev_output_tokens.eq(self.unk)\n word_ins_mask_at = prev_output_tokens_at.ne(self.pad) & word_ins_mask\n\n return {\n #\"word_ins\": {\n # \"out\": word_ins_out, \"tgt\": tgt_tokens,\n # \"mask\": word_ins_mask, \"ls\": self.args.label_smoothing,\n # \"nll_loss\": True,\n # #\"factor\": 0.5,\n #},\n \"word_ins_at\": {\n \"out\": word_ins_out_at, \"tgt\": tgt_tokens,\n \"mask\": word_ins_mask_at, \"ls\": self.args.label_smoothing,\n \"nll_loss\": True,\n #\"factor\": 0.5,\n },\n }\n\n# @torch.jit.export\n# def get_normalized_probs(\n# self,\n# net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]],\n# log_probs: bool,\n# sample: Optional[Dict[str, Tensor]] = None,\n# ):\n# \"\"\"Get normalized probabilities (or log probs) from a net's output.\"\"\"\n# return self.get_normalized_probs_scriptable(net_output, log_probs, sample)\n\n\nclass CMLMATDecoder(TransformerDecoder):\n def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False):\n # Lite\n lite_args = deepcopy(args)\n lite_args.decoder_layers = 1\n super().__init__(\n lite_args, dictionary, embed_tokens, no_encoder_attn,\n )\n self.bottom_nat = NATransformerDecoder(\n args, dictionary, embed_tokens, no_encoder_attn,\n )\n self.bos = dictionary.bos()\n self.unk = dictionary.unk()\n self.eos = dictionary.eos()\n self.pad = dictionary.pad()\n\n def forward_at(\n self,\n prev_output_tokens,\n encoder_out: Optional[EncoderOut] = None,\n incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,\n features_only: bool = False,\n alignment_layer: Optional[int] = None,\n alignment_heads: Optional[int] = None,\n src_lengths: Optional[Any] = None,\n return_all_hiddens: bool = False,\n bottom_features: Optional[Tensor] = None,\n **unused,\n ):\n \"\"\"\n Args:\n prev_output_tokens (LongTensor): previous decoder outputs of shape\n `(batch, tgt_len)`, for teacher forcing\n encoder_out (optional): output from the encoder, used for\n encoder-side attention\n incremental_state (dict): dictionary used for storing state during\n :ref:`Incremental decoding`\n features_only (bool, optional): only return features without\n applying output layer (default: False).\n\n Returns:\n tuple:\n - the decoder's output of shape `(batch, tgt_len, vocab)`\n - a dictionary with any model-specific outputs\n \"\"\"\n x, extra = self.extract_features(\n prev_output_tokens,\n encoder_out=encoder_out,\n incremental_state=incremental_state,\n alignment_layer=alignment_layer,\n alignment_heads=alignment_heads,\n bottom_features = bottom_features,\n )\n if not features_only:\n x = self.output_layer(x)\n return x, extra\n\n def extract_features(\n self,\n prev_output_tokens,\n encoder_out: Optional[EncoderOut] = None,\n incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,\n full_context_alignment: bool = False,\n alignment_layer: Optional[int] = None,\n alignment_heads: Optional[int] = None,\n bottom_features = None,\n ):\n \"\"\"\n Similar to *forward* but only return features.\n\n Includes several features from \"Jointly Learning to Align and\n Translate with Transformer Models\" (Garg et al., EMNLP 2019).\n\n Args:\n full_context_alignment (bool, optional): don't apply\n auto-regressive mask to self-attention (default: False).\n alignment_layer (int, optional): return mean alignment over\n heads at this layer (default: last layer).\n alignment_heads (int, optional): only average alignment over\n this many heads (default: all heads).\n\n Returns:\n tuple:\n - the decoder's features of shape `(batch, tgt_len, embed_dim)`\n - a dictionary with any model-specific outputs\n \"\"\"\n assert bottom_features is not None\n if alignment_layer is None:\n alignment_layer = self.num_layers - 1\n\n # embed positions\n positions = (\n self.embed_positions(\n prev_output_tokens, incremental_state=incremental_state\n )\n if self.embed_positions is not None\n else None\n )\n if incremental_state is not None:\n step = prev_output_tokens.size(1) - 1\n prev_output_tokens = prev_output_tokens[:, -1:]\n if positions is not None:\n positions = positions[:, -1:]\n # add bottom features\n if bottom_features is not None:\n nat_len = bottom_features.size(1)\n # if we already exceeded predicted length from NAT, skip for now.\n # TODO: maybe epsilon training?\n if nat_len > step:\n bottom_features = bottom_features[:, step:step+1]\n else:\n bottom_features = None\n\n if (bottom_features is not None) and (positions is not None):\n bottom_features = bottom_features*0.0\n positions = positions + bottom_features\n\n # embed tokens and positions\n x = self.embed_scale * self.embed_tokens(prev_output_tokens)\n\n\n if self.project_in_dim is not None:\n x = self.project_in_dim(x)\n\n if positions is not None:\n x += positions\n\n if self.layernorm_embedding is not None:\n x = self.layernorm_embedding(x)\n\n x = F.dropout(x, p=self.dropout, training=self.training)\n\n # B x T x C -> T x B x C\n x = x.transpose(0, 1)\n\n self_attn_padding_mask: Optional[Tensor] = None\n if self.cross_self_attention or prev_output_tokens.eq(self.padding_idx).any():\n self_attn_padding_mask = prev_output_tokens.eq(self.padding_idx)\n\n # decoder layers\n attn: Optional[Tensor] = None\n inner_states: List[Optional[Tensor]] = [x]\n for idx, layer in enumerate(self.layers):\n encoder_state: Optional[Tensor] = None\n if encoder_out is not None:\n if self.layer_wise_attention:\n encoder_states = encoder_out.encoder_states\n assert encoder_states is not None\n encoder_state = encoder_states[idx]\n else:\n encoder_state = encoder_out.encoder_out\n\n if incremental_state is None and not full_context_alignment:\n self_attn_mask = self.buffered_future_mask(x)\n else:\n self_attn_mask = None\n\n # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n dropout_probability = torch.empty(1).uniform_()\n if not self.training or (dropout_probability > self.decoder_layerdrop):\n x, layer_attn, _ = layer(\n x,\n encoder_state,\n encoder_out.encoder_padding_mask\n if encoder_out is not None\n else None,\n incremental_state,\n self_attn_mask=self_attn_mask,\n self_attn_padding_mask=self_attn_padding_mask,\n need_attn=bool((idx == alignment_layer)),\n need_head_weights=bool((idx == alignment_layer)),\n )\n inner_states.append(x)\n if layer_attn is not None and idx == alignment_layer:\n attn = layer_attn.float().to(x)\n\n if attn is not None:\n if alignment_heads is not None:\n attn = attn[:alignment_heads]\n\n # average probabilities over heads\n attn = attn.mean(dim=0)\n\n if self.layer_norm is not None:\n x = self.layer_norm(x)\n\n # T x B x C -> B x T x C\n x = x.transpose(0, 1)\n\n if self.project_out_dim is not None:\n x = self.project_out_dim(x)\n\n return x, {\"attn\": [attn], \"inner_states\": inner_states}\n\n \n\n\n def forward(\n self,\n prev_output_tokens,\n encoder_out: Optional[EncoderOut] = None,\n tgt_tokens: Optional[Tensor] = None,\n incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,\n features_only: bool = False,\n alignment_layer: Optional[int] = None,\n alignment_heads: Optional[int] = None,\n src_lengths: Optional[Any] = None,\n return_all_hiddens: bool = False,\n inference: bool = False,\n normalize: bool = True,\n **unused\n ):\n\n step = prev_output_tokens.size(1) - 1\n if not inference:\n # Training so always extract features\n bottom_features, _ = self.bottom_nat.extract_features(\n prev_output_tokens,\n encoder_out=encoder_out,\n embedding_copy=(step == 0) & self.bottom_nat.src_embedding_copy,\n )\n decoder_out = self.bottom_nat.output_layer(bottom_features)\n prev_output_tokens = tgt_tokens.clone()\n prev_output_tokens[:, 1:] = tgt_tokens[:, :-1]\n prev_output_tokens.masked_fill_(\n prev_output_tokens.eq(self.eos), self.pad\n )\n prev_output_tokens[:, 0] = self.eos\n decoder_out_at, _ = self.forward_at(\n prev_output_tokens,\n encoder_out=encoder_out,\n bottom_features=bottom_features,\n )\n if normalize:\n return F.log_softmax(decoder_out, -1), F.log_softmax(decoder_out_at, -1)\n else:\n return decoder_out, decoder_out_at, prev_output_tokens\n\n if step == 0 and inference:\n assert not self.training\n # only when this is the first step, run the bottom NAT\n decoder_out = self.initialize_output_tokens(encoder_out, prev_output_tokens)\n # bottom_features: [B, T_tgt, C]\n # encoder_out.encoder_out: [T_src, B, C]\n bottom_features, _ = self.bottom_nat.extract_features(\n decoder_out.output_tokens,\n encoder_out=encoder_out,\n embedding_copy=(step == 0) & self.bottom_nat.src_embedding_copy,\n )\n encoder_out = encoder_out._replace(\n bottom_features = bottom_features,\n )\n\n else:\n assert not self.training\n # Done with step 0\n #print(step, prev_output_tokens)\n bottom_features = encoder_out.bottom_features\n\n decoder_out_at = self.forward_at(\n prev_output_tokens,\n encoder_out=encoder_out,\n tgt_tokens=tgt_tokens,\n incremental_state=incremental_state,\n features_only=features_only,\n alignment_layer=alignment_layer,\n alignment_heads=alignment_heads,\n src_lengths=src_lengths,\n return_all_hiddens=return_all_hiddens,\n bottom_features=bottom_features,\n )\n\n return decoder_out_at, encoder_out\n\n def initialize_output_tokens(self, encoder_out, prev_output_tokens):\n # length prediction\n src_lengths = (~encoder_out.encoder_padding_mask).sum(1, keepdim=True)\n length_tgt = (src_lengths*1.2+10).long()\n max_length_tgt = length_tgt.max()\n bsz = prev_output_tokens.size(0)\n\n initial_output_tokens = prev_output_tokens.new_ones([bsz, max_length_tgt])*self.pad\n arange_mat = torch.arange(max_length_tgt, \n device=prev_output_tokens.device).squeeze(0).repeat([bsz, 1])\n initial_output_tokens = initial_output_tokens.masked_fill(\n arange_mat < length_tgt-1, self.unk)\n initial_output_tokens = initial_output_tokens.masked_fill(\n arange_mat.eq(length_tgt-1), self.eos)\n\n initial_output_scores = initial_output_tokens.new_zeros(\n *initial_output_tokens.size()\n ).type_as(encoder_out.encoder_out)\n\n return DecoderOut(\n output_tokens=initial_output_tokens,\n output_scores=initial_output_scores,\n attn=None,\n step=0,\n max_step=10000,\n history=None\n )\n\n\n@register_model_architecture(\"cmlm_at\", \"cmlm_at\")\ndef cmlmat_base_architecture(args):\n args.encoder_embed_path = getattr(args, \"encoder_embed_path\", None)\n args.encoder_embed_dim = getattr(args, \"encoder_embed_dim\", 512)\n args.encoder_ffn_embed_dim = getattr(args, \"encoder_ffn_embed_dim\", 2048)\n args.encoder_layers = getattr(args, \"encoder_layers\", 6)\n args.encoder_attention_heads = getattr(args, \"encoder_attention_heads\", 8)\n args.encoder_normalize_before = getattr(args, \"encoder_normalize_before\", False)\n args.encoder_learned_pos = getattr(args, \"encoder_learned_pos\", False)\n args.decoder_embed_path = getattr(args, \"decoder_embed_path\", None)\n args.decoder_embed_dim = getattr(args, \"decoder_embed_dim\", args.encoder_embed_dim)\n args.decoder_ffn_embed_dim = getattr(\n args, \"decoder_ffn_embed_dim\", args.encoder_ffn_embed_dim\n )\n args.decoder_layers = getattr(args, \"decoder_layers\", 6)\n args.decoder_attention_heads = getattr(args, \"decoder_attention_heads\", 8)\n args.decoder_normalize_before = getattr(args, \"decoder_normalize_before\", False)\n args.decoder_learned_pos = getattr(args, \"decoder_learned_pos\", False)\n args.attention_dropout = getattr(args, \"attention_dropout\", 0.0)\n args.activation_dropout = getattr(args, \"activation_dropout\", 0.0)\n args.activation_fn = getattr(args, \"activation_fn\", \"relu\")\n args.dropout = getattr(args, \"dropout\", 0.1)\n args.adaptive_softmax_cutoff = getattr(args, \"adaptive_softmax_cutoff\", None)\n args.adaptive_softmax_dropout = getattr(args, \"adaptive_softmax_dropout\", 0)\n args.share_decoder_input_output_embed = getattr(\n args, \"share_decoder_input_output_embed\", False\n )\n args.share_all_embeddings = getattr(args, \"share_all_embeddings\", True)\n args.no_token_positional_embeddings = getattr(\n args, \"no_token_positional_embeddings\", False\n )\n args.adaptive_input = getattr(args, \"adaptive_input\", False)\n args.apply_bert_init = getattr(args, \"apply_bert_init\", False)\n\n args.decoder_output_dim = getattr(\n args, \"decoder_output_dim\", args.decoder_embed_dim\n )\n args.decoder_input_dim = getattr(args, \"decoder_input_dim\", args.decoder_embed_dim)\n\n # --- special arguments ---\n args.sg_length_pred = getattr(args, \"sg_length_pred\", False)\n args.pred_length_offset = getattr(args, \"pred_length_offset\", False)\n args.length_loss_factor = getattr(args, \"length_loss_factor\", 0.1)\n args.ngram_predictor = getattr(args, \"ngram_predictor\", 1)\n args.src_embedding_copy = getattr(args, \"src_embedding_copy\", False)\n\n\n@register_model_architecture(\"cmlm_at\", \"cmlm_at_wmt_en_de\")\ndef cmlmat_wmt_en_de(args):\n cmlm_base_architecture(args)\n"
] | [
[
"torch.arange",
"torch.empty",
"torch.nn.functional.log_softmax",
"torch.nn.functional.dropout"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Shoebhabeeb/Image_Superresolution | [
"47605afb4a4723a5f4d46c2d27213930af12974f"
] | [
"src/models/Deep BackProp NN.py"
] | [
"import torch\nimport math\nimport torch.nn as nn\n\n\nclass DBPN(nn.Module):\n def __init__(self, num_channels, base_channels, feat_channels, num_stages, scale_factor):\n super(DBPN, self).__init__()\n\n if scale_factor == 2:\n kernel_size = 6\n stride = 2\n padding = 2\n elif scale_factor == 4:\n kernel_size = 8\n stride = 4\n padding = 2\n elif scale_factor == 8:\n kernel_size = 12\n stride = 8\n padding = 2\n else:\n kernel_size = None\n stride = None\n padding = None\n Warning(\"please choose the scale factor from 2, 4, 8\")\n exit()\n\n # Initial Feature Extraction\n self.feat0 = ConvBlock(num_channels, feat_channels, 3, 1, 1, activation='prelu', norm=None)\n self.feat1 = ConvBlock(feat_channels, base_channels, 1, 1, 0, activation='prelu', norm=None)\n # Back-projection stages\n self.up1 = UpBlock(base_channels, kernel_size, stride, padding)\n self.down1 = DownBlock(base_channels, kernel_size, stride, padding)\n self.up2 = UpBlock(base_channels, kernel_size, stride, padding)\n self.down2 = D_DownBlock(base_channels, kernel_size, stride, padding, 2)\n self.up3 = D_UpBlock(base_channels, kernel_size, stride, padding, 2)\n self.down3 = D_DownBlock(base_channels, kernel_size, stride, padding, 3)\n self.up4 = D_UpBlock(base_channels, kernel_size, stride, padding, 3)\n self.down4 = D_DownBlock(base_channels, kernel_size, stride, padding, 4)\n self.up5 = D_UpBlock(base_channels, kernel_size, stride, padding, 4)\n self.down5 = D_DownBlock(base_channels, kernel_size, stride, padding, 5)\n self.up6 = D_UpBlock(base_channels, kernel_size, stride, padding, 5)\n self.down6 = D_DownBlock(base_channels, kernel_size, stride, padding, 6)\n self.up7 = D_UpBlock(base_channels, kernel_size, stride, padding, 6)\n # Reconstruction\n self.output_conv = ConvBlock(num_stages * base_channels, num_channels, 3, 1, 1, activation=None, norm=None)\n\n def weight_init(self):\n for m in self._modules:\n class_name = m.__class__.__name__\n if class_name.find('Conv2d') != -1:\n torch.nn.init.kaiming_normal(m.weight)\n if m.bias is not None:\n m.bias.data.zero_()\n elif class_name.find('ConvTranspose2d') != -1:\n torch.nn.init.kaiming_normal(m.weight)\n if m.bias is not None:\n m.bias.data.zero_()\n\n def forward(self, x):\n x = self.feat0(x)\n x = self.feat1(x)\n\n h1 = self.up1(x)\n l1 = self.down1(h1)\n h2 = self.up2(l1)\n\n concat_h = torch.cat((h2, h1), 1)\n l = self.down2(concat_h)\n\n concat_l = torch.cat((l, l1), 1)\n h = self.up3(concat_l)\n\n concat_h = torch.cat((h, concat_h), 1)\n l = self.down3(concat_h)\n\n concat_l = torch.cat((l, concat_l), 1)\n h = self.up4(concat_l)\n\n concat_h = torch.cat((h, concat_h), 1)\n l = self.down4(concat_h)\n\n concat_l = torch.cat((l, concat_l), 1)\n h = self.up5(concat_l)\n\n concat_h = torch.cat((h, concat_h), 1)\n l = self.down5(concat_h)\n\n concat_l = torch.cat((l, concat_l), 1)\n h = self.up6(concat_l)\n\n concat_h = torch.cat((h, concat_h), 1)\n l = self.down6(concat_h)\n\n concat_l = torch.cat((l, concat_l), 1)\n h = self.up7(concat_l)\n\n concat_h = torch.cat((h, concat_h), 1)\n x = self.output_conv(concat_h)\n\n return x\n\n\nclass DBPNS(nn.Module):\n def __init__(self, num_channels, base_channels, feat_channels, num_stages, scale_factor):\n super(DBPNS, self).__init__()\n\n if scale_factor == 2:\n kernel_size = 6\n stride = 2\n padding = 2\n elif scale_factor == 4:\n kernel_size = 8\n stride = 4\n padding = 2\n elif scale_factor == 8:\n kernel_size = 12\n stride = 8\n padding = 2\n else:\n kernel_size = None\n stride = None\n padding = None\n Warning(\"please choose the scale factor from 2, 4, 8\")\n exit()\n\n # Initial Feature Extraction\n self.feat0 = ConvBlock(num_channels, feat_channels, 3, 1, 1, activation='prelu', norm=None)\n self.feat1 = ConvBlock(feat_channels, base_channels, 1, 1, 0, activation='prelu', norm=None)\n # Back-projection stages\n self.up1 = UpBlock(base_channels, kernel_size, stride, padding)\n self.down1 = DownBlock(base_channels, kernel_size, stride, padding)\n self.up2 = UpBlock(base_channels, kernel_size, stride, padding)\n # Reconstruction\n self.output_conv = ConvBlock(num_stages * base_channels, num_channels, 3, 1, 1, activation=None, norm=None)\n\n def weight_init(self):\n for m in self._modules:\n class_name = m.__class__.__name__\n if class_name.find('Conv2d') != -1:\n torch.nn.init.kaiming_normal(m.weight)\n if m.bias is not None:\n m.bias.data.zero_()\n elif class_name.find('ConvTranspose2d') != -1:\n torch.nn.init.kaiming_normal(m.weight)\n if m.bias is not None:\n m.bias.data.zero_()\n\n def forward(self, x):\n x = self.feat0(x)\n x = self.feat1(x)\n\n h1 = self.up1(x)\n h2 = self.up2(self.down1(h1))\n\n x = self.output_conv(torch.cat((h2, h1), 1))\n\n return x\n\n\nclass DBPNLL(nn.Module):\n def __init__(self, num_channels, base_channels, feat_channels, num_stages, scale_factor):\n super(DBPNLL, self).__init__()\n\n if scale_factor == 2:\n kernel_size = 6\n stride = 2\n padding = 2\n elif scale_factor == 4:\n kernel_size = 8\n stride = 4\n padding = 2\n elif scale_factor == 8:\n kernel_size = 12\n stride = 8\n padding = 2\n else:\n kernel_size = None\n stride = None\n padding = None\n Warning(\"please choose the scale factor from 2, 4, 8\")\n exit()\n\n # Initial Feature Extraction\n self.feat0 = ConvBlock(num_channels, feat_channels, 3, 1, 1, activation='prelu', norm=None)\n self.feat1 = ConvBlock(feat_channels, base_channels, 1, 1, 0, activation='prelu', norm=None)\n # Back-projection stages\n self.up1 = UpBlock(base_channels, kernel_size, stride, padding)\n self.down1 = DownBlock(base_channels, kernel_size, stride, padding)\n self.up2 = UpBlock(base_channels, kernel_size, stride, padding)\n self.down2 = D_DownBlock(base_channels, kernel_size, stride, padding, 2)\n self.up3 = D_UpBlock(base_channels, kernel_size, stride, padding, 2)\n self.down3 = D_DownBlock(base_channels, kernel_size, stride, padding, 3)\n self.up4 = D_UpBlock(base_channels, kernel_size, stride, padding, 3)\n self.down4 = D_DownBlock(base_channels, kernel_size, stride, padding, 4)\n self.up5 = D_UpBlock(base_channels, kernel_size, stride, padding, 4)\n self.down5 = D_DownBlock(base_channels, kernel_size, stride, padding, 5)\n self.up6 = D_UpBlock(base_channels, kernel_size, stride, padding, 5)\n self.down6 = D_DownBlock(base_channels, kernel_size, stride, padding, 6)\n self.up7 = D_UpBlock(base_channels, kernel_size, stride, padding, 6)\n self.down7 = D_DownBlock(base_channels, kernel_size, stride, padding, 7)\n self.up8 = D_UpBlock(base_channels, kernel_size, stride, padding, 7)\n self.down8 = D_DownBlock(base_channels, kernel_size, stride, padding, 8)\n self.up9 = D_UpBlock(base_channels, kernel_size, stride, padding, 8)\n self.down9 = D_DownBlock(base_channels, kernel_size, stride, padding, 9)\n self.up10 = D_UpBlock(base_channels, kernel_size, stride, padding, 9)\n # Reconstruction\n self.output_conv = ConvBlock(num_stages * base_channels, num_channels, 3, 1, 1, activation=None, norm=None)\n\n def weight_init(self):\n for m in self._modules:\n class_name = m.__class__.__name__\n if class_name.find('Conv2d') != -1:\n torch.nn.init.kaiming_normal(m.weight)\n if m.bias is not None:\n m.bias.data.zero_()\n elif class_name.find('ConvTranspose2d') != -1:\n torch.nn.init.kaiming_normal(m.weight)\n if m.bias is not None:\n m.bias.data.zero_()\n\n def forward(self, x):\n x = self.feat0(x)\n x = self.feat1(x)\n\n h1 = self.up1(x)\n l1 = self.down1(h1)\n h2 = self.up2(l1)\n\n concat_h = torch.cat((h2, h1), 1)\n l = self.down2(concat_h)\n\n concat_l = torch.cat((l, l1), 1)\n h = self.up3(concat_l)\n\n concat_h = torch.cat((h, concat_h), 1)\n l = self.down3(concat_h)\n\n concat_l = torch.cat((l, concat_l), 1)\n h = self.up4(concat_l)\n\n concat_h = torch.cat((h, concat_h), 1)\n l = self.down4(concat_h)\n\n concat_l = torch.cat((l, concat_l), 1)\n h = self.up5(concat_l)\n\n concat_h = torch.cat((h, concat_h), 1)\n l = self.down5(concat_h)\n\n concat_l = torch.cat((l, concat_l), 1)\n h = self.up6(concat_l)\n\n concat_h = torch.cat((h, concat_h), 1)\n l = self.down6(concat_h)\n\n concat_l = torch.cat((l, concat_l), 1)\n h = self.up7(concat_l)\n\n concat_h = torch.cat((h, concat_h), 1)\n l = self.down7(concat_h)\n\n concat_l = torch.cat((l, concat_l), 1)\n h = self.up8(concat_l)\n\n concat_h = torch.cat((h, concat_h), 1)\n l = self.down8(concat_h)\n\n concat_l = torch.cat((l, concat_l), 1)\n h = self.up9(concat_l)\n\n concat_h = torch.cat((h, concat_h), 1)\n l = self.down9(concat_h)\n\n concat_l = torch.cat((l, concat_l), 1)\n h = self.up10(concat_l)\n\n concat_h = torch.cat((h, concat_h), 1)\n x = self.output_conv(concat_h)\n\n return x\n\n\n############################################################################################\n# Base models\n############################################################################################\n\n\nclass DenseBlock(torch.nn.Module):\n def __init__(self, input_size, output_size, bias=True, activation='relu', norm='batch'):\n super(DenseBlock, self).__init__()\n self.fc = torch.nn.Linear(input_size, output_size, bias=bias)\n\n self.norm = norm\n if self.norm == 'batch':\n self.bn = torch.nn.BatchNorm1d(output_size)\n elif self.norm == 'instance':\n self.bn = torch.nn.InstanceNorm1d(output_size)\n\n self.activation = activation\n if self.activation == 'relu':\n self.act = torch.nn.ReLU(True)\n elif self.activation == 'prelu':\n self.act = torch.nn.PReLU()\n elif self.activation == 'lrelu':\n self.act = torch.nn.LeakyReLU(0.2, True)\n elif self.activation == 'tanh':\n self.act = torch.nn.Tanh()\n elif self.activation == 'sigmoid':\n self.act = torch.nn.Sigmoid()\n\n def forward(self, x):\n if self.norm is not None:\n out = self.bn(self.fc(x))\n else:\n out = self.fc(x)\n\n if self.activation is not None:\n return self.act(out)\n else:\n return out\n\n\nclass ConvBlock(torch.nn.Module):\n def __init__(self, input_size, output_size, kernel_size=3, stride=1, padding=1, bias=True, activation='prelu',\n norm=None):\n super(ConvBlock, self).__init__()\n self.conv = torch.nn.Conv2d(input_size, output_size, kernel_size, stride, padding, bias=bias)\n\n self.norm = norm\n if self.norm == 'batch':\n self.bn = torch.nn.BatchNorm2d(output_size)\n elif self.norm == 'instance':\n self.bn = torch.nn.InstanceNorm2d(output_size)\n\n self.activation = activation\n if self.activation == 'relu':\n self.act = torch.nn.ReLU(True)\n elif self.activation == 'prelu':\n self.act = torch.nn.PReLU()\n elif self.activation == 'lrelu':\n self.act = torch.nn.LeakyReLU(0.2, True)\n elif self.activation == 'tanh':\n self.act = torch.nn.Tanh()\n elif self.activation == 'sigmoid':\n self.act = torch.nn.Sigmoid()\n\n def forward(self, x):\n if self.norm is not None:\n out = self.bn(self.conv(x))\n else:\n out = self.conv(x)\n\n if self.activation is not None:\n return self.act(out)\n else:\n return out\n\n\nclass DeconvBlock(torch.nn.Module):\n def __init__(self, input_size, output_size, kernel_size=4, stride=2, padding=1, bias=True, activation='prelu',\n norm=None):\n super(DeconvBlock, self).__init__()\n self.deconv = torch.nn.ConvTranspose2d(input_size, output_size, kernel_size, stride, padding, bias=bias)\n\n self.norm = norm\n if self.norm == 'batch':\n self.bn = torch.nn.BatchNorm2d(output_size)\n elif self.norm == 'instance':\n self.bn = torch.nn.InstanceNorm2d(output_size)\n\n self.activation = activation\n if self.activation == 'relu':\n self.act = torch.nn.ReLU(True)\n elif self.activation == 'prelu':\n self.act = torch.nn.PReLU()\n elif self.activation == 'lrelu':\n self.act = torch.nn.LeakyReLU(0.2, True)\n elif self.activation == 'tanh':\n self.act = torch.nn.Tanh()\n elif self.activation == 'sigmoid':\n self.act = torch.nn.Sigmoid()\n\n def forward(self, x):\n if self.norm is not None:\n out = self.bn(self.deconv(x))\n else:\n out = self.deconv(x)\n\n if self.activation is not None:\n return self.act(out)\n else:\n return out\n\n\nclass ResnetBlock(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=3, stride=1, padding=1, bias=True, activation='prelu', norm='batch'):\n super(ResnetBlock, self).__init__()\n self.conv1 = torch.nn.Conv2d(num_filter, num_filter, kernel_size, stride, padding, bias=bias)\n self.conv2 = torch.nn.Conv2d(num_filter, num_filter, kernel_size, stride, padding, bias=bias)\n\n self.norm = norm\n if self.norm == 'batch':\n self.bn = torch.nn.BatchNorm2d(num_filter)\n elif norm == 'instance':\n self.bn = torch.nn.InstanceNorm2d(num_filter)\n\n self.activation = activation\n if self.activation == 'relu':\n self.act = torch.nn.ReLU(True)\n elif self.activation == 'prelu':\n self.act = torch.nn.PReLU()\n elif self.activation == 'lrelu':\n self.act = torch.nn.LeakyReLU(0.2, True)\n elif self.activation == 'tanh':\n self.act = torch.nn.Tanh()\n elif self.activation == 'sigmoid':\n self.act = torch.nn.Sigmoid()\n\n def forward(self, x):\n residual = x\n if self.norm is not None:\n out = self.bn(self.conv1(x))\n else:\n out = self.conv1(x)\n\n if self.activation is not None:\n out = self.act(out)\n\n if self.norm is not None:\n out = self.bn(self.conv2(out))\n else:\n out = self.conv2(out)\n\n out = torch.add(out, residual)\n return out\n\n\nclass UpBlock(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=8, stride=4, padding=2, bias=True, activation='prelu', norm=None):\n super(UpBlock, self).__init__()\n self.up_conv1 = DeconvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n self.up_conv2 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n self.up_conv3 = DeconvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n\n def forward(self, x):\n h0 = self.up_conv1(x)\n l0 = self.up_conv2(h0)\n h1 = self.up_conv3(l0 - x)\n return h1 + h0\n\n\nclass UpBlockPix(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=8, stride=4, padding=2, scale=4, bias=True, activation='prelu', norm=None):\n super(UpBlockPix, self).__init__()\n self.up_conv1 = Upsampler(scale, num_filter)\n self.up_conv2 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n self.up_conv3 = Upsampler(scale, num_filter)\n\n def forward(self, x):\n h0 = self.up_conv1(x)\n l0 = self.up_conv2(h0)\n h1 = self.up_conv3(l0 - x)\n return h1 + h0\n\n\nclass D_UpBlock(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=8, stride=4, padding=2, num_stages=1, bias=True, activation='prelu',\n norm=None):\n super(D_UpBlock, self).__init__()\n self.conv = ConvBlock(num_filter * num_stages, num_filter, 1, 1, 0, activation=activation, norm=None)\n self.up_conv1 = DeconvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n self.up_conv2 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n self.up_conv3 = DeconvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n\n def forward(self, x):\n x = self.conv(x)\n h0 = self.up_conv1(x)\n l0 = self.up_conv2(h0)\n h1 = self.up_conv3(l0 - x)\n return h1 + h0\n\n\nclass D_UpBlockPix(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=8, stride=4, padding=2, num_stages=1, scale=4, bias=True,\n activation='prelu', norm=None):\n super(D_UpBlockPix, self).__init__()\n self.conv = ConvBlock(num_filter * num_stages, num_filter, 1, 1, 0, activation=activation, norm=None)\n self.up_conv1 = Upsampler(scale, num_filter)\n self.up_conv2 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n self.up_conv3 = Upsampler(scale, num_filter)\n\n def forward(self, x):\n x = self.conv(x)\n h0 = self.up_conv1(x)\n l0 = self.up_conv2(h0)\n h1 = self.up_conv3(l0 - x)\n return h1 + h0\n\n\nclass DownBlock(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=8, stride=4, padding=2, bias=True, activation='prelu', norm=None):\n super(DownBlock, self).__init__()\n self.down_conv1 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n self.down_conv2 = DeconvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n self.down_conv3 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n\n def forward(self, x):\n l0 = self.down_conv1(x)\n h0 = self.down_conv2(l0)\n l1 = self.down_conv3(h0 - x)\n return l1 + l0\n\n\nclass DownBlockPix(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=8, stride=4, padding=2, scale=4, bias=True, activation='prelu',\n norm=None):\n super(DownBlockPix, self).__init__()\n self.down_conv1 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n self.down_conv2 = Upsampler(scale, num_filter)\n self.down_conv3 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n\n def forward(self, x):\n l0 = self.down_conv1(x)\n h0 = self.down_conv2(l0)\n l1 = self.down_conv3(h0 - x)\n return l1 + l0\n\n\nclass D_DownBlock(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=8, stride=4, padding=2, num_stages=1, bias=True, activation='prelu',\n norm=None):\n super(D_DownBlock, self).__init__()\n self.conv = ConvBlock(num_filter * num_stages, num_filter, 1, 1, 0, activation=activation, norm=None)\n self.down_conv1 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n self.down_conv2 = DeconvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n self.down_conv3 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n\n def forward(self, x):\n x = self.conv(x)\n l0 = self.down_conv1(x)\n h0 = self.down_conv2(l0)\n l1 = self.down_conv3(h0 - x)\n return l1 + l0\n\n\nclass D_DownBlockPix(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=8, stride=4, padding=2, num_stages=1, scale=4, bias=True,\n activation='prelu', norm=None):\n super(D_DownBlockPix, self).__init__()\n self.conv = ConvBlock(num_filter * num_stages, num_filter, 1, 1, 0, activation=activation, norm=None)\n self.down_conv1 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n self.down_conv2 = Upsampler(scale, num_filter)\n self.down_conv3 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation=activation, norm=None)\n\n def forward(self, x):\n x = self.conv(x)\n l0 = self.down_conv1(x)\n h0 = self.down_conv2(l0)\n l1 = self.down_conv3(h0 - x)\n return l1 + l0\n\n\nclass PSBlock(torch.nn.Module):\n def __init__(self, input_size, output_size, scale_factor, kernel_size=3, stride=1, padding=1, bias=True,\n activation='prelu', norm='batch'):\n super(PSBlock, self).__init__()\n self.conv = torch.nn.Conv2d(input_size, output_size * scale_factor ** 2, kernel_size, stride, padding,\n bias=bias)\n self.ps = torch.nn.PixelShuffle(scale_factor)\n\n self.norm = norm\n if self.norm == 'batch':\n self.bn = torch.nn.BatchNorm2d(output_size)\n elif norm == 'instance':\n self.bn = torch.nn.InstanceNorm2d(output_size)\n\n self.activation = activation\n if self.activation == 'relu':\n self.act = torch.nn.ReLU(True)\n elif self.activation == 'prelu':\n self.act = torch.nn.PReLU()\n elif self.activation == 'lrelu':\n self.act = torch.nn.LeakyReLU(0.2, True)\n elif self.activation == 'tanh':\n self.act = torch.nn.Tanh()\n elif self.activation == 'sigmoid':\n self.act = torch.nn.Sigmoid()\n\n def forward(self, x):\n if self.norm is not None:\n out = self.bn(self.ps(self.conv(x)))\n else:\n out = self.ps(self.conv(x))\n\n if self.activation is not None:\n out = self.act(out)\n return out\n\n\nclass Upsampler(torch.nn.Module):\n def __init__(self, scale, n_feat, bn=False, act='prelu', bias=True):\n super(Upsampler, self).__init__()\n modules = []\n for _ in range(int(math.log(scale, 2))):\n modules.append(ConvBlock(n_feat, 4 * n_feat, 3, 1, 1, bias, activation=None, norm=None))\n modules.append(torch.nn.PixelShuffle(2))\n if bn:\n modules.append(torch.nn.BatchNorm2d(n_feat))\n # modules.append(torch.nn.PReLU())\n self.up = torch.nn.Sequential(*modules)\n\n self.activation = act\n if self.activation == 'relu':\n self.act = torch.nn.ReLU(True)\n elif self.activation == 'prelu':\n self.act = torch.nn.PReLU()\n elif self.activation == 'lrelu':\n self.act = torch.nn.LeakyReLU(0.2, True)\n elif self.activation == 'tanh':\n self.act = torch.nn.Tanh()\n elif self.activation == 'sigmoid':\n self.act = torch.nn.Sigmoid()\n\n def forward(self, x):\n out = self.up(x)\n if self.activation is not None:\n out = self.act(out)\n return out\n\n\nclass Upsample2xBlock(torch.nn.Module):\n def __init__(self, input_size, output_size, bias=True, upsample='deconv', activation='relu', norm='batch'):\n super(Upsample2xBlock, self).__init__()\n scale_factor = 2\n # 1. Deconvolution (Transposed convolution)\n if upsample == 'deconv':\n self.upsample = DeconvBlock(input_size, output_size,\n kernel_size=4, stride=2, padding=1,\n bias=bias, activation=activation, norm=norm)\n\n # 2. Sub-pixel convolution (Pixel shuffler)\n elif upsample == 'ps':\n self.upsample = PSBlock(input_size, output_size, scale_factor=scale_factor,\n bias=bias, activation=activation, norm=norm)\n\n # 3. Resize and Convolution\n elif upsample == 'rnc':\n self.upsample = torch.nn.Sequential(\n torch.nn.Upsample(scale_factor=scale_factor, mode='nearest'),\n ConvBlock(input_size, output_size,\n kernel_size=3, stride=1, padding=1,\n bias=bias, activation=activation, norm=norm)\n )\n\n def forward(self, x):\n out = self.upsample(x)\n return out"
] | [
[
"torch.nn.init.kaiming_normal",
"torch.nn.Sequential",
"torch.nn.BatchNorm1d",
"torch.add",
"torch.nn.ConvTranspose2d",
"torch.cat",
"torch.nn.InstanceNorm1d",
"torch.nn.PReLU",
"torch.nn.Conv2d",
"torch.nn.PixelShuffle",
"torch.nn.Tanh",
"torch.nn.Sigmoid",
"torch.nn.Linear",
"torch.nn.InstanceNorm2d",
"torch.nn.LeakyReLU",
"torch.nn.Upsample",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
avartak/qiskit-terra | [
"44462a8b13ea6c2cce0f9c7345c26c15fb0d4ce3"
] | [
"qiskit/quantum_info/states/densitymatrix.py"
] | [
"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2019.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"\nDensityMatrix quantum state class.\n\"\"\"\n\nfrom numbers import Number\nimport numpy as np\n\nfrom qiskit.circuit.quantumcircuit import QuantumCircuit\nfrom qiskit.circuit.instruction import Instruction\nfrom qiskit.exceptions import QiskitError\nfrom qiskit.quantum_info.states.quantum_state import QuantumState\nfrom qiskit.quantum_info.operators.tolerances import TolerancesMixin\nfrom qiskit.quantum_info.operators.operator import Operator\nfrom qiskit.quantum_info.operators.scalar_op import ScalarOp\nfrom qiskit.quantum_info.operators.predicates import is_hermitian_matrix\nfrom qiskit.quantum_info.operators.predicates import is_positive_semidefinite_matrix\nfrom qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel\nfrom qiskit.quantum_info.operators.channel.superop import SuperOp\nfrom qiskit.quantum_info.states.statevector import Statevector\n\n\nclass DensityMatrix(QuantumState, TolerancesMixin):\n \"\"\"DensityMatrix class\"\"\"\n\n def __init__(self, data, dims=None):\n \"\"\"Initialize a density matrix object.\n\n Args:\n data (np.ndarray or list or matrix_like or QuantumCircuit or\n qiskit.circuit.Instruction):\n A statevector, quantum instruction or an object with a ``to_operator`` or\n ``to_matrix`` method from which the density matrix can be constructed.\n If a vector the density matrix is constructed as the projector of that vector.\n If a quantum instruction, the density matrix is constructed by assuming all\n qubits are initialized in the zero state.\n dims (int or tuple or list): Optional. The subsystem dimension\n of the state (See additional information).\n\n Raises:\n QiskitError: if input data is not valid.\n\n Additional Information:\n The ``dims`` kwarg can be None, an integer, or an iterable of\n integers.\n\n * ``Iterable`` -- the subsystem dimensions are the values in the list\n with the total number of subsystems given by the length of the list.\n\n * ``Int`` or ``None`` -- the leading dimension of the input matrix\n specifies the total dimension of the density matrix. If it is a\n power of two the state will be initialized as an N-qubit state.\n If it is not a power of two the state will have a single\n d-dimensional subsystem.\n \"\"\"\n if isinstance(data, (list, np.ndarray)):\n # Finally we check if the input is a raw matrix in either a\n # python list or numpy array format.\n self._data = np.asarray(data, dtype=complex)\n elif isinstance(data, (QuantumCircuit, Instruction)):\n # If the data is a circuit or an instruction use the classmethod\n # to construct the DensityMatrix object\n self._data = DensityMatrix.from_instruction(data)._data\n elif hasattr(data, 'to_operator'):\n # If the data object has a 'to_operator' attribute this is given\n # higher preference than the 'to_matrix' method for initializing\n # an Operator object.\n op = data.to_operator()\n self._data = op.data\n if dims is None:\n dims = op._output_dims\n elif hasattr(data, 'to_matrix'):\n # If no 'to_operator' attribute exists we next look for a\n # 'to_matrix' attribute to a matrix that will be cast into\n # a complex numpy matrix.\n self._data = np.asarray(data.to_matrix(), dtype=complex)\n else:\n raise QiskitError(\"Invalid input data format for DensityMatrix\")\n # Convert statevector into a density matrix\n ndim = self._data.ndim\n shape = self._data.shape\n if ndim == 2 and shape[0] == shape[1]:\n pass # We good\n elif ndim == 1:\n self._data = np.outer(self._data, np.conj(self._data))\n elif ndim == 2 and shape[1] == 1:\n self._data = np.reshape(self._data, shape[0])\n shape = self._data.shape\n else:\n raise QiskitError(\n \"Invalid DensityMatrix input: not a square matrix.\")\n super().__init__(self._automatic_dims(dims, shape[0]))\n\n def __eq__(self, other):\n return super().__eq__(other) and np.allclose(\n self._data, other._data, rtol=self.rtol, atol=self.atol)\n\n def __repr__(self):\n prefix = 'DensityMatrix('\n pad = len(prefix) * ' '\n return '{}{},\\n{}dims={})'.format(\n prefix, np.array2string(\n self._data, separator=', ', prefix=prefix),\n pad, self._dims)\n\n @property\n def data(self):\n \"\"\"Return data.\"\"\"\n return self._data\n\n def is_valid(self, atol=None, rtol=None):\n \"\"\"Return True if trace 1 and positive semidefinite.\"\"\"\n if atol is None:\n atol = self.atol\n if rtol is None:\n rtol = self.rtol\n # Check trace == 1\n if not np.allclose(self.trace(), 1, rtol=rtol, atol=atol):\n return False\n # Check Hermitian\n if not is_hermitian_matrix(self.data, rtol=rtol, atol=atol):\n return False\n # Check positive semidefinite\n return is_positive_semidefinite_matrix(self.data, rtol=rtol, atol=atol)\n\n def to_operator(self):\n \"\"\"Convert to Operator\"\"\"\n dims = self.dims()\n return Operator(self.data, input_dims=dims, output_dims=dims)\n\n def conjugate(self):\n \"\"\"Return the conjugate of the density matrix.\"\"\"\n return DensityMatrix(np.conj(self.data), dims=self.dims())\n\n def trace(self):\n \"\"\"Return the trace of the density matrix.\"\"\"\n return np.trace(self.data)\n\n def purity(self):\n \"\"\"Return the purity of the quantum state.\"\"\"\n # For a valid statevector the purity is always 1, however if we simply\n # have an arbitrary vector (not correctly normalized) then the\n # purity is equivalent to the trace squared:\n # P(|psi>) = Tr[|psi><psi|psi><psi|] = |<psi|psi>|^2\n return np.trace(np.dot(self.data, self.data))\n\n def tensor(self, other):\n \"\"\"Return the tensor product state self ⊗ other.\n\n Args:\n other (DensityMatrix): a quantum state object.\n\n Returns:\n DensityMatrix: the tensor product operator self ⊗ other.\n\n Raises:\n QiskitError: if other is not a quantum state.\n \"\"\"\n if not isinstance(other, DensityMatrix):\n other = DensityMatrix(other)\n dims = other.dims() + self.dims()\n data = np.kron(self._data, other._data)\n return DensityMatrix(data, dims)\n\n def expand(self, other):\n \"\"\"Return the tensor product state other ⊗ self.\n\n Args:\n other (DensityMatrix): a quantum state object.\n\n Returns:\n DensityMatrix: the tensor product state other ⊗ self.\n\n Raises:\n QiskitError: if other is not a quantum state.\n \"\"\"\n if not isinstance(other, DensityMatrix):\n other = DensityMatrix(other)\n dims = self.dims() + other.dims()\n data = np.kron(other._data, self._data)\n return DensityMatrix(data, dims)\n\n def _add(self, other):\n \"\"\"Return the linear combination self + other.\n\n Args:\n other (DensityMatrix): a quantum state object.\n\n Returns:\n DensityMatrix: the linear combination self + other.\n\n Raises:\n QiskitError: if other is not a quantum state, or has\n incompatible dimensions.\n \"\"\"\n if not isinstance(other, DensityMatrix):\n other = DensityMatrix(other)\n if self.dim != other.dim:\n raise QiskitError(\"other DensityMatrix has different dimensions.\")\n return DensityMatrix(self.data + other.data, self.dims())\n\n def _multiply(self, other):\n \"\"\"Return the scalar multiplied state other * self.\n\n Args:\n other (complex): a complex number.\n\n Returns:\n DensityMatrix: the scalar multiplied state other * self.\n\n Raises:\n QiskitError: if other is not a valid complex number.\n \"\"\"\n if not isinstance(other, Number):\n raise QiskitError(\"other is not a number\")\n return DensityMatrix(other * self.data, self.dims())\n\n def evolve(self, other, qargs=None):\n \"\"\"Evolve a quantum state by an operator.\n\n Args:\n other (Operator or QuantumChannel\n or Instruction or Circuit): The operator to evolve by.\n qargs (list): a list of QuantumState subsystem positions to apply\n the operator on.\n\n Returns:\n QuantumState: the output quantum state.\n\n Raises:\n QiskitError: if the operator dimension does not match the\n specified QuantumState subsystem dimensions.\n \"\"\"\n if qargs is None:\n qargs = getattr(other, 'qargs', None)\n\n # Evolution by a circuit or instruction\n if isinstance(other, (QuantumCircuit, Instruction)):\n return self._evolve_instruction(other, qargs=qargs)\n\n # Evolution by a QuantumChannel\n if hasattr(other, 'to_quantumchannel'):\n return other.to_quantumchannel()._evolve(self, qargs=qargs)\n if isinstance(other, QuantumChannel):\n return other._evolve(self, qargs=qargs)\n\n # Unitary evolution by an Operator\n if not isinstance(other, Operator):\n other = Operator(other)\n return self._evolve_operator(other, qargs=qargs)\n\n def expectation_value(self, oper, qargs=None):\n \"\"\"Compute the expectation value of an operator.\n\n Args:\n oper (Operator): an operator to evaluate expval.\n qargs (None or list): subsystems to apply the operator on.\n\n Returns:\n complex: the expectation value.\n \"\"\"\n if not isinstance(oper, Operator):\n oper = Operator(oper)\n return np.trace(Operator(self).dot(oper.adjoint(), qargs=qargs).data)\n\n def probabilities(self, qargs=None, decimals=None):\n \"\"\"Return the subsystem measurement probability vector.\n\n Measurement probabilities are with respect to measurement in the\n computation (diagonal) basis.\n\n Args:\n qargs (None or list): subsystems to return probabilities for,\n if None return for all subsystems (Default: None).\n decimals (None or int): the number of decimal places to round\n values. If None no rounding is done (Default: None).\n\n Returns:\n np.array: The Numpy vector array of probabilities.\n\n Examples:\n\n Consider a 2-qubit product state :math:`\\\\rho=\\\\rho_1\\\\otimes\\\\rho_0`\n with :math:`\\\\rho_1=|+\\\\rangle\\\\!\\\\langle+|`,\n :math:`\\\\rho_0=|0\\\\rangle\\\\!\\\\langle0|`.\n\n .. jupyter-execute::\n\n from qiskit.quantum_info import DensityMatrix\n\n rho = DensityMatrix.from_label('+0')\n\n # Probabilities for measuring both qubits\n probs = rho.probabilities()\n print('probs: {}'.format(probs))\n\n # Probabilities for measuring only qubit-0\n probs_qubit_0 = rho.probabilities([0])\n print('Qubit-0 probs: {}'.format(probs_qubit_0))\n\n # Probabilities for measuring only qubit-1\n probs_qubit_1 = rho.probabilities([1])\n print('Qubit-1 probs: {}'.format(probs_qubit_1))\n\n We can also permute the order of qubits in the ``qargs`` list\n to change the qubit position in the probabilities output\n\n .. jupyter-execute::\n\n from qiskit.quantum_info import DensityMatrix\n\n rho = DensityMatrix.from_label('+0')\n\n # Probabilities for measuring both qubits\n probs = rho.probabilities([0, 1])\n print('probs: {}'.format(probs))\n\n # Probabilities for measuring both qubits\n # but swapping qubits 0 and 1 in output\n probs_swapped = rho.probabilities([1, 0])\n print('Swapped probs: {}'.format(probs_swapped))\n \"\"\"\n probs = self._subsystem_probabilities(\n np.abs(self.data.diagonal()), self._dims, qargs=qargs)\n if decimals is not None:\n probs = probs.round(decimals=decimals)\n return probs\n\n def reset(self, qargs=None):\n \"\"\"Reset state or subsystems to the 0-state.\n\n Args:\n qargs (list or None): subsystems to reset, if None all\n subsystems will be reset to their 0-state\n (Default: None).\n\n Returns:\n DensityMatrix: the reset state.\n\n Additional Information:\n If all subsystems are reset this will return the ground state\n on all subsystems. If only a some subsystems are reset this\n function will perform evolution by the reset\n :class:`~qiskit.quantum_info.SuperOp` of the reset subsystems.\n \"\"\"\n if qargs is None:\n # Resetting all qubits does not require sampling or RNG\n state = np.zeros(2 * (self._dim, ), dtype=complex)\n state[0, 0] = 1\n return DensityMatrix(state, dims=self._dims)\n\n # Reset by evolving by reset SuperOp\n dims = self.dims(qargs)\n reset_superop = SuperOp(ScalarOp(dims, coeff=0))\n reset_superop.data[0] = Operator(ScalarOp(dims)).data.ravel()\n return self.evolve(reset_superop, qargs=qargs)\n\n @classmethod\n def from_label(cls, label):\n r\"\"\"Return a tensor product of Pauli X,Y,Z eigenstates.\n\n .. list-table:: Single-qubit state labels\n :header-rows: 1\n\n * - Label\n - Statevector\n * - ``\"0\"``\n - :math:`\\begin{pmatrix} 1 & 0 \\\\ 0 & 0 \\end{pmatrix}`\n * - ``\"1\"``\n - :math:`\\begin{pmatrix} 0 & 0 \\\\ 0 & 1 \\end{pmatrix}`\n * - ``\"+\"``\n - :math:`\\frac{1}{2}\\begin{pmatrix} 1 & 1 \\\\ 1 & 1 \\end{pmatrix}`\n * - ``\"-\"``\n - :math:`\\frac{1}{2}\\begin{pmatrix} 1 & -1 \\\\ -1 & 1 \\end{pmatrix}`\n * - ``\"r\"``\n - :math:`\\frac{1}{2}\\begin{pmatrix} 1 & -i \\\\ i & 1 \\end{pmatrix}`\n * - ``\"l\"``\n - :math:`\\frac{1}{2}\\begin{pmatrix} 1 & i \\\\ -i & 1 \\end{pmatrix}`\n\n Args:\n label (string): a eigenstate string ket label (see table for\n allowed values).\n\n Returns:\n Statevector: The N-qubit basis state density matrix.\n\n Raises:\n QiskitError: if the label contains invalid characters, or the length\n of the label is larger than an explicitly specified num_qubits.\n \"\"\"\n return DensityMatrix(Statevector.from_label(label))\n\n @staticmethod\n def from_int(i, dims):\n \"\"\"Return a computational basis state density matrix.\n\n Args:\n i (int): the basis state element.\n dims (int or tuple or list): The subsystem dimensions of the statevector\n (See additional information).\n\n Returns:\n DensityMatrix: The computational basis state :math:`|i\\\\rangle\\\\!\\\\langle i|`.\n\n Additional Information:\n The ``dims`` kwarg can be an integer or an iterable of integers.\n\n * ``Iterable`` -- the subsystem dimensions are the values in the list\n with the total number of subsystems given by the length of the list.\n\n * ``Int`` -- the integer specifies the total dimension of the\n state. If it is a power of two the state will be initialized\n as an N-qubit state. If it is not a power of two the state\n will have a single d-dimensional subsystem.\n \"\"\"\n size = np.product(dims)\n state = np.zeros((size, size), dtype=complex)\n state[i, i] = 1.0\n return DensityMatrix(state, dims=dims)\n\n @classmethod\n def from_instruction(cls, instruction):\n \"\"\"Return the output density matrix of an instruction.\n\n The statevector is initialized in the state :math:`|{0,\\\\ldots,0}\\\\rangle` of\n the same number of qubits as the input instruction or circuit, evolved\n by the input instruction, and the output statevector returned.\n\n Args:\n instruction (qiskit.circuit.Instruction or QuantumCircuit): instruction or circuit\n\n Returns:\n DensityMatrix: the final density matrix.\n\n Raises:\n QiskitError: if the instruction contains invalid instructions for\n density matrix simulation.\n \"\"\"\n # Convert circuit to an instruction\n if isinstance(instruction, QuantumCircuit):\n instruction = instruction.to_instruction()\n # Initialize an the statevector in the all |0> state\n num_qubits = instruction.num_qubits\n init = np.zeros((2**num_qubits, 2**num_qubits), dtype=complex)\n init[0, 0] = 1\n vec = DensityMatrix(init, dims=num_qubits * (2, ))\n vec._append_instruction(instruction)\n return vec\n\n def to_dict(self, decimals=None):\n r\"\"\"Convert the density matrix to dictionary form.\n\n This dictionary representation uses a Ket-like notation where the\n dictionary keys are qudit strings for the subsystem basis vectors.\n If any subsystem has a dimension greater than 10 comma delimiters are\n inserted between integers so that subsystems can be distinguished.\n\n Args:\n decimals (None or int): the number of decimal places to round\n values. If None no rounding is done\n (Default: None).\n\n Returns:\n dict: the dictionary form of the DensityMatrix.\n\n Examples:\n\n The ket-form of a 2-qubit density matrix\n :math:`rho = |-\\rangle\\!\\langle -|\\otimes |0\\rangle\\!\\langle 0|`\n\n .. jupyter-execute::\n\n from qiskit.quantum_info import DensityMatrix\n\n rho = DensityMatrix.from_label('-0')\n print(rho.to_dict())\n\n For non-qubit subsystems the integer range can go from 0 to 9. For\n example in a qutrit system\n\n .. jupyter-execute::\n\n import numpy as np\n from qiskit.quantum_info import DensityMatrix\n\n mat = np.zeros((9, 9))\n mat[0, 0] = 0.25\n mat[3, 3] = 0.25\n mat[6, 6] = 0.25\n mat[-1, -1] = 0.25\n rho = DensityMatrix(mat, dims=(3, 3))\n print(rho.to_dict())\n\n For large subsystem dimensions delimeters are required. The\n following example is for a 20-dimensional system consisting of\n a qubit and 10-dimensional qudit.\n\n .. jupyter-execute::\n\n import numpy as np\n from qiskit.quantum_info import DensityMatrix\n\n mat = np.zeros((2 * 10, 2 * 10))\n mat[0, 0] = 0.5\n mat[-1, -1] = 0.5\n rho = DensityMatrix(mat, dims=(2, 10))\n print(rho.to_dict())\n \"\"\"\n return self._matrix_to_dict(self.data,\n self._dims,\n decimals=decimals,\n string_labels=True)\n\n @property\n def _shape(self):\n \"\"\"Return the tensor shape of the matrix operator\"\"\"\n return 2 * tuple(reversed(self.dims()))\n\n def _evolve_operator(self, other, qargs=None):\n \"\"\"Evolve density matrix by an operator\"\"\"\n if qargs is None:\n # Evolution on full matrix\n if self._dim != other.dim[0]:\n raise QiskitError(\n \"Operator input dimension is not equal to density matrix dimension.\"\n )\n op_mat = other.data\n mat = np.dot(op_mat, self.data).dot(op_mat.T.conj())\n return DensityMatrix(mat, dims=other.output_dims())\n # Otherwise we are applying an operator only to subsystems\n # Check dimensions of subsystems match the operator\n if self.dims(qargs) != other.input_dims():\n raise QiskitError(\n \"Operator input dimensions are not equal to statevector subsystem dimensions.\"\n )\n # Reshape statevector and operator\n tensor = np.reshape(self.data, self._shape)\n # Construct list of tensor indices of statevector to be contracted\n num_indices = len(self.dims())\n indices = [num_indices - 1 - qubit for qubit in qargs]\n # Left multiple by mat\n mat = np.reshape(other.data, other._shape)\n tensor = Operator._einsum_matmul(tensor, mat, indices)\n # Right multiply by mat ** dagger\n adj = other.adjoint()\n mat_adj = np.reshape(adj.data, adj._shape)\n tensor = Operator._einsum_matmul(tensor, mat_adj, indices, num_indices,\n True)\n # Replace evolved dimensions\n new_dims = list(self.dims())\n for qubit, dim in zip(qargs, other.output_dims()):\n new_dims[qubit] = dim\n new_dim = np.product(new_dims)\n return DensityMatrix(np.reshape(tensor, (new_dim, new_dim)),\n dims=new_dims)\n\n def _append_instruction(self, other, qargs=None):\n \"\"\"Update the current Statevector by applying an instruction.\"\"\"\n from qiskit.circuit.reset import Reset\n from qiskit.circuit.barrier import Barrier\n\n # Try evolving by a matrix operator (unitary-like evolution)\n mat = Operator._instruction_to_matrix(other)\n if mat is not None:\n self._data = self._evolve_operator(Operator(mat), qargs=qargs).data\n return\n\n # Special instruction types\n if isinstance(other, Reset):\n self._data = self.reset(qargs)._data\n return\n if isinstance(other, Barrier):\n return\n\n # Otherwise try evolving by a Superoperator\n chan = SuperOp._instruction_to_superop(other)\n if chan is not None:\n # Evolve current state by the superoperator\n self._data = chan._evolve(self, qargs=qargs).data\n return\n # If the instruction doesn't have a matrix defined we use its\n # circuit decomposition definition if it exists, otherwise we\n # cannot compose this gate and raise an error.\n if other.definition is None:\n raise QiskitError('Cannot apply Instruction: {}'.format(\n other.name))\n if not isinstance(other.definition, QuantumCircuit):\n raise QiskitError('{} instruction definition is {}; expected QuantumCircuit'.format(\n other.name, type(other.definition)))\n for instr, qregs, cregs in other.definition:\n if cregs:\n raise QiskitError(\n 'Cannot apply instruction with classical registers: {}'.\n format(instr.name))\n # Get the integer position of the flat register\n if qargs is None:\n new_qargs = [tup.index for tup in qregs]\n else:\n new_qargs = [qargs[tup.index] for tup in qregs]\n self._append_instruction(instr, qargs=new_qargs)\n\n def _evolve_instruction(self, obj, qargs=None):\n \"\"\"Return a new statevector by applying an instruction.\"\"\"\n if isinstance(obj, QuantumCircuit):\n obj = obj.to_instruction()\n vec = DensityMatrix(self.data, dims=self._dims)\n vec._append_instruction(obj, qargs=qargs)\n return vec\n\n def to_statevector(self, atol=None, rtol=None):\n \"\"\"Return a statevector from a pure density matrix.\n\n Args:\n atol (float): Absolute tolerance for checking operation validity.\n rtol (float): Relative tolerance for checking operation validity.\n\n Returns:\n Statevector: The pure density matrix's corresponding statevector.\n Corresponds to the eigenvector of the only non-zero eigenvalue.\n\n Raises:\n QiskitError: if the state is not pure.\n \"\"\"\n if atol is None:\n atol = self.atol\n if rtol is None:\n rtol = self.rtol\n\n if not is_hermitian_matrix(self._data, atol=atol, rtol=rtol):\n raise QiskitError(\"Not a valid density matrix (non-hermitian).\")\n\n evals, evecs = np.linalg.eig(self._data)\n\n nonzero_evals = evals[abs(evals) > atol]\n if len(nonzero_evals) != 1 or not np.isclose(nonzero_evals[0], 1,\n atol=atol, rtol=rtol):\n raise QiskitError(\"Density matrix is not a pure state\")\n\n psi = evecs[:, np.argmax(evals)] # eigenvectors returned in columns.\n return Statevector(psi)\n"
] | [
[
"numpy.dot",
"numpy.product",
"numpy.allclose",
"numpy.conj",
"numpy.reshape",
"numpy.linalg.eig",
"numpy.asarray",
"numpy.kron",
"numpy.argmax",
"numpy.array2string",
"numpy.zeros",
"numpy.trace",
"numpy.isclose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mateus-shima/robot-manipulator-sandbox | [
"a01de40d306d304c2603e86897fc498b780f4a84"
] | [
"scripts/robot_controlling_node.py"
] | [
"#!/usr/bin/env python\n\nfrom dqrobotics import *\nfrom dqrobotics.robots import KukaLw4Robot\nimport numpy as np\nfrom dqrobotics.utils import *\nimport math\nimport time\npinv = DQ_LinearAlgebra.pinv\nimport rospy\nfrom controller import PseudoinverseController\nfrom interface import Interface\n\n\ndef control():\n\tprint(\"control()\")\n\n\t## Defining robot kinematic model\n\trobot = KukaLw4Robot.kinematics()\n\n\t## Desired pose\n\ttranslation = DQ([0.0, 0.1, 0.1, 0.1])\n\trotation = DQ([1.0, 0.0, 0.0, 0.0])\n\t# xd = rotation + E_ * 0.5 * translation * rotation\n\t# xd = robot.fkm((0,math.pi,0,math.pi,0,math.pi/2,0))\n\txd = robot.fkm((0.0, -math.pi/6, 0.0, math.pi/2.0, math.pi/6, 0.0, 0.0))\n\n\t## Defining initial target joints\n\ttheta_init = np.array([0.0, -math.pi/3.7, 0.0, math.pi/2.0, math.pi/3.7, 0.0, 0.0])\n\n\t## Controller gain\n\tgain = 1\n\n\t## Defining controller\n\tpseudoinverse_controller = PseudoinverseController(robot, gain)\n\n\t## Defining communication interface\n\tinterface = Interface(robot.get_dim_configuration_space())\n\n\t## Initialize node\n\trospy.init_node('robot_interface', anonymous=True)\n\n\t## Control loop sampling time (seconds)\n\tsampling_time = 0.05\n\n\t## ROS loop frequency rate\n\trate = rospy.Rate(1/sampling_time)\n\n\t## State machine states\n\tk_set_init_config = 1\n\tk_run_control = 2\n\tk_end_state = 3\n\n\t## Count initial configuration iterations\n\tset_init_config_counter = 1\n\tinit_config_iterations = 100\n\n\trobot_state = k_set_init_config\n\n\twhile not rospy.is_shutdown():\n\n\t\tif robot_state == k_set_init_config:\n\n\t\t\tprint(\"k_set_init_config\")\n\n\t\t\t## Set robot init config\n\t\t\tinterface.send_joint_position(theta_init)\n\n\t\t\t## Init pose\n\t\t\t# x_init = interface.get_joint_positions()\n\n\t\t\tif set_init_config_counter > init_config_iterations:\n\n\t\t\t\t## Reset counter\n\t\t\t\tset_init_config_counter = 0\n\n\t\t\t\t## Set next state\n\t\t\t\trobot_state = k_run_control\n\n\t\t\tset_init_config_counter += 1\n\n\t\tif robot_state == k_run_control:\n\n\t\t\tprint(\"k_run_control\")\n\n\t\t\t## Get joint positions from robot\n\t\t\tjoint_positions = interface.get_joint_positions()\n\n\t\t\t## Desired pose to be set\n\t\t\tx_set = xd\n\n\t\t\t## Compute control signal\n\t\t\t## The control signal is the robot joint velocities\n\t\t\tu = pseudoinverse_controller.compute_control_signal(joint_positions, x_set)\n\n\t\t\t## We are actuating in the robot with joint position commands\n\t\t\t## So we integrate the joint velocities\n\t\t\ttheta_set = joint_positions + u * sampling_time\n\n\t\t\t## Send joint positions to robot\n\t\t\tinterface.send_joint_position(theta_set)\n\n\t\t\t## Get controller error\n\t\t\ttask_error = pseudoinverse_controller.get_last_error_signal()\n\t\t\tprint(\"task_error \", np.linalg.norm(task_error))\n\n\t\t\t## Verify if desired error was reached\n\t\t\tif np.linalg.norm(task_error) < 0.01:\n\t\t\t\trobot_state = k_end_state\n\n\t\tif robot_state == k_end_state:\n\t\t\tprint(\"k_end_state\")\n\n\t\trate.sleep()\n\ndef main():\n\tcontrol()\n\nif __name__ == '__main__':\n\n main()\n\n \n"
] | [
[
"numpy.array",
"numpy.linalg.norm"
]
] | [
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.24",
"1.13",
"1.16",
"1.9",
"1.18",
"1.23",
"1.21",
"1.22",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
drknotter/trimesh | [
"f486bc6cf0e2dc775d9384799b806f2f2c8ac284"
] | [
"trimesh/repair.py"
] | [
"\"\"\"\nrepair.py\n-------------\n\nFill holes and fix winding and normals of meshes.\n\"\"\"\n\nimport numpy as np\n\nfrom . import graph\nfrom . import triangles\n\nfrom .constants import log\nfrom .grouping import group_rows\nfrom .geometry import faces_to_edges\n\n\ntry:\n import networkx as nx\nexcept BaseException as E:\n # create a dummy module which will raise the ImportError\n # or other exception only when someone tries to use networkx\n from .exceptions import ExceptionModule\n nx = ExceptionModule(E)\n\n\ndef fix_winding(mesh):\n \"\"\"\n Traverse and change mesh faces in-place to make sure winding\n is correct, with edges on adjacent faces in\n opposite directions.\n\n Parameters\n -------------\n mesh: Trimesh object\n\n Notes\n -------------\n mesh.face : will reverse columns of certain faces\n \"\"\"\n # anything we would fix is already done\n if mesh.is_winding_consistent:\n return\n\n graph_all = nx.from_edgelist(mesh.face_adjacency)\n flipped = 0\n\n faces = mesh.faces.view(np.ndarray).copy()\n\n # we are going to traverse the graph using BFS\n # start a traversal for every connected component\n for components in nx.connected_components(graph_all):\n # get a subgraph for this component\n g = graph_all.subgraph(components)\n # get the first node in the graph in a way that works on nx's\n # new API and their old API\n start = next(iter(g.nodes()))\n\n # we traverse every pair of faces in the graph\n # we modify mesh.faces and mesh.face_normals in place\n for face_pair in nx.bfs_edges(g, start):\n # for each pair of faces, we convert them into edges,\n # find the edge that both faces share and then see if edges\n # are reversed in order as you would expect\n # (2, ) int\n face_pair = np.ravel(face_pair)\n # (2, 3) int\n pair = faces[face_pair]\n # (6, 2) int\n edges = faces_to_edges(pair)\n overlap = group_rows(np.sort(edges, axis=1),\n require_count=2)\n if len(overlap) == 0:\n # only happens on non-watertight meshes\n continue\n edge_pair = edges[overlap[0]]\n if edge_pair[0][0] == edge_pair[1][0]:\n # if the edges aren't reversed, invert the order of one face\n flipped += 1\n faces[face_pair[1]] = faces[face_pair[1]][::-1]\n\n if flipped > 0:\n mesh.faces = faces\n\n log.debug('flipped %d/%d edges', flipped, len(mesh.faces) * 3)\n\n\ndef fix_inversion(mesh, multibody=False):\n \"\"\"\n Check to see if a mesh has normals pointing \"out.\"\n\n Parameters\n -------------\n mesh : trimesh.Trimesh\n Mesh to fix.\n multibody : bool\n If True will try to fix normals on every body\n\n Notes\n -------------\n mesh.face : may reverse faces\n \"\"\"\n if multibody:\n groups = graph.connected_components(mesh.face_adjacency)\n # escape early for single body\n if len(groups) == 1:\n if mesh.volume < 0.0:\n mesh.invert()\n return\n # mask of faces to flip\n flip = np.zeros(len(mesh.faces), dtype=bool)\n # save these to avoid thrashing cache\n tri = mesh.triangles\n cross = mesh.triangles_cross\n # indexes of mesh.faces, not actual faces\n for faces in groups:\n # calculate the volume of the submesh faces\n volume = triangles.mass_properties(\n tri[faces],\n crosses=cross[faces],\n skip_inertia=True)['volume']\n # if that volume is negative it is either\n # inverted or just total garbage\n if volume < 0.0:\n flip[faces] = True\n # one or more faces needs flipping\n if flip.any():\n # flip normals of necessary faces\n if 'face_normals' in mesh._cache:\n normals = mesh.face_normals.copy()\n normals[flip] *= -1.0\n else:\n normals = None\n # flip faces\n mesh.faces[flip] = np.fliplr(mesh.faces[flip])\n if normals is not None:\n mesh.face_normals = normals\n\n elif mesh.volume < 0.0:\n mesh.invert()\n\n\ndef fix_normals(mesh, multibody=False):\n \"\"\"\n Fix the winding and direction of a mesh face and\n face normals in-place.\n\n Really only meaningful on watertight meshes but will orient all\n faces and winding in a uniform way for non-watertight face\n patches as well.\n\n Parameters\n -------------\n mesh : trimesh.Trimesh\n Mesh to fix normals on\n multibody : bool\n if True try to correct normals direction\n on every body rather than just one\n\n Notes\n --------------\n mesh.faces : will flip columns on inverted faces\n \"\"\"\n # traverse face adjacency to correct winding\n fix_winding(mesh)\n # check to see if a mesh is inverted\n fix_inversion(mesh, multibody=multibody)\n\n\ndef broken_faces(mesh, color=None):\n \"\"\"\n Return the index of faces in the mesh which break the\n watertight status of the mesh.\n\n Parameters\n --------------\n mesh : trimesh.Trimesh\n Mesh to check broken faces on\n color: (4,) uint8 or None\n Will set broken faces to this color if not None\n\n Returns\n ---------------\n broken : (n, ) int\n Indexes of mesh.faces\n \"\"\"\n adjacency = nx.from_edgelist(mesh.face_adjacency)\n broken = [k for k, v in dict(adjacency.degree()).items()\n if v != 3]\n broken = np.array(broken)\n if color is not None and broken.size != 0:\n # if someone passed a broken color\n color = np.array(color)\n if not (color.shape == (4,) or color.shape == (3,)):\n color = [255, 0, 0, 255]\n mesh.visual.face_colors[broken] = color\n return broken\n\n\ndef fill_holes(mesh):\n \"\"\"\n Fill single- triangle holes on triangular meshes by adding\n new triangles to fill the holes. New triangles will have\n proper winding and normals, and if face colors exist the color\n of the last face will be assigned to the new triangles.\n\n Parameters\n ------------\n mesh : trimesh.Trimesh\n Mesh will be repaired in- place\n \"\"\"\n\n def hole_to_faces(hole):\n \"\"\"\n Given a loop of vertex indices representing a hole\n turn it into triangular faces.\n If unable to do so, return None\n\n Parameters\n -----------\n hole : (n,) int\n Ordered loop of vertex indices\n\n Returns\n ---------\n faces : (n, 3) int\n New faces\n vertices : (m, 3) float\n New vertices\n \"\"\"\n hole = np.asanyarray(hole)\n # the case where the hole is just a single missing triangle\n if len(hole) == 3:\n return [hole], []\n # the hole is a quad, which we fill with two triangles\n if len(hole) == 4:\n face_A = hole[[0, 1, 2]]\n face_B = hole[[2, 3, 0]]\n return [face_A, face_B], []\n return [], []\n\n if len(mesh.faces) < 3:\n return False\n\n if mesh.is_watertight:\n return True\n\n # we know that in a watertight mesh every edge will be included twice\n # thus every edge which appears only once is part of a hole boundary\n boundary_groups = group_rows(\n mesh.edges_sorted, require_count=1)\n\n # mesh is not watertight and we have too few edges\n # edges to do a repair\n # since we haven't changed anything return False\n if len(boundary_groups) < 3:\n return False\n\n boundary_edges = mesh.edges[boundary_groups]\n index_as_dict = [{'index': i} for i in boundary_groups]\n\n # we create a graph of the boundary edges, and find cycles.\n g = nx.from_edgelist(\n np.column_stack((boundary_edges,\n index_as_dict)))\n new_faces = []\n new_vertex = []\n for hole in nx.cycle_basis(g):\n # convert the hole, which is a polygon of vertex indices\n # to triangles and new vertices\n faces, vertex = hole_to_faces(hole=hole)\n if len(faces) == 0:\n continue\n # remeshing returns new vertices as negative indices, so change those\n # to absolute indices which won't be screwed up by the later appends\n faces = np.array(faces)\n faces[faces < 0] += len(new_vertex) + len(mesh.vertices) + len(vertex)\n new_vertex.extend(vertex)\n new_faces.extend(faces)\n new_faces = np.array(new_faces)\n new_vertex = np.array(new_vertex)\n\n if len(new_faces) == 0:\n # no new faces have been added, so nothing further to do\n # the mesh is NOT watertight, as boundary groups exist\n # but we didn't add any new faces to fill them in\n return False\n\n for face_index, face in enumerate(new_faces):\n # we compare the edge from the new face with\n # the boundary edge from the source mesh\n edge_test = face[:2]\n edge_boundary = mesh.edges[g.get_edge_data(*edge_test)['index']]\n\n # in a well construtced mesh, the winding is such that adjacent triangles\n # have reversed edges to each other. Here we check to make sure the\n # edges are reversed, and if they aren't we simply reverse the face\n reversed = edge_test[0] == edge_boundary[1]\n if not reversed:\n new_faces[face_index] = face[::-1]\n\n # stack vertices into clean (n, 3) float\n if len(new_vertex) != 0:\n new_vertices = np.vstack((mesh.vertices, new_vertex))\n else:\n new_vertices = mesh.vertices\n\n # try to save face normals if we can\n if 'face_normals' in mesh._cache.cache:\n cached_normals = mesh._cache.cache['face_normals']\n else:\n cached_normals = None\n\n # also we can remove any zero are triangles by masking here\n new_normals, valid = triangles.normals(new_vertices[new_faces])\n # all the added faces were broken\n if not valid.any():\n return False\n\n # this is usually the case where two vertices of a triangle are just\n # over tol.merge apart, but the normal calculation is screwed up\n # these could be fixed by merging the vertices in question here:\n # if not valid.all():\n if mesh.visual.defined and mesh.visual.kind == 'face':\n color = mesh.visual.face_colors\n else:\n color = None\n\n # apply the new faces and vertices\n mesh.faces = np.vstack((mesh._data['faces'], new_faces[valid]))\n mesh.vertices = new_vertices\n\n # dump the cache and set id to the new hash\n mesh._cache.verify()\n\n # save us a normals recompute if we can\n if cached_normals is not None:\n mesh.face_normals = np.vstack((cached_normals,\n new_normals))\n\n # this is usually the case where two vertices of a triangle are just\n # over tol.merge apart, but the normal calculation is screwed up\n # these could be fixed by merging the vertices in question here:\n # if not valid.all():\n if color is not None:\n # if face colors exist, assign the last face color to the new faces\n # note that this is a little cheesey, but it is very inexpensive and\n # is the right thing to do if the mesh is a single color.\n color_shape = np.shape(color)\n if len(color_shape) == 2:\n new_colors = np.tile(color[-1], (np.sum(valid), 1))\n new_colors = np.vstack((color,\n new_colors))\n mesh.visual.face_colors = new_colors\n\n log.debug('Filled in mesh with %i triangles', np.sum(valid))\n return mesh.is_watertight\n"
] | [
[
"numpy.fliplr",
"numpy.sort",
"numpy.asanyarray",
"numpy.shape",
"numpy.column_stack",
"numpy.ravel",
"numpy.array",
"numpy.sum",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ChengF-Lab/CoV-KGE | [
"3fdf7109ac5c0f82bb5a7b3e8bb928ae5a8beeac"
] | [
"gnbr/concat.py"
] | [
"import pandas as pd\r\npd.set_option(\"precision\",10)\r\ndef triples():\r\n che_dis = pd.read_csv(\"triples_che_rel_dis\", delimiter='\\t', names=[\"ent1\", 'rel', 'ent2', 'score'])\r\n\r\n che_gen = pd.read_csv(\"triples_che_rel_gen\", delimiter='\\t', names=[\"ent1\", 'rel', 'ent2', 'score'])\r\n gen_dis = pd.read_csv(\"triples_gen_rel_dis.tsv\", delimiter='\\t', names=[\"ent1\", 'rel', 'ent2', 'score'])\r\n gen_gen = pd.read_csv(\"triples_gen_rel_gen.tsv\", delimiter='\\t', names=[\"ent1\", 'rel', 'ent2', 'score'])\r\n\r\n triples =pd.concat([che_dis,che_gen,gen_dis,gen_gen])\r\n print(\"done\")\r\n triples.to_csv(\"triples.tsv\", sep=\"\\t\", header=False, index=False)\r\n\r\n #得到所有实体\r\n # dis\r\n entity_cd_disease = pd.read_csv(\"original entitys/entity_cd_disease.tsv\", delimiter=\"\\t\", names=None)\r\n print(\"done\")\r\n print(entity_cd_disease)\r\n entity_gd_disease = pd.read_csv(\"original entitys/entity_gd_disease.tsv\", delimiter=\"\\t\", names=None)\r\n print(\"done\")\r\n print(entity_gd_disease)\r\n\r\n new_dis = pd.concat([entity_cd_disease, entity_gd_disease], axis=0)\r\n new_dis.rename(columns={'Entity2': 'entity', 'DB_ID2': 'GNBR_id'}, inplace=True)\r\n filter_disease = new_dis[[\"entity\", 'GNBR_id']].drop_duplicates(['GNBR_id'])\r\n print(filter_disease)\r\n\r\n ######################\r\n # chemical\r\n entity_cd_chemical = pd.read_csv(\"original entitys/entity_cd_chemical.tsv\", delimiter=\"\\t\", names=None)\r\n print(\"done\")\r\n print(entity_cd_chemical)\r\n entity_cg_chemical = pd.read_csv(\"original entitys/entity_cg_chemical.tsv\", delimiter=\"\\t\", names=None)\r\n print(\"done\")\r\n print(entity_cg_chemical)\r\n\r\n new_che = pd.concat([entity_cd_chemical, entity_cg_chemical], axis=0)\r\n new_che.rename(columns={'Entity1': 'entity', 'DB_ID1': 'GNBR_id'}, inplace=True)\r\n filter_chemical = new_che[[\"entity\", 'GNBR_id']].drop_duplicates(['GNBR_id'])\r\n print(filter_chemical)\r\n\r\n ##############################\r\n # gene\r\n entity_cg_gene = pd.read_csv(\"original entitys/entity_cg_gene.tsv\", delimiter=\"\\t\")\r\n entity_cg_gene.rename(columns={'Entity2': \"entity\", 'DB_ID2': 'GNBR_id'}, inplace=True)\r\n print(\"done\")\r\n print(entity_cg_gene)\r\n entity_gd_gene = pd.read_csv(\"original entitys/entity_gd_gene.tsv\", delimiter=\"\\t\")\r\n entity_gd_gene.rename(columns={'Entity1': \"entity\", 'DB_ID1': 'GNBR_id'}, inplace=True)\r\n print(\"done\")\r\n print(entity_gd_gene)\r\n\r\n entity_gg_gene1 = pd.read_csv(\"original entitys/entity_gg_gene1.tsv\", delimiter=\"\\t\")\r\n entity_gg_gene1.rename(columns={'Entity1': \"entity\", 'DB_ID1': 'GNBR_id'}, inplace=True)\r\n print(\"done\")\r\n print(entity_gg_gene1)\r\n entity_gg_gene2 = pd.read_csv(\"original entitys/entity_gg_gene2.tsv\", delimiter=\"\\t\")\r\n entity_gg_gene2.rename(columns={'Entity2': \"entity\", 'DB_ID2': 'GNBR_id'}, inplace=True)\r\n print(\"done\")\r\n print(entity_gg_gene2)\r\n new_gene = pd.concat([entity_cg_gene, entity_gd_gene, entity_gg_gene1, entity_gg_gene2], axis=0)\r\n filter_gene = new_gene[[\"entity\", 'GNBR_id']].drop_duplicates(['GNBR_id'])\r\n print(filter_gene)\r\n entity_to_GNBRid = pd.concat([filter_disease, filter_chemical, filter_gene], axis=0)\r\n print(\"all_entities:\", entity_to_GNBRid)\r\n entity_to_GNBRid.to_csv(\"entity_GNBRid.tsv\", sep=\"\\t\", header=True, index=False)\r\n\r\n entities_id = entity_to_GNBRid[\"GNBR_id\"]\r\n\r\n entities_id.to_csv(\"gnbr_entities.tsv\", sep=\"\\t\", header=True, index=False)\r\n\r\ndef prepare():\r\n #去重特殊的chemical实体\r\n gnbr_tri = pd.read_csv(\"triples.tsv\", delimiter='\\t', names=[\"h\", \"r\", \"t\", \"score\"])\r\n gnbr_ent1 = pd.read_csv(\"gnbr_entities.tsv\", delimiter='\\t', names=[\"gnbrid\"])\r\n gnbr_ent1 = gnbr_ent1[[\"gnbrid\",\"id\"]]\r\n\r\n not_gnbrc = gnbr_ent1[~gnbr_ent1[\"gnbrid\"].str.contains(\"C:\")]\r\n gnbr_ent = gnbr_ent1[gnbr_ent1[\"gnbrid\"].str.contains(\"C:\")]\r\n\r\n c_ent = gnbr_ent[~(gnbr_ent[\"gnbrid\"].str.contains(\"C:MESH\") | gnbr_ent[\"gnbrid\"].str.contains(\"C:CHEBI\"))]\r\n no_c_ent = gnbr_ent[(gnbr_ent[\"gnbrid\"].str.contains(\"C:MESH\") | gnbr_ent[\"gnbrid\"].str.contains(\"C:CHEBI\"))]\r\n print(c_ent)\r\n cs = c_ent[[\"gnbrid\"]].iloc[:, :].values\r\n\r\n c_ent[\"gnbrid\"] = c_ent[\"gnbrid\"].apply(lambda x: x.replace(\":\", \":MESH:\"))\r\n print(c_ent)\r\n all_ent = pd.concat([no_c_ent, not_gnbrc, c_ent], axis=0)\r\n print(all_ent)\r\n all_ent.drop_duplicates([\"gnbrid\"], keep=\"first\", inplace=True)\r\n all_ent = all_ent[\"gnbrid\"]\r\n print(all_ent)\r\n all_ent.to_csv(\"final_gnbr_entities.tsv\", sep='\\t', header=False, index=False)\r\n # 把C开头的三元组提取出来\r\n # not_c = gnbr_tri[~(gnbr_tri[\"h\"].str.contains(\"C:\") | gnbr_tri[\"t\"].str.contains(\"C:\"))]\r\n\r\n not_ctri = gnbr_tri[~gnbr_tri[\"h\"].isin(cs[:, 0])]\r\n print(not_ctri)\r\n c_tri = gnbr_tri[gnbr_tri[\"h\"].isin(cs[:, 0])]\r\n print(c_tri)\r\n c_tri[\"h\"] = c_tri[\"h\"].apply(lambda x: x.replace(\":\", \":MESH:\"))\r\n print(c_tri)\r\n all_tri = pd.concat([not_ctri, c_tri], axis=0)\r\n print(all_tri)\r\n final_tri = all_tri.sort_values(by=[\"score\"], ascending=False).groupby(by=[\"h\", \"t\", \"r\"]).first().reset_index()\r\n print(final_tri)\r\n final_tri.to_csv(\"final_gnbr_triples.tsv\", sep='\\t', header=False, index=False)\r\n\r\n\r\nif __name__ == '__main__':\r\n triples()\r\n prepare()\r\n\r\n\r\n"
] | [
[
"pandas.set_option",
"pandas.read_csv",
"pandas.concat"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
DavidStirling/centrosome | [
"c1ea6629d510e376cd34d229ba3ba5079b3a7093"
] | [
"centrosome/kirsch.py"
] | [
"from __future__ import absolute_import\nimport numpy\nimport scipy.ndimage.filters\nfrom six.moves import range\n\n\ndef kirsch(image):\n convolution_mask = [5, -3, -3, -3, -3, -3, 5, 5]\n\n derivatives = numpy.zeros(image.shape)\n\n kernel = numpy.zeros((3, 3), image.dtype)\n kindex = numpy.array([[0, 1, 2], [7, -1, 3], [6, 5, 4]])\n for _ in range(len(convolution_mask)):\n kernel[kindex >= 0] = numpy.array(convolution_mask)[kindex[kindex >= 0]]\n derivatives = numpy.maximum(\n derivatives, scipy.ndimage.filters.convolve(image, kernel)\n )\n\n convolution_mask = convolution_mask[-1:] + convolution_mask[:-1]\n\n return derivatives\n"
] | [
[
"numpy.array",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
SbstnErhrdt/fastnode2vec | [
"42609fb418f5e76935332c3f0ec81f65f672a977"
] | [
"fastnode2vec/graph.py"
] | [
"from collections import defaultdict\n\nimport numpy as np\n\nfrom numba import njit\nfrom scipy.sparse import csr_matrix\nfrom tqdm import tqdm\n\n\n@njit(nogil=True)\ndef _csr_row_cumsum(indptr, data):\n out = np.empty_like(data)\n for i in range(len(indptr) - 1):\n acc = 0\n for j in range(indptr[i], indptr[i + 1]):\n acc += data[j]\n out[j] = acc\n out[j] = 1.0\n return out\n\n\n@njit(nogil=True)\ndef _neighbors(indptr, indices_or_data, t):\n return indices_or_data[indptr[t] : indptr[t + 1]]\n\n\n@njit(nogil=True)\ndef _isin_sorted(a, x):\n return a[np.searchsorted(a, x)] == x\n\n\n@njit(nogil=True)\ndef _random_walk(indptr, indices, walk_length, p, q, t):\n max_prob = max(1 / p, 1, 1 / q)\n prob_0 = 1 / p / max_prob\n prob_1 = 1 / max_prob\n prob_2 = 1 / q / max_prob\n\n walk = np.empty(walk_length, dtype=indices.dtype)\n walk[0] = t\n walk[1] = np.random.choice(_neighbors(indptr, indices, t))\n for j in range(2, walk_length):\n neighbors = _neighbors(indptr, indices, walk[j - 1])\n if p == q == 1:\n # faster version\n walk[j] = np.random.choice(neighbors)\n continue\n while True:\n new_node = np.random.choice(neighbors)\n r = np.random.rand()\n if new_node == walk[j - 2]:\n if r < prob_0:\n break\n elif _isin_sorted(_neighbors(indptr, indices, walk[j - 2]), new_node):\n if r < prob_1:\n break\n elif r < prob_2:\n break\n walk[j] = new_node\n return walk\n\n\n@njit(nogil=True)\ndef _random_walk_weighted(indptr, indices, data, walk_length, p, q, t):\n max_prob = max(1 / p, 1, 1 / q)\n prob_0 = 1 / p / max_prob\n prob_1 = 1 / max_prob\n prob_2 = 1 / q / max_prob\n\n walk = np.empty(walk_length, dtype=indices.dtype)\n walk[0] = t\n walk[1] = _neighbors(indptr, indices, t)[\n np.searchsorted(_neighbors(indptr, data, t), np.random.rand())\n ]\n for j in range(2, walk_length):\n neighbors = _neighbors(indptr, indices, walk[j - 1])\n neighbors_p = _neighbors(indptr, data, walk[j - 1])\n if p == q == 1:\n # faster version\n walk[j] = neighbors[np.searchsorted(neighbors_p, np.random.rand())]\n continue\n while True:\n new_node = neighbors[np.searchsorted(neighbors_p, np.random.rand())]\n r = np.random.rand()\n if new_node == walk[j - 2]:\n if r < prob_0:\n break\n elif _isin_sorted(_neighbors(indptr, indices, walk[j - 2]), new_node):\n if r < prob_1:\n break\n elif r < prob_2:\n break\n walk[j] = new_node\n return walk\n\n\nclass Graph:\n def __init__(self, edges, directed, weighted, n_edges=None):\n if n_edges is None:\n try:\n n_edges = len(edges)\n except TypeError:\n pass\n\n self.weighted = weighted\n\n nodes = defaultdict(lambda: len(nodes))\n\n from_ = []\n to = []\n if weighted:\n data = []\n for tpl in tqdm(edges, desc=\"Reading graph\", total=n_edges):\n if weighted:\n a, b, w = tpl\n data.append(w)\n else:\n a, b = tpl\n a = nodes[a]\n b = nodes[b]\n from_.append(a)\n to.append(b)\n if not directed:\n from_.append(b)\n to.append(a)\n if weighted:\n data.append(w)\n\n if not weighted:\n data = np.ones(len(from_), dtype=bool)\n\n n = len(nodes)\n\n edges = csr_matrix((data, (from_, to)), shape=(n, n))\n edges.sort_indices()\n self.indptr = edges.indptr\n self.indices = edges.indices\n if weighted:\n data = edges.data / edges.sum(axis=1).A1.repeat(np.diff(self.indptr))\n self.data = _csr_row_cumsum(self.indptr, data)\n\n node_names = [None] * n\n for name, i in nodes.items():\n node_names[i] = name\n self.node_names = np.array(node_names)\n\n def generate_random_walk(self, walk_length, p, q, start):\n if self.weighted:\n walk = _random_walk_weighted(\n self.indptr, self.indices, self.data, walk_length, p, q, start\n )\n else:\n walk = _random_walk(self.indptr, self.indices, walk_length, p, q, start)\n return self.node_names[walk].tolist()\n"
] | [
[
"numpy.random.choice",
"numpy.empty_like",
"scipy.sparse.csr_matrix",
"numpy.diff",
"numpy.random.rand",
"numpy.searchsorted",
"numpy.array",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
Stimson-Center/stimson-web-scraper | [
"c2e6c3ae4abb8e8697b10d844bfb0fa3d305d05f"
] | [
"scraper/named_entity_recognition.py"
] | [
"import re\nfrom collections import OrderedDict\n\nimport dateparser\nimport numpy as np\nfrom date_extractor import extract_dates\nfrom spacy.lang.en.stop_words import STOP_WORDS\nfrom spacy.matcher import Matcher\n\n\n# https://gist.github.com/BrambleXu/3d47bbdbd1ee4e6fc695b0ddb88cbf99\n# https://spacy.io/usage/linguistic-features\n# https://spacy.io/api/doc\nclass TextRank4Keyword:\n \"\"\"Extract keywords from text\"\"\"\n\n def __init__(self, nlp):\n self.nlp = nlp\n # initialize matcher with a vocab\n self.matcher = Matcher(nlp.vocab)\n self.d = 0.85 # damping coefficient, usually is .85\n self.min_diff = 1e-5 # convergence threshold\n self.steps = 10 # iteration steps\n self.node_weight = None # save keywords and its weight\n self.doc = None\n self.stopwords = STOP_WORDS\n\n def set_stopwords(self, stopwords):\n \"\"\"\n Set stop words\n \"\"\"\n self.stopwords = self.stopwords.union(set(stopwords))\n for word in self.stopwords:\n lexeme = self.nlp.vocab[word]\n lexeme.is_stop = True\n\n def sentence_segment(self, candidate_pos, lower):\n \"\"\"\n Store those words only in cadidate_pos\n \"\"\"\n sentences = []\n for sent in self.doc.sents:\n selected_words = []\n for token in sent:\n # Store words only with cadidate POS tag\n if token.pos_ in candidate_pos and token.is_stop is False:\n if lower is True:\n selected_words.append(token.text.lower())\n else:\n selected_words.append(token.text)\n sentences.append(selected_words)\n return sentences\n\n def get_vocab(self, sentences):\n \"\"\"\n Get all tokens\n \"\"\"\n vocab = OrderedDict()\n i = 0\n for sentence in sentences:\n for word in sentence:\n if word not in vocab:\n vocab[word] = i\n i += 1\n return vocab\n\n def get_token_pairs(self, window_size, sentences):\n \"\"\"\n Build token_pairs from windows in sentences\n \"\"\"\n token_pairs = list()\n for sentence in sentences:\n for i, word in enumerate(sentence):\n for j in range(i + 1, i + window_size):\n if j >= len(sentence):\n break\n pair = (word, sentence[j])\n if pair not in token_pairs:\n token_pairs.append(pair)\n return token_pairs\n\n @staticmethod\n def symmetrize(a):\n return a + a.T - np.diag(a.diagonal())\n\n def get_matrix(self, vocab, token_pairs):\n \"\"\"\n Get normalized matrix\n \"\"\"\n # Build matrix\n vocab_size = len(vocab)\n g = np.zeros((vocab_size, vocab_size), dtype='float')\n for word1, word2 in token_pairs:\n i, j = vocab[word1], vocab[word2]\n g[i][j] = 1\n\n # Get Symmeric matrix\n g = self.symmetrize(g)\n\n # Normalize matrix by column\n norm = np.sum(g, axis=0)\n g_norm = np.divide(g, norm, where=norm != 0) # this is ignore the 0 element in norm\n\n return g_norm\n\n def get_keywords(self, number=10):\n \"\"\"\n Print top number keywords\n \"\"\"\n node_weight = OrderedDict(sorted(self.node_weight.items(), key=lambda t: t[1], reverse=True))\n keywords = dict()\n for i, (k, v) in enumerate(node_weight.items()):\n if k.isalnum():\n keywords[k] = v\n if i > number:\n break\n return keywords\n\n def get_phrases(self, number=10):\n phrases = list()\n # noinspection PyProtectedMember\n for i, p in enumerate(self.doc._.phrases):\n if i >= number:\n break\n phrases.append(p)\n return phrases\n\n def get_sentences(self, number=5):\n sentences = list()\n for i, s in enumerate(self.doc.sents):\n if i >= number:\n break\n sentences.append(s)\n return sentences\n\n def get_dates(self):\n # https://spacy.io/usage/linguistic-features#101\n ents = [ent for ent in self.doc.ents if ent.label_ == 'DATE']\n for ent in self.doc.ents:\n if ent.label_ == \"01/04/1937\":\n pass\n dates = list()\n for ent in ents:\n date = dateparser.parse(ent.text)\n dates.append(date)\n if not dates:\n extracted_dates = extract_dates(self.doc.text)\n dates += extracted_dates\n return dates\n\n def get_persons(self):\n # https://omkarpathak.in/2018/12/18/writing-your-own-resume-parser/#rule-based-matching\n # First name and Last name are always Proper Nouns\n # pattern = [{'POS': 'PROPN'}, {'POS': 'PROPN'}]\n # self.matcher.add('NAME', None, pattern)\n # matches = self.matcher(self.doc)\n # persons = list()\n # for match_id, start, end in matches:\n # span = self.doc[start:end]\n # persons.append(span.text)\n # return persons\n return [ent.text for ent in self.doc.ents if ent.label_ == 'PERSON']\n\n def get_education(self):\n # https://omkarpathak.in/2018/12/18/writing-your-own-resume-parser/#rule-based-matching\n # Education Degrees\n # noinspection PyPep8Naming\n EDUCATION = [\n 'BE', 'B.E.', 'B.E',\n 'BS', 'B.S.', 'B.S',\n 'BA', 'B.A', 'B.A',\n 'ME', 'M.E.', 'M.E',\n 'MS', 'M.S.', 'M.S'\n 'BTECH', 'B.TECH',\n 'M.TECH', 'MTECH',\n 'PhD', 'Ph.D.', 'Ph.D', 'DPhil',\n 'SSC', 'HSC', 'CBSE', 'ICSE', 'X', 'XII'\n ]\n # Sentence Tokenizer\n nlp_text = [sent.string.strip() for sent in self.doc.sents]\n edu = dict()\n # Extract education degree\n for index, text in enumerate(nlp_text):\n for tex in text.split():\n # Replace all special symbols\n tex = re.sub(r'[?|$|.|!|,]', r'', tex)\n if tex.upper() in EDUCATION and tex not in self.stopwords:\n edu[tex] = text + nlp_text[index + 1]\n\n # Extract year\n education = []\n for key in edu.keys():\n year = re.search(re.compile(r'(((20|19)(\\d{2})))'), edu[key])\n if year:\n education.append((key, ''.join(year[0])))\n else:\n education.append(key)\n return education\n\n def analyze(self, text, candidate_pos=None, window_size=4, lower=False, stopwords=None):\n \"\"\"\n Main function to analyze text\n \"\"\"\n\n # Set stop words\n if stopwords is None:\n stopwords = list()\n if candidate_pos is None:\n candidate_pos = ['NOUN', 'PROPN']\n self.set_stopwords(stopwords)\n\n # Pare text by spaCy\n self.doc = self.nlp(text)\n\n # Filter sentences\n sentences = self.sentence_segment(candidate_pos, lower) # list of list of words\n\n # Build vocabulary\n vocab = self.get_vocab(sentences)\n\n # Get token_pairs from windows\n token_pairs = self.get_token_pairs(window_size, sentences)\n\n # Get normalized matrix\n g = self.get_matrix(vocab, token_pairs)\n\n # Initialization for weight(pagerank value)\n pr = np.array([1] * len(vocab))\n\n # Iteration\n previous_pr = 0\n for epoch in range(self.steps):\n pr = (1 - self.d) + self.d * np.dot(g, pr)\n if abs(previous_pr - sum(pr)) < self.min_diff:\n break\n else:\n previous_pr = sum(pr)\n\n # Get weight for each node\n node_weight = dict()\n for word, index in vocab.items():\n node_weight[word] = pr[index]\n\n self.node_weight = node_weight\n"
] | [
[
"numpy.dot",
"numpy.zeros",
"numpy.sum",
"numpy.divide"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Solrovivrus/MedicalApp | [
"2dd819d0f89d9162c5cab35b224b9118e0000e63"
] | [
"src/Python_Files/testing_playground/depreciated_files/json_pretty_print.py"
] | [
"import pandas\nimport json\n\nfiles = [\n \"Central_Montana_Medical_Center\"\n]\n\nfor item in files:\n print(\"Scanning: \", item)\n \n excel_data_df = pandas.read_excel(item + '.xlsx', sheet_name=item)\n\n #Add hospital name to each row\n excel_data_df[\"Hospital\"] = item.replace(\"_\", \" \")\n #print(excel_data_df)\n\n thisisjson = excel_data_df.to_json(orient='records')\n\n\n thisisjson_dict = json.loads(thisisjson)\n\n with open(item + '.json', 'w') as json_file:\n json.dump(thisisjson_dict, json_file, indent=4, sort_keys=True)\n\n print(\"Completed\")\n print()\n\n#Test Successful\n#Awaiting Implementation\n"
] | [
[
"pandas.read_excel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
Shuijing725/VAE_trait_inference | [
"a018455f992a9270092ac925bfbd1f3680ed2b20"
] | [
"rl/rl_models/rnn_base.py"
] | [
"import torch.nn as nn\nimport torch\n\n\n'''\nbase class for all RNN policies\n\ndifference from default RNNs in pytorch: RNNBase can use masks to reset the RNN hidden states appropriately, when an episode is done\n'''\nclass RNNBase(nn.Module):\n\n def __init__(self, config):\n super(RNNBase, self).__init__()\n self.config = config\n\n self.gru = nn.GRU(config.network.embedding_size, config.network.rnn_hidden_size)\n\n for name, param in self.gru.named_parameters():\n if 'bias' in name:\n nn.init.constant_(param, 0)\n elif 'weight' in name:\n nn.init.orthogonal_(param)\n\n # x: [seq_len, nenv, human_num, ?]\n # hxs: [1, nenv, human_num, ?]\n # masks: [seq_len, nenv, 1]\n def _forward_gru(self, x, hxs, masks):\n # for acting model, input shape[0] == hidden state shape[0]\n if x.size(0) == hxs.size(0):\n # use env dimension as batch\n # [1, 12, 6, ?] -> [1, 12*6, ?] or [30, 6, 6, ?] -> [30, 6*6, ?]\n seq_len, nenv, agent_num, _ = x.size()\n x = x.view(seq_len, nenv*agent_num, -1)\n hxs_times_masks = hxs * (masks.view(seq_len, nenv, 1, 1))\n hxs_times_masks = hxs_times_masks.view(seq_len, nenv*agent_num, -1)\n x, hxs = self.gru(x, hxs_times_masks) # we already unsqueezed the inputs in SRNN forward function\n x = x.view(seq_len, nenv, agent_num, -1)\n hxs = hxs.view(seq_len, nenv, agent_num, -1)\n\n # during update, input shape[0] * nsteps (30) = hidden state shape[0]\n else:\n\n # N: nenv, T: seq_len, agent_num: node num or edge num\n T, N, agent_num, _ = x.size()\n # x = x.view(T, N, agent_num, x.size(2))\n\n # Same deal with masks\n masks = masks.view(T, N)\n\n # Let's figure out which steps in the sequence have a zero for any agent\n # We will always assume t=0 has a zero in it as that makes the logic cleaner\n # for the [29, num_env] boolean array, if any entry in the second axis (num_env) is True -> True\n # to make it [29, 1], then select the indices of True entries\n has_zeros = ((masks[1:] == 0.0) \\\n .any(dim=-1)\n .nonzero()\n .squeeze()\n .cpu())\n\n # +1 to correct the masks[1:]\n if has_zeros.dim() == 0:\n # Deal with scalar\n has_zeros = [has_zeros.item() + 1]\n else:\n has_zeros = (has_zeros + 1).numpy().tolist()\n\n # add t=0 and t=T to the list\n has_zeros = [0] + has_zeros + [T]\n\n # hxs = hxs.unsqueeze(0)\n # hxs = hxs.view(hxs.size(0), hxs.size(1)*hxs.size(2), hxs.size(3))\n outputs = []\n for i in range(len(has_zeros) - 1):\n # We can now process steps that don't have any zeros in masks together!\n # This is much faster\n start_idx = has_zeros[i]\n end_idx = has_zeros[i + 1]\n\n # x and hxs have 4 dimensions, merge the 2nd and 3rd dimension\n x_in = x[start_idx:end_idx]\n x_in = x_in.view(x_in.size(0), x_in.size(1)*x_in.size(2), x_in.size(3))\n hxs = hxs.view(hxs.size(0), N, agent_num, -1)\n hxs = hxs * (masks[start_idx].view(1, -1, 1, 1))\n hxs = hxs.view(hxs.size(0), hxs.size(1) * hxs.size(2), hxs.size(3))\n rnn_scores, hxs = self.gru(x_in, hxs)\n\n outputs.append(rnn_scores)\n\n # assert len(outputs) == T\n # x is a (T, N, -1) tensor\n x = torch.cat(outputs, dim=0)\n # flatten\n x = x.view(T, N, agent_num, -1)\n hxs = hxs.view(1, N, agent_num, -1)\n\n return x, hxs\n\n\ndef reshapeT(T, seq_length, nenv):\n shape = T.size()[1:]\n return T.unsqueeze(0).reshape((seq_length, nenv, *shape))"
] | [
[
"torch.nn.init.constant_",
"torch.nn.GRU",
"torch.nn.init.orthogonal_",
"torch.cat"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
czbiohub/fluorophore_backward_dp | [
"b8292cb5ebc7443fa159fef624d597c4e35f6eb0"
] | [
"test_fluorophore_backward_dp.py"
] | [
"import numpy as np\n\nfrom fluorophore_backward_dp import *\n\ndef test_mle():\n np.random.seed(12345)\n b = 1\n r = 1000\n N = 10\n t = simulate_emission_times(r, simulate_bleaching_times(b, N))\n l = emission_times_loglik(t, b, r, truncate=1000)\n assert np.argmax(l) == N\n"
] | [
[
"numpy.argmax",
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nabeelsana/DataCamp-courses | [
"383b644907cca1c14befb4706a32579bec01a134"
] | [
"Importing Data in Python pt1/Chapter 2 - Importing data from other file types.py"
] | [
"\n#Chapter 2 - Importing data from other file types\n\n\n\n\n#Loading a pickled file\n# Import pickle package\nimport pickle\n\n# Open pickle file and load data: d\nwith open('data.pkl', 'rb') as file:\n d = pickle.load(file)\n\n# Print d\nprint(d)\n\n# Print datatype of d\nprint(type(d))\n\n#Listing sheets in Excel files\n# Import pandas\nimport pandas as pd\n\n# Assign spreadsheet filename: file\nfile = 'battledeath.xlsx'\n\n# Load spreadsheet: xl\nxl = pd.ExcelFile(file)\n\n# Print sheet names\nprint(xl.sheet_names)\n\n#Importing sheets from Excel files\n# Load a sheet into a DataFrame by name: df1\ndf1 = xl.parse('2004')\n\n# Print the head of the DataFrame df1\nprint(df1.head())\n\n# Load a sheet into a DataFrame by index: df2\ndf2 = xl.parse(0)\n\n# Print the head of the DataFrame df2\nprint(df2.head())\n\n#Customizing your spreadsheet import\n# Parse the first sheet and rename the columns: df1\ndf1 = xl.parse(0, skiprows=[0], names=['Country', 'AAM due to War (2002)'])\n\n# Print the head of the DataFrame df1\nprint(df1.head())\n\n# Parse the first column of the second sheet and rename the column: df2\ndf2 = xl.parse(1, parse_cols=[0], skiprows=[0], names=['Country'])\n\n# Print the head of the DataFrame df2\nprint(df2.head())\n\n\n#Importing SAS files\n# Import sas7bdat package\nfrom sas7bdat import SAS7BDAT \n\n# Save file to a DataFrame: df_sas\nwith SAS7BDAT('sales.sas7bdat') as file:\n df_sas = file.to_data_frame()\n\n# Print head of DataFrame\nprint(df_sas.head())\n\n# Plot histogram of DataFrame features (pandas and pyplot already imported)\npd.DataFrame.hist(df_sas[['P']])\nplt.ylabel('count')\nplt.show()\n\n#Importing Stata files\n# Import pandas\nimport pandas as pd\n\n# Load Stata file into a pandas DataFrame: df\ndf = pd.read_stata('disarea.dta')\n\n# Print the head of the DataFrame df\nprint(df.head())\n\n# Plot histogram of one column of the DataFrame\npd.DataFrame.hist(df[['disa10']])\nplt.xlabel('Extent of disease')\nplt.ylabel('Number of coutries')\nplt.show()\n\n#Using h5py to import HDF5 files\n# Import packages\nimport numpy as np\nimport h5py\n\n# Assign filename: file\nfile = 'LIGO_data.hdf5'\n\n# Load file: data\ndata = h5py.File(file, 'r')\n\n# Print the datatype of the loaded file\nprint(type(data))\n\n# Print the keys of the file\nfor key in data.keys():\n print(key)\n\n# Extracting data from your HDF5 file\n# Get the HDF5 group: group\ngroup = data['strain']\n\n# Check out keys of group\nfor key in group.keys():\n print(key)\n\n# Set variable equal to time series data: strain\nstrain = data['strain']['Strain'].value\n\n# Set number of time points to sample: num_samples\nnum_samples = 10000\n\n# Set time vector\ntime = np.arange(0, 1, 1/num_samples)\n\n# Plot data\nplt.plot(time, strain[:num_samples])\nplt.xlabel('GPS Time (s)')\nplt.ylabel('strain')\nplt.show()\n\n#Loading .mat files\n# Import package\nimport scipy.io\n\n# Load MATLAB file: mat\nmat = scipy.io.loadmat('albeck_gene_expression.mat')\n\n# Print the datatype type of mat\nprint(type(mat))\n\n# The structure of .mat in Python\n# Print the keys of the MATLAB dictionary\nprint(mat.keys())\n\n# Print the type of the value corresponding to the key 'CYratioCyt'\nprint(type(mat['CYratioCyt']))\n\n# Print the shape of the value corresponding to the key 'CYratioCyt'\nprint(np.shape(mat['CYratioCyt']))\n\n# Subset the array and plot it\ndata = mat['CYratioCyt'][25, 5:]\nfig = plt.figure()\nplt.plot(data)\nplt.xlabel('time (min.)')\nplt.ylabel('normalized fluorescence (measure of expression)')\n"
] | [
[
"pandas.DataFrame.hist",
"numpy.arange",
"numpy.shape",
"pandas.ExcelFile",
"pandas.read_stata"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
JosepLeder/Lekai-Reinforcement-Learning-Notes | [
"d9476cf1f959cca43880886104e4aa9892e970fc"
] | [
"code/utils.py"
] | [
"import numpy as np\nfrom torch.utils.data.sampler import BatchSampler, SubsetRandomSampler\nimport torch as th\nfrom torch import nn\nfrom typing import Generator, Optional, Union, Tuple, NamedTuple\nfrom gym import spaces\n\n\ndef init(module, weight_init, bias_init, gain=1):\n weight_init(module.weight.data, gain=gain)\n bias_init(module.bias.data)\n return module\n\n\ndef _flatten_helper(T, N, _tensor):\n return _tensor.view(T * N, *_tensor.size()[2:])\n\n\nclass TrajectoryBuffer(object):\n def __init__(self, num_steps, num_processes, obs_shape, action_space):\n self.obs = th.zeros(num_steps + 1, num_processes, *obs_shape)\n self.rewards = th.zeros(num_steps + 1, num_processes, 1)\n self.returns = th.zeros(num_steps + 1, num_processes, 1)\n self.action_log_probs = th.zeros(num_steps, num_processes, 1)\n self.actions = th.zeros(num_steps, num_processes, action_space.shape[0])\n self.masks = th.ones(num_steps + 1, num_processes, 1)\n\n # Masks that indicate whether it's a true terminal state\n # or time limit end state\n self.bad_masks = th.ones(num_steps + 1, num_processes, 1)\n\n self.num_steps = num_steps\n self.step = 0\n\n def to(self, device):\n self.obs = self.obs.to(device)\n self.rewards = self.rewards.to(device)\n self.returns = self.returns.to(device)\n self.action_log_probs = self.action_log_probs.to(device)\n self.actions = self.actions.to(device)\n self.masks = self.masks.to(device)\n self.bad_masks = self.bad_masks.to(device)\n\n def insert(self, obs, actions, action_log_probs, rewards, masks, bad_masks):\n self.obs[self.step + 1].copy_(obs)\n self.actions[self.step].copy_(actions)\n self.action_log_probs[self.step].copy_(action_log_probs)\n self.rewards[self.step + 1].copy_(rewards)\n self.masks[self.step + 1].copy_(masks)\n self.bad_masks[self.step + 1].copy_(bad_masks)\n\n self.step = (self.step + 1) % self.num_steps\n\n def after_update(self):\n self.obs[0].copy_(self.obs[-1])\n self.rewards[0].copy_(self.rewards[-1])\n self.masks[0].copy_(self.masks[-1])\n self.bad_masks[0].copy_(self.bad_masks[-1])\n\n def compute_returns(self, gamma):\n self.returns[-1] = self.rewards[0]\n for step in reversed(range(self.num_steps)):\n self.returns[step] = (self.returns[step + 1] * gamma * self.masks[step + 1] +\n self.rewards[step + 1]) * self.bad_masks[step + 1]\n\n\nclass ReplayBuffer(object):\n def __init__(self, state_dim, action_dim, max_size=int(1e6)):\n self.max_size = max_size\n self.pos = 0\n self.size = 0\n\n self.state = np.zeros((max_size, state_dim))\n self.action = np.zeros((max_size, action_dim))\n self.next_state = np.zeros((max_size, state_dim))\n self.reward = np.zeros((max_size, 1))\n self.not_done = np.zeros((max_size, 1))\n\n self.device = th.device(\"cpu\")\n\n def add(self, state, action, next_state, reward, done):\n self.state[self.pos] = state\n self.action[self.pos] = action\n self.next_state[self.pos] = next_state\n self.reward[self.pos] = reward\n self.not_done[self.pos] = 1. - done\n\n self.pos = (self.pos + 1) % self.max_size\n self.size = min(self.size + 1, self.max_size)\n\n def sample(self, batch_size):\n ind = np.random.randint(0, self.size, size=batch_size)\n\n return (\n th.FloatTensor(self.state[ind]).to(self.device),\n th.FloatTensor(self.action[ind]).to(self.device),\n th.FloatTensor(self.next_state[ind]).to(self.device),\n th.FloatTensor(self.reward[ind]).to(self.device),\n th.FloatTensor(self.not_done[ind]).to(self.device)\n )\n\n\nclass RolloutBuffer(object):\n def __init__(self, num_steps, num_processes, obs_shape, action_space):\n self.obs = th.zeros(num_steps + 1, num_processes, *obs_shape)\n self.rewards = th.zeros(num_steps, num_processes, 1)\n self.value_preds = th.zeros(num_steps + 1, num_processes, 1)\n self.returns = th.zeros(num_steps + 1, num_processes, 1)\n self.action_log_probs = th.zeros(num_steps, num_processes, 1)\n self.actions = th.zeros(num_steps, num_processes, action_space.shape[0])\n self.masks = th.ones(num_steps + 1, num_processes, 1)\n\n # Masks that indicate whether it's a true terminal state\n # or time limit end state\n self.bad_masks = th.ones(num_steps + 1, num_processes, 1)\n\n self.num_steps = num_steps\n self.step = 0\n\n def to(self, device):\n self.obs = self.obs.to(device)\n self.rewards = self.rewards.to(device)\n self.value_preds = self.value_preds.to(device)\n self.returns = self.returns.to(device)\n self.action_log_probs = self.action_log_probs.to(device)\n self.actions = self.actions.to(device)\n self.masks = self.masks.to(device)\n self.bad_masks = self.bad_masks.to(device)\n\n def insert(self, obs, actions, action_log_probs,\n value_preds, rewards, masks, bad_masks):\n self.obs[self.step + 1].copy_(obs)\n self.actions[self.step].copy_(actions)\n self.action_log_probs[self.step].copy_(action_log_probs)\n self.value_preds[self.step].copy_(value_preds)\n self.rewards[self.step].copy_(rewards)\n self.masks[self.step + 1].copy_(masks)\n self.bad_masks[self.step + 1].copy_(bad_masks)\n\n self.step = (self.step + 1) % self.num_steps\n\n def after_update(self):\n self.obs[0].copy_(self.obs[-1])\n self.masks[0].copy_(self.masks[-1])\n self.bad_masks[0].copy_(self.bad_masks[-1])\n\n def compute_returns(self, next_value, gamma):\n self.returns[-1] = next_value\n for step in reversed(range(self.rewards.size(0))):\n self.returns[step] = (self.returns[step + 1] * gamma * self.masks[step + 1] + self.rewards[step]) * \\\n self.bad_masks[step + 1] + (1 - self.bad_masks[step + 1]) * self.value_preds[step]\n\n\ndef sum_independent_dims(tensor: th.Tensor) -> th.Tensor:\n \"\"\"\n Continuous actions are usually considered to be independent,\n so we can sum components of the ``log_prob`` or the entropy.\n :param tensor: (th.Tensor) shape: (n_batch, n_actions) or (n_batch,)\n :return: (th.Tensor) shape: (n_batch,)\n \"\"\"\n if len(tensor.shape) > 1:\n tensor = tensor.sum(dim=1)\n else:\n tensor = tensor.sum()\n return tensor\n\n\n"
] | [
[
"torch.ones",
"torch.zeros",
"torch.FloatTensor",
"torch.device",
"numpy.zeros",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
IST-DASLab/ACDC | [
"ac53210b6adc1f2506ff909de08172ed9cad25d5"
] | [
"policies/pruners.py"
] | [
"\"\"\"\nImplement Pruners here.\n\n\"\"\"\nimport numpy as np\n\nfrom policies.policy import PolicyBase\nfrom utils import (get_total_sparsity,\n recompute_bn_stats,\n percentile,\n get_prunable_children)\n\n\nimport torch\nimport torch.optim as optim\nfrom torch.utils.data.sampler import SubsetRandomSampler\n\nimport logging\nfrom typing import List, Dict\nfrom copy import deepcopy\n\nfrom tqdm import tqdm\nfrom torch.utils.data import DataLoader\nimport torch.nn.functional as F\n\nimport pdb\n\ndef build_pruner_from_config(model, pruner_config):\n \"\"\"\n This function takes the takes pruner config and model that are provided by function\n build_pruners_from_config. We assume that each pruner have one parameter\n group, i.e., which shares sparsity levels and pruning schedules.\n\n The *suggested!* .yaml file structure is defined in build_pruners_from_config.\n \"\"\"\n pruner_class = pruner_config['class']\n pruner_args = {k: v for k, v in pruner_config.items() if k != 'class'}\n pruner = globals()[pruner_class](model, **pruner_args)\n return pruner\n\ndef build_pruners_from_config(model, config):\n \"\"\"\n This function takes *general* config file for current run and model \n and returns a list of pruners which are build by build_pruner_from_config.\n\n Example config.yaml for pruner instances:\n\n >>> pruners:\n >>> pruner_1:\n >>> class: MagnitudePruner\n >>> epochs: [0,2,4] # [start, freq, end] for now (TODO: but can extend functionality?)\n >>> weight_only: True # if True prunes only *.weight parameters in specified layers\n >>> # if *.bias is None thif flag is just ignored\n >>> initial_sparsity: 0.05 # initial sparsity level for parameters\n >>> target_sparsity: 0.7 # desired sparsity level at the end of pruning\n >>> modules: [net.0] # modules of type (nn.Conv2d, nn.Linear, effnet.StaticPaddingConv2d) (or\n >>> # any instance containing as parameters *.weight and *.bias? TODO: maybe useful?)\n >>> keep_pruned: False # Optional from now on\n >>> degree: 3 # Optional degree to use for polynomial schedule\n >>> pruner_2:\n >>> class: MagnitudePruner\n >>> epochs: [0,2,4]\n >>> weight_only: True\n >>> initial_sparsity: 0.05\n >>> target_sparsity: 0.8\n >>> modules: [net.2]\n >>> keep_pruned: False\n\n\n There is an optional arguments:\n keep_pruned: whether pruned weights values shoud be store, recommended values is false \n unless you want to use reintroduction with previous magnitudes\n \"\"\"\n if 'pruners' not in config: return []\n pruners_config = config['pruners']\n pruners = [build_pruner_from_config(model, pruner_config) \n for pruner_config in pruners_config.values()]\n return pruners\n\n\nclass Pruner(PolicyBase):\n def __init__(self, *args, **kwargs):\n # TODO: figure out a better initialization strategy so that we make sure these attributes are present in all descendant objects,\n # as well as a method to check that the supplied modules comply with our assumptions. Maybe it is fine this way, too.\n # the following asserts are needed because the base class relies on these attributes:\n assert hasattr(self, '_modules'), \"@Pruner: make sure any Pruner has 'modules' and 'module_names' attribute\"\n assert hasattr(self, '_module_names'), \"@Pruner: make sure any Pruner has 'modules' and 'module_names' attribute\"\n # this is needed because after_parameter_optimization method assumes this:\n assert all([is_wrapped_layer(_module) for _module in self._modules]), \\\n \"@Pruner: currently the code assumes that you supply prunable layers' names directly in the config\"\n\n def on_epoch_end(self, **kwargs):\n # Included for completeness, but there is nothing to close out here.\n pass\n\n def measure_sparsity(self, **kwargs):\n sparsity_dict = {}\n for _name, _module in zip(self._module_names, self._modules):\n num_zeros, num_params = get_total_sparsity(_module)\n sparsity_dict[_name] = (num_zeros, num_params)\n return sparsity_dict\n\n def after_parameter_optimization(self, model, **kwargs):\n \"\"\"\n Currently this stage is used to mask pruned neurons within the layer's data.\n TODO: think if this is general enough to be all Pruners' method, or\n it is GradualPruners' method only.\n \"\"\"\n for _module in self._modules:\n _module.apply_masks_to_data()\n\n\nclass GradualPruner(Pruner):\n def __init__(self, model, **kwargs):\n \"\"\"\n Arguments:\n model {nn.Module}: network with wrapped modules to bound pruner\n Key arguments:\n kwargs['initial_sparsity']: initial_sparsity layer sparsity\n kwargs['target_sparsity']: target sparsity for pruning end\n kwargs['weight_only']: bool, if only weights are pruned\n kwargs['epochs']: list, [start_epoch, pruning_freq, end_epoch]\n kwargs['modules']: list of module names to be pruned\n kwargs['degree']: float/int, degree to use in polinomial schedule, \n degree == 1 stands for uniform schedule\n \"\"\"\n self._start, self._freq, self._end = kwargs['epochs']\n self._weight_only = kwargs['weight_only']\n self._initial_sparsity = kwargs['initial_sparsity']\n self._target_sparsity = kwargs['target_sparsity']\n\n self._keep_pruned = kwargs['keep_pruned'] if 'keep_pruned' in kwargs else False\n self._degree = kwargs['degree'] if 'degree' in kwargs else 3\n\n self._model = model\n modules_dict = dict(self._model.named_modules())\n\n prefix = ''\n if isinstance(self._model, torch.nn.DataParallel):\n prefix = 'module.'\n # Unwrap user-specified modules to prune into lowest-level prunables:\n self._module_names = [prefix + _name for _name in kwargs['modules']]\n # self._module_names = [prefix + _name for _name in get_prunable_children(self._model, kwargs['modules'])]\n\n self._modules = [\n modules_dict[module_name] for module_name in self._module_names\n ]\n\n if self._keep_pruned:\n for module in self._modules:\n module.copy_pruned(True)\n\n logging.debug(f'Constructed {self.__class__.__name__} with config:')\n logging.debug('\\n'.join([f' -{k}:{v}' for k,v in kwargs.items()]) + '\\n')\n\n def update_initial_sparsity(self):\n parameter_sparsities = []\n for module in self._modules:\n w_sparsity, b_sparsity = module.weight_sparsity, module.bias_sparsity\n parameter_sparsities.append(w_sparsity)\n if b_sparsity is not None: parameter_sparsities.append(b_sparsity)\n self._initial_sparsity = np.mean(parameter_sparsities)\n\n @staticmethod\n def _get_param_stat(param):\n raise NotImplementedError(\"Implement in child class.\")\n\n def _polynomial_schedule(self, curr_epoch):\n scale = self._target_sparsity - self._initial_sparsity\n progress = min(float(curr_epoch - self._start) / (self._end - self._start), 1.0)\n remaining_progress = (1.0 - progress) ** self._degree\n return self._target_sparsity - scale * remaining_progress\n\n def _required_sparsity(self, curr_epoch):\n return self._polynomial_schedule(curr_epoch)\n\n def _pruner_not_active(self, epoch_num):\n return ((epoch_num - self._start) % self._freq != 0 or epoch_num > self._end or epoch_num < self._start)\n\n\n @staticmethod\n def _get_pruning_mask(param_stats, sparsity=None, threshold=None):\n if param_stats is None: return None\n if sparsity is None and threshold is None: return None\n if threshold is None:\n threshold = percentile(param_stats, sparsity)\n return (param_stats > threshold).float()\n\n\nclass MagnitudePruner(GradualPruner):\n def __init__(self, model, **kwargs):\n super(MagnitudePruner, self).__init__(model, **kwargs)\n\n @staticmethod\n def _get_param_stat(param, param_mask):\n if param is None or param_mask is None: return None\n return (param.abs() + 1e-4) * param_mask\n\n def on_epoch_begin(self, epoch_num, **kwargs):\n if self._pruner_not_active(epoch_num):\n return False, {}\n for module in self._modules:\n level = self._required_sparsity(epoch_num)\n w_stat, b_stat = self._get_param_stat(module.weight, module.weight_mask),\\\n self._get_param_stat(module.bias, module.bias_mask)\n module.weight_mask, module.bias_mask = self._get_pruning_mask(w_stat, level),\\\n self._get_pruning_mask(None if self._weight_only else b_stat, level)\n return True, {\"level\": level}\n\n\n\nclass UnstructuredMagnitudePruner(GradualPruner):\n def __init__(self, model, **kwargs):\n super(UnstructuredMagnitudePruner, self).__init__(model, **kwargs)\n\n @staticmethod\n def _get_param_stat(param, param_mask):\n if param is None or param_mask is None: return None\n return ((param.abs() + 1e-4) * param_mask)\n\n def on_epoch_begin(self, epoch_num, device, **kwargs):\n if self._pruner_not_active(epoch_num):\n return False, {}\n\n level = self._required_sparsity(epoch_num)\n logging.debug(\"Desired sparsity level is \", level)\n if level == 0:\n return False, {}\n weights = torch.zeros(0)\n if device.type == 'cuda':\n weights = weights.cuda()\n total_params = 0\n for module in self._modules:\n weights = torch.cat((weights, self._get_param_stat(module.weight, module.weight_mask).view(-1)))\n if not self._weight_only:\n if module.bias is not None:\n weights = torch.cat((weights, self._get_param_stat(module.bias, module.bias_mask).view(-1)))\n threshold = percentile(weights, level)\n\n for module in self._modules:\n w_stat, b_stat = self._get_param_stat(module.weight, module.weight_mask),\\\n self._get_param_stat(module.bias, module.bias_mask)\n module.weight_mask, module.bias_mask = self._get_pruning_mask(w_stat, threshold=threshold),\\\n self._get_pruning_mask(None if self._weight_only else b_stat,\n threshold=threshold)\n return True, {\"level\": level}\n\n\n\n# Implements N:M pruner for structured sparsity, as in here: https://github.com/NM-sparsity/NM-sparsity\n# Paper: https://openreview.net/pdf?id=K9bw7vqp_s\nclass MagnitudeNMPruner(Pruner):\n def __init__(self, model, **kwargs):\n\n self._start, self._freq, self._end = kwargs['epochs']\n self._weight_only = kwargs['weight_only']\n self._N = kwargs['N']\n self._M = kwargs['M']\n\n self._model = model\n modules_dict = dict(self._model.named_modules())\n\n prefix = ''\n if isinstance(self._model, torch.nn.DataParallel):\n prefix = 'module.'\n # Unwrap user-specified modules to prune into lowest-level prunables:\n self._module_names = [prefix + _name for _name in kwargs['modules']]\n # self._module_names = [prefix + _name for _name in get_prunable_children(self._model, kwargs['modules'])]\n\n self._modules = [\n modules_dict[module_name] for module_name in self._module_names\n ]\n logging.debug(f'Constructed {self.__class__.__name__} with config:')\n logging.debug('\\n'.join([f' -{k}:{v}' for k, v in kwargs.items()]) + '\\n')\n\n\n def _pruner_not_active(self, epoch_num):\n return ((epoch_num - self._start) % self._freq != 0 or epoch_num > self._end or epoch_num < self._start)\n\n\n def on_epoch_begin(self, epoch_num, device, **kwargs):\n if self._pruner_not_active(epoch_num):\n return False, {}\n\n level = self._N / self._M\n\n for module in self._modules:\n module.bias_mask = None\n\n cloned_weight = module.weight.clone()\n elem_w = module.weight.numel()\n group_w = int(elem_w / self._M)\n\n if len(module.weight.shape)==4:\n # N:M sparsity for convolutional layers\n weight_temp = module.weight.detach().abs().permute(0, 2, 3, 1).reshape(group_w, self._M)\n idxs = torch.argsort(weight_temp, dim=1)[:, :int(self._M - self._N)]\n w_b = torch.ones(weight_temp.shape, device=weight_temp.device)\n w_b = w_b.scatter_(dim=1, index=idxs, value=0).reshape(cloned_weight.permute(0, 2, 3, 1).shape)\n module.weight_mask = w_b.permute(0, 3, 1, 2)\n elif len(module.weight.shape)==2:\n # N:M sparsity for linear layers\n weight_temp = module.weight.detach().abs().reshape(group_w, self._M)\n idxs = torch.argsort(weight_temp, dim=1)[:, :int(self._M - self._N)]\n w_b = torch.ones(weight_temp.shape, device=weight_temp.device)\n module.weight_mask = w_b.scatter_(dim=1, index=idxs, value=0).reshape(module.weight.shape)\n\n else:\n raise NotImplementedError(\"Only support layers of dimension 2 or 4\")\n\n return True, {\"level\": level}\n\n\nclass TrustRegionMagnitudePruner(GradualPruner):\n def __init__(self, model, **kwargs):\n super(TrustRegionMagnitudePruner, self).__init__(model, **kwargs)\n\n @staticmethod\n def _get_param_stat(param, param_mask):\n if param is None or param_mask is None: return None\n return (param.abs() + 1e-4) * param_mask\n\n def _get_meta(self):\n meta = {'bottom magnitudes': {}, 'weights': {}}\n for idx, module in enumerate(self._modules):\n weight = module.weight[module.weight_mask.byte()].abs()\n for sp in [0.05,0.1,0.2,0.3,0.4,0.5]:\n threshold = percentile(weight, sp)\n val = (weight * (weight <= threshold).float()).norm()\n meta['bottom magnitudes'][self._module_names[idx] + f'_{sp}'] = val\n meta['weights'][self._module_names[idx]] = module.weight * module.weight_mask\n return meta\n\n def on_epoch_begin(self, epoch_num, **kwargs):\n meta = self._get_meta()\n level = self._required_sparsity(epoch_num)\n if self._pruner_not_active(epoch_num):\n return False, meta\n for idx, module in enumerate(self._modules):\n w_stat, b_stat = self._get_param_stat(module.weight, module.weight_mask),\\\n self._get_param_stat(module.bias, module.bias_mask)\n module.weight_mask, module.bias_mask = self._get_pruning_mask(w_stat, level),\\\n self._get_pruning_mask(None if self._weight_only else b_stat, level)\n return True, meta\n\n\nclass FisherPruner(GradualPruner):\n def __init__(self, model, **kwargs):\n super(FisherPruner, self).__init__(model, **kwargs)\n\n @staticmethod\n def _get_param_stat(param, param_mask):\n if param is None or param_mask is None: return None\n return (param.grad * param ** 2 + 1e-4) * param_mask\n\n def _release_grads(self):\n optim.SGD(self._model.parameters(), lr=1e-10).zero_grad() # Yeah, I know but don't want to do it manually\n\n def _compute_avg_sum_grad_squared(self, dset, subset_inds, device, num_workers):\n self._release_grads() \n\n tmp_hooks, N = [], len(subset_inds) #len(dset)\n for module in self._modules:\n tmp_hooks.append(module.weight.register_hook(lambda grad: grad ** 2 / (2 * N)))\n if module.bias is not None:\n tmp_hooks.append(module.bias.register_hook(lambda grad: grad ** 2 / (2 * N)))\n\n dummy_loader = torch.utils.data.DataLoader(dset, batch_size=1, num_workers=num_workers, \n sampler=SubsetRandomSampler(subset_inds))\n for in_tensor, target in dummy_loader:\n in_tensor, target = in_tensor.to(device), target.to(device)\n output = self._model(in_tensor)\n loss = torch.nn.functional.cross_entropy(output, target)\n loss.backward()\n\n for hook in tmp_hooks:\n hook.remove()\n\n def on_epoch_begin(self, dset, subset_inds, device, num_workers, epoch_num, **kwargs):\n meta = {}\n if self._pruner_not_active(epoch_num):\n return False, {}\n self._compute_avg_sum_grad_squared(dset, subset_inds, device, num_workers)\n for module in self._modules:\n level = self._required_sparsity(epoch_num)\n w_stat, b_stat = self._get_param_stat(module.weight, module.weight_mask),\\\n self._get_param_stat(module.bias, module.bias_mask)\n module.weight_mask, module.bias_mask = self._get_pruning_mask(w_stat, level),\\\n self._get_pruning_mask(None if self._weight_only else b_stat, level)\n self._release_grads()\n return True, meta\n\n\nclass SNIPPruner(GradualPruner):\n def __init__(self, model, **kwargs):\n super(SNIPPruner, self).__init__(model, **kwargs)\n\n @staticmethod\n def _get_param_stat(param, param_mask):\n if param is None and param_mask is None: return None\n return (param.abs() / param.abs().sum() + 1e-4) * param_mask\n\n def _release_grads(self):\n optim.SGD(self._model.parameters(), lr=1e-10).zero_grad()\n\n def _compute_mask_grads(self, dset, subset_inds, device, num_workers, batch_size):\n self._release_grads() \n\n dummy_loader = torch.utils.data.DataLoader(dset, batch_size=batch_size, num_workers=num_workers,\n sampler=SubsetRandomSampler(subset_inds))\n for in_tensor, target in dummy_loader:\n in_tensor, target = in_tensor.to(device), target.to(device)\n output = self._model(in_tensor)\n loss = torch.nn.functional.cross_entropy(output, target)\n loss.backward()\n\n def on_epoch_begin(self, dset, subset_inds, device, num_workers, batch_size, epoch_num, **kwargs):\n meta = {}\n if self._pruner_not_active(epoch_num):\n return False, {}\n self._compute_mask_grads(dset, subset_inds, device, num_workers, batch_size)\n for module in self._modules:\n level = self._required_sparsity(epoch_num)\n w_stat, b_stat = self._get_param_stat(module.weight_mask_grad, module.weight_mask),\\\n self._get_param_stat(module.bias_mask_grad, module.bias_mask)\n module.weight_mask, module.bias_mask = self._get_pruning_mask(w_stat, level),\\\n self._get_pruning_mask(None if self._weight_only else b_stat, level)\n self._release_grads()\n return True, meta\n\n\nclass NaiveHessianPruner(GradualPruner):\n def __init__(self, model, **kwargs):\n super(NaiveHessianPruner, self).__init__(model, **kwargs)\n\n @staticmethod\n def _get_param_stat(param, param_mask):\n if param is None or param_mask is None: return None\n #statistic can be negative so zeros breaking sparsity level\n #can substract (minimal + eps) and then zero out pruned stats\n param_stat = param.pow(2).mul(param.hess_diag.view_as(param))\n return (param_stat - param_stat.min() + 1e-8) * param_mask\n # param_stat = param.pow(2).mul(param.hess_diag).abs()\n # return (param_stat + 1e-4) * param_mask\n\n def _release_grads(self):\n optim.SGD(self._model.parameters(), lr=1e-10).zero_grad()\n\n def _add_hess_attr(self):\n self._release_grads()\n for param in self._model.parameters():\n setattr(param, 'hess_diag', torch.zeros(param.numel()))\n\n def _del_hess_attr(self):\n self._release_grads()\n for param in self._model.parameters():\n delattr(param, 'hess_diag')\n\n def _compute_second_derivatives(self):\n for module in self._modules:\n for param in module.parameters():\n for i in tqdm(range(param.grad.numel())):\n param.hess_diag[i] += torch.autograd.grad(param.grad.view(-1)[i], param, \n retain_graph=True)[0].view(-1)[i]\n\n def _compute_diag_hessian(self, dset, subset_inds, device, num_workers, batch_size):\n dummy_loader = torch.utils.data.DataLoader(dset, batch_size=batch_size, num_workers=num_workers,\n sampler=SubsetRandomSampler(subset_inds))\n loss = 0.\n for in_tensor, target in tqdm(dummy_loader):\n in_tensor, target = in_tensor.to(device), target.to(device)\n output = self._model(in_tensor)\n loss += torch.nn.functional.cross_entropy(output, target, reduction='sum') / len(dummy_loader.dataset)\n loss.backward(create_graph=True)\n self._compute_second_derivatives()\n self._release_grads()\n\n def on_epoch_begin(self, dset, subset_inds, device, num_workers, batch_size, epoch_num, **kwargs):\n\n ####### meta for TrainingProgressTracker ######\n meta = {\n 'hess_diag_negatives': {}\n }\n ###############################################\n\n if self._pruner_not_active(epoch_num):\n return False, {}\n self._add_hess_attr()\n self._compute_diag_hessian(dset, subset_inds, device, num_workers, batch_size)\n for idx, module in enumerate(self._modules):\n level = self._required_sparsity(epoch_num)\n w_stat, b_stat = self._get_param_stat(module.weight, module.weight_mask),\\\n self._get_param_stat(module.bias, module.bias_mask)\n module.weight_mask, module.bias_mask = self._get_pruning_mask(w_stat, level),\\\n self._get_pruning_mask(None if self._weight_only else b_stat, level)\n \n ############# adding proportion of negatives in diag hessian meta ############\n total_negatives, total = (module.weight.hess_diag < 0).sum().int(),\\\n module.weight.numel()\n if module.bias_mask is not None:\n total_negatives += (module.bias.hess_diag < 0).sum().int()\n total += (module.bias.numel())\n meta['hess_diag_negatives'][self._module_names[idx]] = (total_negatives, total)\n ##############################################################################\n\n self._del_hess_attr()\n return True, meta\n\n\nclass SignSwitchPruner(GradualPruner):\n def __init__(self, model, **kwargs):\n super(SignSwitchPruner, self).__init__(model, **kwargs)\n self._update_old_modules()\n \n def _update_old_modules(self):\n self._old_modules = []\n for module in self._modules:\n self._old_modules.append(deepcopy(module))\n\n @staticmethod\n def _get_pruning_mask(param_stats):\n if param_stats is None: return None\n return (param_stats > 0.).float()\n\n @staticmethod\n def _get_param_stat(param, old_param, param_mask):\n if param is None or param_mask is None: return None\n param_stat = 1. + torch.sign(param) * torch.sign(old_param)\n print('stats')\n print(param_stat.sum() / 2, param.numel())\n return (param_stat * param_mask > 0).float()\n\n def on_epoch_begin(self, dset, subset_inds, device, num_workers, \n batch_size, epoch_num, **kwargs):\n meta = {}\n if self._pruner_not_active(epoch_num):\n return False, {}\n for idx, module in enumerate(self._modules):\n old_module = self._old_modules[idx]\n w_stat, b_stat = self._get_param_stat(module.weight, old_module.weight, \n module.weight_mask),\\\n self._get_param_stat(module.bias, old_module.bias, \n module.bias_mask)\n module.weight_mask, module.bias_mask = self._get_pruning_mask(w_stat),\\\n self._get_pruning_mask(None if self._weight_only else b_stat)\n self._update_old_modules()\n return True, meta\n\n\nclass AdjustedTaylorPruner(GradualPruner):\n def __init__(self, model, **kwargs):\n super(AdjustedTaylorPruner, self).__init__(model, **kwargs)\n\n @staticmethod\n def _get_param_stat(param, param_mask):\n if param is None or param_mask is None: return None\n param_stat = (\n param.pow(2).mul(0.5).mul(param.hess_diag)\n - param.mul(param.grad_tmp)\n )\n return (param_stat - param_stat.min() + 1e-10) * param_mask\n\n def _release_grads(self):\n optim.SGD(self._model.parameters(), lr=1e-10).zero_grad()\n\n def _add_attrs(self):\n self._release_grads()\n for param in self._model.parameters():\n setattr(param, 'hess_diag', 0)\n setattr(param, 'grad_tmp', 0)\n\n def _del_attrs(self):\n self._release_grads()\n for param in self._model.parameters():\n delattr(param, 'hess_diag')\n delattr(param, 'grad_tmp')\n\n def _compute_first_second_derivatives(self):\n for module in self._modules:\n for param in module.parameters():\n param.grad_tmp += param.grad.data\n param.hess_diag += torch.autograd.grad(param.grad, param, grad_outputs=torch.ones_like(param),\n retain_graph=True)[0]\n\n def _compute_derivatives(self, dset, subset_inds, device, num_workers, batch_size):\n dummy_loader = torch.utils.data.DataLoader(dset, batch_size=batch_size, num_workers=num_workers,\n sampler=SubsetRandomSampler(subset_inds))\n\n for in_tensor, target in dummy_loader:\n in_tensor, target = in_tensor.to(device), target.to(device)\n output = self._model(in_tensor)\n loss = torch.nn.functional.cross_entropy(output, target)\n loss.backward(create_graph=True)\n self._compute_first_second_derivatives()\n self._release_grads()\n\n def on_epoch_begin(self, dset, subset_inds, device, num_workers, batch_size, epoch_num, **kwargs):\n meta = {}\n if self._pruner_not_active(epoch_num):\n return False, {}\n self._add_attrs()\n self._compute_derivatives(dset, subset_inds, device, num_workers, batch_size)\n for idx, module in enumerate(self._modules):\n level = self._required_sparsity(epoch_num)\n w_stat, b_stat = self._get_param_stat(module.weight, module.weight_mask),\\\n self._get_param_stat(module.bias, module.bias_mask)\n module.weight_mask, module.bias_mask = self._get_pruning_mask(w_stat, level),\\\n self._get_pruning_mask(None if self._weight_only else b_stat, level)\n for _module in self._modules:\n _module.apply_masks_to_data()\n self._del_attrs()\n return True, meta\n\n\nif __name__ == '__main__':\n pass\n"
] | [
[
"torch.ones",
"torch.zeros",
"torch.sign",
"torch.nn.functional.cross_entropy",
"torch.utils.data.sampler.SubsetRandomSampler",
"numpy.mean",
"torch.argsort",
"torch.ones_like"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tjcdev/bipedal-walker-with-tl | [
"828fdca6caea9e8e15dcb9de920ad1be2f4ed8fb"
] | [
"baselines/ppo2/model.py"
] | [
"import tensorflow as tf\nimport functools\n\nimport sys\n\nfrom baselines.common.tf_util import get_session, save_variables, load_variables\nfrom baselines.common.tf_util import initialize\n\ntry:\n from baselines.common.mpi_adam_optimizer import MpiAdamOptimizer\n from mpi4py import MPI\n from baselines.common.mpi_util import sync_from_root\nexcept ImportError:\n MPI = None\n\nclass Model(object):\n \"\"\"\n We use this object to :\n __init__:\n - Creates the step_model\n - Creates the train_model\n\n train():\n - Make the training part (feedforward and retropropagation of gradients)\n\n save/load():\n - Save load the model\n \"\"\"\n def __init__(self, *, policy, ob_space, ac_space, nbatch_act, nbatch_train,\n nsteps, ent_coef, vf_coef, max_grad_norm, load_path, skip_layers=[], frozen_weights=[], transfer_weights=False, microbatch_size=None):\n self.sess = sess = get_session()\n\n with tf.variable_scope('ppo2_model', reuse=tf.AUTO_REUSE):\n # CREATE OUR TWO MODELS\n # act_model that is used for sampling\n act_model = policy(nbatch_act, 1, sess)\n\n # Train model for training\n if microbatch_size is None:\n train_model = policy(nbatch_train, nsteps, sess)\n else:\n train_model = policy(microbatch_size, nsteps, sess)\n\n # CREATE THE PLACEHOLDERS\n self.A = A = train_model.pdtype.sample_placeholder([None])\n self.ADV = ADV = tf.placeholder(tf.float32, [None])\n self.R = R = tf.placeholder(tf.float32, [None])\n # Keep track of old actor\n self.OLDNEGLOGPAC = OLDNEGLOGPAC = tf.placeholder(tf.float32, [None])\n # Keep track of old critic\n self.OLDVPRED = OLDVPRED = tf.placeholder(tf.float32, [None])\n self.LR = LR = tf.placeholder(tf.float32, [])\n # Cliprange\n self.CLIPRANGE = CLIPRANGE = tf.placeholder(tf.float32, [])\n\n neglogpac = train_model.pd.neglogp(A)\n\n # Calculate the entropy\n # Entropy is used to improve exploration by limiting the premature convergence to suboptimal policy.\n entropy = tf.reduce_mean(train_model.pd.entropy())\n\n # CALCULATE THE LOSS\n # Total loss = Policy gradient loss - entropy * entropy coefficient + Value coefficient * value loss\n\n # Clip the value to reduce variability during Critic training\n # Get the predicted value\n vpred = train_model.vf\n vpredclipped = OLDVPRED + tf.clip_by_value(train_model.vf - OLDVPRED, - CLIPRANGE, CLIPRANGE)\n # Unclipped value\n vf_losses1 = tf.square(vpred - R)\n # Clipped value\n vf_losses2 = tf.square(vpredclipped - R)\n\n vf_loss = .5 * tf.reduce_mean(tf.maximum(vf_losses1, vf_losses2))\n\n # Calculate ratio (pi current policy / pi old policy)\n ratio = tf.exp(OLDNEGLOGPAC - neglogpac)\n\n # Defining Loss = - J is equivalent to max J\n pg_losses = -ADV * ratio\n\n pg_losses2 = -ADV * tf.clip_by_value(ratio, 1.0 - CLIPRANGE, 1.0 + CLIPRANGE)\n\n # Final PG loss\n pg_loss = tf.reduce_mean(tf.maximum(pg_losses, pg_losses2))\n approxkl = .5 * tf.reduce_mean(tf.square(neglogpac - OLDNEGLOGPAC))\n clipfrac = tf.reduce_mean(tf.to_float(tf.greater(tf.abs(ratio - 1.0), CLIPRANGE)))\n\n # Total loss\n loss = pg_loss - entropy * ent_coef + vf_loss * vf_coef\n\n # UPDATE THE PARAMETERS USING LOSS\n def print_weights(params):\n variables_names = [v.name for v in params]\n values = sess.run(variables_names)\n for k, v in zip(variables_names, values):\n if str(k) == 'ppo2_model/vf/w:0':\n print(\"Variable: \" + str(k))\n print(\"Shape: \" + str(v.shape))\n print(v)\n \n # Initialise the already_initialised array\n already_inits = []\n\n # Transfer weights from an already trained model\n # TODO: this is if we are going to use transfer learning\n if transfer_weights:\n # Get all variables from the model.\n variables_to_restore = {v.name.split(\":\")[0]: v\n for v in tf.get_collection(\n tf.GraphKeys.GLOBAL_VARIABLES)}\n \n # Skip some variables during restore.\n skip_pretrained_var = skip_layers\n\n variables_to_restore = {\n v: variables_to_restore[v] for\n v in variables_to_restore if not\n any(x in v for x in skip_pretrained_var)}\n\n already_inits = variables_to_restore\n\n # Restore the remaining variables\n if variables_to_restore:\n saver_pre_trained = tf.train.Saver(\n var_list=variables_to_restore)\n \n saver_pre_trained.restore(sess, tf.train.latest_checkpoint(load_path))\n\n # Collect all trainale variables\n params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)\n\n # Freeze certain variables\n params = tf.contrib.framework.filter_variables(\n params,\n include_patterns=['model'],\n exclude_patterns= frozen_weights)\n\n # Initialise all the other variables\n '''\n \"\"\"Initialize all the uninitialized variables in the global scope.\"\"\"\n new_variables = set(tf.global_variables())\n new_variables = tf.contrib.framework.filter_variables(\n new_variables,\n include_patterns=[],\n exclude_patterns= variables_to_restore)\n tf.get_default_session().run(tf.variables_initializer(new_variables)) \n '''\n else:\n # If we are not using transfer learning\n # 1. Get the model parameters\n params = tf.trainable_variables('ppo2_model')\n \n # 2. Build our trainer\n if MPI is not None:\n self.trainer = MpiAdamOptimizer(MPI.COMM_WORLD, learning_rate=LR, epsilon=1e-5)\n else:\n self.trainer = tf.train.AdamOptimizer(learning_rate=LR, epsilon=1e-5)\n # 3. Calculate the gradients\n grads_and_var = self.trainer.compute_gradients(loss, params)\n grads, var = zip(*grads_and_var)\n\n if max_grad_norm is not None:\n # Clip the gradients (normalize)\n grads, _grad_norm = tf.clip_by_global_norm(grads, max_grad_norm)\n grads_and_var = zip(grads, var)\n # zip aggregate each gradient with parameters associated\n # For instance zip(ABCD, xyza) => Ax, By, Cz, Da\n\n self.grads = grads\n self.var = var\n self._train_op = self.trainer.apply_gradients(grads_and_var)\n self.loss_names = ['policy_loss', 'value_loss', 'policy_entropy', 'approxkl', 'clipfrac']\n self.stats_list = [pg_loss, vf_loss, entropy, approxkl, clipfrac]\n\n\n self.train_model = train_model\n self.act_model = act_model\n self.step = act_model.step\n self.value = act_model.value\n self.initial_state = act_model.initial_state\n\n #self.save = functools.partial(save_variables, sess=sess)\n #self.load = functools.partial(load_variables, sess=sess)\n\n initialize(already_inits)\n\n\n global_variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=\"\")\n if MPI is not None:\n sync_from_root(sess, global_variables) #pylint: disable=E1101\n\n def save(self, save_path):\n \"\"\"\n Save the model\n \"\"\"\n saver = tf.train.Saver()\n saver.save(self.sess, save_path)\n\n def load(self, load_path):\n \"\"\"\n Load the model\n \"\"\"\n saver = tf.train.Saver()\n print('Loading ' + load_path)\n saver.restore(self.sess, load_path)\n\n def train(self, lr, cliprange, obs, returns, masks, actions, values, neglogpacs, states=None):\n # Here we calculate advantage A(s,a) = R + yV(s') - V(s)\n # Returns = R + yV(s')\n advs = returns - values\n\n # Normalize the advantages\n advs = (advs - advs.mean()) / (advs.std() + 1e-8)\n\n td_map = {\n self.train_model.X : obs,\n self.A : actions,\n self.ADV : advs,\n self.R : returns,\n self.LR : lr,\n self.CLIPRANGE : cliprange,\n self.OLDNEGLOGPAC : neglogpacs,\n self.OLDVPRED : values\n }\n if states is not None:\n td_map[self.train_model.S] = states\n td_map[self.train_model.M] = masks\n\n return self.sess.run(\n self.stats_list + [self._train_op],\n td_map\n )[:-1]\n\n"
] | [
[
"tensorflow.clip_by_value",
"tensorflow.train.latest_checkpoint",
"tensorflow.get_collection",
"tensorflow.maximum",
"tensorflow.exp",
"tensorflow.placeholder",
"tensorflow.trainable_variables",
"tensorflow.contrib.framework.filter_variables",
"tensorflow.clip_by_global_norm",
"tensorflow.variable_scope",
"tensorflow.square",
"tensorflow.train.AdamOptimizer",
"tensorflow.train.Saver",
"tensorflow.abs"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
leonardoandresgaray/wheat-quality-detector-2 | [
"8dce39befdc2177b7de64e5e711125f9e92ce6fb"
] | [
"classifier_2_v2.py"
] | [
"import warnings\nwarnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\")\nwarnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size changed\")\n\n\nimport cv2, numpy as np, random, os, pickle, keras, itertools\nfrom mlp import train\nfrom PCA import pca\nfrom util_ import get_boundry_img_matrix, get_files\n\ndef make_sets(inputs, out, percent):\n if len(inputs) != len(out): print(\"Error input size not equal to output size !!!\")\n x_train = []\n y_train = []\n x_test = []\n y_test = []\n rang = range(len(inputs))\n random.shuffle(rang)\n for i in rang:\n if random.random() < percent:\n x_test.append(inputs[i])\n y_test.append(out[i])\n else:\n x_train.append(inputs[i])\n y_train.append(out[i])\n return x_train, y_train, x_test, y_test\n\n############### constant ################\nMEAN_AREA =0\nPERIMETER = 1\nR = 2\nB = 3\nG = 4\nEIGEN_VALUE_1 = 5\nEIGEN_VALUE_2 = 6\nECCENTRICITY = 7\nfeatures = {0:'MEAN_AREA', 1:'PERIMETER', 2:'R', 3:'B', 4:'G', 5:'EIGEN_VALUE_1', 6:'EIGEN_VALUE_2', 7:'ECCENTRICITY', 8:'NUMBER_GRAIN',}\n#########################################\n\ndata_dir = './dataset5_dep_on_4/'\nresult_dir = './weights_results_2out/'\n\nif __name__ == \"__main__\":\n ftrain = []\n ftest = []\n grain_class = {\n 'grain': 0,\n 'not_grain':1,\n }\n # extracting features of grains\n feat_data = result_dir + 'grain_feature.pkl'\n if os.path.isfile(feat_data):\n ftrain, y_train, ftest, y_test = pickle.load(open(feat_data, 'rb'), encoding=\"bytes\")\n else:\n grain_particles = {\n 'damaged_grain' : data_dir + 'damaged_grain',\n 'foreign' : data_dir + 'foreign_particles',\n 'grain' : data_dir + 'grain',\n 'broken_grain' : data_dir + 'grain_broken',\n 'grain_cover' : data_dir + 'grain_covered'\n }\n grain_partical_list = {'grain' :get_files(grain_particles['grain'])}\n grain_partical_list['not_grain'] = get_files(grain_particles['damaged_grain']) + get_files(grain_particles['foreign']) + get_files(grain_particles['broken_grain']) + get_files(grain_particles['grain_cover'])\n # impurity_list = get_files(impure)\n # grain_list = get_files(grain)\n all_partical = []\n for i in grain_partical_list: all_partical += grain_partical_list[i]\n partical_classes = []\n for i in grain_partical_list:\n a = np.zeros(len(grain_class))\n a[grain_class[i]] = 1\n partical_classes += [a for j in range(len(grain_partical_list[i]))]\n # out = [[1, 0] for i in range(len(grain_list))] + [[0, 1] for i in range(len(impurity_list))]\n x_train, y_train, x_test, y_test = make_sets(all_partical, partical_classes, 0.3)\n\n print(' Number of grain: ', len(grain_partical_list['grain']))\n print(' Number of not grain: ', len(grain_partical_list['not_grain']))\n print(\"Total of sample: \", len(all_partical))\n\n xgtrain = []\n xctrain = []\n for g in x_train:\n img = cv2.imread(g, cv2.IMREAD_COLOR)\n xctrain.append(img)\n xgtrain.append(img[:, :, 2])\n\n xgtest = []\n xctest = []\n for i in x_test:\n img = cv2.imread(i, cv2.IMREAD_COLOR)\n xctest.append(img)\n xgtest.append(img[:, :, 2])\n\n for gi in range(len(xctrain)):\n gcolor = xctrain[gi]\n ggray = xgtrain[gi]\n h, w = ggray.shape\n thresh = np.array([[255 if pixel > 0 else 0 for pixel in row] for row in ggray])\n b = np.array(get_boundry_img_matrix(thresh, bval=1), dtype=np.float32)\n perameter = np.sum(b)/(h*w)\n area = np.sum(np.sum([[1.0 for j in range(w) if ggray[i,j]] for i in range(h)]))\n mean_area = area/(h*w)\n r, b, g = np.sum([gcolor[i,j] for j in range(gcolor.shape[1]) for i in range(gcolor.shape[0])], axis=0)/(area*256)\n _,_,eigen_value = pca(ggray)\n eccentricity = eigen_value[0]/eigen_value[1]\n l = [mean_area, perameter, r,b,g,eigen_value[0],eigen_value[1], eccentricity]\n ftrain.append(np.array(l))\n\n for gi in range(len(xctest)):\n gcolor = xctest[gi]\n ggray = xgtest[gi]\n h, w = ggray.shape\n thresh = np.array([[255 if pixel > 0 else 0 for pixel in row] for row in ggray])\n b = np.array(get_boundry_img_matrix(thresh, bval=1), dtype=np.float32)\n perameter = np.sum(b)/(h*w)\n area = np.sum(np.sum([[1.0 for j in range(w) if ggray[i,j]] for i in range(h)]))\n mean_area = area / (h * w)\n r, b, g = np.sum([gcolor[i, j] for j in range(gcolor.shape[1]) for i in range(gcolor.shape[0])], axis=0) / (area*256)\n _, _, eigen_value = pca(ggray)\n eccentricity = eigen_value[0] / eigen_value[1]\n l = [mean_area, perameter, r, b, g, eigen_value[0], eigen_value[1], eccentricity]\n ftest.append(l)\n pickle.dump([ftrain, y_train, ftest, y_test], open(result_dir + 'grain_feature.pkl', 'wb'))\n\n print(\"Total of sample for training :\", len(ftrain))\n print(\"Total of sample for testing :\", len(ftest))\n\n # MLP\n fd = open(result_dir + 'Test_results.txt','a')\n # m = [MEAN_AREA, PERIMETER, R, B, G]\n # n = [[EIGEN_VALUE_1, EIGEN_VALUE_2], [ECCENTRICITY], [NUMBER_GRAIN]]\n print(\"Trainning linear MLP...\")\n # allComb = [list(j) for i in range(1,len(n)+1) for j in itertools.combinations(n, i)]\n allComb = [[MEAN_AREA, PERIMETER, R, B, G, EIGEN_VALUE_1, EIGEN_VALUE_2, ECCENTRICITY]]\n for feat in allComb:\n # print(n, np.array(ftrain)[:, n].shape)\n # feat = [i for i in m]\n # for i in n: feat += i\n print('Paremeters :', [features[i] for i in feat],\" ##### Number of classes :\", [i for i in grain_class])\n modleFile = result_dir + 'weights_'+''.join([str(i) for i in feat])+'.h5'\n if os.path.isfile(modleFile):\n model = keras.models.load_model(modleFile)\n else:\n model = train(np.array(ftrain)[:,feat], np.array(y_train), modelf=modleFile)\n model.save(modleFile)\n score = model.evaluate(np.array(ftest)[:,feat], np.array(y_test))\n print('MLP Test loss:', score[0])\n print('MLP Test accuracy:', score[1])\n\n fd.write(\"Featrues: \"+str([features[i] for i in feat])+'\\n')\n fd.write('MLP Test loss: %f\\n'%(score[0]))\n fd.write('MLP Test accuracy: %f\\n\\n'%(score[1]))\n"
] | [
[
"numpy.array",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
yathindrakodithuwakku/AGC_sample | [
"9963de5430585b448e16e441550e900d7005b589"
] | [
"model.py"
] | [
"\"\"\"Code for constructing the model and get the outputs from the model.\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\nimport layers\n\n# The number of samples per batch.\nBATCH_SIZE = 1\n\n# The height of each image.\nIMG_HEIGHT = 256\n\n# The width of each image.\nIMG_WIDTH = 256\n\n# The number of color channels per image.\nIMG_CHANNELS = 3\n\nPOOL_SIZE = 50\nngf = 32\nndf = 64\n\n\ndef get_outputs(inputs, skip=False):\n\n images_a = inputs['images_a']\n images_b = inputs['images_b']\n fake_pool_a = inputs['fake_pool_a']\n fake_pool_b = inputs['fake_pool_b']\n fake_pool_a_mask = inputs['fake_pool_a_mask']\n fake_pool_b_mask = inputs['fake_pool_b_mask']\n transition_rate = inputs['transition_rate']\n donorm = inputs['donorm']\n with tf.compat.v1.variable_scope(\"Model\") as scope:\n\n current_autoenc = autoenc_upsample\n current_discriminator = discriminator\n current_generator = build_generator_resnet_9blocks\n\n mask_a = current_autoenc(images_a, \"g_A_ae\")\n mask_b = current_autoenc(images_b, \"g_B_ae\")\n mask_a = tf.concat([mask_a] * 3, axis=3)\n mask_b = tf.concat([mask_b] * 3, axis=3)\n\n mask_a_on_a = tf.multiply(images_a, mask_a)\n mask_b_on_b = tf.multiply(images_b, mask_b)\n\n prob_real_a_is_real = current_discriminator(images_a, mask_a, transition_rate, donorm, \"d_A\")\n prob_real_b_is_real = current_discriminator(images_b, mask_b, transition_rate, donorm, \"d_B\")\n\n fake_images_b_from_g = current_generator(images_a, name=\"g_A\", skip=skip)\n fake_images_b = tf.multiply(fake_images_b_from_g, mask_a) + tf.multiply(images_a, 1-mask_a)\n\n fake_images_a_from_g = current_generator(images_b, name=\"g_B\", skip=skip)\n fake_images_a = tf.multiply(fake_images_a_from_g, mask_b) + tf.multiply(images_b, 1-mask_b)\n scope.reuse_variables()\n\n prob_fake_a_is_real = current_discriminator(fake_images_a, mask_b, transition_rate, donorm, \"d_A\")\n prob_fake_b_is_real = current_discriminator(fake_images_b, mask_a, transition_rate, donorm, \"d_B\")\n\n mask_acycle = current_autoenc(fake_images_a, \"g_A_ae\")\n mask_bcycle = current_autoenc(fake_images_b, \"g_B_ae\")\n mask_bcycle = tf.concat([mask_bcycle] * 3, axis=3)\n mask_acycle = tf.concat([mask_acycle] * 3, axis=3)\n\n mask_acycle_on_fakeA = tf.multiply(fake_images_a, mask_acycle)\n mask_bcycle_on_fakeB = tf.multiply(fake_images_b, mask_bcycle)\n\n cycle_images_a_from_g = current_generator(fake_images_b, name=\"g_B\", skip=skip)\n cycle_images_b_from_g = current_generator(fake_images_a, name=\"g_A\", skip=skip)\n\n cycle_images_a = tf.multiply(cycle_images_a_from_g,\n mask_bcycle) + tf.multiply(fake_images_b, 1 - mask_bcycle)\n\n cycle_images_b = tf.multiply(cycle_images_b_from_g,\n mask_acycle) + tf.multiply(fake_images_a, 1 - mask_acycle)\n\n scope.reuse_variables()\n\n prob_fake_pool_a_is_real = current_discriminator(fake_pool_a, fake_pool_a_mask, transition_rate, donorm, \"d_A\")\n prob_fake_pool_b_is_real = current_discriminator(fake_pool_b, fake_pool_b_mask, transition_rate, donorm, \"d_B\")\n\n return {\n 'prob_real_a_is_real': prob_real_a_is_real,\n 'prob_real_b_is_real': prob_real_b_is_real,\n 'prob_fake_a_is_real': prob_fake_a_is_real,\n 'prob_fake_b_is_real': prob_fake_b_is_real,\n 'prob_fake_pool_a_is_real': prob_fake_pool_a_is_real,\n 'prob_fake_pool_b_is_real': prob_fake_pool_b_is_real,\n 'cycle_images_a': cycle_images_a,\n 'cycle_images_b': cycle_images_b,\n 'fake_images_a': fake_images_a,\n 'fake_images_b': fake_images_b,\n 'masked_ims': [mask_a_on_a, mask_b_on_b, mask_acycle_on_fakeA, mask_bcycle_on_fakeB],\n 'masks': [mask_a, mask_b, mask_acycle, mask_bcycle],\n 'masked_gen_ims' : [fake_images_b_from_g, fake_images_a_from_g , cycle_images_a_from_g, cycle_images_b_from_g],\n 'mask_tmp' : mask_a,\n }\n\ndef autoenc_upsample(inputae, name):\n\n with tf.compat.v1.variable_scope(name):\n f = 7\n ks = 3\n padding = \"REFLECT\"\n\n pad_input = tf.pad(inputae, [[0, 0], [ks, ks], [\n ks, ks], [0, 0]], padding)\n o_c1 = layers.general_conv2d(\n pad_input, tf.constant(True, dtype=bool), ngf, f, f, 2, 2, 0.02, name=\"c1\")\n o_c2 = layers.general_conv2d(\n o_c1, tf.constant(True, dtype=bool), ngf * 2, ks, ks, 2, 2, 0.02, \"SAME\", \"c2\")\n\n o_r1 = build_resnet_block_Att(o_c2, ngf * 2, \"r1\", padding)\n\n size_d1 = o_r1.get_shape().as_list()\n o_c4 = layers.upsamplingDeconv(o_r1, size=[size_d1[1] * 2, size_d1[2] * 2], is_scale=False, method=1,\n align_corners=False,name= 'up1')\n # o_c4_pad = tf.pad(o_c4, [[0, 0], [1, 1], [1, 1], [0, 0]], \"REFLECT\", name='padup1')\n o_c4_end = layers.general_conv2d(o_c4, tf.constant(True, dtype=bool), ngf * 2, (3, 3), (1, 1), padding='VALID', name='c4')\n\n size_d2 = o_c4_end.get_shape().as_list()\n o_c5 = layers.upsamplingDeconv(o_c4_end, size=[size_d2[1] * 2, size_d2[2] * 2], is_scale=False, method=1,\n align_corners=False, name='up2')\n # o_c5_pad = tf.pad(o_c5, [[0, 0], [1, 1], [1, 1], [0, 0]], \"REFLECT\", name='padup2')\n oc5_end = layers.general_conv2d(o_c5, tf.constant(True, dtype=bool), ngf , (3, 3), (1, 1), padding='VALID', name='c5')\n\n # o_c6 = tf.pad(oc5_end, [[0, 0], [3, 3], [3, 3], [0, 0]], \"REFLECT\", name='padup3')\n o_c6_end = layers.general_conv2d(oc5_end, tf.constant(False, dtype=bool),\n 1 , (f, f), (1, 1), padding='VALID', name='c6', do_relu=False)\n\n return tf.nn.sigmoid(o_c6_end,'sigmoid')\n\ndef build_resnet_block(inputres, dim, name=\"resnet\", padding=\"REFLECT\"):\n \"\"\"build a single block of resnet.\n\n :param inputres: inputres\n :param dim: dim\n :param name: name\n :param padding: for tensorflow version use REFLECT; for pytorch version use\n CONSTANT\n :return: a single block of resnet.\n \"\"\"\n with tf.compat.v1.variable_scope(name):\n out_res = tf.pad(inputres, [[0, 0], [1, 1], [\n 1, 1], [0, 0]], padding)\n out_res = layers.general_conv2d(\n out_res, tf.constant(True, dtype=bool), dim, 3, 3, 1, 1, 0.02, \"VALID\", \"c1\")\n out_res = tf.pad(out_res, [[0, 0], [1, 1], [1, 1], [0, 0]], padding)\n out_res = layers.general_conv2d(\n out_res, tf.constant(True, dtype=bool), dim, 3, 3, 1, 1, 0.02, \"VALID\", \"c2\", do_relu=False)\n\n return tf.nn.relu(out_res + inputres)\n\ndef build_resnet_block_Att(inputres, dim, name=\"resnet\", padding=\"REFLECT\"):\n \"\"\"build a single block of resnet.\n\n :param inputres: inputres\n :param dim: dim\n :param name: name\n :param padding: for tensorflow version use REFLECT; for pytorch version use\n CONSTANT\n :return: a single block of resnet.\n \"\"\"\n with tf.compat.v1.variable_scope(name):\n out_res = tf.pad(inputres, [[0, 0], [1, 1], [\n 1, 1], [0, 0]], padding)\n out_res = layers.general_conv2d(\n out_res, tf.constant(True, dtype=bool), dim, 3, 3, 1, 1, 0.02, \"VALID\", \"c1\")\n out_res = tf.pad(out_res, [[0, 0], [1, 1], [1, 1], [0, 0]], padding)\n out_res = layers.general_conv2d(\n out_res, tf.constant(True, dtype=bool), dim, 3, 3, 1, 1, 0.02, \"VALID\", \"c2\", do_relu=False)\n\n return tf.nn.relu(out_res + inputres)\n\ndef build_generator_resnet_9blocks(inputgen, name=\"generator\", skip=False):\n\n with tf.compat.v1.variable_scope(name):\n f = 7\n ks = 3\n padding = \"CONSTANT\"\n inputgen = tf.pad(inputgen, [[0, 0], [ks, ks], [\n ks, ks], [0, 0]], padding)\n\n o_c1 = layers.general_conv2d(\n inputgen, tf.constant(True, dtype=bool), ngf, f, f, 1, 1, 0.02, name=\"c1\")\n\n o_c2 = layers.general_conv2d(\n o_c1, tf.constant(True, dtype=bool),ngf * 2, ks, ks, 2, 2, 0.02, padding='same', name=\"c2\")\n\n o_c3 = layers.general_conv2d(\n o_c2, tf.constant(True, dtype=bool), ngf * 4, ks, ks, 2, 2, 0.02, padding='same', name=\"c3\")\n\n\n o_r1 = build_resnet_block(o_c3, ngf * 4, \"r1\", padding)\n o_r2 = build_resnet_block(o_r1, ngf * 4, \"r2\", padding)\n o_r3 = build_resnet_block(o_r2, ngf * 4, \"r3\", padding)\n o_r4 = build_resnet_block(o_r3, ngf * 4, \"r4\", padding)\n o_r5 = build_resnet_block(o_r4, ngf * 4, \"r5\", padding)\n o_r6 = build_resnet_block(o_r5, ngf * 4, \"r6\", padding)\n o_r7 = build_resnet_block(o_r6, ngf * 4, \"r7\", padding)\n o_r8 = build_resnet_block(o_r7, ngf * 4, \"r8\", padding)\n o_r9 = build_resnet_block(o_r8, ngf * 4, \"r9\", padding)\n\n o_c4 = layers.general_deconv2d(\n o_r9, [BATCH_SIZE, 128, 128, ngf * 2], ngf * 2, ks, ks, 2, 2, 0.02,\n \"SAME\", \"c4\")\n\n o_c5 = layers.general_deconv2d(\n o_c4, [BATCH_SIZE, 256, 256, ngf], ngf, ks, ks, 2, 2, 0.02,\n \"SAME\", \"c5\")\n\n o_c6 = layers.general_conv2d(o_c5, tf.constant(False, dtype=bool), IMG_CHANNELS, f, f, 1, 1,\n 0.02, \"SAME\", \"c6\", do_relu=False)\n\n if skip is True:\n out_gen = tf.nn.tanh(inputgen + o_c6, \"t1\")\n else:\n out_gen = tf.nn.tanh(o_c6, \"t1\")\n\n return out_gen\n\ndef discriminator(inputdisc, mask, transition_rate, donorm, name=\"discriminator\"):\n\n with tf.compat.v1.variable_scope(name):\n mask = tf.cast(tf.greater_equal(mask, transition_rate), tf.float32)\n inputdisc = tf.multiply(inputdisc, mask)\n f = 4\n padw = 2\n pad_input = tf.pad(inputdisc, [[0, 0], [padw, padw], [\n padw, padw], [0, 0]], \"CONSTANT\")\n\n o_c1 = layers.general_conv2d(pad_input, donorm, ndf, f, f, 2, 2,\n 0.02, \"VALID\", \"c1\",\n relufactor=0.2)\n\n pad_o_c1 = tf.pad(o_c1, [[0, 0], [padw, padw], [\n padw, padw], [0, 0]], \"CONSTANT\")\n\n o_c2 = layers.general_conv2d(pad_o_c1, donorm, ndf * 2, f, f, 2, 2,\n 0.02, \"VALID\", \"c2\", relufactor=0.2)\n\n pad_o_c2 = tf.pad(o_c2, [[0, 0], [padw, padw], [\n padw, padw], [0, 0]], \"CONSTANT\")\n\n o_c3 = layers.general_conv2d(pad_o_c2, donorm, ndf * 4, f, f, 2, 2,\n 0.02, \"VALID\", \"c3\", relufactor=0.2)\n\n pad_o_c3 = tf.pad(o_c3, [[0, 0], [padw, padw], [\n padw, padw], [0, 0]], \"CONSTANT\")\n\n o_c4 = layers.general_conv2d(pad_o_c3, donorm, ndf * 8, f, f, 1, 1,\n 0.02, \"VALID\", \"c4\", relufactor=0.2)\n # o_c4 = tf.multiply(o_c4, mask_4)\n pad_o_c4 = tf.pad(o_c4, [[0, 0], [padw, padw], [\n padw, padw], [0, 0]], \"CONSTANT\")\n\n o_c5 = layers.general_conv2d(\n pad_o_c4, tf.constant(False, dtype=bool), 1, f, f, 1, 1, 0.02, \"VALID\", \"c5\", do_relu=False)\n\n\n return o_c5\n"
] | [
[
"tensorflow.nn.relu",
"tensorflow.multiply",
"tensorflow.concat",
"tensorflow.nn.sigmoid",
"tensorflow.constant",
"tensorflow.nn.tanh",
"tensorflow.pad",
"tensorflow.greater_equal",
"tensorflow.compat.v1.variable_scope"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mymakar/causally_motivated_shortcut_removal | [
"06cc5f0cdefe17dfb543d3cfd046437f5255d092"
] | [
"chexpert/cohort_creation.py"
] | [
"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Script to create the chexpert dataset\"\"\"\nimport argparse\nimport numpy as np\nimport pandas as pd\npd.set_option('mode.chained_assignment', None)\n\ndef main(chexpert_directory, save_directory):\n\t# combine the train/validation data into one big dataset\n\ttrdf = pd.read_csv(f'{chexpert_directory}/train.csv')\n\tvdf = pd.read_csv(f'{chexpert_directory}/valid.csv')\n\tdf = trdf.append(vdf)\n\tdel trdf, vdf\n\t# only keep healthy patients and penumonia patients\n\tdf = df[((df['No Finding'] == 1) | (df['Pneumonia'] == 1))]\n\n\t# create a unique ID for each patient/study\n\tdf['patient'] = df.Path.str.extract(r'(patient)(\\d+)')[1]\n\tdf['study'] = df.Path.str.extract(r'(study)(\\d+)')[1].astype(int)\n\tdf['uid'] = df['patient'] + \"_\" + df['study'].astype(str)\n\tdf = df[['uid', 'patient', 'study', 'Sex', 'Frontal/Lateral', 'Pneumonia', 'Path']]\n\n\t# get the main outcome\n\tdf['y0'] = df['Pneumonia'].copy()\n\tdf.y0.fillna(0, inplace = True)\n\tdf.y0[(df.y0 == -1)] = 1\n\tdf.y0.value_counts(dropna = False, normalize = True)\n\n\t# get the auxiliary label\n\tdf = df[(df.Sex != 'Unknown')]\n\tdf['y1'] = (df.Sex == 'Male').astype(int)\n\tdf.drop('Sex', axis = 1, inplace = True)\n\n\t# keep only studies with frontal views\n\t# PS: almost all have fontal views (only 0.019% don't)\n\tdf['frontal'] = (df['Frontal/Lateral'] == 'Frontal').astype(int)\n\tdf = df[(df.frontal ==1)]\n\n\n\t# some final cleanups\n\tdf.drop_duplicates(subset=['uid'], inplace = True)\n\tdf.drop(['Frontal/Lateral', 'frontal', 'Pneumonia'], axis = 1, inplace = True)\n\n\t# save file\n\tdf.to_csv(f'{save_directory}/clean_data.csv', index = False)\n\n\nif __name__==\"__main__\":\n\tparser = argparse.ArgumentParser()\n\n\tparser.add_argument('--chexpert_directory', '-chexpert_directory',\n\t\thelp=\"Directory where the chexpert data is saved\",\n\t\ttype=str)\n\n\tparser.add_argument('--save_directory', '-save_directory',\n\t\thelp=\"Directory where the final cohort will be saved\",\n\t\ttype=str)\n\n\targs = vars(parser.parse_args())\n\tmain(**args)\n"
] | [
[
"pandas.set_option",
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
tasptz/pytorch-smooth | [
"cb2a2845afbdf5524648eed066b6dea9ac594cfd"
] | [
"smooth/kernel.py"
] | [
"import numpy as np\n\ndef sobel(k:int):\n '''\n Generate a horizontal sobel kernel with shape `(k, k)`\n '''\n if k % 2 == 0:\n y, x = np.mgrid[:k, :k] + 0.5 - k / 2\n else:\n y, x = np.mgrid[:k, :k] - k // 2\n norm = np.square(x) + np.square(y)\n norm[norm == 0.] = 1.\n f = x / norm\n # construct img with gradient gx = 1\n i = np.tile(np.arange(k)[None], (k, 1))\n # response\n r = (f * i).sum()\n # normalize to response = 1\n f = f / r\n return f\n"
] | [
[
"numpy.square",
"numpy.arange"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
chaohuaM/deeplabv3-plus-pytorch | [
"71aba5db71247c6e649460705819bd9ac8bab611"
] | [
"nets/mobilenetv2.py"
] | [
"import math\r\nimport os\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.utils.model_zoo as model_zoo\r\n\r\nBatchNorm2d = nn.BatchNorm2d\r\n\r\ndef conv_bn(inp, oup, stride):\r\n return nn.Sequential(\r\n nn.Conv2d(inp, oup, 3, stride, 1, bias=False),\r\n BatchNorm2d(oup),\r\n nn.ReLU6(inplace=True)\r\n )\r\n\r\ndef conv_1x1_bn(inp, oup):\r\n return nn.Sequential(\r\n nn.Conv2d(inp, oup, 1, 1, 0, bias=False),\r\n BatchNorm2d(oup),\r\n nn.ReLU6(inplace=True)\r\n )\r\n\r\nclass InvertedResidual(nn.Module):\r\n def __init__(self, inp, oup, stride, expand_ratio):\r\n super(InvertedResidual, self).__init__()\r\n self.stride = stride\r\n assert stride in [1, 2]\r\n\r\n hidden_dim = round(inp * expand_ratio)\r\n self.use_res_connect = self.stride == 1 and inp == oup\r\n\r\n if expand_ratio == 1:\r\n self.conv = nn.Sequential(\r\n #--------------------------------------------#\r\n # 进行3x3的逐层卷积,进行跨特征点的特征提取\r\n #--------------------------------------------#\r\n nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),\r\n BatchNorm2d(hidden_dim),\r\n nn.ReLU6(inplace=True),\r\n #-----------------------------------#\r\n # 利用1x1卷积进行通道数的调整\r\n #-----------------------------------#\r\n nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),\r\n BatchNorm2d(oup),\r\n )\r\n else:\r\n self.conv = nn.Sequential(\r\n #-----------------------------------#\r\n # 利用1x1卷积进行通道数的上升\r\n #-----------------------------------#\r\n nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False),\r\n BatchNorm2d(hidden_dim),\r\n nn.ReLU6(inplace=True),\r\n #--------------------------------------------#\r\n # 进行3x3的逐层卷积,进行跨特征点的特征提取\r\n #--------------------------------------------#\r\n nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),\r\n BatchNorm2d(hidden_dim),\r\n nn.ReLU6(inplace=True),\r\n #-----------------------------------#\r\n # 利用1x1卷积进行通道数的下降\r\n #-----------------------------------#\r\n nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),\r\n BatchNorm2d(oup),\r\n )\r\n\r\n def forward(self, x):\r\n if self.use_res_connect:\r\n return x + self.conv(x)\r\n else:\r\n return self.conv(x)\r\n\r\nclass MobileNetV2(nn.Module):\r\n def __init__(self, n_class=1000, input_size=224, width_mult=1.):\r\n super(MobileNetV2, self).__init__()\r\n block = InvertedResidual\r\n input_channel = 32\r\n last_channel = 1280\r\n interverted_residual_setting = [\r\n # t, c, n, s\r\n [1, 16, 1, 1], # 256, 256, 32 -> 256, 256, 16\r\n [6, 24, 2, 2], # 256, 256, 16 -> 128, 128, 24 2\r\n [6, 32, 3, 2], # 128, 128, 24 -> 64, 64, 32 4\r\n [6, 64, 4, 2], # 64, 64, 32 -> 32, 32, 64 7\r\n [6, 96, 3, 1], # 32, 32, 64 -> 32, 32, 96\r\n [6, 160, 3, 2], # 32, 32, 96 -> 16, 16, 160 14\r\n [6, 320, 1, 1], # 16, 16, 160 -> 16, 16, 320\r\n ]\r\n\r\n assert input_size % 32 == 0\r\n input_channel = int(input_channel * width_mult)\r\n self.last_channel = int(last_channel * width_mult) if width_mult > 1.0 else last_channel\r\n # 512, 512, 3 -> 256, 256, 32\r\n self.features = [conv_bn(3, input_channel, 2)]\r\n\r\n for t, c, n, s in interverted_residual_setting:\r\n output_channel = int(c * width_mult)\r\n for i in range(n):\r\n if i == 0:\r\n self.features.append(block(input_channel, output_channel, s, expand_ratio=t))\r\n else:\r\n self.features.append(block(input_channel, output_channel, 1, expand_ratio=t))\r\n input_channel = output_channel\r\n\r\n self.features.append(conv_1x1_bn(input_channel, self.last_channel))\r\n self.features = nn.Sequential(*self.features)\r\n\r\n self.classifier = nn.Sequential(\r\n nn.Dropout(0.2),\r\n nn.Linear(self.last_channel, n_class),\r\n )\r\n\r\n self._initialize_weights()\r\n\r\n def forward(self, x):\r\n x = self.features(x)\r\n x = x.mean(3).mean(2)\r\n x = self.classifier(x)\r\n return x\r\n\r\n def _initialize_weights(self):\r\n for m in self.modules():\r\n if isinstance(m, nn.Conv2d):\r\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\r\n m.weight.data.normal_(0, math.sqrt(2. / n))\r\n if m.bias is not None:\r\n m.bias.data.zero_()\r\n elif isinstance(m, BatchNorm2d):\r\n m.weight.data.fill_(1)\r\n m.bias.data.zero_()\r\n elif isinstance(m, nn.Linear):\r\n n = m.weight.size(1)\r\n m.weight.data.normal_(0, 0.01)\r\n m.bias.data.zero_()\r\n\r\n\r\ndef load_url(url, model_dir='./model_data', map_location=None):\r\n if not os.path.exists(model_dir):\r\n os.makedirs(model_dir)\r\n filename = url.split('/')[-1]\r\n cached_file = os.path.join(model_dir, filename)\r\n if os.path.exists(cached_file):\r\n return torch.load(cached_file, map_location=map_location)\r\n else:\r\n return model_zoo.load_url(url,model_dir=model_dir)\r\n\r\ndef mobilenetv2(pretrained=False, **kwargs):\r\n model = MobileNetV2(n_class=1000, **kwargs)\r\n if pretrained:\r\n model.load_state_dict(load_url('https://github.com/bubbliiiing/deeplabv3-plus-pytorch/releases/download/v1.0/mobilenet_v2.pth.tar'), strict=False)\r\n return model\r\n\r\nif __name__ == \"__main__\":\r\n model = mobilenetv2()\r\n for i, layer in enumerate(model.features):\r\n print(i, layer)\r\n"
] | [
[
"torch.nn.Sequential",
"torch.nn.Dropout",
"torch.nn.ReLU6",
"torch.load",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.utils.model_zoo.load_url"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bmkramer/automated-systematic-review | [
"f99079926f381bc7895ff6fefa9e6e729a2c26b8"
] | [
"asreview/query_strategies/uncertainty.py"
] | [
"# Copyright 2019 The ASReview 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\"\"\"Uncertainty sampling while saving probabilities.\"\"\"\n\n# from typing import Tuple\n\nimport numpy as np\nfrom modAL.utils.selection import multi_argmax\nfrom modAL.utils.selection import shuffled_argmax\n\n\nfrom asreview.query_strategies.base import ProbaQueryStrategy\n\n\nclass UncertaintyQuery(ProbaQueryStrategy):\n \"\"\"Maximum uncertainty query strategy.\"\"\"\n\n name = \"uncertainty\"\n\n def __init__(self, random_tie_break=False):\n \"\"\"Initialize the maximum uncertainty query strategy.\n\n Arguments:\n ----------\n random_tie_break: bool\n If true randomly decide which ones to include by tie-break.\n \"\"\"\n super(UncertaintyQuery, self).__init__()\n self.random_tie_break = random_tie_break\n\n def _query(self, X, pool_idx, n_instances=1, proba=None):\n uncertainty = 1 - np.max(proba[pool_idx], axis=1)\n if not self.random_tie_break:\n query_idx = multi_argmax(uncertainty, n_instances=n_instances)\n else:\n query_idx = shuffled_argmax(uncertainty, n_instances=n_instances)\n\n return pool_idx[query_idx], X[pool_idx[query_idx]]\n"
] | [
[
"numpy.max"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.