repo_name
stringlengths
8
130
hexsha
list
file_path
list
code
list
apis
list
NooneBug/adapter_on_entity_typing
[ "b8d2850dbed47adbf21c9a8021cef69a9b5d60dd" ]
[ "result_scripts/generate_predictions.py" ]
[ "import configparser\nfrom adapter_entity_typing.network_classes.classifiers import EarlyStoppingWithColdStart\nfrom torch.utils.data.dataloader import DataLoader\nfrom adapter_entity_typing.network import load_model\nfrom collections import defaultdict\nimport torch\nimport json\nimport numpy as np\nfrom tqdm import tqdm\n\nimport sys\n\n# parameter_tags = ['bert_ft_2_figer']\nparameter_tags = [sys.argv[1]]\n\nconfig = configparser.ConfigParser()\ntraining_config_file = \"result_scripts/generate_predictions_parameters.ini\"\nconfig.read(\"result_scripts/generate_predictions_parameters.ini\")\nprint(list(config.keys()))\nconfig = config[parameter_tags[0]]\n\nsig = torch.nn.Sigmoid()\n\n# model_path = config['ModelRootPath'] + config['ModelName']\n# classifier = get_model(model_path)\n\n# max_context_side_size = classifier.configuration('MaxContextSideSize')\n# max_entity_size = classifier.configuration('MaxEntitySize')\n\n# train_dataset, dev_dataset, test_dataset, label2id = prepare_entity_typing_datasets(classifier)\n\n\n# vocab_len = len(id2label)\n\n# add_classifier(model = classifier, labels = label2id)\n\n# model = adapterPLWrapper.load_from_checkpoint(model_path, \n# adapterClassifier = classifier, \n# id2label = id2label, \n# lr = 1e-4)\n# model.cuda()\n# model.eval()\n\nmicros = {\n \"p\": [],\n \"r\": [],\n \"f1\": []}\nmacros = {\n \"p\": [],\n \"r\": [],\n \"f1\": []}\nmacro_examples = {\n \"p\": [],\n \"r\": [],\n \"f1\": []}\n \nexperiment_name = config['fileName']\nperformance_file = config['performanceFile'] + experiment_name\nprediction_file = config['predictionFile'] + experiment_name\naverage_std_file = config['AvgStdFile'] + experiment_name\n\ndev_or_test = config['dev_or_test']\nif dev_or_test == 'both':\n keys = ['dev', 'test']\nelif dev_or_test == 'dev':\n keys = ['dev']\nelif dev_or_test == 'test':\n keys = ['test']\nelse:\n raise Exception('please provide a meaningfull value for \"dev_or_test\"')\n\nmacros = {k: {subk: [] for subk in keys} for k, v in macros.items()}\nmicros = {k: {subk: [] for subk in keys} for k, v in macros.items()}\nmacro_examples= {k: {subk: [] for subk in keys} for k, v in macros.items()}\n\nfor model, _, dev_dataset, test_dataset, label2id in load_model(parameter_tags[0]): # , \"results_scripts/generate_preditcions_parameters.ini\"):\n\n dev_loader = DataLoader(dev_dataset, batch_size = 100, num_workers=20)\n test_loader = DataLoader(test_dataset, batch_size = 100, num_workers=20)\n id2label = {v: k for k,v in label2id.items()}\n\n\n if dev_or_test == 'both':\n data_to_pred = ['dev', 'test']\n datasets = [dev_loader, test_loader]\n dataset_paths = [model.configuration('PathInputDev'), model.configuration('PathInputTest')]\n\n elif dev_or_test == 'dev':\n data_to_pred = ['dev']\n datasets = [dev_loader]\n dataset_paths = [model.configuration('PathInputDev')]\n\n elif dev_or_test == 'test':\n data_to_pred = ['test']\n datasets = [test_loader]\n dataset_paths = [model.configuration('PathInputTest')]\n\n else:\n raise Exception('please provide a meaningfull value for \"dev_or_test\"')\n\n for dataset_id, d in enumerate(data_to_pred):\n all_preds = []\n all_preds_and_logits = []\n all_labels = []\n top_k_labels = []\n loader = datasets[dataset_id]\n for mention, attn, labels in loader:\n \n mention = mention.cuda()\n attn = attn.cuda()\n preds = sig(model(mention, attn))\n \n batch_preds = []\n batch_preds_and_logits = []\n batch_top_k_labels = []\n for i, pred in enumerate(preds):\n mask = pred > .5\n ex_preds = []\n ex_preds_and_logits = [] \n pred_ids = mask.nonzero()\n no_pred = True\n for p in pred_ids:\n ex_preds.append(id2label[p.item()])\n ex_preds_and_logits.append((id2label[p.item()], round(preds[i][p].item(), 3)))\n no_pred = False\n # sort logits by pred\n topk_values, topk_indexes = torch.topk(pred, k = 5)\n top_k_l = []\n for val, index in zip(topk_values, topk_indexes):\n val = round(val.item(), 3)\n lab = id2label[index.item()]\n top_k_l.append((lab, val))\n \n if no_pred:\n ex_preds.append(top_k_l[0][0])\n ex_preds_and_logits.append(top_k_l[0])\n\n sorted_ex_preds_and_logits = sorted(ex_preds_and_logits, key=lambda tup: tup[1], reverse = True)\n batch_preds.append(ex_preds)\n batch_preds_and_logits.append(sorted_ex_preds_and_logits)\n batch_top_k_labels.append(top_k_l)\n \n all_preds.extend(batch_preds)\n all_preds_and_logits.extend(batch_preds_and_logits)\n top_k_labels.extend(batch_top_k_labels)\n\n mask = labels == 1\n batch_labels = []\n for m in mask:\n ex_labels = []\n labels_ids = m.nonzero()\n for l in labels_ids:\n ex_labels.append(id2label[l.item()])\n batch_labels.append(ex_labels)\n all_labels.extend(batch_labels)\n\n correct_count = defaultdict(int)\n actual_count = defaultdict(int)\n predict_count = defaultdict(int)\n # compute singular class performances and macro performances\n bar = tqdm(desc=\"computing macro performances\", total=len(all_preds))\n for labels, preds in zip(all_labels, all_preds):\n for pred in preds:\n predict_count[pred] += 1\n\n if pred in labels:\n correct_count[pred] += 1\n \n for label in labels:\n actual_count[label] += 1\n bar.update(1)\n bar.close()\n\n def compute_f1(p, r):\n return (2*p*r)/(p + r) if p + r else 0\n\n precisions = {k: correct_count[k]/predict_count[k] if predict_count[k] else 0 for k in label2id.keys()}\n recalls = {k: correct_count[k]/actual_count[k] if actual_count[k] else 0 for k in label2id.keys()}\n f1s = {k: compute_f1(precisions[k], recalls[k]) for k in label2id.keys()}\n\n macro_p = np.mean(list(precisions.values()))\n macro_r = np.mean(list(recalls.values()))\n macro_f1 = compute_f1(macro_p, macro_r)\n\n macros['p'][d].append(macro_p)\n macros['r'][d].append(macro_r)\n macros['f1'][d].append(macro_f1)\n\n #compute macro_example performances\n ma_e_precisions = []\n ma_e_recalls = []\n n = len(all_labels)\n\n bar = tqdm(desc=\"computing macro examples performances\", total=len(all_preds))\n \n for labels, preds in zip(all_labels, all_preds):\n correct_preds = len(set(labels).intersection(set(preds)))\n ma_e_precisions.append(correct_preds/len(preds))\n ma_e_recalls.append(correct_preds / len(labels))\n bar.update(1)\n bar.close()\n\n macro_example_p = np.mean(ma_e_precisions)\n macro_example_r = np.mean(ma_e_recalls)\n macro_example_f1 = compute_f1(macro_example_p, macro_example_r)\n \n macro_examples['p'][d].append(macro_example_p)\n macro_examples['r'][d].append(macro_example_r)\n macro_examples['f1'][d].append(macro_example_f1)\n \n #compute micro performances\n micro_correct_counter = 0\n micro_true_counter = 0\n micro_pred_counter = 0\n\n bar = tqdm(desc=\"computing micro performances\", total=len(all_preds)) \n for labels, preds in zip(all_labels, all_preds):\n micro_true_counter += len(labels)\n micro_pred_counter += len(preds)\n correct_preds = len(set(labels).intersection(set(preds)))\n micro_correct_counter += correct_preds\n bar.update(1)\n bar.close()\n micro_p = micro_correct_counter/micro_pred_counter\n micro_r = micro_correct_counter/micro_true_counter\n micro_f1 = compute_f1(micro_p, micro_r)\n\n micros['p'][d].append(micro_p)\n micros['r'][d].append(micro_r)\n micros['f1'][d].append(micro_f1)\n\n with open(dataset_paths[dataset_id], 'r') as inp:\n lines = [json.loads(l) for l in inp.readlines()]\n\n label_sentences = defaultdict(list)\n\n bar = tqdm(desc=\"generating sentences\", total=len(lines))\n \n for l, preds_and_logits, top_k in zip(lines, all_preds_and_logits, top_k_labels):\n sentence = ' '.join(l['left_context_token'])\n sentence += ' ' + l['mention_span'] + ' '\n sentence += ' '.join(l['right_context_token'])\n labels = l['y_str']\n\n for lab in labels:\n label_sentences[lab].append((sentence, l['mention_span'], preds_and_logits, top_k, labels))\n bar.update(1)\n bar.close()\n\n ordered_labels = list(sorted(label2id.keys()))\n\n with open(prediction_file + '_' + d + '.txt', 'a') as out:\n out.write('{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n'.format('label_#', 'precision', \n 'recall', 'f1', 'sentence', 'mention', \n 'preds_and_logits', 'top_k_labels_and_logits', 'true_labels'))\n for label in ordered_labels:\n i = 0\n for sentence, mention, preds_and_logits, top_k, true_label in label_sentences[label]:\n out_string = '{}\\t{:.4f}\\t{:.4f}\\t{:.4f}\\t{}\\t{}\\t{}\\t{}\\t{}\\n'.format(label + '_' + str(i + 1),\n precisions[label],\n recalls[label],\n f1s[label],\n sentence,\n mention,\n preds_and_logits,\n top_k,\n true_label)\n out.write(out_string)\n i += 1\n with open(performance_file + '_' + d + '.txt', 'a') as out:\n out.write('{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n'.format('macro_examples_p', 'macro_examples_r', 'macro_examples_f1',\n 'macro_p','macro_r', 'macro_f1',\n 'micro_p', 'micro_r', 'micro_f1'))\n out.write('{:.4f}\\t{:.4f}\\t{:.4f}\\t{:.4f}\\t{:.4f}\\t{:.4f}\\t{:.4f}\\t{:.4f}\\t{:.4f}\\n'.format(macro_example_p,\n macro_example_r,\n macro_example_f1,\n macro_p,\n macro_r,\n macro_f1,\n micro_p,\n micro_r,\n micro_f1))\n \n\n\n\nname = {\n \"p\": \"precision\",\n \"r\": \"recall\",\n \"f1\": \"f1\"\n}\nfor d in keys:\n results = {}\n for result_name, result in zip([\"micro\", \"macro\", \"example\"],\n [ micros, macros, macro_examples]):\n print(result_name)\n print(result)\n print()\n for k, v in result.items():\n v = np.array(v[d])\n mu = np.mean(v)\n sd = np.std(v)\n results[\"{}_{}\".format(result_name, k)] = (mu, sd)\n\n with open(average_std_file + '_'+ d + '.txt', 'a') as out:\n # out.write('{:^40}\\n'.format('-'))\n out.write(\"model,mu,sd\\n\")\n for k, (m, s) in results.items():\n out.write('{},{:.4f},{:.4f}\\n'.format(k, m, s))\n out.write('\\n')\n" ]
[ [ "torch.utils.data.dataloader.DataLoader", "torch.topk", "numpy.array", "numpy.std", "torch.nn.Sigmoid", "numpy.mean" ] ]
macthecadillac/Interacting-Fermions
[ "6122d2a7e67533b28e581929995ce8e2a2ad41fc" ]
[ "spinsys/time_dependent.py" ]
[ "\"\"\"\nThis file is part of spinsys.\n\nSpinsys is free software: you can redistribute it and/or modify\nit under the terms of the BSD 3-clause license. See LICENSE.txt\nfor exact terms and conditions.\n\"\"\"\n\nimport numpy as np\n\n\nclass TimeMachine():\n\n def __init__(self, eigvs, eigvecs, psi):\n \"\"\"\n Time evolves a given vector to any point in the past or future.\n\n Args: \"eigvs\" eigenenergies of the Hamiltonian. Numpy 1D array\n \"eigvecs\" eigenvectors of the Hamiltonian. Numpy 2D square array\n \"psi\" initial state. Numpy 1D array\n \"\"\"\n self.eigenenergies = eigvs\n self.back_transform_matrix = eigvecs\n self.initial_state = self._convert_to_eigenbasis(eigvecs, psi)\n self.curr_state = self.initial_state.copy()\n self.coeffs = 1 # the exponential coeffs for psi when time evolving\n self.last_dt = 0\n\n def _convert_to_eigenbasis(self, U, psi):\n return U.T.conjugate().dot(psi)\n\n def evolve_by_step(self, dt, basis='orig'):\n \"\"\"Evolves the state by dt\n\n Args: \"dt\" time step, float\n \"basis\" \"orig\" or \"energy\". The basis of the returned state\n Returns: Numpy 1D array\n \"\"\"\n if not dt == self.last_dt:\n self.coeffs = np.exp(-1j * self.eigenenergies * dt)\n self.last_dt = dt\n self.curr_state *= self.coeffs\n if basis == 'orig':\n return self.back_transform_matrix.dot(self.curr_state)\n elif basis == 'energy':\n return self.curr_state\n\n def evolve_to_time(self, t, basis='orig'):\n \"\"\"Evolves the state by time \"t\"\n\n Args: \"t\" time, float\n \"basis\" \"orig\" or \"energy\". The basis of the returned state\n Returns: Numpy 1D array\n \"\"\"\n self.coeffs = np.exp(-1j * self.eigenenergies * t)\n self.curr_state = self.coeffs * self.initial_state\n if basis == 'orig':\n return self.back_transform_matrix.dot(self.curr_state)\n elif basis == 'energy':\n return self.curr_state\n" ]
[ [ "numpy.exp" ] ]
indutny/gradtype
[ "0e7e1290e6b4e669126e42339a739ec58dc1154e" ]
[ "tools/tsne.py" ]
[ "import matplotlib\nimport sys\nimport json\n\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport matplotlib.axes as axes\nimport numpy as np\nimport sklearn.decomposition\nimport sklearn.preprocessing\nfrom sklearn.manifold import TSNE\n\nCOLOR_MAP = plt.cm.gist_rainbow\nSEED = 0x37255c25\nUSE_TSNE = True\n\nNORMALIZE = False\n\nCATEGORIES = {}\ncategory = 'train' if len(sys.argv) < 3 else sys.argv[2]\n\ndef to_color(index):\n return index / len(CATEGORIES)\n\ndef visualize(entries):\n fig = plt.figure(1, figsize=(8, 6))\n\n axes = plt.gca()\n\n if len(entries[0]['features']) == 2:\n decomps = []\n elif USE_TSNE:\n decomps = [\n sklearn.decomposition.PCA( \\\n n_components=min(50, len(entries[0]['features'])), random_state=SEED),\n TSNE(n_components=2, verbose=2, random_state=SEED,\n perplexity=30)\n ]\n else:\n decomps = [ sklearn.decomposition.PCA(n_components=2, random_state=SEED) ]\n\n coords = [ np.array(e['features']) for e in entries ]\n if NORMALIZE:\n coords = [ x / (np.linalg.norm(x) + 1e-23) for x in coords ]\n\n for decomp in decomps:\n coords = decomp.fit_transform(coords)\n if isinstance(decomp, sklearn.decomposition.PCA):\n print('Explained variance ratio: {}'.format( \\\n decomp.explained_variance_ratio_))\n\n for e, coords in zip(entries, coords):\n e['coords'] = coords\n category = e['category']\n if category in CATEGORIES:\n index = CATEGORIES[category]\n else:\n index = len(CATEGORIES)\n CATEGORIES[category] = index\n e['index'] = index\n\n legend = []\n for label, index in CATEGORIES.items():\n color = COLOR_MAP(to_color(index))\n legend.append(mpatches.Patch(color=color, label=label))\n # axes.legend(handles=legend, fontsize=8)\n\n for e in entries:\n label = e['category']\n index = e['index']\n\n x = e['coords'][0]\n y = e['coords'][1]\n\n color = COLOR_MAP(to_color(index))\n\n marker = 'o'\n size = 8\n alpha = 0.6\n plt.scatter(x, y, c=[ color ], marker=marker,\n edgecolor='k', s=size, alpha=alpha, linewidths=0.0,\n edgecolors='none')\n\n plt.show()\n\nwith open(sys.argv[1]) as input:\n data = json.load(input)\n visualize(data[category])\n" ]
[ [ "matplotlib.pyplot.figure", "matplotlib.pyplot.gca", "sklearn.manifold.TSNE", "matplotlib.pyplot.show", "numpy.array", "numpy.linalg.norm", "matplotlib.patches.Patch", "matplotlib.pyplot.scatter" ] ]
Fostereee/Transformer-MM-Explainability
[ "6dc4925b83a38e39069369da599b11d548128eb5" ]
[ "VisualBERT/tests/models/test_mmbt.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\n\nimport unittest\n\nimport tests.test_utils as test_utils\nimport torch\nfrom VisualBERT.mmf.common.sample import Sample, SampleList\nfrom VisualBERT.mmf.models.mmbt import MMBT\nfrom VisualBERT.mmf.modules.encoders import (\n ImageEncoderFactory,\n ImageEncoderTypes,\n ResNet152ImageEncoder,\n TextEncoderFactory,\n TextEncoderTypes,\n)\nfrom VisualBERT.mmf.utils.build import build_model\nfrom VisualBERT.mmf.utils.configuration import Configuration\nfrom VisualBERT.mmf.utils.env import setup_imports\nfrom omegaconf import OmegaConf\n\n\nclass TestMMBTTorchscript(unittest.TestCase):\n def setUp(self):\n test_utils.setup_proxy()\n setup_imports()\n model_name = \"mmbt\"\n args = test_utils.dummy_args(model=model_name)\n configuration = Configuration(args)\n config = configuration.get_config()\n model_config = config.model_config[model_name]\n model_config[\"training_head_type\"] = \"classification\"\n model_config[\"num_labels\"] = 2\n model_config.model = model_name\n self.finetune_model = build_model(model_config)\n\n def test_load_save_finetune_model(self):\n self.assertTrue(test_utils.verify_torchscript_models(self.finetune_model))\n\n def test_finetune_model(self):\n self.finetune_model.eval()\n test_sample = Sample()\n test_sample.input_ids = torch.randint(low=0, high=30255, size=(128,)).long()\n test_sample.input_mask = torch.ones(128).long()\n test_sample.segment_ids = torch.zeros(128).long()\n test_sample.image = torch.rand((3, 300, 300)).float()\n test_sample_list = SampleList([test_sample.copy()])\n\n with torch.no_grad():\n model_output = self.finetune_model.model(test_sample_list)\n\n test_sample_list = SampleList([test_sample])\n script_model = torch.jit.script(self.finetune_model.model)\n with torch.no_grad():\n script_output = script_model(test_sample_list)\n\n self.assertTrue(torch.equal(model_output[\"scores\"], script_output[\"scores\"]))\n\n def test_modal_end_token(self):\n self.finetune_model.eval()\n\n # Suppose 0 for <cls>, 1 for <pad> 2 for <sep>\n CLS = 0\n PAD = 1\n SEP = 2\n size = 128\n\n input_ids = torch.randint(low=0, high=30255, size=(size,)).long()\n input_mask = torch.ones(size).long()\n\n input_ids[0] = CLS\n length = torch.randint(low=2, high=size - 1, size=(1,))\n input_ids[length] = SEP\n input_ids[length + 1 :] = PAD\n input_mask[length + 1 :] = 0\n\n test_sample = Sample()\n test_sample.input_ids = input_ids.clone()\n test_sample.input_mask = input_mask.clone()\n test_sample.segment_ids = torch.zeros(size).long()\n test_sample.image = torch.rand((3, 300, 300)).float()\n test_sample_list = SampleList([test_sample])\n\n mmbt_base = self.finetune_model.model.bert\n with torch.no_grad():\n actual_modal_end_token = mmbt_base.extract_modal_end_token(test_sample_list)\n\n expected_modal_end_token = torch.zeros([1]).fill_(SEP).long()\n self.assertTrue(torch.equal(actual_modal_end_token, expected_modal_end_token))\n self.assertTrue(torch.equal(test_sample_list.input_ids[0, :-1], input_ids[1:]))\n self.assertTrue(\n torch.equal(test_sample_list.input_mask[0, :-1], input_mask[1:])\n )\n\n\nclass TestMMBTConfig(unittest.TestCase):\n def test_mmbt_from_params(self):\n # default init\n mmbt = MMBT.from_params(\n modal_encoder=ImageEncoderFactory.Config(\n type=ImageEncoderTypes.resnet152,\n params=ResNet152ImageEncoder.Config(pretrained=False),\n ),\n text_encoder=TextEncoderFactory.Config(type=TextEncoderTypes.identity),\n )\n\n config = OmegaConf.structured(\n MMBT.Config(\n modal_encoder=ImageEncoderFactory.Config(\n type=ImageEncoderTypes.resnet152,\n params=ResNet152ImageEncoder.Config(pretrained=False),\n ),\n text_encoder=TextEncoderFactory.Config(type=TextEncoderTypes.identity),\n )\n )\n self.assertIsNotNone(mmbt)\n # Make sure that the config is created from MMBT.Config\n self.assertEqual(mmbt.config, config)\n\n def test_mmbt_pretrained(self):\n test_utils.setup_proxy()\n mmbt = MMBT.from_params()\n self.assertIsNotNone(mmbt)\n\n def test_mmbt_directly_from_config(self):\n config = OmegaConf.structured(\n MMBT.Config(\n modal_encoder=ImageEncoderFactory.Config(\n type=ImageEncoderTypes.resnet152,\n params=ResNet152ImageEncoder.Config(pretrained=False),\n ),\n text_encoder=TextEncoderFactory.Config(type=TextEncoderTypes.identity),\n )\n )\n mmbt = MMBT(config)\n self.assertIsNotNone(mmbt)\n # Make sure that the config is created from MMBT.Config\n self.assertEqual(mmbt.config, config)\n" ]
[ [ "torch.jit.script", "torch.ones", "torch.randint", "torch.rand", "torch.no_grad", "torch.equal", "torch.zeros" ] ]
zachary2wave/UAV-aid-communication
[ "801fe22d839261af43127e31db00f166ed6484a0" ]
[ "gym/envs/wlan/SingleAP.py" ]
[ "import gym\nfrom gym import spaces\nimport numpy as np\nfrom gym.envs.wlan import env_simulated as env\nfrom gym.envs.wlan import thought_out as tho\nfrom gym.utils import seeding\n\nclass ApEnv(gym.Env):\n\n def __init__(self):\n self.Num_AP = 1\n self.Num_UE = 50\n self.channel = [1]\n self.oriTHO = np.zeros([1, self.Num_AP])\n loss_cal = env.Scenario(self.Num_AP, self.Num_UE, freq=2, avr_ap=1)\n self.contact, self.placeAP, self.placeUE, self.Loss = loss_cal.sendout()\n\n self.action_space = spaces.Box(low=-0.2, high=0.2, shape=(self.Num_AP,), dtype=np.float32)\n self.observation_space = spaces.Box(low=-0, high=1, shape=(self.Num_AP,), dtype=np.float32)\n\n self.state = self.Num_AP * [0.5]\n envir = tho.ThoughtOutCal(self.channel, self.state * 60, self.Num_AP, self.Num_UE)\n RSSI, Speed, self.connection = envir.subspeed(self.Loss)\n thought_out_ue, P = envir.thomain(Speed, self.connection)\n # 将UE的转化为AP的\n thought_out_AP = np.zeros([self.Num_AP])\n for kki in range(0, self.Num_AP):\n tempN = np.argwhere(self.connection == kki)\n for kkj in tempN:\n thought_out_AP[kki] += thought_out_ue[kkj]\n self.oriTHO[:] = thought_out_AP[:]\n\n def step(self, u):\n reward = np.zeros([1, self.Num_AP])\n s_ = np.zeros([self.Num_AP])\n for kk in range(0, self.Num_AP):\n if self.state[kk] + u[kk] < 0:\n s_[kk] = 0\n elif self.state[kk] + u[kk] > 1:\n s_[kk] = 1\n else:\n s_[kk] = self.state[kk] + u[kk]\n envir = tho.ThoughtOutCal(self.channel, s_*60, self.Num_AP, self.Num_UE)\n RSSI, Speed, connection = envir.subspeed(self.Loss)\n thought_out_ue, P = envir.thomain(Speed, connection)\n # 将UE的转化为AP的\n thought_out_AP = np.zeros([self.Num_AP])\n for kki in range(0, self.Num_AP):\n tempN = np.argwhere(connection == kki)\n for kkj in tempN:\n thought_out_AP[kki] += thought_out_ue[kkj]\n # 计算reward\n for kk in range(0, self.Num_AP):\n if self.state[kk]+u[kk] < 0:\n reward[kk] = -100\n elif self.state[kk]+u[kk] > 1:\n reward[kk] = -100\n else:\n tempppppp = thought_out_AP[kk]\n reward[kk] = tempppppp * 10\n # reward[kk] = (thought_out_AP[kk]-self.oriTHO[kk])*10\n self.oriTHO[:] = thought_out_AP[:]\n # print(s_.shape)\n return s_, np.sum(reward), False, {}\n\n def reset(self):\n self.state = np.array(self.Num_AP*[0.5])\n # print(self.state.shape)\n return self.state\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n def render(self, mode='human'):\n tho.showplot(self.placeAP, self.placeUE, self.state, self.channel, self.connection)\n return {}" ]
[ [ "numpy.array", "numpy.sum", "numpy.argwhere", "numpy.zeros" ] ]
mattjshannon/mattpy
[ "52278419fcf56a5a0c25efb1bbc3ffe0f037c1bb" ]
[ "pennyspec/scripts/helpers.py" ]
[ "#!/usr/bin/env python3\n\"\"\"\nhelpers.py\n\nHelpers functions for analyze_pahs.py\n\"\"\"\n\nimport errno\nimport os\nimport pickle\n\nimport matplotlib.gridspec as gridspec\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom gaussfitter import onedgaussian, multigaussfit\nfrom scipy.integrate import simps\n\nfrom mattpy.utils import to_sigma, to_fwhm, quant_str\n\n\ndef ensure_exists(path):\n \"\"\"Ensure the path exists; if not, make the directory.\"\"\"\n try:\n os.makedirs(path)\n except OSError as exception:\n if exception.errno != errno.EEXIST:\n raise\n\n\ndef jy_to_si(flux_jy, wave):\n \"\"\"Returns a flux array (converted from Jy to W/m^2/micron).\"\"\"\n flux_si = flux_jy * 3e-12 / wave**2\n return flux_si\n\n\ndef smooth(x, window_len=50, window='hanning'):\n \"\"\"Returns a smoothed version of an array, from Stack Overflow.\"\"\"\n if x.ndim != 1:\n raise ValueError(\"smooth only accepts 1 dimension arrays.\")\n if x.size < window_len:\n raise ValueError(\"Input vector must be bigger than window size.\")\n if window_len < 3:\n return x\n\n acceptable_windows = ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']\n if window not in acceptable_windows:\n raise ValueError(\"Window must be in: \", str(acceptable_windows))\n\n s = np.r_[2 * x[0] - x[window_len - 1::-1], x,\n 2 * x[-1] - x[-1:-window_len:-1]]\n\n if window == 'flat':\n w = np.ones(window_len, 'd')\n else:\n w = eval('np.' + window + '(window_len)')\n\n y = np.convolve(w / w.sum(), s, mode='same')\n\n return y[window_len:-window_len + 1]\n\n\ndef compute_feature_uncertainty(gposition, gsigma, wave_feat, rms):\n\n myrange = [gposition - (3. * gsigma), gposition + (3. * gsigma)]\n\n dl = wave_feat[1] - wave_feat[0]\n N = (myrange[1] - myrange[0]) / dl\n feature_uncertainty = (rms * np.sqrt(N) * dl * 2)\n\n return feature_uncertainty\n\n\ndef params_6gauss(basename, guess):\n\n p_non_aliphatics = {\n 'params':\n [\n guess / 200., 6.89, to_sigma(0.15),\n guess / 200., 7.25, to_sigma(0.12),\n guess / 2., 7.55, to_sigma(0.44),\n guess / 1., 7.87, to_sigma(0.40),\n guess / 2., 8.25, to_sigma(0.29),\n guess / 2., 8.59, to_sigma(0.36),\n ],\n 'limitedmin': [True] * 18,\n 'limitedmax': [True] * 18,\n 'fixed':\n [\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n ],\n 'minpars':\n [\n 0., 6.82, to_sigma(0.06),\n 0, 7.15, to_sigma(0.05),\n 0, 7.45, to_sigma(0.315),\n 0, 7.77, to_sigma(0.275),\n 0, 8.15, to_sigma(0.165),\n 0, 8.49, to_sigma(0.235),\n ],\n 'maxpars':\n [\n guess / 100., 6.96, to_sigma(0.21),\n guess / 100, 7.35, to_sigma(0.15),\n guess, 7.65, to_sigma(0.565),\n guess, 7.97, to_sigma(0.525),\n guess, 8.35, to_sigma(0.415),\n guess, 8.69, to_sigma(0.485),\n ]\n }\n\n p_non_aliphatics_xxoph = {\n 'params':\n [\n 0., 6.89, to_sigma(0.15),\n 0., 7.25, to_sigma(0.12),\n guess / 2., 7.55, to_sigma(0.44),\n guess / 1., 7.87, to_sigma(0.40),\n guess / 2., 8.25, to_sigma(0.29),\n guess / 2., 8.59, to_sigma(0.36),\n ],\n 'limitedmin': [True] * 18,\n 'limitedmax': [True] * 18,\n 'fixed':\n [\n True, False, False,\n True, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n ],\n 'minpars':\n [\n 0., 6.82, to_sigma(0.06),\n 0, 7.15, to_sigma(0.05),\n 0, 7.45, to_sigma(0.315),\n 0, 7.77, to_sigma(0.275),\n 0, 8.15, to_sigma(0.165),\n 0, 8.49, to_sigma(0.235),\n ],\n 'maxpars':\n [\n guess / 100., 6.96, to_sigma(0.21),\n guess / 100, 7.35, to_sigma(0.15),\n guess, 7.65, to_sigma(0.565),\n guess, 7.97, to_sigma(0.525),\n guess, 8.35, to_sigma(0.415),\n guess, 8.69, to_sigma(0.485),\n ]\n }\n\n\n p0 = {\n 'params':\n [\n guess / 2., 6.89, to_sigma(0.15),\n guess / 4., 7.25, to_sigma(0.12),\n guess / 2., 7.55, to_sigma(0.44),\n guess / 1., 7.87, to_sigma(0.40),\n guess / 2., 8.25, to_sigma(0.29),\n guess / 2., 8.59, to_sigma(0.36),\n ],\n 'limitedmin': [True] * 18,\n 'limitedmax': [True] * 18,\n 'fixed':\n [\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n ],\n 'minpars':\n [\n guess / 30., 6.82, to_sigma(0.06),\n 0, 7.15, to_sigma(0.05),\n 0, 7.45, to_sigma(0.315),\n 0, 7.77, to_sigma(0.275),\n 0, 8.15, to_sigma(0.165),\n 0, 8.49, to_sigma(0.235),\n ],\n 'maxpars':\n [\n guess, 6.96, to_sigma(0.21),\n guess, 7.35, to_sigma(0.15),\n guess, 7.65, to_sigma(0.565),\n guess, 7.97, to_sigma(0.525),\n guess, 8.35, to_sigma(0.415),\n guess, 8.69, to_sigma(0.485),\n ]\n }\n\n p1 = {\n 'params':\n [\n guess / 2., 6.89, to_sigma(0.15),\n guess / 4., 7.25, to_sigma(0.12),\n guess / 2., 7.55, to_sigma(0.44),\n guess / 1., 7.87, to_sigma(0.40),\n guess / 2., 8.25, to_sigma(0.29),\n guess / 2., 8.59, to_sigma(0.36),\n ],\n 'limitedmin': [True] * 18,\n 'limitedmax': [True] * 18,\n 'fixed':\n [\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n ],\n 'minpars':\n [\n guess / 30., 6.82, to_sigma(0.06),\n guess / 40., 7.15, to_sigma(0.05),\n guess / 30., 7.45, to_sigma(0.315),\n guess / 30., 7.77, to_sigma(0.275),\n 0, 8.15, to_sigma(0.165),\n guess / 30., 8.49, to_sigma(0.235),\n ],\n 'maxpars':\n [\n guess, 6.96, to_sigma(0.21),\n guess, 7.35, to_sigma(0.15),\n guess, 7.65, to_sigma(0.565),\n guess, 7.97, to_sigma(0.525),\n guess, 8.35, to_sigma(0.415),\n guess, 8.69, to_sigma(0.485),\n ]\n }\n\n p2 = {\n 'params':\n [\n guess / 2., 6.89, to_sigma(0.15),\n 0., 7.25, to_sigma(0.12),\n guess / 2., 7.55, to_sigma(0.44),\n guess / 1., 7.87, to_sigma(0.40),\n guess / 2., 8.25, to_sigma(0.29),\n guess / 2., 8.59, to_sigma(0.36),\n ],\n 'limitedmin': [True] * 18,\n 'limitedmax': [True] * 18,\n 'fixed':\n [\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n ],\n 'minpars':\n [\n guess / 30., 6.82, to_sigma(0.06),\n 0., 7.15, to_sigma(0.05),\n guess / 30., 7.45, to_sigma(0.315),\n guess / 30., 7.77, to_sigma(0.275),\n 0., 8.15, to_sigma(0.165),\n guess / 30., 8.49, to_sigma(0.235),\n ],\n 'maxpars':\n [\n guess, 6.96, to_sigma(0.21),\n guess, 7.35, to_sigma(0.15),\n guess, 7.65, to_sigma(0.565),\n guess, 7.97, to_sigma(0.525),\n guess, 8.35, to_sigma(0.415),\n guess, 8.69, to_sigma(0.485),\n ]\n }\n\n p3 = {\n 'params':\n [\n guess / 2., 6.89, to_sigma(0.15),\n guess / 4., 7.25, to_sigma(0.12),\n guess / 2., 7.55, to_sigma(0.44),\n guess / 1., 7.87, to_sigma(0.40),\n guess / 2., 8.25, to_sigma(0.29),\n guess / 2., 8.59, to_sigma(0.36),\n ],\n 'limitedmin': [True] * 18,\n 'limitedmax': [True] * 18,\n 'fixed':\n [\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n ],\n 'minpars':\n [\n guess / 30., 6.82, to_sigma(0.06),\n guess / 30., 7.15, to_sigma(0.05),\n guess / 30., 7.45, to_sigma(0.315),\n guess / 30., 7.77, to_sigma(0.275),\n guess / 30., 8.15, to_sigma(0.165),\n guess / 30., 8.49, to_sigma(0.235),\n ],\n 'maxpars':\n [\n guess, 6.96, to_sigma(0.21),\n guess, 7.35, to_sigma(0.15),\n guess, 7.65, to_sigma(0.565),\n guess, 7.97, to_sigma(0.525),\n guess, 8.35, to_sigma(0.415),\n guess, 8.69, to_sigma(0.485),\n ]\n }\n\n p4 = {\n 'params':\n [\n guess / 2., 6.89, to_sigma(0.15),\n guess / 6., 7.25, to_sigma(0.12),\n guess / 2., 7.55, to_sigma(0.44),\n guess / 1., 7.87, to_sigma(0.40),\n guess / 2., 8.25, to_sigma(0.29),\n guess / 2., 8.59, to_sigma(0.36),\n ],\n 'limitedmin': [True] * 18,\n 'limitedmax': [True] * 18,\n 'fixed':\n [\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n ],\n 'minpars':\n [\n guess / 30., 6.82, to_sigma(0.06),\n guess / 30., 7.15, to_sigma(0.05),\n guess / 30., 7.45, to_sigma(0.315),\n guess / 30., 7.77, to_sigma(0.275),\n 0., 8.15, to_sigma(0.165),\n guess / 30., 8.49, to_sigma(0.235),\n ],\n 'maxpars':\n [\n guess, 6.96, to_sigma(0.21),\n guess, 7.35, to_sigma(0.15),\n guess, 7.65, to_sigma(0.565),\n guess, 7.97, to_sigma(0.525),\n guess, 8.35, to_sigma(0.415),\n guess, 8.69, to_sigma(0.485),\n ]\n }\n\n p5 = {\n 'params':\n [\n guess / 2., 6.89, to_sigma(0.15),\n 1.21852599e-15 * 0.1, 7.25, to_sigma(0.1),\n guess / 2., 7.55, to_sigma(0.44),\n guess / 1., 7.87, to_sigma(0.40),\n guess / 2., 8.25, to_sigma(0.29),\n guess / 2., 8.59, to_sigma(0.36),\n ],\n 'limitedmin': [True] * 18,\n 'limitedmax': [True] * 18,\n 'fixed':\n [\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n ],\n 'minpars':\n [\n guess / 30., 6.82, to_sigma(0.06),\n 0., 7.15, to_sigma(0.05),\n guess / 30., 7.45, to_sigma(0.315),\n guess / 30., 7.77, to_sigma(0.275),\n 0., 8.15, to_sigma(0.165),\n guess / 30., 8.49, to_sigma(0.235),\n ],\n 'maxpars':\n [\n guess, 6.96, to_sigma(0.21),\n 1.21852599e-15 * 0.25, 7.35, to_sigma(0.13),\n guess, 7.65, to_sigma(0.565),\n guess, 7.97, to_sigma(0.525),\n guess, 8.35, to_sigma(0.415),\n guess, 8.69, to_sigma(0.485),\n ]\n }\n\n p6 = {\n 'params':\n [\n guess / 2., 6.93, to_sigma(0.15),\n guess / 6., 7.25, to_sigma(0.12),\n guess / 2., 7.55, to_sigma(0.40),\n guess / 1., 7.87, to_sigma(0.40),\n guess / 2., 8.25, to_sigma(0.29),\n guess / 2., 8.59, to_sigma(0.36),\n ],\n 'limitedmin': [True] * 18,\n 'limitedmax': [True] * 18,\n 'fixed':\n [\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n ],\n 'minpars':\n [\n guess / 30., 6.91, to_sigma(0.06),\n 0., 7.15, to_sigma(0.05),\n guess / 30., 7.53, to_sigma(0.315),\n guess / 30., 7.77, to_sigma(0.275),\n 0., 8.15, to_sigma(0.165),\n guess / 30., 8.49, to_sigma(0.235),\n ],\n 'maxpars':\n [\n guess, 6.96, to_sigma(0.16),\n guess, 7.35, to_sigma(0.15),\n guess, 7.65, to_sigma(0.41),\n guess, 7.97, to_sigma(0.525),\n guess, 8.35, to_sigma(0.415),\n guess, 8.69, to_sigma(0.485),\n ]\n }\n\n p7 = {\n 'params':\n [\n guess / 2., 6.89, to_sigma(0.15),\n guess / 6., 7.25, to_sigma(0.12),\n guess / 2., 7.55, to_sigma(0.44),\n guess / 1., 7.87, to_sigma(0.40),\n guess / 2., 8.25, to_sigma(0.29),\n guess / 2., 8.59, to_sigma(0.36),\n ],\n 'limitedmin': [True] * 18,\n 'limitedmax': [True] * 18,\n 'fixed':\n [\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n ],\n 'minpars':\n [\n guess / 30., 6.82, to_sigma(0.06),\n guess / 30., 7.15, to_sigma(0.05),\n guess / 30., 7.45, to_sigma(0.315),\n guess / 30., 7.77, to_sigma(0.275),\n 0., 8.15, to_sigma(0.165),\n guess / 30., 8.49, to_sigma(0.235),\n ],\n 'maxpars':\n [\n guess, 6.96, to_sigma(0.21),\n guess, 7.35, to_sigma(0.15),\n guess, 7.65, to_sigma(0.565),\n guess, 7.97, to_sigma(0.525),\n guess, 8.35, to_sigma(0.415),\n guess, 8.69, to_sigma(0.485),\n ]\n }\n\n p8 = {\n 'params':\n [\n guess / 2., 6.89, to_sigma(0.15),\n guess / 6., 7.25, to_sigma(0.12),\n guess / 2., 7.60, to_sigma(0.44),\n guess / 1., 7.87, to_sigma(0.40),\n guess / 2., 8.25, to_sigma(0.29),\n guess / 2., 8.59, to_sigma(0.36),\n ],\n 'limitedmin': [True] * 18,\n 'limitedmax': [True] * 18,\n 'fixed':\n [\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n ],\n 'minpars':\n [\n guess / 30., 6.82, to_sigma(0.06),\n guess / 30., 7.15, to_sigma(0.05),\n guess / 30., 7.45, to_sigma(0.315),\n guess / 30., 7.77, to_sigma(0.275),\n guess / 30., 8.15, to_sigma(0.165),\n guess / 30., 8.49, to_sigma(0.235),\n ],\n 'maxpars':\n [\n guess, 6.96, to_sigma(0.21),\n guess, 7.35, to_sigma(0.15),\n guess, 7.65, to_sigma(0.565),\n guess, 7.97, to_sigma(0.525),\n guess, 8.35, to_sigma(0.415),\n guess, 8.69, to_sigma(0.485),\n ]\n }\n\n p9 = {\n 'minpars':\n [\n guess / 30., 6.82, to_sigma(0.06),\n 0., 7.15, to_sigma(0.05),\n guess / 30., 7.45, to_sigma(0.315),\n guess / 30., 7.77, to_sigma(0.275),\n 0., 8.15, to_sigma(0.165),\n guess / 30., 8.49, to_sigma(0.235),\n ],\n 'params':\n [\n guess / 2., 6.89, to_sigma(0.15),\n guess / 6., 7.25, to_sigma(0.12),\n guess / 2., 7.55, to_sigma(0.44),\n guess / 1., 7.87, to_sigma(0.40),\n guess / 2., 8.25, to_sigma(0.29),\n guess / 2., 8.59, to_sigma(0.36),\n ],\n 'maxpars':\n [\n guess, 6.96, to_sigma(0.21),\n guess, 7.35, to_sigma(0.15),\n guess, 7.65, to_sigma(0.565),\n guess, 7.97, to_sigma(0.525),\n guess, 8.35, to_sigma(0.415),\n guess, 8.69, to_sigma(0.485),\n ],\n 'limitedmin': [True] * 18,\n 'limitedmax': [True] * 18,\n 'fixed':\n [\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n ]\n }\n\n p10 = {\n 'params':\n [\n guess / 2., 6.89, to_sigma(0.15),\n guess / 4., 7.25, to_sigma(0.12),\n guess / 2., 7.55, to_sigma(0.44),\n guess / 1., 7.87, to_sigma(0.40),\n guess / 2., 8.25, to_sigma(0.29),\n guess / 2., 8.59, to_sigma(0.36),\n ],\n 'limitedmin': [True] * 18,\n 'limitedmax': [False] * 18,\n 'fixed':\n [\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n ],\n 'minpars':\n [\n guess / 30., 6.82, to_sigma(0.06),\n guess / 40., 7.22, to_sigma(0.07),\n guess / 30., 7.45, to_sigma(0.315),\n guess / 30., 7.77, to_sigma(0.275),\n 0, 8.15, to_sigma(0.165),\n guess / 30., 8.49, to_sigma(0.235),\n ],\n 'maxpars':\n [\n guess, 6.96, to_sigma(0.16),\n guess, 7.32, to_sigma(0.15),\n guess, 7.65, to_sigma(0.6),\n guess, 7.97, to_sigma(0.525),\n guess, 8.35, to_sigma(0.415),\n guess, 8.69, to_sigma(0.485),\n ]\n }\n\n p11 = {\n 'params':\n [\n guess / 2., 6.89, to_sigma(0.15),\n guess / 4., 7.25, to_sigma(0.12),\n guess / 100., 7.55, to_sigma(0.44),\n guess / 1., 7.87, to_sigma(0.40),\n guess / 2., 8.25, to_sigma(0.29),\n guess / 2., 8.59, to_sigma(0.36),\n ],\n 'limitedmin': [True] * 18,\n 'limitedmax': [True] * 18,\n 'fixed':\n [\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n ],\n 'minpars':\n [\n guess / 30., 6.82, to_sigma(0.06),\n 0, 7.15, to_sigma(0.05),\n 0, 7.45, to_sigma(0.315),\n 0, 7.77, to_sigma(0.275),\n 0, 8.15, to_sigma(0.165),\n 0, 8.49, to_sigma(0.235),\n ],\n 'maxpars':\n [\n guess, 6.96, to_sigma(0.21),\n guess, 7.35, to_sigma(0.15),\n guess / 98., 7.65, to_sigma(0.565),\n guess, 7.97, to_sigma(0.525),\n guess, 8.35, to_sigma(0.415),\n guess, 8.69, to_sigma(0.485),\n ]\n }\n\n p12 = {\n 'params':\n [\n guess / 2., 6.89, to_sigma(0.15),\n guess / 4., 7.25, to_sigma(0.12),\n guess / 2., 7.55, to_sigma(0.44),\n guess / 1., 7.87, to_sigma(0.40),\n guess / 2., 8.25, to_sigma(0.29),\n guess / 2., 8.59, to_sigma(0.36),\n ],\n 'limitedmin': [True] * 18,\n 'limitedmax': [True] * 18,\n 'fixed':\n [\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n False, False, False,\n ],\n 'minpars':\n [\n guess / 30., 6.82, to_sigma(0.06),\n guess / 40., 7.15, to_sigma(0.05),\n guess / 30., 7.45, to_sigma(0.315),\n guess / 30., 7.77, to_sigma(0.275),\n 0, 8.15, to_sigma(0.165),\n guess / 30., 8.49, to_sigma(0.235),\n ],\n 'maxpars':\n [\n guess, 6.96, to_sigma(0.21),\n guess, 7.35, to_sigma(0.15),\n guess, 7.65, to_sigma(0.565),\n guess, 7.97, to_sigma(0.525),\n guess, 8.35, to_sigma(0.415),\n guess, 8.69, to_sigma(0.485),\n ]\n }\n\n param_dict = {\n 'hd97048_convCWsub': p0, # GOOD, wouldn't trust 72 tho\n 'hd135344_convCWsub': p11, # * NO ALIPHATICS TRUSTED!!! *\n 'IRAS05063_CWsub': p3, # GOOD\n 'IRAS05092_CWsub': p0, # GOOD\n 'IRAS05186_CWsub': p0, # GOOD\n 'IRAS05361_CWsub': p0, # GOOD. TRY LIMIT G7.6 FROM LEFT?\n 'IRAS05370_CWsub': p4, # GOOD, don't trust 7.2\n 'IRAS05413_CWsub': p2, # GOOD? ONLY TRUST 6.9, maybe 77 flux\n 'IRAS05588_CWsub': p0, # GOOD\n 'IRAS06111_CWsub': p0, # GOOD\n 'IRAS14429_CWsub': p0, # GOOD\n 'IRAS15482_CWsub': p5, # GOOD, don't trust 7.2 maybe (manual)\n 'iras17047_SWS_CWsub': p10, # GOOD, had to do ct myself\n 'IRASF05110-6616_LR_CWsub': p0, # GOOD\n 'IRASf05192_CWsub': p1, # GOOD, quesitonable 69/72. tho\n 'J004441_CWsub': p0, # GOOD\n 'J010546_CWsub': p6, # GOOD, not perfect but good enough?\n 'j050713_CWsub': p7, # GOOD\n 'J052043_CWsub': p8, # GOOD, had to drop errors?\n 'J052520_CWsub': p1, # GOOD\n 'NGC1978WBT2665_CWsub': p1, # GOOD\n 'SMPLMC076_CWsub': p12, # new\n 'SMPSMC006_CWsub': p9, # GOOD, dropping fluxerr in fit (!!)\n 'SMPSMC011_CWsub': p1, # GOOD\n\n 'xxOph_SWS_CWsub': p_non_aliphatics_xxoph,\n }\n\n\n if basename in param_dict:\n print('In standard PARAM DICT.')\n parameters = param_dict[basename]\n else:\n parameters = p_non_aliphatics\n\n return parameters\n\n # TO DO: UNCERTAINTIES!!!\n\n # pos, flux, sigma = line69_params[basename]\n # amp = flux / (np.sqrt(2) * np.abs(sigma) * np.sqrt(np.pi))\n\n # max_flux72 = 0.35 * flux\n # amp_72_approx = max_flux72 / (np.sqrt(2) * np.abs(sigma)* np.sqrt(np.pi))\n\n # p0['params'][0] = amp\n # p0['params'][1] = pos\n # p0['params'][2] = sigma\n\n # p0['fixed'][0] = True\n # p0['fixed'][1] = True\n # p0['fixed'][2] = True\n\n # p0['maxpars'][3] = amp_72_approx\n # p0['params'][3] = amp_72_approx * 0.5\n\n\n\n\ndef measure_112_RMS(wave, csub):\n xmin = 11.9\n xmax = 12.1\n\n myrange = np.where((wave >= xmin) & (wave <= xmax))\n csub_mr = csub[myrange]\n rms = np.sqrt(np.mean(csub_mr**2))\n\n return rms # , xmin, xmax\n\n\ndef fit_aliphatics(basename, wave, flux, fluxerr, rms, output_dir):\n\n def fit_straight_line(wave, flux, fluxerr):\n\n # Section 1: Fit Aliphatics\n # Define wavelength range of relevance\n lim = np.where((wave > 6.6) & (wave < 7.65))\n waveLim = wave[lim]\n fluxLim = flux[lim]\n errLim = fluxerr[lim]\n\n # Region where 7.2 is found\n lim2 = np.where((wave > 6.7) & (wave < 7.6))\n waveLim2 = wave[lim2]\n fluxLim2 = flux[lim2]\n # errLim2 = fluxerr[lim2]\n\n # Draw a straight line under 7.2 feature\n # Comment section out if no 7.2\n\n winDX = np.where((waveLim2 >= 7.) & (waveLim2 <= 7.2)\n ) # Find the first ancor point\n winWave = waveLim2[winDX]\n winFlux = fluxLim2[winDX]\n anchor1Wave = winWave[np.nanargmin(winFlux)]\n anchor1Flux = np.nanmin(winFlux)\n\n winDX = np.where((waveLim2 >= 7.5)) # Find the second anchor point\n winWave = waveLim2[winDX]\n winFlux = fluxLim2[winDX]\n anchor2Wave = winWave[np.nanargmin(winFlux)]\n anchor2Flux = np.nanmin(winFlux)\n\n # Define the straight line from the anchor points\n x = np.array([anchor1Wave, anchor2Wave])\n y = np.array([anchor1Flux, anchor2Flux])\n StrLine = np.polyfit(x, y, deg=1) # Fit straight line\n StrLineFit = StrLine[0] * waveLim2 + StrLine[1]\n\n # Plot straight line to check\n fig1, ax = plt.subplots()\n ax.plot(waveLim, fluxLim, '-r', lw=2) # Make figure\n ax.errorbar(\n waveLim,\n fluxLim,\n errLim,\n color='r',\n ecolor='0.45',\n lw=2,\n elinewidth=1)\n ax.plot(waveLim2, StrLineFit, 'g-', label='7.2 Cont', lw=2)\n ax.plot(x, y, 'bo')\n\n ax.legend(loc=0, fontsize='small')\n ax.set_xlabel('Wavelength (microns)')\n ax.set_ylabel('Flux (W/m^2)')\n # ax.set_title(fnameStr + ' -- Line fit')\n ax.grid()\n ax.minorticks_on()\n\n ensure_exists(output_dir)\n pdf_filename = output_dir + basename + '_aliphatic_fit_1.pdf'\n print('Saved: ', pdf_filename)\n fig1.savefig(pdf_filename, format='pdf', bbox_inches='tight')\n\n plt.close()\n fig1.clear()\n\n if StrLine[0] > 0: # Subtract straight line from data\n\n lim69 = np.where(waveLim < x[0]) # Create limits of subtraction\n lim72 = np.where((waveLim >= x[0]) & (waveLim <= x[1]))\n limOver = np.where(waveLim > x[1])\n\n flux69 = fluxLim[lim69]\n # Subtraction\n flux72 = fluxLim[lim72] - \\\n (StrLine[0] * waveLim[lim72] + StrLine[1])\n fluxOver = fluxLim[limOver]\n\n fluxFull = []\n fluxFull = np.append(flux69, flux72)\n fluxFull = np.append(fluxFull, fluxOver) # Create array\n\n else:\n fluxFull = fluxLim\n\n return waveLim, fluxFull, errLim\n\n def fit_gaussians(waveLim, fluxFull, errLim, fnameStr='temp_label'):\n\n # End of commented section if no 7.2\n # fluxFull = fluxLim # Comment if spectrum has 7.2 feature\n\n # Fit Gaussian functions to peaks\n # Change ngauss and parameters as needed\n\n # fitAli = multigaussfit(\n # waveLim, fluxFull, ngauss=2, err=errLim,\n # params=[0.12e-15,6.85,0.1,0.5e-16,7.23,0.05],\n # limitedmin=[True,True,True,True,True,True],\n # limitedmax=[True,True,True,True,True,True],\n # minpars=[0.01e-18,6.8,0.03,0,7,0],\n # maxpars=[1.5e-14,6.86,0.2,0.5e-15,7.3,0.06]\n # )\n\n fitAli = multigaussfit(\n waveLim, fluxFull, ngauss=2, err=errLim, params=[\n 0.2e-14, 6.9, 0.1, 0.17e-14, 7.23, 0.05], limitedmin=[\n True, True, True, True, True, True], minpars=[\n 0, 6.8, 0.04, 0, 7, 0], limitedmax=[\n True, True, True, True, True, True], maxpars=[\n 0.5e-13, 7, 0.2, 0.1e-13, 7.25, 0.2])\n\n # Plot fit\n fig2, ax = plt.subplots()\n\n ax.plot(waveLim, fluxFull, '-r', label=fnameStr, lw=2)\n ax.errorbar(\n waveLim,\n fluxFull,\n errLim,\n color='r',\n ecolor='0.45',\n lw=2,\n elinewidth=1)\n ax.plot(waveLim, fitAli[1], '-g', label='Spectral Fit', lw=1.5)\n ax.fill_between(waveLim, fitAli[1], facecolor='green', alpha=0.15)\n ax.axhline(y=0, color='k', ls='-', zorder=-10, lw=2)\n\n ax.legend(loc=0, fontsize='small')\n ax.set_xlabel('Wavelength (microns)')\n ax.set_ylabel('Flux (W/m^2)')\n ax.set_title(fnameStr + ' -- Gaussian Fit')\n ax.grid()\n ax.minorticks_on()\n\n ensure_exists(output_dir)\n pdf_filename = output_dir + basename + '_aliphatic_fit_2.pdf'\n print('Saved: ', pdf_filename)\n fig2.savefig(pdf_filename, format='pdf', bbox_inches='tight')\n\n plt.close()\n fig2.clear()\n\n # print('Fit parameters for aliphatic features:')\n # print(fitAli[0])\n\n return fitAli\n\n def compute_aliphatic_fluxes(fitAli, waveLim, rms):\n\n # Calculate integrated flux of aliphatic features from fit\n Gauss69 = fitAli[0][0] * \\\n np.exp(-(waveLim - fitAli[0][1])**2 / (2 * fitAli[0][2]**2))\n area69 = simps(Gauss69, waveLim)\n\n Gauss72 = fitAli[0][3] * \\\n np.exp(-(waveLim - fitAli[0][4])**2 / (2 * fitAli[0][5]**2))\n area72 = simps(Gauss72, waveLim)\n\n err69 = compute_feature_uncertainty(\n fitAli[0][1], fitAli[0][2], waveLim, rms)\n err72 = compute_feature_uncertainty(\n fitAli[0][4], fitAli[0][5], waveLim, rms)\n\n # fitErr69 = np.sqrt((fitAli[2][0]/fitAli[0][0])**2 + \\\n # (fitAli[2][2]/fitAli[0][2])**2) * area69\n # fitErr72 = np.sqrt((fitAli[2][3]/fitAli[0][3])**2 + \\\n # (fitAli[2][5]/fitAli[0][5])**2) * area72\n\n errTot69 = err69 # + fitErr69\n errTot72 = err72 # + fitErr72\n\n # print('Integrated fluxes of aliphatics:')\n # print(area69, area72)\n\n SNR69 = area69 / errTot69\n SNR72 = area72 / errTot72\n\n # print('S/N of aliphatics: ', SNR69, SNR72)\n\n return area69, err69, SNR69, area72, err72, SNR72\n\n waveLim, fluxFull, errLim = fit_straight_line(wave, flux, fluxerr)\n\n fitAli = fit_gaussians(waveLim, fluxFull, errLim, fnameStr='temp_label')\n\n area69, err69, SNR69, area72, err72, SNR72 = \\\n compute_aliphatic_fluxes(fitAli, waveLim, rms)\n\n return fitAli, waveLim, area69, SNR69, area72, SNR72\n\n\ndef fit_aromatics(basename, wave, flux, fluxerr, rms, output_dir):\n\n def fit_straight_line(wave, flux, fluxerr, fnameStr='temp_label'):\n\n # Section 2: Fit 7.7\n # Limits of feature - change as needed\n lim77 = np.where((wave >= 6.9) & (wave <= 9))\n waveLim77 = wave[lim77]\n fluxLim77 = flux[lim77]\n errLim77 = fluxerr[lim77]\n\n # Limit for 7.2 feature - change as needed\n lim2_a = np.where((wave > 6.9) & (wave < 7.45))\n waveLim2_a = wave[lim2_a]\n fluxLim2_a = flux[lim2_a]\n # errLim2_a = fluxerr[lim2_a]\n\n # Draw a straight line under 7.2 feature\n # Comment section out if no 7.2\n\n winDX77 = np.where((waveLim2_a >= 7.) & (waveLim2_a <= 7.2))\n winWave77 = waveLim2_a[winDX77]\n winFlux77 = fluxLim2_a[winDX77]\n anchor1Wave77 = winWave77[np.nanargmin(winFlux77)]\n anchor1Flux77 = np.nanmin(winFlux77)\n\n winDX77 = np.where((waveLim2_a >= 7.2))\n winWave77 = waveLim2_a[winDX77]\n winFlux77 = fluxLim2_a[winDX77]\n anchor2Wave77 = winWave77[np.nanargmin(winFlux77)]\n anchor2Flux77 = np.nanmin(winFlux77)\n\n # Define the straight line from the anchor points\n x77 = np.array([anchor1Wave77, anchor2Wave77])\n y77 = np.array([anchor1Flux77, anchor2Flux77])\n StrLine77 = np.polyfit(x77, y77, deg=1) # Fit straight line\n StrLineFit77 = StrLine77[0] * waveLim2_a + StrLine77[1]\n\n # Comment out section if no 7.2\n fig3, ax = plt.subplots() # Define figure\n ax.plot(waveLim77, fluxLim77, '-r', label=fnameStr, lw=2)\n ax.errorbar(\n waveLim77,\n fluxLim77,\n errLim77,\n color='r',\n ecolor='0.45',\n lw=2,\n elinewidth=1)\n # Plot straight line - comment out if no 7.2 feature\n ax.plot(waveLim2_a, StrLineFit77, 'g-', lw=2)\n\n ax.axhline(y=0, color='k', ls='-', zorder=-10, lw=2)\n ax.legend(loc=0, fontsize='small')\n ax.grid()\n ax.minorticks_on()\n\n ax.set_title(fnameStr + ' 7.7 complex')\n ax.set_xlabel('Wavelength (microns)')\n ax.set_ylabel('Flux (W/m^2)')\n\n ensure_exists(output_dir)\n pdf_filename = output_dir + basename + '_aromatic_fit_1.pdf'\n print('Saved: ', pdf_filename)\n fig3.savefig(pdf_filename, format='pdf', bbox_inches='tight')\n\n plt.close()\n fig3.clear()\n # End comments if no 7.2\n\n if StrLine77[0] > 0: # Use if spectrum has 7.2\n # Create limits of subtraction\n lim69_a = np.where(waveLim77 < x77[0])\n lim72_a = np.where((waveLim77 >= x77[0]) & (waveLim77 <= x77[1]))\n limOver_a = np.where(waveLim77 > x77[1])\n\n flux69_a = fluxLim77[lim69_a]\n flux72_a = (\n StrLine77[0] *\n waveLim77[lim72_a] +\n StrLine77[1]) # Straight Line\n fluxOver_a = fluxLim77[limOver_a]\n\n fluxFull77 = []\n fluxFull77 = np.append(flux69_a, flux72_a)\n # Create array from wavelength subtraction\n fluxFull77 = np.append(fluxFull77, fluxOver_a)\n\n else:\n fluxFull77 = fluxLim77 # Use if spectrum has no 7.2\n\n return waveLim77, fluxLim77, errLim77, fluxFull77\n\n def fit_gaussians(waveLim77, fluxLim77, errLim77, fluxFull77,\n fnameStr='temp_label'):\n\n # End commented section\n # fluxFull77 = fluxLim77 # Comment if spectrum has a 7.2 feature\n\n # Define feature:\n feature = np.where(\n (waveLim77 > 7.1) & (\n waveLim77 < 8.9)) # Change as needed\n\n # # Fit Gaussian\n # fit77 = multigaussfit(\n # waveLim77[feature], fluxFull77[feature], ngauss=4,\n # err=errLim77[feature],\n # params=[5e-15,7.5,0.07,5.8e-15,7.75,0.06,\n # 1.2e-15,8.1,0.07,1.8e-15,8.65,0.07],\n # limitedmin=[True,True,True,True,True,True,\n # True,True,True,True,True,True],\n # limitedmax=[False,True,False,False,True,False,\n # False,True,False,True,True,False],\n # minpars=[0,7.4,0.05,0,7.7,0.2e-16,8.1,\n # 0.01,0.7e-16,8.4,0.01],\n # maxpars=[3e-14,7.7,0.1,3e-14,8.1,0.2,\n # 3e-14,8.4,0.2,3e-14,8.7,0.2]\n # )\n\n fit77 = multigaussfit(\n waveLim77[feature],\n fluxFull77[feature],\n ngauss=4,\n err=errLim77[feature],\n params=[\n 1.25e-14,\n 7.68,\n 0.1,\n 0.2e-14,\n 7.95,\n 0.06,\n 3e-15,\n 8.227557,\n 0.15,\n 0.3e-14,\n 8.609484,\n 0.08],\n limitedmin=[\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True],\n minpars=[\n 0.2e-18,\n 7.5,\n 0.05,\n 0.2e-18,\n 7.75,\n 0.01,\n 0.2e-18,\n 8.1,\n 0.03,\n 0.3e-18,\n 8.5,\n 0],\n limitedmax=[\n True,\n True,\n True,\n True,\n True,\n True,\n False,\n True,\n True,\n True,\n True,\n False],\n maxpars=[\n 2.3e-12,\n 7.9,\n 0.25,\n 1.5e-12,\n 8.2,\n 0.25,\n 8e-12,\n 8.5,\n 0.2,\n 1e-11,\n 8.7,\n 0.12])\n\n # print('Fit parameters of the 7.7 micron complex:')\n # print(fit77[0])\n waveArr = np.arange(waveLim77[feature][0],\n waveLim77[feature][-1], 0.0001)\n # Seperate Gaussian functions\n Gauss76 = fit77[0][0] * \\\n np.exp(-(waveArr - fit77[0][1])**2 / (2 * fit77[0][2]**2))\n Gauss79 = fit77[0][3] * \\\n np.exp(-(waveArr - fit77[0][4])**2 / (2 * fit77[0][5]**2))\n Gauss82 = fit77[0][6] * \\\n np.exp(-(waveArr - fit77[0][7])**2 / (2 * fit77[0][8]**2))\n Gauss86 = fit77[0][9] * \\\n np.exp(-(waveArr - fit77[0][10])**2 / (2 * fit77[0][11]**2))\n\n # err76 = compute_feature_uncertainty(\n # fit77[0][1], fit77[0][2], waveLim77[feature], rms\n # )\n # err79 = compute_feature_uncertainty(\n # fit77[0][4], fit77[0][5], waveLim77[feature], rms\n # )\n # err82 = compute_feature_uncertainty(\n # fit77[0][7], fit77[0][8], waveLim77[feature], rms\n # )\n\n fluxFeat = Gauss76 + Gauss79 + Gauss82\n waveFeat = waveArr\n area77 = simps(fluxFeat, waveFeat)\n\n # fitErr77 = area77 * np.sqrt(\n # (fit77[2][0]/fit77[0][0])**2 + (fit77[2][2]/fit77[0][2])**2 +\n # (fit77[2][3]/fit77[0][3])**2 + (fit77[2][5]/fit77[0][5])**2 +\n # (fit77[2][6]/fit77[0][6])**2 + (fit77[2][8]/fit77[0][8])**2\n # )\n # errTot77 = fitErr77\n\n # SNR77 = area77/errTot77\n\n # wave0 = 7.9 # Initial guess for central wavelength\n # errPercent = 1\n # count = 0\n '''\n # Define function to calculate difference in blue and red flux\n def areaEq(wave0):\n blue = np.where(waveFeat<=wave0)\n # Integration limits to find central wavelengths\n red = np.where(waveFeat>wave0)\n print '**************'\n area77b = simps(fluxFeat[blue], waveFeat[blue])\n area77r = simps(fluxFeat[red], waveFeat[red])\n return area77b - area77r\n\n lambdaC = fsolve(areaEq, wave0, xtol=1.5E-1)\n # Optimise difference in blue and red flux to find central wavelength\n print 'Central wavelength of 7.7 complex'\n print lambdaC\n\n while errPercent >= 0.01:\n count = count + 1\n #print count\n blue = np.where(waveFeat<=wave0)\n # Integration limits to find central wavelengths\n\n red = np.where(waveFeat>wave0)\n area77b = simps(fluxFeat[blue], waveFeat[blue])\n area77r = simps(fluxFeat[red], waveFeat[red])\n errPercent = np.absolute((area77b-area77r)/((area77b+area77r)/2))\n if area77b > area77r:\n wave0 = wave0 - 0.001\n elif area77r > area77b:\n wave0 = wave0 + 0.001\n else:\n continue\n #print area77b, area77r, wave0\n if count > 1000:\n break\n\n print 'error: ', errPercent\n print 'count: ', count\n lambdaC = wave0\n print 'Central wavelength of 7.7 complex: ', lambdaC\n\n blue1 = np.where(waveFeat<=lambdaC)\n red1 = np.where(waveFeat>lambdaC)\n area77blue = simps(fluxFeat[blue1], waveFeat[blue1])\n area77red = simps(fluxFeat[red1], waveFeat[red1])\n\n print 'Total integrated flux of 7.7 complex: ', area77\n #print 'SNR77: ', SNR77\n print 'Blue flux: ', area77blue\n print 'Red flux: ', area77red\n '''\n # Plot Gaussian fit\n fig4, ax = plt.subplots() # Define figure\n\n ax.plot(waveLim77, fluxLim77, '-r', label=fnameStr, lw=2)\n ax.errorbar(\n waveLim77,\n fluxLim77,\n errLim77,\n color='r',\n ecolor='0.45',\n lw=2,\n elinewidth=1)\n ax.plot(waveLim77[feature], fit77[1], '-g', label='Spectral fit', lw=2)\n # ax.plot(waveLim2_a, StrLineFit77, 'b-', lw=2)\n # Plot straight line - comment out if no 7.2 feature\n\n # ax.plot(x77, y77, 'bo')\n # Straight line anchor points - comments out\n # if no 7.2 feature\n\n # Overplot individual Gaussian functions\n ax.plot(waveArr, Gauss76, '-g', lw=2)\n ax.fill_between(waveArr, Gauss76, facecolor='green', alpha=0.15)\n ax.plot(waveArr, Gauss79, '-g', lw=2)\n ax.fill_between(waveArr, Gauss79, facecolor='green', alpha=0.15)\n ax.plot(waveArr, Gauss82, '-g', lw=2)\n ax.fill_between(waveArr, Gauss82, facecolor='green', alpha=0.15)\n ax.plot(waveArr, Gauss86, '-g', lw=2)\n ax.fill_between(waveArr, Gauss86, facecolor='green', alpha=0.15)\n\n # ax.axvline(x=lambdaC, color='black', ls='-', lw=2)\n ax.axhline(y=0, color='b', ls='-', zorder=-10, lw=2)\n ax.legend(loc=0, fontsize='small')\n ax.grid()\n ax.minorticks_on()\n\n ax.set_title(fnameStr + ' 7.7 complex - fit')\n ax.set_xlabel(r'Wavelength ($\\mu m$)')\n ax.set_ylabel('Flux ($W$/$m^2$)')\n axes = plt.gca()\n axes.set_xlim([7.1, 9])\n # axes.set_ylim([0,2e-15])\n\n ensure_exists(output_dir)\n pdf_filename = output_dir + basename + '_aromatic_fit_2.pdf'\n print('Saved: ', pdf_filename)\n fig4.savefig(pdf_filename, format='pdf', bbox_inches='tight')\n\n plt.close()\n fig4.clear()\n\n return fit77, area77, feature\n\n waveLim77, fluxLim77, errLim77, fluxFull77 = \\\n fit_straight_line(wave, flux, fluxerr)\n\n fit77, area77, feature = fit_gaussians(\n waveLim77, fluxLim77, errLim77, fluxFull77)\n\n return waveLim77, fit77, area77, feature\n\n\ndef fit_all(basename, wave, flux, fluxerr, rms, output_dir):\n \"\"\"Fit Gaussians and straight line at the same time or something. Or maybe\n no straight line.\"\"\"\n def param_constraints_OK(p0, line, index):\n # Test if any parameter hitting min/max of constrained range.\n\n def nums_equal(num1, num2, acc=0.01):\n \"\"\"Returns True if numbers are equal within some accuracy.\"\"\"\n if np.abs(num1 - num2) < acc:\n return False\n else:\n return True\n\n # Line position.\n pindex = index * 3 + 1\n fixed_position = p0['fixed'][pindex]\n\n if not fixed_position:\n limited_min = p0['limitedmin'][pindex]\n limited_max = p0['limitedmax'][pindex]\n if limited_min:\n if not nums_equal(p0['minpars'][pindex], line['position']):\n print('Hitting minimum line position.')\n return False\n if limited_max:\n if not nums_equal(p0['maxpars'][pindex], line['position']):\n print('Hitting maximum line position.')\n return False\n\n # Line sigma.\n pindex = index * 3 + 2\n fixed_sigma = p0['fixed'][pindex]\n\n if not fixed_sigma:\n limited_min = p0['limitedmin'][pindex]\n limited_max = p0['limitedmax'][pindex]\n if limited_min:\n if not nums_equal(p0['minpars'][pindex], line['sigma']):\n print('Hitting minimum line sigma.')\n return False\n if limited_max:\n if not nums_equal(p0['maxpars'][pindex], line['sigma']):\n print('Hitting maximum line sigma.')\n return False\n\n return True\n\n def fit_4gauss_2lines(wave, flux, fluxerr, trim, trim_wide):\n\n # Multigauss fit. Intensity, center, sigma (or FWHM?).\n yscale = flux[trim]\n guess = np.nanmax(yscale)\n yfit = multigaussfit(\n wave[trim], flux[trim], ngauss=4, err=fluxerr[trim],\n params=[\n # 0.2e-14, 6.90, 0.10,\n # 0.2e-14, 7.23, 0.05,\n guess / 2., 7.68, 0.10,\n guess, 7.95, 0.06,\n guess / 2., 8.23, 0.15,\n guess / 2., 8.61, 0.08\n ],\n limitedmin=[True] * 12,\n limitedmax=[True] * 12,\n minpars=[\n # 0, 6.8, 0.04,\n # 0, 7, 0,\n 0, 7.5, 0.05,\n 0, 7.75, 0.01,\n 0, 8.1, 0.03,\n 0, 8.5, 0\n ],\n maxpars=[\n # 0.5e-13, 7, 0.2,\n # 0.1e-13, 7.25, 0.2,\n guess, 7.9, 0.25,\n guess, 8.2, 0.25,\n guess, 8.5, 0.2,\n guess, 8.7, 0.12\n ])\n\n g76 = onedgaussian(wave, 0, yfit[0][0], yfit[0][1], yfit[0][2])\n g78 = onedgaussian(wave, 0, yfit[0][3], yfit[0][4], yfit[0][5])\n g82 = onedgaussian(wave, 0, yfit[0][6], yfit[0][7], yfit[0][8])\n g86 = onedgaussian(wave, 0, yfit[0][9], yfit[0][10], yfit[0][11])\n model = g76 + g78 + g82 + g86\n\n # Multigauss fit. Intensity, center, sigma (or FWHM?).\n resid = flux - model\n yfit2 = multigaussfit(\n wave, resid, ngauss=2,\n params=[\n np.nanmax(resid) / 2., 6.88, 0.10,\n np.nanmax(resid) / 2., 7.23, 0.05,\n ],\n limitedmin=[True] * 6,\n limitedmax=[True] * 6,\n minpars=[\n 0, 6.8, 0.04,\n 0, 7, 0,\n ],\n maxpars=[\n np.nanmax(resid), 7, 0.2,\n np.nanmax(resid), 7.30, 0.2,\n ])\n\n line69 = onedgaussian(wave, 0, yfit2[0][0], yfit2[0][1], yfit2[0][2])\n line72 = onedgaussian(wave, 0, yfit2[0][3], yfit2[0][4], yfit2[0][5])\n\n wpeak = {\n '69': yfit2[0][1],\n '72': yfit2[0][4],\n }\n\n return g76, g78, g82, g86, line69, line72, model, yfit, yfit2, wpeak\n\n def fit_6gauss(wave, flux, fluxerr, trim, basename):\n\n # Initial parameters and constraints.\n yscale = flux[trim]\n guess = np.nanmax(yscale)\n p_init = params_6gauss(basename, guess)\n\n # If fluxerr[trim] has zeroes, don't use errors for now?\n if 0 in fluxerr[trim]:\n errpass = None\n else:\n errpass = fluxerr[trim]\n\n if basename in ['J052043_CWsub', 'SMPSMC006_CWsub']:\n errpass = None\n\n # Multigauss fit. Intensity, center, sigma (or FWHM?).\n yfit = multigaussfit(\n wave[trim], flux[trim], ngauss=6, err=errpass,\n params=p_init['params'],\n limitedmin=p_init['limitedmin'],\n limitedmax=p_init['limitedmax'],\n fixed=p_init['fixed'],\n minpars=p_init['minpars'],\n maxpars=p_init['maxpars']\n )\n\n # Save results.\n features = ('line69', 'line72', 'g76', 'g78', 'g82', 'g86')\n keys = ('scale_factor', 'position', 'sigma')\n keys_err = ('scale_factor_err', 'position_err', 'sigma_err')\n results = {}\n\n for i in range(6):\n fit_params = (yfit[0][3*i: 3*i+3])\n fit_params_err = (yfit[2][3*i: 3*i+3])\n\n integrated_fluxerr = compute_feature_uncertainty(\n fit_params[1], fit_params[2], wave[trim], rms\n )\n results[features[i]] = dict(zip(keys, fit_params))\n results[features[i]].update(dict(zip(keys_err, fit_params_err)))\n results[features[i]]['wave'] = wave\n results[features[i]]['spectrum'] = onedgaussian(\n wave, 0, *fit_params)\n results[features[i]]['integrated_flux'] = simps(\n results[features[i]]['spectrum'], results[features[i]]['wave'])\n results[features[i]]['integrated_fluxerr'] = integrated_fluxerr\n\n return yfit, results, p_init\n\n print(basename)\n\n fit4 = False\n\n if fit4:\n\n # Only fit 7-9 micron zone.\n trim = np.where((wave > 7.3) & (wave < 9.2))\n trim_wide = np.where((wave >= 6.0) & (wave <= 10))\n\n # Return fit.\n g76, g78, g82, g86, line69, line72, model, yfit, yfit2, wpeak = \\\n fit_4gauss_2lines(wave, flux, fluxerr, trim, trim_wide)\n\n flux69 = simps(line69, wave)\n flux72 = simps(line72, wave)\n\n # Plot results.\n fig = plt.figure()\n gs = gridspec.GridSpec(ncols=1, nrows=2, figure=fig, hspace=0.3)\n ax1 = plt.subplot(gs[0])\n ax2 = plt.subplot(gs[1])\n\n # Upper panel.\n gsum = g76 + g78 + g82\n ax1.plot(wave[trim_wide], flux[trim_wide], label='Data')\n ax1.plot(wave[trim_wide], model[trim_wide],\n label='Model (Flux: {:.2e} W/m^2)'.format(simps(gsum, wave)))\n for index, item in enumerate((g76, g78, g82, g86)):\n ax1.fill_between(\n wave[trim_wide],\n wave[trim_wide] * 0,\n item[trim_wide],\n lw=0.5,\n alpha=0.3)\n ax1.axhline(y=0, ls='--', lw=0.5, color='k')\n ax1.legend(loc=0)\n xmin, xmax = ax1.get_xlim()\n\n # Lower panel.\n trim_wide2 = np.where((wave >= 6.5) & (wave <= 10))\n ax2.plot(\n wave[trim_wide2],\n flux[trim_wide2] -\n model[trim_wide2],\n label='Residual from 4gauss')\n label69 = \\\n '6.9 ({:.2f} µm, Flux: {:.2e} W/m^2)'.format(wpeak['69'], flux69)\n label72 = \\\n '7.2 ({:.2f} µm, Flux: {:.2e} W/m^2)'.format(wpeak['72'], flux72)\n ax2.fill_between(wave, wave * 0, line69, alpha=0.3, label=label69)\n ax2.fill_between(wave, wave * 0, line72, alpha=0.3, label=label72)\n ax2.axhline(y=0, ls='--', lw=0.5, color='k')\n ax2.legend(loc=0)\n ax2.set_xlim(xmin, xmax)\n\n # Save.\n savename = output_dir + 'fullspec/' + basename + '_test.pdf'\n fig.savefig(savename, bbox_inches='tight')\n print('Saved: ', savename)\n plt.close()\n fig.clear()\n\n else:\n\n # Only fit 7-9 micron zone.\n trim = np.where((wave > 6.0) & (wave < 10))\n\n # Try 6-components.\n yfit, results, p0 = fit_6gauss(wave, flux, fluxerr, trim, basename)\n\n # # Try 6, with LMFIT!\n # yfit2, results2, p02 = fit_6gauss_lmfit(wave, flux, fluxerr, trim)\n # st()\n\n # Plot results.\n fig = plt.figure(figsize=(8, 6))\n gs = gridspec.GridSpec(ncols=1, nrows=2, figure=fig, hspace=0.3)\n ax1 = plt.subplot(gs[0])\n ax2 = plt.subplot(gs[1])\n\n ##############################\n # Upper panel.\n ##############################\n\n flux77 = sum([results[x]['integrated_flux']\n for x in ('g76', 'g78', 'g82')])\n flux77_err = sum([results[x]['integrated_fluxerr']\n for x in ('g76', 'g78', 'g82')])\n spec77 = results['g76']['spectrum'] + results['g78']['spectrum'] + \\\n results['g82']['spectrum']\n\n centroid77 = np.sum(spec77 * wave) / np.sum(spec77)\n model_label = \\\n r'Model (g1-3: {:.2f} µm, {:.2e} +- ' \\\n '{:.2e} W/m$^2$)'.format(centroid77, flux77, flux77_err)\n ax1.errorbar(wave[trim], flux[trim], yerr=fluxerr[trim], label='Data')\n # ax1.plot(wave[trim], flux[trim], label='Data')\n\n ax1.plot(wave[trim], yfit[1], label=model_label, zorder=1000)\n for index, key in enumerate(results):\n ax1.fill_between(wave[trim], wave[trim] * 0,\n results[key]['spectrum'][trim],\n lw=0.5, alpha=0.3)\n ax1.axvline(x=centroid77, color='k', ls='-', lw=0.5)\n ax1.axhline(y=0, ls='--', lw=0.5, color='k')\n ax1.axvline(x=6.9, color='k', ls='-', lw=0.5)\n ax1.axvline(x=7.25, color='k', ls='-', lw=0.5)\n ax1.legend(loc=0, fontsize=8)\n xmin, xmax = ax1.get_xlim()\n\n ##############################\n # Lower panel.\n ##############################\n\n f72_69 = results['line72']['integrated_flux'] / \\\n results['line69']['integrated_flux']\n\n label = 'Residuals (7.2/6.9 = {}' \\\n ')'.format(quant_str(f72_69, precision=\"0.01\"))\n ax2.plot(wave[trim], flux[trim] - yfit[1],\n label=label)\n ax2.axvline(x=6.9, color='k', ls='-', lw=0.5)\n ax2.axvline(x=7.25, color='k', ls='-', lw=0.5)\n\n param_OK_list = [True]\n for index, key in enumerate(results):\n line = results[key]\n label = '{:.2f} µm, {:.2e} +- {:.2e} W/m^2, FWHM={:.2f} µm'.format(\n line['position'], line['integrated_flux'],\n line['integrated_fluxerr'],\n to_fwhm(line['sigma'])\n )\n param_OK_list.append(param_constraints_OK(p0, line, index))\n ax2.fill_between(wave[trim], wave[trim] * 0,\n results[key]['spectrum'][trim],\n lw=0.5, alpha=0.3, label=label)\n ax2.axhline(y=0, ls='--', lw=0.5, color='k')\n mylegend = ax2.legend(loc=0, fontsize=8)\n\n for index, text in enumerate(mylegend.get_texts()):\n if not param_OK_list[index]:\n text.set_color(\"red\")\n\n # Save.\n savename = output_dir + 'fullspec/' + basename + '_6gauss.pdf'\n fig.savefig(savename, bbox_inches='tight')\n print('Saved: ', savename)\n plt.close()\n fig.clear()\n\n # Insert the 7.7 results.\n results['pah77'] = {\n 'flux': flux77,\n 'fluxerr': flux77_err,\n 'centroid': centroid77,\n }\n\n pkl_name = output_dir + 'numeric/' + basename + '.pkl'\n # Record results to disk.\n with open(pkl_name, 'wb') as file:\n pickle.dump(results, file, protocol=pickle.HIGHEST_PROTOCOL)\n print('Saved: ', pkl_name)\n\n txt_name = output_dir + 'numeric/' + basename + '.txt'\n with open(txt_name, 'w') as f:\n f.write('Object name, flux (W/m^2), flux error (W/m^2)\\n')\n f.write(basename + '\\n')\n f.write(str(flux77) + '\\n')\n f.write(str(flux77_err) + '\\n')\n print('Saved: ', txt_name)\n\n return (basename, flux77, flux77_err)\n\n\ndef measure_112(basename, wave, flux, fluxerr, rms, output_dir,\n fnameStr='temp_label'):\n\n lim11 = np.where((wave >= 10.8) & (wave <= 12))\n waveLim11 = wave[lim11]\n fluxLim11 = flux[lim11]\n errLim11 = fluxerr[lim11]\n\n feature11 = np.where((waveLim11 >= 11.1) & (\n waveLim11 <= 11.85)) # Define actual feature\n # Start at 11.1, change end point as needed\n\n area11 = simps(fluxLim11[feature11], waveLim11[feature11]) # Integrate\n\n # print('Integrated flux of 11.2 feature: ', area11)\n\n fig5, ax = plt.subplots() # Define figure\n\n ax.plot(waveLim11, fluxLim11, '-r', label=fnameStr, lw=2)\n ax.errorbar(\n waveLim11,\n fluxLim11,\n errLim11,\n color='r',\n ecolor='0.45',\n lw=2,\n elinewidth=1)\n ax.fill_between(\n waveLim11[feature11],\n fluxLim11[feature11],\n facecolor='red',\n alpha=0.15)\n ax.axhline(y=0, color='k', ls='-', zorder=-10, lw=2)\n\n ax.legend(loc=0, fontsize='small')\n ax.set_title(fnameStr + ' -- 11.2 feature')\n ax.set_xlabel('Wavelength (microns)')\n ax.set_ylabel('Flux (W/m^2)')\n ax.grid()\n ax.minorticks_on()\n\n ensure_exists(output_dir)\n pdf_filename = output_dir + basename + '_11.pdf'\n print('Saved: ', pdf_filename)\n fig5.savefig(pdf_filename, format='pdf', bbox_inches='tight')\n\n plt.close()\n fig5.clear()\n\n return area11\n\n\ndef save_fit_parameters(output_dir, results):\n\n ensure_exists(output_dir)\n\n fitAli, fit77, basename, waveLim, waveLim77, area69, \\\n area72, area77, area11, SNR69, SNR72, feature = results\n\n fnameStr = basename\n\n # Save all fit parameters in one file\n arrParamsID = np.append(fitAli[0] * 0, fit77[0] * 0 + 1)\n arrParams = np.append(fitAli[0], fit77[0])\n # arrParamsErr = np.append(fitAli[2], fit77[2])\n\n txt_filename = output_dir + fnameStr + '_fitParams.txt'\n print('Saved: ', txt_filename)\n np.savetxt(\n txt_filename,\n np.c_[\n arrParamsID,\n arrParams],\n delimiter=',',\n header='Gaussian fit parameters\\n col1: ID - 0=aliphatic, '\n '1=7.7 complex, col2: parameters, col3: fit error')\n # np.savetxt(fnameStr + '_fitParams.txt',\n # np.c_[arrParamsID, arrParams, arrParamsErr], delimiter=',',\n # header='Gaussian fit parameters\\n col1: ID - 0=aliphatic, 1=7.7 complex,\n # col2: parameters, col3: fit error')\n\n # Save all fit models in one file\n arrID = np.append(fitAli[1] * 0, fit77[1] * 0 + 1)\n arrWave = np.append(waveLim, waveLim77[feature])\n arrFluxDensity = np.append(fitAli[1], fit77[1])\n\n txt_filename = output_dir + fnameStr + '_fitModel.txt'\n print('Saved: ', txt_filename)\n np.savetxt(\n txt_filename,\n np.c_[\n arrID,\n arrWave,\n arrFluxDensity],\n delimiter=',',\n header='Full model fit\\n col1: ID - 0=aliphatic, 1=7.7 complex, '\n 'col2: wavelength, col3: flux density')\n\n # arrIntegratedFluxes = np.array([area69, area72, area77, area77blue,\n # area77red, area11, lambdaC]) # Save all integrated fluxes in one file\n # Save all integrated fluxes in one file\n # arrIntegratedFluxes = np.array([area69, area72, area77, area11])\n\n txt_filename = output_dir + fnameStr + '_intFlux.txt'\n print('Saved: ', txt_filename)\n np.savetxt(\n txt_filename,\n np.c_[\n area69,\n area72,\n area77,\n area11],\n delimiter=',',\n header='Integrated fluxes of features\\n col1: 6.9 microns, '\n 'col2: 7.2 microns, col3: total 7.7 complex, col4: blue 7.7, '\n 'col5: red 7.7, col6: 11.2 feature, '\n 'col7: central wavelength of 7.7 (microns)')\n\n txt_filename = output_dir + fnameStr + '_SNR.txt'\n print('Saved: ', txt_filename)\n np.savetxt(\n txt_filename,\n np.c_[\n SNR69,\n SNR72],\n delimiter=',',\n header='col1:SNR69, col2: SNR72, col3: SNR77')\n\n txt_filename = output_dir + fnameStr + 'Full.txt'\n workFile = open(txt_filename, 'w') # Write all data into single file\n workFile.write(fnameStr + 'Fitting and integrated flux data\\n\\n')\n\n workFile.write('Section 1: Aliphatic features\\n')\n workFile.write(\n 'Gaussian fitting parameters for 6.9 and 7.2 micron features\\n')\n workFile.write(str(fitAli[0]) + '\\n')\n workFile.write('Errors on aliphatic fitting parameters\\n')\n workFile.write(str(fitAli[2]) + '\\n')\n workFile.write('Fit model - aliphatic features\\n')\n workFile.write(str(waveLim) + '\\n' + str(fitAli[1]) + '\\n\\n')\n workFile.write('Integrated fluxes of aliphatic features\\n')\n workFile.write('6.9 micron feature ' + str(area69) + '\\n')\n workFile.write('7.2 micron feature ' + str(area72) + '\\n')\n workFile.write('S/N of 6.9: ' + str(SNR69) + '\\n')\n workFile.write('S/N of 7.2: ' + str(SNR72) + '\\n\\n')\n\n workFile.write('Section 2: 7.7 micron complex\\n')\n workFile.write('Gaussian fitting parameters for 7.7 micron complex\\n')\n workFile.write(str(fit77[0]) + '\\n')\n workFile.write('Errors on fitting parameters\\n')\n workFile.write(str(fit77[2]) + '\\n')\n workFile.write('Fit model - 7.7 micron complex\\n')\n workFile.write(str(waveLim77[feature]) + '\\n' + str(fit77[1]) + '\\n')\n workFile.write('Integrated fluxes\\n')\n workFile.write('Total integrated flux of complex: ' + str(area77) + '\\n')\n # workFile.write('Blue flux: ' + str(area77blue) + '\\n')\n # workFile.write('Red flux: ' + str(area77red) + '\\n')\n # workFile.write('SNR77: ' + str(SNR77) + '\\n')\n # workFile.write('Central wavelength of 7.7 complex:' + str(lambdaC) +\n # '\\n\\n')\n\n workFile.write('Section 3: 11.2 micron feature\\n')\n workFile.write('Integrated flux of 11.2 micron feature:\\n')\n workFile.write(str(area11) + '\\n')\n\n workFile.close()\n print('Saved: ', txt_filename)\n\n return\n" ]
[ [ "numpy.ones", "numpy.sum", "numpy.savetxt", "numpy.polyfit", "numpy.append", "matplotlib.pyplot.figure", "matplotlib.pyplot.gca", "numpy.abs", "numpy.where", "matplotlib.gridspec.GridSpec", "numpy.mean", "numpy.sqrt", "matplotlib.pyplot.subplots", "numpy.arange", "numpy.nanargmin", "matplotlib.pyplot.close", "numpy.nanmax", "scipy.integrate.simps", "numpy.exp", "numpy.nanmin", "matplotlib.pyplot.subplot", "numpy.array" ] ]
entslscheia/allennlp
[ "eeba62e34c8e211ed5963f830528c957f178607b" ]
[ "allennlp/data/fields/knowledge_graph_field.py" ]
[ "\"\"\"\n``KnowledgeGraphField`` is a ``Field`` which stores a knowledge graph representation.\n\"\"\"\nfrom typing import Callable, Dict, List, Set\nfrom collections import defaultdict\n\nimport editdistance\nfrom overrides import overrides\nimport torch\n\nfrom allennlp.common import util\nfrom allennlp.common.checks import ConfigurationError\nfrom allennlp.data.fields.field import Field\nfrom allennlp.data.token_indexers.token_indexer import TokenIndexer, TokenType\nfrom allennlp.data.tokenizers.word_splitter import SpacyWordSplitter\nfrom allennlp.data.tokenizers.token import Token\nfrom allennlp.data.tokenizers import Tokenizer, WordTokenizer\nfrom allennlp.data.vocabulary import Vocabulary\nfrom allennlp.nn import util as nn_util\nfrom allennlp.semparse.contexts.knowledge_graph import KnowledgeGraph\n\nTokenList = List[TokenType]\n\n\nclass KnowledgeGraphField(Field[Dict[str, torch.Tensor]]):\n \"\"\"\n A ``KnowledgeGraphField`` represents a ``KnowledgeGraph`` as a ``Field`` that can be used in a\n ``Model``. For each entity in the graph, we output two things: a text representation of the\n entity, handled identically to a ``TextField``, and a list of linking features for each token\n in some input utterance.\n\n The output of this field is a dictionary::\n\n {\n \"text\": Dict[str, torch.Tensor], # each tensor has shape (batch_size, num_entities, num_entity_tokens)\n \"linking\": torch.Tensor # shape (batch_size, num_entities, num_utterance_tokens, num_features)\n }\n\n The ``text`` component of this dictionary is suitable to be passed into a\n ``TextFieldEmbedder`` (which handles the additional ``num_entities`` dimension without any\n issues). The ``linking`` component of the dictionary can be used however you want to decide\n which tokens in the utterance correspond to which entities in the knowledge graph.\n\n In order to create the ``text`` component, we use the same dictionary of ``TokenIndexers``\n that's used in a ``TextField`` (as we're just representing the text corresponding to each\n entity). For the ``linking`` component, we use a set of hard-coded feature extractors that\n operate between the text corresponding to each entity and each token in the utterance.\n\n Parameters\n ----------\n knowledge_graph : ``KnowledgeGraph``\n The knowledge graph that this field stores.\n utterance_tokens : ``List[Token]``\n The tokens in some utterance that is paired with the ``KnowledgeGraph``. We compute a set\n of features for linking tokens in the utterance to entities in the graph.\n tokenizer : ``Tokenizer``, optional (default=``WordTokenizer()``)\n We'll use this ``Tokenizer`` to tokenize the text representation of each entity.\n token_indexers : ``Dict[str, TokenIndexer]``\n Token indexers that convert entities into arrays, similar to how text tokens are treated in\n a ``TextField``. These might operate on the name of the entity itself, its type, its\n neighbors in the graph, etc.\n feature_extractors : ``List[str]``, optional\n Names of feature extractors to use for computing linking features. These must be\n attributes of this object, without the first underscore. The feature extraction functions\n are listed as the last methods in this class. For example, to use\n :func:`_exact_token_match`, you would pass the string ``exact_token_match``. We will add\n an underscore and look for a function matching that name. If this list is omitted, we will\n use all available feature functions.\n entity_tokens : ``List[List[Token]]``, optional\n If you have pre-computed the tokenization of the table text, you can pass it in here. The\n must be a list of the tokens in the entity text, for each entity in the knowledge graph, in\n the same order in which the knowledge graph returns entities.\n linking_features : ``List[List[List[float]]]``, optional\n If you have pre-computed the linking features between the utterance and the table text, you\n can pass it in here.\n include_in_vocab : ``bool``, optional (default=True)\n If this is ``False``, we will skip the ``count_vocab_items`` logic, leaving out all table\n entity text from the vocabulary computation. You might want to do this if you have a lot\n of rare entities in your tables, and you see the same table in multiple training instances,\n so your vocabulary counts get skewed and include too many rare entities.\n max_table_tokens : ``int``, optional\n If given, we will only keep this number of total table tokens. This bounds the memory\n usage of the table representations, truncating cells with really long text. We specify a\n total number of tokens, not a max cell text length, because the number of table entities\n varies.\n \"\"\"\n\n def __init__(\n self,\n knowledge_graph: KnowledgeGraph,\n utterance_tokens: List[Token],\n token_indexers: Dict[str, TokenIndexer],\n tokenizer: Tokenizer = None,\n feature_extractors: List[str] = None,\n entity_tokens: List[List[Token]] = None,\n linking_features: List[List[List[float]]] = None,\n include_in_vocab: bool = True,\n max_table_tokens: int = None,\n ) -> None:\n\n self.knowledge_graph = knowledge_graph\n self._tokenizer = tokenizer or WordTokenizer(word_splitter=SpacyWordSplitter(pos_tags=True))\n if not entity_tokens:\n entity_texts = [\n knowledge_graph.entity_text[entity].lower() for entity in knowledge_graph.entities\n ]\n # TODO(mattg): Because we do tagging on each of these entities in addition to just\n # tokenizations, this is quite slow, and about half of our data processing time just\n # goes to this (~15 minutes when there are 7k instances). The reason we do tagging is\n # so that we can add lemma features. If we can remove the need for lemma / other\n # hand-written features, like with a CNN, we can cut down our data processing time by a\n # factor of 2.\n self.entity_texts = self._tokenizer.batch_tokenize(entity_texts)\n else:\n self.entity_texts = entity_tokens\n self.utterance_tokens = utterance_tokens\n self._token_indexers: Dict[str, TokenIndexer] = token_indexers\n self._include_in_vocab = include_in_vocab\n self._indexed_entity_texts: Dict[str, TokenList] = None\n self._max_table_tokens = max_table_tokens\n\n feature_extractors = (\n feature_extractors\n if feature_extractors is not None\n else [\n \"number_token_match\",\n \"exact_token_match\",\n \"contains_exact_token_match\",\n \"lemma_match\",\n \"contains_lemma_match\",\n \"edit_distance\",\n \"related_column\",\n \"related_column_lemma\",\n \"span_overlap_fraction\",\n \"span_lemma_overlap_fraction\",\n ]\n )\n self._feature_extractors: List[\n Callable[[str, List[Token], Token, int, List[Token]], float]\n ] = []\n for feature_extractor_name in feature_extractors:\n extractor = getattr(self, \"_\" + feature_extractor_name, None)\n if not extractor:\n raise ConfigurationError(\n f\"Invalid feature extractor name: {feature_extractor_name}\"\n )\n self._feature_extractors.append(extractor)\n\n if not linking_features:\n # For quicker lookups in our feature functions, we'll additionally store some\n # dictionaries that map entity strings to useful information about the entity.\n self._entity_text_map: Dict[str, List[Token]] = {}\n for entity, entity_text in zip(knowledge_graph.entities, self.entity_texts):\n self._entity_text_map[entity] = entity_text\n\n self._entity_text_exact_text: Dict[str, Set[str]] = {}\n for entity, entity_text in zip(knowledge_graph.entities, self.entity_texts):\n self._entity_text_exact_text[entity] = set(e.text for e in entity_text)\n\n self._entity_text_lemmas: Dict[str, Set[str]] = {}\n for entity, entity_text in zip(knowledge_graph.entities, self.entity_texts):\n self._entity_text_lemmas[entity] = set(e.lemma_ for e in entity_text)\n self.linking_features = self._compute_linking_features()\n else:\n self.linking_features = linking_features\n\n @overrides\n def count_vocab_items(self, counter: Dict[str, Dict[str, int]]):\n if self._include_in_vocab:\n for indexer in self._token_indexers.values():\n for entity_text in self.entity_texts:\n for token in entity_text:\n indexer.count_vocab_items(token, counter)\n\n @overrides\n def index(self, vocab: Vocabulary):\n self._indexed_entity_texts = {}\n for indexer_name, indexer in self._token_indexers.items():\n indexer_arrays: Dict[str, List] = defaultdict(list)\n\n for entity_text in self.entity_texts:\n for index_name, indexed in indexer.tokens_to_indices(\n entity_text, vocab, indexer_name\n ).items():\n indexer_arrays[index_name].append(indexed)\n\n self._indexed_entity_texts.update(indexer_arrays)\n\n @overrides\n def get_padding_lengths(self) -> Dict[str, int]:\n num_entities = len(self.entity_texts)\n num_entity_tokens = max(len(entity_text) for entity_text in self.entity_texts)\n\n if self._max_table_tokens:\n # This truncates the number of entity tokens used, enabling larger tables (either in\n # the number of entities in the table, or the number of tokens per entity) to fit in\n # memory, particularly when using ELMo.\n if num_entities * num_entity_tokens > self._max_table_tokens:\n num_entity_tokens = int(self._max_table_tokens / num_entities)\n\n padding_lengths = {\n \"num_entities\": num_entities,\n \"num_utterance_tokens\": len(self.utterance_tokens),\n }\n padding_lengths[\"num_entity_tokens\"] = num_entity_tokens\n lengths = []\n assert self._indexed_entity_texts is not None, (\n \"This field is not indexed yet. Call \"\n \".index(vocab) before determining padding \"\n \"lengths.\"\n )\n for indexer_name, indexer in self._token_indexers.items():\n indexer_lengths = {}\n\n # This is a list of dicts, one for each token in the field.\n entity_lengths = [\n indexer.get_padding_lengths(token)\n for entity_text in self._indexed_entity_texts[indexer_name]\n for token in entity_text\n ]\n # Iterate over the keys in the first element of the list. This is fine as for a given\n # indexer, all entities will return the same keys, so we can just use the first one.\n for key in entity_lengths[0].keys():\n indexer_lengths[key] = max(x.get(key, 0) for x in entity_lengths)\n lengths.append(indexer_lengths)\n\n # Get all the keys which have been used for padding.\n padding_keys = {key for d in lengths for key in d.keys()}\n for padding_key in padding_keys:\n padding_lengths[padding_key] = max(x.get(padding_key, 0) for x in lengths)\n return padding_lengths\n\n @overrides\n def as_tensor(self, padding_lengths: Dict[str, int]) -> Dict[str, torch.Tensor]:\n tensors = {}\n desired_num_entities = padding_lengths[\"num_entities\"]\n desired_num_entity_tokens = padding_lengths[\"num_entity_tokens\"]\n desired_num_utterance_tokens = padding_lengths[\"num_utterance_tokens\"]\n for indexer_name, indexer in self._token_indexers.items():\n padded_entities = util.pad_sequence_to_length(\n self._indexed_entity_texts[indexer_name],\n desired_num_entities,\n default_value=lambda: [],\n )\n padded_tensors = []\n for padded_entity in padded_entities:\n padded_tensor = indexer.as_padded_tensor(\n {\"key\": padded_entity}, {\"key\": desired_num_entity_tokens}, padding_lengths\n )[\"key\"]\n padded_tensors.append(padded_tensor)\n tensor = torch.stack(padded_tensors)\n tensors[indexer_name] = tensor\n padded_linking_features = util.pad_sequence_to_length(\n self.linking_features, desired_num_entities, default_value=lambda: []\n )\n padded_linking_arrays = []\n\n def default_feature_value():\n return [0.0] * len(self._feature_extractors)\n\n for linking_features in padded_linking_features:\n padded_features = util.pad_sequence_to_length(\n linking_features, desired_num_utterance_tokens, default_value=default_feature_value\n )\n padded_linking_arrays.append(padded_features)\n linking_features_tensor = torch.FloatTensor(padded_linking_arrays)\n return {\"text\": tensors, \"linking\": linking_features_tensor}\n\n def _compute_linking_features(self) -> List[List[List[float]]]:\n linking_features = []\n for entity, entity_text in zip(self.knowledge_graph.entities, self.entity_texts):\n entity_features = []\n for token_index, token in enumerate(self.utterance_tokens):\n token_features = []\n for feature_extractor in self._feature_extractors:\n token_features.append(\n feature_extractor(\n entity, entity_text, token, token_index, self.utterance_tokens\n )\n )\n entity_features.append(token_features)\n linking_features.append(entity_features)\n return linking_features\n\n @overrides\n def empty_field(self) -> \"KnowledgeGraphField\":\n return KnowledgeGraphField(KnowledgeGraph(set(), {}), [], self._token_indexers)\n\n @overrides\n def batch_tensors(self, tensor_list: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]:\n\n batched_text = nn_util.batch_tensor_dicts(\n tensor[\"text\"] for tensor in tensor_list # type: ignore\n )\n batched_linking = torch.stack([tensor[\"linking\"] for tensor in tensor_list])\n return {\"text\": batched_text, \"linking\": batched_linking}\n\n # Below here we have feature extractor functions. To keep a consistent API for easy logic\n # above, some of these functions have unused arguments.\n\n # These feature extractors are generally pretty specific to the logical form language and\n # problem setting in WikiTableQuestions. This whole notion of feature extraction should\n # eventually be made more general (or just removed, if we can replace it with CNN features...).\n # For the feature functions used in the original parser written in PNP, see here:\n # https://github.com/allenai/pnp/blob/wikitables2/src/main/scala/org/allenai/wikitables/SemanticParserFeatureGenerator.scala\n\n # One notable difference between how the features work here and how they worked in PNP is that\n # we're using the table text when computing string matches, while PNP used the _entity name_.\n # It turns out that the entity name is derived from the table text, so this should be roughly\n # equivalent, except in the case of some numbers. If there are cells with different text that\n # normalize to the same name, you could get `_2` or similar appended to the name, so the way we\n # do it here should just be better. But it's a possible minor source of variation from the\n # original parser.\n\n # Another difference between these features and the PNP features is that the span overlap used\n # a weighting scheme to downweight matches on frequent words (like \"the\"), and the lemma\n # overlap feature value was calculated a little differently. I'm guessing that doesn't make a\n # huge difference...\n\n def _number_token_match(\n self,\n entity: str,\n entity_text: List[Token],\n token: Token,\n token_index: int,\n tokens: List[Token],\n ) -> float:\n # PNP had a \"spanFeatures\" function that said whether an entity was a-priori known to link\n # to a token or set of tokens in the question. This was only used for numbers, and it's\n # not totally clear to me how this number feature overlapped with the token match features\n # in the original implementation (I think in most cases it was the same, except for things\n # like \"four million\", because the token match is derived from the entity name, which would\n # be 4000000, and wouldn't match \"four million\").\n #\n # Our implementation basically just adds a duplicate token match feature that's specific to\n # numbers. It'll break in some rare cases (e.g., \"Which four had four million ...\"), but\n # those shouldn't be a big deal.\n if \":\" in entity:\n # This check works because numbers are the only entities that don't contain \":\". All\n # others in both WikiTables languages do (e.g.: fb:row.row.column_name,\n # date_column:year, string:usl_a_league etc.).\n return 0.0\n return self._contains_exact_token_match(entity, entity_text, token, token_index, tokens)\n\n def _exact_token_match(\n self,\n entity: str,\n entity_text: List[Token],\n token: Token,\n token_index: int,\n tokens: List[Token],\n ) -> float:\n if len(entity_text) != 1:\n return 0.0\n return self._contains_exact_token_match(entity, entity_text, token, token_index, tokens)\n\n def _contains_exact_token_match(\n self,\n entity: str,\n entity_text: List[Token],\n token: Token,\n token_index: int,\n tokens: List[Token],\n ) -> float:\n if token.text in self._entity_text_exact_text[entity]:\n return 1.0\n return 0.0\n\n def _lemma_match(\n self,\n entity: str,\n entity_text: List[Token],\n token: Token,\n token_index: int,\n tokens: List[Token],\n ) -> float:\n if len(entity_text) != 1:\n return 0.0\n return self._contains_lemma_match(entity, entity_text, token, token_index, tokens)\n\n def _contains_lemma_match(\n self,\n entity: str,\n entity_text: List[Token],\n token: Token,\n token_index: int,\n tokens: List[Token],\n ) -> float:\n if token.text in self._entity_text_exact_text[entity]:\n return 1.0\n if token.lemma_ in self._entity_text_lemmas[entity]:\n return 1.0\n return 0.0\n\n def _edit_distance(\n self,\n entity: str,\n entity_text: List[Token],\n token: Token,\n token_index: int,\n tokens: List[Token],\n ) -> float:\n edit_distance = float(editdistance.eval(\" \".join(e.text for e in entity_text), token.text))\n return 1.0 - edit_distance / len(token.text)\n\n def _related_column(\n self,\n entity: str,\n entity_text: List[Token],\n token: Token,\n token_index: int,\n tokens: List[Token],\n ) -> float:\n # Check if the entity is a column name in one of the two WikiTables languages.\n if not entity.startswith(\"fb:row.row\") and \"_column:\" not in entity:\n return 0.0\n for neighbor in self.knowledge_graph.neighbors[entity]:\n if token.text in self._entity_text_exact_text[neighbor]:\n return 1.0\n return 0.0\n\n def _related_column_lemma(\n self,\n entity: str,\n entity_text: List[Token],\n token: Token,\n token_index: int,\n tokens: List[Token],\n ) -> float:\n # Check if the entity is a column name in one of the two WikiTables languages.\n if not entity.startswith(\"fb:row.row\") and \"_column:\" not in entity:\n return 0.0\n for neighbor in self.knowledge_graph.neighbors[entity]:\n if token.text in self._entity_text_exact_text[neighbor]:\n return 1.0\n if token.lemma_ in self._entity_text_lemmas[neighbor]:\n return 1.0\n return 0.0\n\n def _span_overlap_fraction(\n self,\n entity: str,\n entity_text: List[Token],\n token: Token,\n token_index: int,\n tokens: List[Token],\n ) -> float:\n entity_words = set(entity_token.text for entity_token in entity_text)\n if not entity_words:\n # Some tables have empty cells.\n return 0\n seen_entity_words = set()\n token_index_left = token_index\n while token_index < len(tokens) and tokens[token_index].text in entity_words:\n seen_entity_words.add(tokens[token_index].text)\n token_index += 1\n while token_index_left >= 0 and tokens[token_index_left].text in entity_words:\n seen_entity_words.add(tokens[token_index_left].text)\n token_index_left -= 1\n return len(seen_entity_words) / len(entity_words)\n\n def _span_lemma_overlap_fraction(\n self,\n entity: str,\n entity_text: List[Token],\n token: Token,\n token_index: int,\n tokens: List[Token],\n ) -> float:\n entity_lemmas = set(entity_token.lemma_ for entity_token in entity_text)\n if not entity_lemmas:\n # Some tables have empty cells.\n return 0\n seen_entity_lemmas = set()\n token_index_left = token_index\n while token_index < len(tokens) and tokens[token_index].lemma_ in entity_lemmas:\n seen_entity_lemmas.add(tokens[token_index].lemma_)\n token_index += 1\n while token_index_left >= 0 and tokens[token_index_left].lemma_ in entity_lemmas:\n seen_entity_lemmas.add(tokens[token_index_left].lemma_)\n token_index_left -= 1\n return len(seen_entity_lemmas) / len(entity_lemmas)\n" ]
[ [ "torch.FloatTensor", "torch.stack" ] ]
vishalbelsare/py-bbn
[ "fe6848b4e0fe78d78af13cd06c0d29980ecd5d7f" ]
[ "pybbn/graph/factory.py" ]
[ "import itertools\nimport json\nfrom itertools import product\n\nimport networkx as nx\nimport pandas as pd\nfrom networkx.algorithms.dag import topological_sort\n\nfrom pybbn.graph.dag import Bbn\nfrom pybbn.graph.edge import Edge, EdgeType\nfrom pybbn.graph.node import BbnNode\nfrom pybbn.graph.variable import Variable\n\n\nclass Factory(object):\n \"\"\"\n Factory to convert other API BBNs into py-bbn.\n \"\"\"\n\n @staticmethod\n def from_libpgm_discrete_json(j):\n \"\"\"\n Converts a libpgm discrete network as specified by a JSON string into a py-bbn one.\n Look at https://pythonhosted.org/libpgm/unittestdict.html.\n\n :param j: String representing JSON.\n :return: py-bbn BBN.\n \"\"\"\n return Factory.from_libpgm_discrete_dictionary(json.loads(j))\n\n @staticmethod\n def from_libpgm_discrete_dictionary(d):\n \"\"\"\n Converts a libpgm discrete network as specified by a dictionary into a py-bbn one.\n Look at https://pythonhosted.org/libpgm/unittestdict.html.\n\n :param d: A dictionary representing a libpgm discrete network.\n :return: py-bbn BBN.\n \"\"\"\n\n class LibpgmBBN(object):\n def __init__(self, V, E, Vdata):\n self.V = V\n self.E = E\n self.Vdata = Vdata\n\n bn = LibpgmBBN(d['V'], d['E'], d['Vdata'])\n return Factory.from_libpgm_discrete_object(bn)\n\n @staticmethod\n def from_libpgm_discrete_object(bn):\n \"\"\"\n Converts a libpgm discrete network object into a py-bbn one.\n\n :param bn: libpgm discrete BBN.\n :return: py-bbn BBN.\n \"\"\"\n\n def get_nodes(bn, domain_spaces=True):\n def get_parent_domains(name, bn):\n parents = bn.Vdata[name]['parents']\n domains = []\n\n if parents is None or len(parents) == 0:\n return domains\n\n for parent in parents:\n domain = bn.Vdata[parent]['vals'][:]\n domains.append(domain)\n return domains\n\n def cross_product(domains):\n products = []\n\n if domains is None or len(domains) == 0:\n return products\n\n for e in itertools.product(*domains):\n products.append(e)\n return products\n\n def stringify_cross_product(pa_domains, domain_spaces=True):\n joiner_delim = ', ' if domain_spaces is True else ','\n s = []\n for pa_domain in pa_domains:\n r = joiner_delim.join([\"'{}'\".format(v) for v in pa_domain])\n r = '[{}]'.format(r)\n s.append(r)\n return s\n\n def get_cond_probs(name, bn, domain_spaces=True):\n probs = []\n pa_domains = stringify_cross_product(cross_product(get_parent_domains(name, bn)), domain_spaces)\n if len(pa_domains) == 0:\n probs = bn.Vdata[name]['cprob'][:]\n else:\n for pa_domain in pa_domains:\n cprob = bn.Vdata[name]['cprob'][pa_domain]\n probs.extend(cprob)\n\n return probs\n\n nodes = {}\n for name in bn.V:\n domain = bn.Vdata[name]['vals'][:]\n order = bn.Vdata[name]['ord']\n probs = get_cond_probs(name, bn, domain_spaces)\n node = BbnNode(Variable(order, name, domain), probs)\n nodes[name] = node\n return nodes\n\n def get_edges(bn, nodes):\n edges = []\n for k, v in bn.Vdata.items():\n ch = nodes[k]\n if v['parents'] is not None and len(v['parents']) > 0:\n parents = [nodes[pa] for pa in v['parents']]\n for pa in parents:\n edge = Edge(pa, ch, EdgeType.DIRECTED)\n edges.append(edge)\n return edges\n\n nodes = get_nodes(bn)\n edges = get_edges(bn, nodes)\n\n bbn = Bbn()\n\n for node in sorted(nodes.values(), key=lambda n: n.id):\n bbn.add_node(node)\n\n for e in edges:\n bbn.add_edge(e)\n\n return bbn\n\n @staticmethod\n def from_data(structure, df):\n \"\"\"\n Creates a BBN.\n\n :param structure: A dictionary where keys are names of children and values are list of parent names.\n :param df: A dataframe.\n :return: BBN.\n \"\"\"\n\n def get_profile(df):\n profile = {}\n for c in df.columns:\n values = sorted(list(df[c].value_counts().index))\n profile[c] = values\n return profile\n\n def get_n2i(parents):\n g = nx.DiGraph()\n for k in parents:\n g.add_node(k)\n for ch, pas in parents.items():\n for pa in pas:\n g.add_edge(pa, ch)\n nodes = list(topological_sort(g))\n return {n: i for i, n in enumerate(nodes)}\n\n def get_cpt(name, parents, n2v, df):\n parents = sorted(parents)\n n2v = {k: sorted(v) for k, v in n2v.items()}\n\n n = df.shape[0]\n\n cpts = []\n if len(parents) == 0:\n for v in n2v[name]:\n c = df[df[name] == v].shape[0]\n p = c / n\n cpts.append(p)\n else:\n domains = [(n, d) for n, d in n2v.items() if n in parents]\n domains = sorted(domains, key=lambda tup: tup[0])\n domain_names = [tup[0] for tup in domains]\n domain_values = [tup[1] for tup in domains]\n domains = list(product(*domain_values))\n\n for values in domains:\n probs = []\n denom_q = ' and '.join([f'{n}==\"{v}\"' for n, v in zip(domain_names, values)])\n for v in n2v[name]:\n numer_q = f'{name}==\"{v}\" and {denom_q}'\n\n numer = df.query(numer_q).shape[0] / n\n denom = df.query(denom_q).shape[0] / n\n prob = numer / denom\n probs.append(prob)\n probs = pd.Series(probs)\n probs = probs / probs.sum()\n probs = list(probs)\n cpts.extend(probs)\n\n return cpts\n\n n2v = get_profile(df)\n n2i = get_n2i(df)\n n2c = {n: get_cpt(n, structure[n], n2v, df) for n in structure}\n\n bbn = Bbn()\n\n nodes = {}\n for name in n2v:\n idx = n2i[name]\n values = n2v[name]\n cpts = n2c[name]\n\n v = Variable(idx, name, values)\n node = BbnNode(v, cpts)\n nodes[name] = node\n bbn.add_node(node)\n\n for ch, parents in structure.items():\n ch_node = nodes[ch]\n for pa in parents:\n pa_node = nodes[pa]\n\n edge = Edge(pa_node, ch_node, EdgeType.DIRECTED)\n bbn.add_edge(edge)\n\n return bbn\n" ]
[ [ "pandas.Series" ] ]
harrisonfeng/ray
[ "7b08db9f8cd85d185879e5bef778e8855f2a06cf" ]
[ "rllib/evaluation/sampler.py" ]
[ "from collections import defaultdict, namedtuple\nimport logging\nimport numpy as np\nimport queue\nimport threading\nimport time\n\nfrom ray.util.debug import log_once\nfrom ray.rllib.evaluation.episode import MultiAgentEpisode, _flatten_action\nfrom ray.rllib.evaluation.rollout_metrics import RolloutMetrics\nfrom ray.rllib.evaluation.sample_batch_builder import \\\n MultiAgentSampleBatchBuilder\nfrom ray.rllib.policy.policy import clip_action\nfrom ray.rllib.policy.tf_policy import TFPolicy\nfrom ray.rllib.env.base_env import BaseEnv, ASYNC_RESET_RETURN\nfrom ray.rllib.env.atari_wrappers import get_wrapper_by_cls, MonitorEnv\nfrom ray.rllib.offline import InputReader\nfrom ray.rllib.utils.annotations import override\nfrom ray.rllib.utils.debug import summarize\nfrom ray.rllib.utils.tuple_actions import TupleActions\nfrom ray.rllib.utils.tf_run_builder import TFRunBuilder\n\nlogger = logging.getLogger(__name__)\n\nPolicyEvalData = namedtuple(\"PolicyEvalData\", [\n \"env_id\", \"agent_id\", \"obs\", \"info\", \"rnn_state\", \"prev_action\",\n \"prev_reward\"\n])\n\n\nclass PerfStats:\n \"\"\"Sampler perf stats that will be included in rollout metrics.\"\"\"\n\n def __init__(self):\n self.iters = 0\n self.env_wait_time = 0.0\n self.processing_time = 0.0\n self.inference_time = 0.0\n\n def get(self):\n return {\n \"mean_env_wait_ms\": self.env_wait_time * 1000 / self.iters,\n \"mean_processing_ms\": self.processing_time * 1000 / self.iters,\n \"mean_inference_ms\": self.inference_time * 1000 / self.iters\n }\n\n\nclass SamplerInput(InputReader):\n \"\"\"Reads input experiences from an existing sampler.\"\"\"\n\n @override(InputReader)\n def next(self):\n batches = [self.get_data()]\n batches.extend(self.get_extra_batches())\n if len(batches) > 1:\n return batches[0].concat_samples(batches)\n else:\n return batches[0]\n\n\nclass SyncSampler(SamplerInput):\n def __init__(self,\n env,\n policies,\n policy_mapping_fn,\n preprocessors,\n obs_filters,\n clip_rewards,\n rollout_fragment_length,\n callbacks,\n horizon=None,\n pack=False,\n tf_sess=None,\n clip_actions=True,\n soft_horizon=False,\n no_done_at_end=False):\n self.base_env = BaseEnv.to_base_env(env)\n self.rollout_fragment_length = rollout_fragment_length\n self.horizon = horizon\n self.policies = policies\n self.policy_mapping_fn = policy_mapping_fn\n self.preprocessors = preprocessors\n self.obs_filters = obs_filters\n self.extra_batches = queue.Queue()\n self.perf_stats = PerfStats()\n self.rollout_provider = _env_runner(\n self.base_env, self.extra_batches.put, self.policies,\n self.policy_mapping_fn, self.rollout_fragment_length, self.horizon,\n self.preprocessors, self.obs_filters, clip_rewards, clip_actions,\n pack, callbacks, tf_sess, self.perf_stats, soft_horizon,\n no_done_at_end)\n self.metrics_queue = queue.Queue()\n\n def get_data(self):\n while True:\n item = next(self.rollout_provider)\n if isinstance(item, RolloutMetrics):\n self.metrics_queue.put(item)\n else:\n return item\n\n def get_metrics(self):\n completed = []\n while True:\n try:\n completed.append(self.metrics_queue.get_nowait()._replace(\n perf_stats=self.perf_stats.get()))\n except queue.Empty:\n break\n return completed\n\n def get_extra_batches(self):\n extra = []\n while True:\n try:\n extra.append(self.extra_batches.get_nowait())\n except queue.Empty:\n break\n return extra\n\n\nclass AsyncSampler(threading.Thread, SamplerInput):\n def __init__(self,\n env,\n policies,\n policy_mapping_fn,\n preprocessors,\n obs_filters,\n clip_rewards,\n rollout_fragment_length,\n callbacks,\n horizon=None,\n pack=False,\n tf_sess=None,\n clip_actions=True,\n blackhole_outputs=False,\n soft_horizon=False,\n no_done_at_end=False):\n for _, f in obs_filters.items():\n assert getattr(f, \"is_concurrent\", False), \\\n \"Observation Filter must support concurrent updates.\"\n self.base_env = BaseEnv.to_base_env(env)\n threading.Thread.__init__(self)\n self.queue = queue.Queue(5)\n self.extra_batches = queue.Queue()\n self.metrics_queue = queue.Queue()\n self.rollout_fragment_length = rollout_fragment_length\n self.horizon = horizon\n self.policies = policies\n self.policy_mapping_fn = policy_mapping_fn\n self.preprocessors = preprocessors\n self.obs_filters = obs_filters\n self.clip_rewards = clip_rewards\n self.daemon = True\n self.pack = pack\n self.tf_sess = tf_sess\n self.callbacks = callbacks\n self.clip_actions = clip_actions\n self.blackhole_outputs = blackhole_outputs\n self.soft_horizon = soft_horizon\n self.no_done_at_end = no_done_at_end\n self.perf_stats = PerfStats()\n self.shutdown = False\n\n def run(self):\n try:\n self._run()\n except BaseException as e:\n self.queue.put(e)\n raise e\n\n def _run(self):\n if self.blackhole_outputs:\n queue_putter = (lambda x: None)\n extra_batches_putter = (lambda x: None)\n else:\n queue_putter = self.queue.put\n extra_batches_putter = (\n lambda x: self.extra_batches.put(x, timeout=600.0))\n rollout_provider = _env_runner(\n self.base_env, extra_batches_putter, self.policies,\n self.policy_mapping_fn, self.rollout_fragment_length, self.horizon,\n self.preprocessors, self.obs_filters, self.clip_rewards,\n self.clip_actions, self.pack, self.callbacks, self.tf_sess,\n self.perf_stats, self.soft_horizon, self.no_done_at_end)\n while not self.shutdown:\n # The timeout variable exists because apparently, if one worker\n # dies, the other workers won't die with it, unless the timeout is\n # set to some large number. This is an empirical observation.\n item = next(rollout_provider)\n if isinstance(item, RolloutMetrics):\n self.metrics_queue.put(item)\n else:\n queue_putter(item)\n\n def get_data(self):\n if not self.is_alive():\n raise RuntimeError(\"Sampling thread has died\")\n rollout = self.queue.get(timeout=600.0)\n\n # Propagate errors\n if isinstance(rollout, BaseException):\n raise rollout\n\n return rollout\n\n def get_metrics(self):\n completed = []\n while True:\n try:\n completed.append(self.metrics_queue.get_nowait()._replace(\n perf_stats=self.perf_stats.get()))\n except queue.Empty:\n break\n return completed\n\n def get_extra_batches(self):\n extra = []\n while True:\n try:\n extra.append(self.extra_batches.get_nowait())\n except queue.Empty:\n break\n return extra\n\n\ndef _env_runner(base_env, extra_batch_callback, policies, policy_mapping_fn,\n rollout_fragment_length, horizon, preprocessors, obs_filters,\n clip_rewards, clip_actions, pack, callbacks, tf_sess,\n perf_stats, soft_horizon, no_done_at_end):\n \"\"\"This implements the common experience collection logic.\n\n Args:\n base_env (BaseEnv): env implementing BaseEnv.\n extra_batch_callback (fn): function to send extra batch data to.\n policies (dict): Map of policy ids to Policy instances.\n policy_mapping_fn (func): Function that maps agent ids to policy ids.\n This is called when an agent first enters the environment. The\n agent is then \"bound\" to the returned policy for the episode.\n rollout_fragment_length (int): Number of episode steps before\n `SampleBatch` is yielded. Set to infinity to yield complete\n episodes.\n horizon (int): Horizon of the episode.\n preprocessors (dict): Map of policy id to preprocessor for the\n observations prior to filtering.\n obs_filters (dict): Map of policy id to filter used to process\n observations for the policy.\n clip_rewards (bool): Whether to clip rewards before postprocessing.\n pack (bool): Whether to pack multiple episodes into each batch. This\n guarantees batches will be exactly `rollout_fragment_length` in\n size.\n clip_actions (bool): Whether to clip actions to the space range.\n callbacks (dict): User callbacks to run on episode events.\n tf_sess (Session|None): Optional tensorflow session to use for batching\n TF policy evaluations.\n perf_stats (PerfStats): Record perf stats into this object.\n soft_horizon (bool): Calculate rewards but don't reset the\n environment when the horizon is hit.\n no_done_at_end (bool): Ignore the done=True at the end of the episode\n and instead record done=False.\n\n Yields:\n rollout (SampleBatch): Object containing state, action, reward,\n terminal condition, and other fields as dictated by `policy`.\n \"\"\"\n\n # Try to get Env's max_episode_steps prop. If it doesn't exist, catch\n # error and continue.\n max_episode_steps = None\n try:\n max_episode_steps = base_env.get_unwrapped()[0].spec.max_episode_steps\n except Exception:\n pass\n\n # Trainer has a given `horizon` setting.\n if horizon:\n # `horizon` is larger than env's limit -> Error and explain how\n # to increase Env's own episode limit.\n if max_episode_steps and horizon > max_episode_steps:\n raise ValueError(\n \"Your `horizon` setting ({}) is larger than the Env's own \"\n \"timestep limit ({})! Try to increase the Env's limit via \"\n \"setting its `spec.max_episode_steps` property.\".format(\n horizon, max_episode_steps))\n # Otherwise, set Trainer's horizon to env's max-steps.\n elif max_episode_steps:\n horizon = max_episode_steps\n logger.debug(\n \"No episode horizon specified, setting it to Env's limit ({}).\".\n format(max_episode_steps))\n else:\n horizon = float(\"inf\")\n logger.debug(\"No episode horizon specified, assuming inf.\")\n\n # Pool of batch builders, which can be shared across episodes to pack\n # trajectory data.\n batch_builder_pool = []\n\n def get_batch_builder():\n if batch_builder_pool:\n return batch_builder_pool.pop()\n else:\n return MultiAgentSampleBatchBuilder(\n policies, clip_rewards, callbacks.get(\"on_postprocess_traj\"))\n\n def new_episode():\n episode = MultiAgentEpisode(policies, policy_mapping_fn,\n get_batch_builder, extra_batch_callback)\n # Call each policy's Exploration.on_episode_start method.\n for p in policies.values():\n p.exploration.on_episode_start(\n policy=p,\n environment=base_env,\n episode=episode,\n tf_sess=getattr(p, \"_sess\", None))\n # Call custom on_episode_start callback.\n if callbacks.get(\"on_episode_start\"):\n callbacks[\"on_episode_start\"]({\n \"env\": base_env,\n \"policy\": policies,\n \"episode\": episode,\n })\n return episode\n\n active_episodes = defaultdict(new_episode)\n\n while True:\n perf_stats.iters += 1\n t0 = time.time()\n # Get observations from all ready agents\n unfiltered_obs, rewards, dones, infos, off_policy_actions = \\\n base_env.poll()\n perf_stats.env_wait_time += time.time() - t0\n\n if log_once(\"env_returns\"):\n logger.info(\"Raw obs from env: {}\".format(\n summarize(unfiltered_obs)))\n logger.info(\"Info return from env: {}\".format(summarize(infos)))\n\n # Process observations and prepare for policy evaluation\n t1 = time.time()\n active_envs, to_eval, outputs = _process_observations(\n base_env, policies, batch_builder_pool, active_episodes,\n unfiltered_obs, rewards, dones, infos, off_policy_actions, horizon,\n preprocessors, obs_filters, rollout_fragment_length, pack,\n callbacks, soft_horizon, no_done_at_end)\n perf_stats.processing_time += time.time() - t1\n for o in outputs:\n yield o\n\n # Do batched policy eval\n t2 = time.time()\n eval_results = _do_policy_eval(tf_sess, to_eval, policies,\n active_episodes)\n perf_stats.inference_time += time.time() - t2\n\n # Process results and update episode state\n t3 = time.time()\n actions_to_send = _process_policy_eval_results(\n to_eval, eval_results, active_episodes, active_envs,\n off_policy_actions, policies, clip_actions)\n perf_stats.processing_time += time.time() - t3\n\n # Return computed actions to ready envs. We also send to envs that have\n # taken off-policy actions; those envs are free to ignore the action.\n t4 = time.time()\n base_env.send_actions(actions_to_send)\n perf_stats.env_wait_time += time.time() - t4\n\n\ndef _process_observations(base_env, policies, batch_builder_pool,\n active_episodes, unfiltered_obs, rewards, dones,\n infos, off_policy_actions, horizon, preprocessors,\n obs_filters, rollout_fragment_length, pack,\n callbacks, soft_horizon, no_done_at_end):\n \"\"\"Record new data from the environment and prepare for policy evaluation.\n\n Returns:\n active_envs: set of non-terminated env ids\n to_eval: map of policy_id to list of agent PolicyEvalData\n outputs: list of metrics and samples to return from the sampler\n \"\"\"\n\n active_envs = set()\n to_eval = defaultdict(list)\n outputs = []\n large_batch_threshold = max(1000, rollout_fragment_length * 10) if \\\n rollout_fragment_length != float(\"inf\") else 5000\n\n # For each environment\n for env_id, agent_obs in unfiltered_obs.items():\n new_episode = env_id not in active_episodes\n episode = active_episodes[env_id]\n if not new_episode:\n episode.length += 1\n episode.batch_builder.count += 1\n episode._add_agent_rewards(rewards[env_id])\n\n if (episode.batch_builder.total() > large_batch_threshold\n and log_once(\"large_batch_warning\")):\n logger.warning(\n \"More than {} observations for {} env steps \".format(\n episode.batch_builder.total(),\n episode.batch_builder.count) + \"are buffered in \"\n \"the sampler. If this is more than you expected, check that \"\n \"that you set a horizon on your environment correctly and that\"\n \" it terminates at some point. \"\n \"Note: In multi-agent environments, `rollout_fragment_length` \"\n \"sets the batch size based on environment steps, not the \"\n \"steps of \"\n \"individual agents, which can result in unexpectedly large \"\n \"batches. Also, you may be in evaluation waiting for your Env \"\n \"to terminate (batch_mode=`complete_episodes`). Make sure it \"\n \"does at some point.\")\n\n # Check episode termination conditions\n if dones[env_id][\"__all__\"] or episode.length >= horizon:\n hit_horizon = (episode.length >= horizon\n and not dones[env_id][\"__all__\"])\n all_done = True\n atari_metrics = _fetch_atari_metrics(base_env)\n if atari_metrics is not None:\n for m in atari_metrics:\n outputs.append(\n m._replace(custom_metrics=episode.custom_metrics))\n else:\n outputs.append(\n RolloutMetrics(episode.length, episode.total_reward,\n dict(episode.agent_rewards),\n episode.custom_metrics, {},\n episode.hist_data))\n else:\n hit_horizon = False\n all_done = False\n active_envs.add(env_id)\n\n # For each agent in the environment.\n for agent_id, raw_obs in agent_obs.items():\n policy_id = episode.policy_for(agent_id)\n prep_obs = _get_or_raise(preprocessors,\n policy_id).transform(raw_obs)\n if log_once(\"prep_obs\"):\n logger.info(\"Preprocessed obs: {}\".format(summarize(prep_obs)))\n\n filtered_obs = _get_or_raise(obs_filters, policy_id)(prep_obs)\n if log_once(\"filtered_obs\"):\n logger.info(\"Filtered obs: {}\".format(summarize(filtered_obs)))\n\n agent_done = bool(all_done or dones[env_id].get(agent_id))\n if not agent_done:\n to_eval[policy_id].append(\n PolicyEvalData(env_id, agent_id, filtered_obs,\n infos[env_id].get(agent_id, {}),\n episode.rnn_state_for(agent_id),\n episode.last_action_for(agent_id),\n rewards[env_id][agent_id] or 0.0))\n\n last_observation = episode.last_observation_for(agent_id)\n episode._set_last_observation(agent_id, filtered_obs)\n episode._set_last_raw_obs(agent_id, raw_obs)\n episode._set_last_info(agent_id, infos[env_id].get(agent_id, {}))\n\n # Record transition info if applicable\n if (last_observation is not None and infos[env_id].get(\n agent_id, {}).get(\"training_enabled\", True)):\n episode.batch_builder.add_values(\n agent_id,\n policy_id,\n t=episode.length - 1,\n eps_id=episode.episode_id,\n agent_index=episode._agent_index(agent_id),\n obs=last_observation,\n actions=episode.last_action_for(agent_id),\n rewards=rewards[env_id][agent_id],\n prev_actions=episode.prev_action_for(agent_id),\n prev_rewards=episode.prev_reward_for(agent_id),\n dones=(False if (no_done_at_end\n or (hit_horizon and soft_horizon)) else\n agent_done),\n infos=infos[env_id].get(agent_id, {}),\n new_obs=filtered_obs,\n **episode.last_pi_info_for(agent_id))\n\n # Invoke the step callback after the step is logged to the episode\n if callbacks.get(\"on_episode_step\"):\n callbacks[\"on_episode_step\"]({\"env\": base_env, \"episode\": episode})\n\n # Cut the batch if we're not packing multiple episodes into one,\n # or if we've exceeded the requested batch size.\n if episode.batch_builder.has_pending_agent_data():\n if dones[env_id][\"__all__\"] and not no_done_at_end:\n episode.batch_builder.check_missing_dones()\n if (all_done and not pack) or \\\n episode.batch_builder.count >= rollout_fragment_length:\n outputs.append(episode.batch_builder.build_and_reset(episode))\n elif all_done:\n # Make sure postprocessor stays within one episode\n episode.batch_builder.postprocess_batch_so_far(episode)\n\n if all_done:\n # Handle episode termination\n batch_builder_pool.append(episode.batch_builder)\n # Call each policy's Exploration.on_episode_end method.\n for p in policies.values():\n p.exploration.on_episode_end(\n policy=p,\n environment=base_env,\n episode=episode,\n tf_sess=getattr(p, \"_sess\", None))\n # Call custom on_episode_end callback.\n if callbacks.get(\"on_episode_end\"):\n callbacks[\"on_episode_end\"]({\n \"env\": base_env,\n \"policy\": policies,\n \"episode\": episode\n })\n if hit_horizon and soft_horizon:\n episode.soft_reset()\n resetted_obs = agent_obs\n else:\n del active_episodes[env_id]\n resetted_obs = base_env.try_reset(env_id)\n if resetted_obs is None:\n # Reset not supported, drop this env from the ready list\n if horizon != float(\"inf\"):\n raise ValueError(\n \"Setting episode horizon requires reset() support \"\n \"from the environment.\")\n elif resetted_obs != ASYNC_RESET_RETURN:\n # Creates a new episode if this is not async return\n # If reset is async, we will get its result in some future poll\n episode = active_episodes[env_id]\n for agent_id, raw_obs in resetted_obs.items():\n policy_id = episode.policy_for(agent_id)\n policy = _get_or_raise(policies, policy_id)\n prep_obs = _get_or_raise(preprocessors,\n policy_id).transform(raw_obs)\n filtered_obs = _get_or_raise(obs_filters,\n policy_id)(prep_obs)\n episode._set_last_observation(agent_id, filtered_obs)\n to_eval[policy_id].append(\n PolicyEvalData(\n env_id, agent_id, filtered_obs,\n episode.last_info_for(agent_id) or {},\n episode.rnn_state_for(agent_id),\n np.zeros_like(\n _flatten_action(policy.action_space.sample())),\n 0.0))\n\n return active_envs, to_eval, outputs\n\n\ndef _do_policy_eval(tf_sess, to_eval, policies, active_episodes):\n \"\"\"Call compute actions on observation batches to get next actions.\n\n Returns:\n eval_results: dict of policy to compute_action() outputs.\n \"\"\"\n\n eval_results = {}\n\n if tf_sess:\n builder = TFRunBuilder(tf_sess, \"policy_eval\")\n pending_fetches = {}\n else:\n builder = None\n\n if log_once(\"compute_actions_input\"):\n logger.info(\"Inputs to compute_actions():\\n\\n{}\\n\".format(\n summarize(to_eval)))\n\n for policy_id, eval_data in to_eval.items():\n rnn_in = [t.rnn_state for t in eval_data]\n policy = _get_or_raise(policies, policy_id)\n if builder and (policy.compute_actions.__code__ is\n TFPolicy.compute_actions.__code__):\n\n obs_batch = [t.obs for t in eval_data]\n state_batches = _to_column_format(rnn_in)\n\n # TODO(ekl): how can we make info batch available to TF code?\n pending_fetches[policy_id] = policy._build_compute_actions(\n builder,\n obs_batch=obs_batch,\n state_batches=state_batches,\n prev_action_batch=[t.prev_action for t in eval_data],\n prev_reward_batch=[t.prev_reward for t in eval_data],\n timestep=policy.global_timestep)\n else:\n # TODO(sven): Does this work for LSTM torch?\n rnn_in_cols = [\n np.stack([row[i] for row in rnn_in])\n for i in range(len(rnn_in[0]))\n ]\n eval_results[policy_id] = policy.compute_actions(\n [t.obs for t in eval_data],\n state_batches=rnn_in_cols,\n prev_action_batch=[t.prev_action for t in eval_data],\n prev_reward_batch=[t.prev_reward for t in eval_data],\n info_batch=[t.info for t in eval_data],\n episodes=[active_episodes[t.env_id] for t in eval_data],\n timestep=policy.global_timestep)\n if builder:\n for pid, v in pending_fetches.items():\n eval_results[pid] = builder.get(v)\n\n if log_once(\"compute_actions_result\"):\n logger.info(\"Outputs of compute_actions():\\n\\n{}\\n\".format(\n summarize(eval_results)))\n\n return eval_results\n\n\ndef _process_policy_eval_results(to_eval, eval_results, active_episodes,\n active_envs, off_policy_actions, policies,\n clip_actions):\n \"\"\"Process the output of policy neural network evaluation.\n\n Records policy evaluation results into the given episode objects and\n returns replies to send back to agents in the env.\n\n Returns:\n actions_to_send: nested dict of env id -> agent id -> agent replies.\n \"\"\"\n\n actions_to_send = defaultdict(dict)\n for env_id in active_envs:\n actions_to_send[env_id] = {} # at minimum send empty dict\n\n for policy_id, eval_data in to_eval.items():\n rnn_in_cols = _to_column_format([t.rnn_state for t in eval_data])\n\n actions = eval_results[policy_id][0]\n rnn_out_cols = eval_results[policy_id][1]\n pi_info_cols = eval_results[policy_id][2]\n\n if len(rnn_in_cols) != len(rnn_out_cols):\n raise ValueError(\"Length of RNN in did not match RNN out, got: \"\n \"{} vs {}\".format(rnn_in_cols, rnn_out_cols))\n # Add RNN state info\n for f_i, column in enumerate(rnn_in_cols):\n pi_info_cols[\"state_in_{}\".format(f_i)] = column\n for f_i, column in enumerate(rnn_out_cols):\n pi_info_cols[\"state_out_{}\".format(f_i)] = column\n # Save output rows\n actions = _unbatch_tuple_actions(actions)\n policy = _get_or_raise(policies, policy_id)\n for i, action in enumerate(actions):\n env_id = eval_data[i].env_id\n agent_id = eval_data[i].agent_id\n if clip_actions:\n actions_to_send[env_id][agent_id] = clip_action(\n action, policy.action_space)\n else:\n actions_to_send[env_id][agent_id] = action\n episode = active_episodes[env_id]\n episode._set_rnn_state(agent_id, [c[i] for c in rnn_out_cols])\n episode._set_last_pi_info(\n agent_id, {k: v[i]\n for k, v in pi_info_cols.items()})\n if env_id in off_policy_actions and \\\n agent_id in off_policy_actions[env_id]:\n episode._set_last_action(agent_id,\n off_policy_actions[env_id][agent_id])\n else:\n episode._set_last_action(agent_id, action)\n\n return actions_to_send\n\n\ndef _fetch_atari_metrics(base_env):\n \"\"\"Atari games have multiple logical episodes, one per life.\n\n However for metrics reporting we count full episodes all lives included.\n \"\"\"\n unwrapped = base_env.get_unwrapped()\n if not unwrapped:\n return None\n atari_out = []\n for u in unwrapped:\n monitor = get_wrapper_by_cls(u, MonitorEnv)\n if not monitor:\n return None\n for eps_rew, eps_len in monitor.next_episode_results():\n atari_out.append(RolloutMetrics(eps_len, eps_rew))\n return atari_out\n\n\ndef _unbatch_tuple_actions(action_batch):\n # convert list of batches -> batch of lists\n if isinstance(action_batch, TupleActions):\n out = []\n for j in range(len(action_batch.batches[0])):\n out.append([\n action_batch.batches[i][j]\n for i in range(len(action_batch.batches))\n ])\n return out\n return action_batch\n\n\ndef _to_column_format(rnn_state_rows):\n num_cols = len(rnn_state_rows[0])\n return [[row[i] for row in rnn_state_rows] for i in range(num_cols)]\n\n\ndef _get_or_raise(mapping, policy_id):\n \"\"\"Returns a Policy object under key `policy_id` in `mapping`.\n\n Throws an error if `policy_id` cannot be found.\n\n Returns:\n Policy: The found Policy object.\n \"\"\"\n if policy_id not in mapping:\n raise ValueError(\n \"Could not find policy for agent: agent policy id `{}` not \"\n \"in policy map keys {}.\".format(policy_id, mapping.keys()))\n return mapping[policy_id]\n" ]
[ [ "numpy.stack" ] ]
zinechant/BERT-pytorch
[ "7c8bc555f29ff7ba336b38f2eddd072d7910e2bd" ]
[ "trainer/pretrain.py" ]
[ "import torch\nimport torch.nn as nn\nfrom torch.optim import Adam\nfrom torch.utils.data import DataLoader\n\nfrom ..model import BERTLM, BERT\nfrom .optim_schedule import ScheduledOptim\n\nimport tqdm\nimport numpy\n\ndef hook(arr, l, iNo):\n def trace(module, input, output):\n if iNo:\n cid = input[0].get_device()\n arr[l][cid].append(input[0].cpu().detach().numpy())\n print(input[0].shape)\n else:\n cid = output[0].get_device()\n arr[l][cid].append(output[0].cpu().detach().numpy())\n print(output[0].shape)\n return trace\n\nclass BERTTrainer:\n \"\"\"\n BERTTrainer make the pretrained BERT model with two LM training method.\n\n 1. Masked Language Model : 3.3.1 Task #1: Masked LM\n 2. Next Sentence prediction : 3.3.2 Task #2: Next Sentence Prediction\n\n please check the details on README.md with simple example.\n\n \"\"\"\n\n def __init__(self, bert: BERT, vocab_size: int,\n train_dataloader: DataLoader, test_dataloader: DataLoader = None,\n lr: float = 1e-4, betas=(0.9, 0.999), weight_decay: float = 0.01, warmup_steps=10000,\n with_cuda: bool = True, cuda_devices=None, log_freq: int = 10):\n \"\"\"\n :param bert: BERT model which you want to train\n :param vocab_size: total word vocab size\n :param train_dataloader: train dataset data loader\n :param test_dataloader: test dataset data loader [can be None]\n :param lr: learning rate of optimizer\n :param betas: Adam optimizer betas\n :param weight_decay: Adam optimizer weight decay param\n :param with_cuda: traning with cuda\n :param log_freq: logging frequency of the batch iteration\n \"\"\"\n\n # Setup cuda device for BERT training, argument -c, --cuda should be true\n cuda_condition = torch.cuda.is_available() and with_cuda\n self.device = torch.device(\"cuda:0\" if cuda_condition else \"cpu\")\n\n # This BERT model will be saved every epoch\n self.bert = bert\n # Initialize the BERT Language Model, with BERT model\n self.model = BERTLM(bert, vocab_size).to(self.device)\n\n # Distributed GPU training if CUDA can detect more than 1 GPU\n if with_cuda and torch.cuda.device_count() > 1:\n print(\"Using %d GPUS for BERT\" % torch.cuda.device_count())\n self.model = nn.DataParallel(self.model, device_ids=cuda_devices)\n\n # Setting the train and test data loader\n self.train_data = train_dataloader\n self.test_data = test_dataloader\n\n # Setting the Adam optimizer with hyper-param\n self.optim = Adam(self.model.parameters(), lr=lr, betas=betas, weight_decay=weight_decay)\n self.optim_schedule = ScheduledOptim(self.optim, self.bert.hidden, n_warmup_steps=warmup_steps)\n\n # Using Negative Log Likelihood Loss function for predicting the masked_token\n self.criterion = nn.NLLLoss(ignore_index=0)\n\n self.log_freq = log_freq\n\n print(\"Total Parameters:\", sum([p.nelement() for p in self.model.parameters()]))\n\n def train(self, epoch, output_path):\n self.iteration(epoch, self.train_data, output_path)\n\n def test(self, epoch):\n self.iteration(epoch, self.test_data, None, train=False)\n\n def iteration(self, epoch, data_loader, output_path, train=True):\n \"\"\"\n loop over the data_loader for training or testing\n if on train status, backward operation is activated\n and also auto save the model every peoch\n\n :param epoch: current epoch index\n :param data_loader: torch.utils.data.DataLoader for iteration\n :param train: boolean value of is train or test\n :return: None\n \"\"\"\n str_code = \"train\" if train else \"test\"\n\n # Setting the tqdm progress bar\n data_iter = tqdm.tqdm(enumerate(data_loader),\n desc=\"EP_%s:%d\" % (str_code, epoch),\n total=len(data_loader),\n bar_format=\"{l_bar}{r_bar}\")\n\n avg_loss = 0.0\n total_correct = 0\n total_element = 0\n\n if output_path:\n handles = []\n ls = range(len(self.bert.transformer_blocks))\n cs = range(torch.cuda.device_count())\n arrs = [[[[] for c in cs] for l in ls],\n [[[] for c in cs] for l in ls]]\n for l, layer in enumerate(self.bert.transformer_blocks):\n handles.append(layer.register_forward_hook(hook(arrs[0], l, True)))\n handles.append(layer.register_full_backward_hook(hook(arrs[1], l, True)))\n # handles.append(layer.register_forward_hook(hook(arrs[0], False)))\n\n for i, data in data_iter:\n if output_path and (i == 10):\n for handle in handles:\n handle.remove()\n arr = numpy.array(arrs)\n print(\"[TRACE]: \" + str(arr.shape))\n with open(output_path + (\"_ep%d.trace\" % epoch), \"wb\") as no:\n numpy.save(no, arr)\n\n # 0. batch_data will be sent into the device(GPU or cpu)\n data = {key: value.to(self.device) for key, value in data.items()}\n\n # 1. forward the next_sentence_prediction and masked_lm model\n next_sent_output, mask_lm_output = self.model.forward(data[\"bert_input\"], data[\"segment_label\"])\n\n # 2-1. NLL(negative log likelihood) loss of is_next classification result\n next_loss = self.criterion(next_sent_output, data[\"is_next\"])\n\n # 2-2. NLLLoss of predicting masked token word\n mask_loss = self.criterion(mask_lm_output.transpose(1, 2), data[\"bert_label\"])\n\n # 2-3. Adding next_loss and mask_loss : 3.4 Pre-training Procedure\n loss = next_loss + mask_loss\n\n # 3. backward and optimization only in train\n if train:\n self.optim_schedule.zero_grad()\n loss.backward()\n self.optim_schedule.step_and_update_lr()\n\n # next sentence prediction accuracy\n correct = next_sent_output.argmax(dim=-1).eq(data[\"is_next\"]).sum().item()\n avg_loss += loss.item()\n total_correct += correct\n total_element += data[\"is_next\"].nelement()\n\n post_fix = {\n \"epoch\": epoch,\n \"iter\": i,\n \"avg_loss\": avg_loss / (i + 1),\n \"avg_acc\": total_correct / total_element * 100,\n \"loss\": loss.item()\n }\n\n if i % self.log_freq == 0:\n data_iter.write(str(post_fix))\n\n print(\"EP%d_%s, avg_loss=\" % (epoch, str_code), avg_loss / len(data_iter), \"total_acc=\",\n total_correct * 100.0 / total_element)\n\n def save(self, epoch, file_path=\"output/bert_trained.model\"):\n \"\"\"\n Saving the current BERT model on file_path\n\n :param epoch: current epoch number\n :param file_path: model output path which gonna be file_path+\"ep%d\" % epoch\n :return: final_output_path\n \"\"\"\n output_path = file_path + \".ep%d\" % epoch\n torch.save(self.bert.state_dict(), output_path)\n print(\"EP:%d Model Saved on:\" % epoch, output_path)\n return output_path\n" ]
[ [ "torch.nn.NLLLoss", "numpy.save", "torch.cuda.device_count", "torch.cuda.is_available", "numpy.array", "torch.nn.DataParallel", "torch.device" ] ]
zxsted/PythonRobotics
[ "ed73b26db7eca9712dca696a9054f6ea2fcf26e9" ]
[ "PathPlanning/PotentialFieldPlanning/potential_field_planning.py" ]
[ "\"\"\"\n\nPotential Field based path planner\n\nauthor: Atsushi Sakai (@Atsushi_twi)\n\nRef:\nhttps://www.cs.cmu.edu/~motionplanning/lecture/Chap4-Potential-Field_howie.pdf\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Parameters\nKP = 5.0 # attractive potential gain\nETA = 100.0 # repulsive potential gain\nAREA_WIDTH = 30.0 # potential area width [m]\n\nshow_animation = True\n\n\ndef calc_potential_field(gx, gy, ox, oy, reso, rr):\n minx = min(ox) - AREA_WIDTH / 2.0\n miny = min(oy) - AREA_WIDTH / 2.0\n maxx = max(ox) + AREA_WIDTH / 2.0\n maxy = max(oy) + AREA_WIDTH / 2.0\n xw = round((maxx - minx) / reso)\n yw = round((maxy - miny) / reso)\n\n # calc each potential\n pmap = [[0.0 for i in range(yw)] for i in range(xw)]\n\n for ix in range(xw):\n x = ix * reso + minx\n\n for iy in range(yw):\n y = iy * reso + miny\n ug = calc_attractive_potential(x, y, gx, gy)\n uo = calc_repulsive_potential(x, y, ox, oy, rr)\n uf = ug + uo\n pmap[ix][iy] = uf\n\n return pmap, minx, miny\n\n\ndef calc_attractive_potential(x, y, gx, gy):\n return 0.5 * KP * np.hypot(x - gx, y - gy)\n\n\ndef calc_repulsive_potential(x, y, ox, oy, rr):\n # search nearest obstacle\n minid = -1\n dmin = float(\"inf\")\n for i in range(len(ox)):\n d = np.hypot(x - ox[i], y - oy[i])\n if dmin >= d:\n dmin = d\n minid = i\n\n # calc repulsive potential\n dq = np.hypot(x - ox[minid], y - oy[minid])\n\n if dq <= rr:\n if dq <= 0.1:\n dq = 0.1\n\n return 0.5 * ETA * (1.0 / dq - 1.0 / rr) ** 2\n else:\n return 0.0\n\n\ndef get_motion_model():\n # dx, dy\n motion = [[1, 0],\n [0, 1],\n [-1, 0],\n [0, -1],\n [-1, -1],\n [-1, 1],\n [1, -1],\n [1, 1]]\n\n return motion\n\n\ndef potential_field_planning(sx, sy, gx, gy, ox, oy, reso, rr):\n\n # calc potential field\n pmap, minx, miny = calc_potential_field(gx, gy, ox, oy, reso, rr)\n\n # search path\n d = np.hypot(sx - gx, sy - gy)\n ix = round((sx - minx) / reso)\n iy = round((sy - miny) / reso)\n gix = round((gx - minx) / reso)\n giy = round((gy - miny) / reso)\n\n if show_animation:\n draw_heatmap(pmap)\n plt.plot(ix, iy, \"*k\")\n plt.plot(gix, giy, \"*m\")\n\n rx, ry = [sx], [sy]\n motion = get_motion_model()\n while d >= reso:\n minp = float(\"inf\")\n minix, miniy = -1, -1\n for i in range(len(motion)):\n inx = ix + motion[i][0]\n iny = iy + motion[i][1]\n if inx >= len(pmap) or iny >= len(pmap[0]):\n p = float(\"inf\") # outside area\n else:\n p = pmap[inx][iny]\n if minp > p:\n minp = p\n minix = inx\n miniy = iny\n ix = minix\n iy = miniy\n xp = ix * reso + minx\n yp = iy * reso + miny\n d = np.hypot(gx - xp, gy - yp)\n rx.append(xp)\n ry.append(yp)\n\n if show_animation:\n plt.plot(ix, iy, \".r\")\n plt.pause(0.01)\n\n print(\"Goal!!\")\n\n return rx, ry\n\n\ndef draw_heatmap(data):\n data = np.array(data).T\n plt.pcolor(data, vmax=100.0, cmap=plt.cm.Blues)\n\n\ndef main():\n print(\"potential_field_planning start\")\n\n sx = 0.0 # start x position [m]\n sy = 10.0 # start y positon [m]\n gx = 30.0 # goal x position [m]\n gy = 30.0 # goal y position [m]\n grid_size = 0.5 # potential grid size [m]\n robot_radius = 5.0 # robot radius [m]\n\n ox = [15.0, 5.0, 20.0, 25.0] # obstacle x position list [m]\n oy = [25.0, 15.0, 26.0, 25.0] # obstacle y position list [m]\n\n if show_animation:\n plt.grid(True)\n plt.axis(\"equal\")\n\n # path generation\n rx, ry = potential_field_planning(\n sx, sy, gx, gy, ox, oy, grid_size, robot_radius)\n\n if show_animation:\n plt.show()\n\n\nif __name__ == '__main__':\n print(__file__ + \" start!!\")\n main()\n print(__file__ + \" Done!!\")\n" ]
[ [ "matplotlib.pyplot.pause", "numpy.hypot", "matplotlib.pyplot.grid", "matplotlib.pyplot.axis", "matplotlib.pyplot.pcolor", "matplotlib.pyplot.show", "numpy.array", "matplotlib.pyplot.plot" ] ]
Westlanderz/AI-Plat1
[ "1187c22819e5135e8e8189c99b86a93a0d66b8d8" ]
[ "venv/Lib/site-packages/caffe2/quantization/server/dequantize_dnnlowp_op_test.py" ]
[ "\r\n\r\nimport collections\r\n\r\nimport caffe2.python.hypothesis_test_util as hu\r\nimport hypothesis.strategies as st\r\nimport numpy as np\r\nfrom caffe2.python import core, dyndep, workspace\r\nfrom caffe2.quantization.server.dnnlowp_test_utils import check_quantized_results_close\r\nfrom hypothesis import given\r\n\r\n\r\ndyndep.InitOpsLibrary(\"//caffe2/caffe2/quantization/server:dnnlowp_ops\")\r\nworkspace.GlobalInit([\"caffe2\", \"--caffe2_omp_num_threads=11\"])\r\n\r\n\r\nclass DNNLowPDequantizeOpTest(hu.HypothesisTestCase):\r\n @given(size=st.integers(1024, 2048), is_empty=st.booleans(), **hu.gcs_cpu_only)\r\n def test_dnnlowp_dequantize(self, size, is_empty, gc, dc):\r\n if is_empty:\r\n size = 0\r\n min_ = -10.0\r\n max_ = 20.0\r\n X = (np.random.rand(size) * (max_ - min_) + min_).astype(np.float32)\r\n\r\n Output = collections.namedtuple(\"Output\", [\"Y\", \"op_type\", \"engine\"])\r\n outputs = []\r\n\r\n op_type_list = [\"Dequantize\", \"Int8Dequantize\"]\r\n engine = \"DNNLOWP\"\r\n\r\n outputs.append(Output(X, op_type=\"\", engine=\"\"))\r\n\r\n for op_type in op_type_list:\r\n net = core.Net(\"test_net\")\r\n\r\n quantize = core.CreateOperator(\r\n \"Quantize\", [\"X\"], [\"X_q\"], engine=engine, device_option=gc\r\n )\r\n net.Proto().op.extend([quantize])\r\n\r\n dequantize = core.CreateOperator(\r\n op_type, [\"X_q\"], [\"Y\"], engine=engine, device_option=gc\r\n )\r\n net.Proto().op.extend([dequantize])\r\n\r\n self.ws.create_blob(\"X\").feed(X, device_option=gc)\r\n self.ws.run(net)\r\n outputs.append(\r\n Output(Y=self.ws.blobs[\"Y\"].fetch(), op_type=op_type, engine=engine)\r\n )\r\n\r\n check_quantized_results_close(outputs)\r\n" ]
[ [ "numpy.random.rand" ] ]
LothairKizardjian/EfficientNeuralSearch
[ "45dd9c052fb74f9bb56efd9b914761dafb1a7ac9" ]
[ "enas/src/chess/data_utils.py" ]
[ "import os\nimport sys\nimport _pickle as pickle\nimport numpy as np\nimport tensorflow as tf\nimport chess.pgn\nimport pgn_tensors_utils\nimport bz2\n\ndef read_data(data_path, num_valids=20000):\n print(\"-\" * 80)\n print(\"Reading data\")\n\n nb_games = 200\n #nb_games = sys.maxsize\n boards, labels, results = {}, {}, {}\n\n train_files = [\n \"pgn_games/chess_games_2000.pgn\",\n \"pgn_games/chess_games_2001.pgn\",\n \"pgn_games/chess_games_2002.pgn\",\n \"pgn_games/chess_games_2003.pgn\",\n \"pgn_games/chess_games_2004.pgn\"\n ]\n test_file = [ \n \"pgn_games/chess_games_2005.pgn\"\n ]\n boards[\"train\"], labels[\"train\"], results[\"train\"] = load_data(data_path, train_files, nb_games)\n\n num_valids = int(len(boards[\"train\"])*0.1)\n \n if num_valids:\n boards[\"valid\"] = boards[\"train\"][-num_valids:]\n labels[\"valid\"] = labels[\"train\"][-num_valids:]\n results[\"valid\"]= results[\"train\"][-num_valids:]\n\n boards[\"train\"] = boards[\"train\"][:-num_valids]\n labels[\"train\"] = labels[\"train\"][:-num_valids]\n results[\"train\"]= results[\"train\"][:-num_valids]\n else:\n boards[\"valid\"], labels[\"valid\"], results[\"valid\"] = None, None, None\n\n boards[\"test\"], labels[\"test\"], results[\"test\"] = load_data(data_path, test_file, nb_games)\n\n return boards, results\n\ndef load_pgn_from_bz2(bz2_path):\n bz2_file_exist = os.path.isfile(bz2_path)\n if bz2_file_exist == False:\n print('File {} not found'.format(bz2_path))\n return 0\n with open(bz2_path, 'rb') as source, open(bz2_path.replace('.bz2',''), 'wb') as dest:\n dest.write(bz2.decompress(source.read()))\n return 1\n \ndef load_games_from_pgn_path(pgn_path,game_nb):\n pgn_file_exist = os.path.isfile(pgn_path)\n if pgn_file_exist == False:\n if(load_pgn_from_bz2(pgn_path+'.bz2')==0): \n print('File {} not found'.format(pgn_path))\n return 0\n pgn = open(pgn_path)\n return load_games_from_pgn(pgn,game_nb)\n\ndef load_games_from_pgn(pgn,game_nb):\n name = pgn.name.split('/')[3].replace('.pgn','')\n print('Loading games for pgn {} ...'.format(name))\n games = []\n game = chess.pgn.read_game(pgn)\n counter = 0\n \n while game != None and counter < game_nb:\n games.append(game)\n game = chess.pgn.read_game(pgn)\n counter+=1\n \n print(\"{} games loaded\".format(counter))\n return games\n \n\ndef _load_data(data_path,pgn_path,game_nb):\n '''\n Load the tensors, the according labels and store them in a .npy file\n '''\n suffixe = pgn_path.split('/') \n suffixe = suffixe[1].replace('.pgn','')\n tensors_file_exist = os.path.isfile(data_path+'/tensors/tensors_numpy_{}games_{}.npy'.format(game_nb,suffixe))\n labels_files_exist = os.path.isfile(data_path+'/tensors/labels_numpy_{}games_{}.npy'.format(game_nb,suffixe))\n\n \n print(\"Loading data for {}\".format(suffixe))\n \n if tensors_file_exist == False or labels_files_exist == False: \n full_name = os.path.join(data_path,pgn_path)\n games = load_games_from_pgn_path(full_name,game_nb)\n print(\"loading tensors and according labels ...\")\n tensors,labels,results = pgn_tensors_utils.tensors_labels_from_games(games)\n np.save(data_path+'/tensors/labels_numpy_{}games_{}.npy'.format(game_nb,suffixe), labels)\n np.save(data_path+'/tensors/tensors_numpy_{}games_{}.npy'.format(game_nb,suffixe), tensors)\n np.save(data_path+'/tensors/results_numpy_{}games_{}.npy'.format(game_nb,suffixe), results)\n else:\n tensors = np.load(data_path+'/tensors/tensors_numpy_{}games_{}.npy'.format(game_nb,suffixe))\n labels = np.load(data_path+'/tensors/labels_numpy_{}games_{}.npy'.format(game_nb,suffixe)) \n results = np.load(data_path+'/tensors/results_numpy_{}games_{}.npy'.format(game_nb,suffixe))\n return tensors,labels,results\n\ndef load_data(data_path,paths,game_nb):\n print(\"Loading data ...\")\n tensors = []\n labels = []\n results = []\n for pgn_path in paths:\n t,l,r = _load_data(data_path,pgn_path,game_nb)\n for row in t:\n tensors.append(row)\n for row in l:\n labels.append(row)\n for row in r:\n results.append(row)\n \n tensors = np.asarray(tensors)\n labels = np.asarray(labels)\n results = np.asarray(results)\n \n tensors = np.concatenate(tensors, axis=0)\n tensors = np.reshape(tensors, [-1, 7, 8, 8])\n tensors = np.transpose(tensors, [0, 2, 3, 1])\n \n return tensors,labels,results\n\ndef select_random_examples(tensors,labels,nb_ex):\n if len(tensors) != len(labels) :\n raise('Tensors and labels have different length')\n else:\n samples = np.random.choice(len(tensors), size=nb_ex, replace=False)\n x = tensors[samples]\n y = labels[samples]\n return x,y\n" ]
[ [ "numpy.concatenate", "numpy.reshape", "numpy.transpose", "numpy.asarray" ] ]
NSLS-II-ISS/isstools
[ "54102529384f2c76633ca0393d637225a4104f93" ]
[ "isstools/widgets/widget_camera.py" ]
[ "import datetime\nfrom timeit import default_timer as timer\n\nimport numpy as np\nimport pkg_resources\nfrom PyQt5 import uic, QtWidgets, QtCore\nfrom PyQt5.QtCore import QThread, QSettings\n\nfrom matplotlib.backends.backend_qt5agg import (\n FigureCanvasQTAgg as FigureCanvas,\n NavigationToolbar2QT as NavigationToolbar)\nfrom matplotlib.figure import Figure\nimport matplotlib.patches as patches\nimport time\n\nimport bluesky.plan_stubs as bps\nfrom xas.xray import generate_energy_grid\n\nfrom isstools.dialogs.BasicDialogs import question_message_box, message_box\nfrom isstools.elements.figure_update import update_figure\nfrom isstools.elements.parameter_handler import parse_plan_parameters, return_parameters_from_widget\nfrom isstools.widgets import widget_energy_selector\nfrom isstools.elements.batch_motion import SamplePositioner\nimport time as ttime\nfrom isstools.widgets import widget_sample_positioner\nfrom isstools.widgets import widget_sample_registry\n# from isstools.process_callbacks.callback import run_router\n\n\nui_path = pkg_resources.resource_filename('isstools', 'ui/ui_camera.ui')\n\nclass UICamera(*uic.loadUiType(ui_path)):\n def __init__(self,\n camera_dict={},\n sample_stage = {},\n sample_positioner=None,\n RE = None,\n parent_gui = None,\n sample_registry=None,\n *args, **kwargs):\n\n super().__init__(*args, **kwargs)\n self.setupUi(self)\n # beamline controls\n self.camera_dict = camera_dict\n self.sample_stage = sample_stage\n self.RE = RE\n self.parent = parent_gui\n\n # figure management\n self.addCanvas()\n self.cid = self.canvas_c1.mpl_connect('button_press_event', self.set_hcursor)\n self.cid = self.canvas_c2.mpl_connect('button_press_event', self.set_vcursor)\n self.cid = self.canvas_qr.mpl_connect('button_press_event', self.set_qr_roi)\n self.h_vc = None\n self.h_hc = None\n\n self.qr_roi_patch = None\n self.qr_hlines = None\n self.qr_vlines = None\n\n # taking images management\n self.push_show_image.clicked.connect(self.show_image)\n self.timer_track_camera = QtCore.QTimer(self)\n self.timer_track_camera.setInterval(1000)\n self.timer_track_camera.timeout.connect(self.track_camera)\n\n # stage positioning management\n self.push_stage_up.clicked.connect(self.stage_up)\n self.push_stage_down.clicked.connect(self.stage_down)\n self.push_stage_left.clicked.connect(self.stage_left)\n self.push_stage_right.clicked.connect(self.stage_right)\n self.push_update_stage_parking.clicked.connect(self.update_stage_parking)\n self.push_park_stage.clicked.connect(self.park_stage)\n self.push_update_sample_parking.clicked.connect(self.update_sample_parking)\n\n self.sample_registry=sample_registry\n\n self.sample_positioner = sample_positioner\n self.settings = parent_gui.settings\n self.widget_sample_positioner = widget_sample_positioner.UISamplePositioner(parent=self,\n settings=self.settings,\n RE=RE,\n sample_positioner=sample_positioner)\n self.layout_sample_positioner.addWidget(self.widget_sample_positioner)\n\n self.widget_sample_registry = widget_sample_registry.UISampleRegistry(parent=self,\n settings=self.settings,\n RE=RE,\n sample_registry=sample_registry)\n self.layout_sample_registry.addWidget(self.widget_sample_registry)\n\n # persistence management\n\n # stage_park_x = self.settings.value('stage_park_x', defaultValue=0, type=float)\n # stage_park_y = self.settings.value('stage_park_y', defaultValue=0, type=float)\n\n stage_park_x = sample_positioner.stage_park_x\n stage_park_y = sample_positioner.stage_park_y\n self.spinBox_stage_x.setValue(stage_park_x)\n self.spinBox_stage_y.setValue(stage_park_y)\n\n # sample_park_x = self.settings.value('sample_park_x', defaultValue=0, type=float)\n # sample_park_y = self.settings.value('sample_park_y', defaultValue=0, type=float)\n sample_park_x = sample_positioner.stage_park_x + sample_positioner.delta_first_holder_x\n sample_park_y = sample_positioner.stage_park_y + sample_positioner.delta_first_holder_y\n self.spinBox_sample_x.setValue(sample_park_x)\n self.spinBox_sample_y.setValue(sample_park_y)\n\n self.beam_x_position_on_camera = self.settings.value('beam_x_position_on_camera', defaultValue=250)\n self.beam_y_position_on_camera = self.settings.value('beam_y_position_on_camera', defaultValue=250)\n\n\n x1 = self.settings.value('qr_roi_x1', defaultValue=0, type=int)\n x2 = self.settings.value('qr_roi_x2', defaultValue=0, type=int)\n y1 = self.settings.value('qr_roi_y1', defaultValue=0, type=int)\n y2 = self.settings.value('qr_roi_y2', defaultValue=0, type=int)\n self.qr_roi = [(x1, y1), [x2, y2]]\n\n # sample positioner handle\n\n\n # get pictures on the GUI upon opening\n self.show_image()\n #self.timer_track_camera.start()\n\n # self.pushButton_sreg_get_start.clicked.connect(self.set_start_sreg_points)\n # self.pushButton_sreg_get_end.clicked.connect(self.set_end_sreg_points)\n # self.pushButton_sreg_initialize.clicked.connect(self.sreg_initialize)\n # self.pushButton_sreg_reset.clicked.connect(self.sreg_reset)\n # self.pushButton_sreg_move_to_beg.clicked.connect(self.sreg_move_to_beginning)\n # self.pushButton_sreg_move_to_next.clicked.connect(self.sreg_move_to_next)\n # self.pushButton_sreg_move_to_unexposed.clicked.connect(self.sreg_move_to_unexposed)\n # self.pushButton_sreg_save.clicked.connect(self.sreg_save_to_file)\n # self.pushButton_sreg_load.clicked.connect(self.sreg_load_file)\n # def _save_sample_index_settings(self):\n # self.settings.setValue('index_stack', self.spinBox_index_stack.value())\n # self.settings.setValue('index_holder', self.spinBox_index_holder.value())\n # self.settings.setValue('index_sample', self.spinBox_index_sample.value())\n\n\n\n def addCanvas(self):\n self.figure_c1 = Figure()\n self.figure_c1.set_facecolor(color='#FcF9F6')\n self.canvas_c1 = FigureCanvas(self.figure_c1)\n self.figure_c1.ax = self.figure_c1.add_subplot(111)\n\n self.figure_c1.tight_layout()\n self.toolbar_c1 = NavigationToolbar(self.canvas_c1, self, coordinates=True)\n self.plot_camera1.addWidget(self.toolbar_c1)\n self.plot_camera1.addWidget(self.canvas_c1)\n self.canvas_c1.draw_idle()\n\n self.figure_c2 = Figure()\n self.figure_c2.set_facecolor(color='#FcF9F6')\n self.canvas_c2 = FigureCanvas(self.figure_c2)\n self.figure_c2.ax = self.figure_c2.add_subplot(111)\n\n self.figure_c2.tight_layout()\n self.toolbar_c2 = NavigationToolbar(self.canvas_c2, self, coordinates=True)\n self.plot_camera2.addWidget(self.toolbar_c2)\n self.plot_camera2.addWidget(self.canvas_c2)\n self.canvas_c2.draw_idle()\n\n self.figure_qr = Figure()\n self.figure_qr.set_facecolor(color='#FcF9F6')\n self.canvas_qr = FigureCanvas(self.figure_qr)\n self.figure_qr.ax = self.figure_qr.add_subplot(111)\n\n self.figure_qr.tight_layout()\n self.toolbar_qr = NavigationToolbar(self.canvas_qr, self, coordinates=True)\n self.plot_camera_qr.addWidget(self.toolbar_qr)\n self.plot_camera_qr.addWidget(self.canvas_qr)\n self.canvas_qr.draw_idle()\n\n\n # def show_image(self, camera_):\n\n\n def show_image(self):\n if self.push_track.isChecked():\n self.timer_track_camera.start()\n else:\n self.timer_track_camera.singleShot(0, self.track_camera)\n\n def track_camera(self):\n init_time = ttime.time()\n camera1 = self.camera_dict['camera_sample1']\n camera2 = self.camera_dict['camera_sample2']\n camera_qr = self.camera_dict['camera_sample4']\n image1 = camera1.image.image\n image2 = camera2.image.image\n image_qr = camera_qr.image.image\n vmin1, vmax1 = np.percentile(image1, 5), np.percentile(image1, 90)\n vmin2, vmax2 = np.percentile(image2, 5), np.percentile(image2, 90)\n vminqr, vmaxqr = np.percentile(image_qr, 5), np.percentile(image_qr, 90)\n print(f'Got images from PV {ttime.time()-init_time}')\n self.figure_c1.ax.imshow(image1, cmap='gray', vmin=vmin1, vmax=vmax1)\n self.figure_c2.ax.imshow(image2, cmap='gray', vmin=vmin2, vmax=vmax2)\n self.figure_qr.ax.imshow(image_qr, cmap='gray', origin='lower', vmin=vminqr, vmax=vmaxqr)\n print(f'Imshow {ttime.time() - init_time}')\n # beam position from previous session\n self._set_vcursor()\n self._set_hcursor()\n self.plot_qr_roi()\n # pretty cross\n # self.set_qr_cursor()\n\n self.canvas_c1.draw_idle()\n self.canvas_c2.draw_idle()\n self.canvas_qr.draw_idle()\n print(f'Done with images {ttime.time() - init_time}')\n\n\n def stage_up(self):\n v_step = self.spinBox_ver_step.value()\n self.RE(bps.mvr(self.sample_stage.y, v_step))\n self.show_image()\n\n def stage_down(self):\n v_step = self.spinBox_ver_step.value()\n self.RE(bps.mvr(self.sample_stage.y, -v_step))\n self.show_image()\n\n def stage_right(self):\n h_step = self.spinBox_hor_step.value()\n self.RE(bps.mvr(self.sample_stage.x, -h_step))\n self.show_image()\n\n def stage_left(self):\n h_step = self.spinBox_hor_step.value()\n self.RE(bps.mvr(self.sample_stage.x, h_step))\n self.show_image()\n\n\n def park_stage(self):\n # stage_x = self.spinBox_zero_x_rbk.value()\n # stage_y = self.spinBox_zero_y_rbk.value()\n # self.RE(bps.mv(self.sample_stage.x, stage_x))\n # self.RE(bps.mv(self.sample_stage.y, stage_y))\n self.sample_positioner.goto_park()\n self.show_image()\n\n\n def update_stage_parking(self):\n\n ret = question_message_box(self, 'Stage Parking Update',\n ('Are you sure you want to update stage parking position?\\n' +\n 'You may need to recalibrate the stage/sample positioning'))\n if ret:\n stage_park_x = self.sample_stage.x.read()[self.sample_stage.x.name]['value']\n stage_park_y = self.sample_stage.y.read()[self.sample_stage.y.name]['value']\n\n self.spinBox_stage_x.setValue(stage_park_x)\n self.spinBox_stage_y.setValue(stage_park_y)\n\n self.settings.setValue('stage_park_x', stage_park_x)\n self.settings.setValue('stage_park_y', stage_park_y)\n\n sample_park_x = self.spinBox_sample_x.value()\n sample_park_y = self.spinBox_sample_y.value()\n\n self.sample_positioner = SamplePositioner(self.RE,\n self.sample_stage,\n stage_park_x,\n stage_park_y,\n delta_first_holder_x=sample_park_x - stage_park_x,\n delta_first_holder_y=sample_park_y - stage_park_y)\n\n def update_sample_parking(self):\n\n ret = question_message_box(self, 'Sample Parking Update',\n ('Are you sure you want to update sample parking position?\\n' +\n 'You may need to recalibrate the stage/sample positioning'))\n if ret:\n sample_park_x = self.sample_stage.x.read()[self.sample_stage.x.name]['value']\n sample_park_y = self.sample_stage.y.read()[self.sample_stage.y.name]['value']\n\n self.spinBox_sample_x.setValue(sample_park_x)\n self.spinBox_sample_y.setValue(sample_park_y)\n\n self.settings.setValue('sample_park_x', sample_park_x)\n self.settings.setValue('sample_park_y', sample_park_y)\n\n stage_park_x = self.spinBox_stage_x.value()\n stage_park_y = self.spinBox_stage_y.value()\n\n self.sample_positioner = SamplePositioner(self.RE,\n self.sample_stage,\n stage_park_x,\n stage_park_y,\n delta_first_holder_x=sample_park_x - stage_park_x,\n delta_first_holder_y=sample_park_y - stage_park_y)\n\n # def zero_stage(self):\n # camera_qr = self.camera_dict['camera_sample4']\n # image_qr = camera_qr.image.image\n # qr_codes = pzDecode(image_qr)\n # if qr_codes:\n # for qr_code in qr_codes:\n # qr_text = qr_code.data.decode('utf8')\n # if qr_text == '0 position':\n # # self.label_qrcode.setText(qr_text)\n #\n # # print('qr code center:',\n # # qr_code.rect.left + qr_code.rect.width/2,\n # # qr_code.rect.top + qr_code.rect.height/2)\n # # print('qr code should be moved by these pixels:',\n # # qr_code.rect.left + qr_code.rect.width/2 - self.spinBox_zero_x.value(),\n # # qr_code.rect.top + qr_code.rect.height/2 - self.spinBox_zero_y.value())\n #\n # delta_x, delta_y = shift_stage_to_zero( qr_code.rect.left + qr_code.rect.width/2,\n # qr_code.rect.top + qr_code.rect.height/2,\n # self.spinBox_zero_x.value(),\n # self.spinBox_zero_y.value())\n # print('moving the giant_xy stage by (', delta_x, ',', delta_y, ')')\n # self.RE(bps.mvr(self.sample_stage.x, delta_x))\n # self.RE(bps.mvr(self.sample_stage.y, delta_y))\n # self.show_image()\n #\n # self.sample_x_zero_pos = self.sample_stage.x.read()[self.sample_stage.x.name]['value']\n # self.sample_y_zero_pos = self.sample_stage.y.read()[self.sample_stage.y.name]['value']\n #\n # self.spinBox_zero_x_rbk.setValue(self.sample_x_zero_pos)\n # self.spinBox_zero_y_rbk.setValue(self.sample_y_zero_pos)\n #\n # # need to change the (delta_first_holder_x, delta_first_holder_y) upon update\n # self.sample_positioner = SamplePositioner(self.sample_x_zero_pos,\n # self.sample_y_zero_pos,\n # 10.0, # delta_first_holder_x\n # 10.0, # delta_first_holder_y\n # self.RE,\n # self.sample_stage)\n #\n # self.settings.setValue('sample_stage_zero_x_pix', self.spinBox_zero_x.value())\n # self.settings.setValue('sample_stage_zero_y_pix', self.spinBox_zero_y.value())\n # self.settings.setValue('sample_stage_zero_x_rbk', self.spinBox_zero_x_rbk.value())\n # self.settings.setValue('sample_stage_zero_y_rbk', self.spinBox_zero_y_rbk.value())\n\n\n\n\n def move_to_sample(self):\n self._save_sample_index_settings()\n index_stack = self.spinBox_index_stack.value()\n index_holder = self.spinBox_index_holder.value()\n index_sample = self.spinBox_index_sample.value()\n self.sample_positioner.goto_sample(index_stack, index_holder, index_sample)\n self.RE(bps.sleep(0.1))\n self.show_image()\n\n\n def set_qr_roi(self, event):\n if event.button == 3:\n x, y = int(event.xdata), int(event.ydata)\n if self.qr_roi is None:\n self.qr_roi = [(x, y)]\n else:\n if len(self.qr_roi) == 1:\n self.qr_roi.append((x, y))\n self.settings.setValue('qr_roi_x1', self.qr_roi[0][0])\n self.settings.setValue('qr_roi_x2', self.qr_roi[1][0])\n self.settings.setValue('qr_roi_y1', self.qr_roi[0][1])\n self.settings.setValue('qr_roi_y2', self.qr_roi[1][1])\n\n elif len(self.qr_roi) == 2:\n self.qr_roi = [(x, y)]\n self.show_image()\n\n\n\n def plot_qr_roi(self):\n if self.qr_vlines:\n self.qr_vlines.remove()\n if self.qr_hlines:\n self.qr_hlines.remove()\n try:\n if self.qr_roi_patch:\n self.qr_roi_patch.remove()\n except ValueError:\n pass\n\n if self.qr_roi:\n xlim = self.figure_qr.ax.get_xlim()\n ylim = self.figure_qr.ax.get_ylim()\n xs = [i[0] for i in self.qr_roi]\n ys = [i[1] for i in self.qr_roi]\n self.qr_vlines = self.figure_qr.ax.vlines(xs, ylim[0], ylim[1], linestyles='--', colors='r', linewidths=0.5)\n self.qr_hlines = self.figure_qr.ax.hlines(ys, xlim[0], xlim[1], linestyles='--', colors='r', linewidths=0.5)\n if len(self.qr_roi) == 2:\n x1, x2 = self.qr_roi[0][0], self.qr_roi[1][0]\n y1, y2 = self.qr_roi[0][1], self.qr_roi[1][1]\n rect = patches.Rectangle((min(x1, x2), min(y1, y2)), abs(x1-x2), abs(y1-y2), linewidth=1, edgecolor='r', facecolor='none')\n\n self.qr_roi_patch = self.figure_qr.ax.add_patch(rect)\n\n\n\n\n def set_vcursor(self, event):\n # wrapper for separation of event and xdata\n if event.button == 3:\n self.beam_x_position_on_camera = event.xdata\n self.settings.setValue('beam_x_position_on_camera', self.beam_x_position_on_camera)\n self._set_vcursor()\n\n def _set_vcursor(self):\n xdata = self.beam_x_position_on_camera\n if self.h_vc:\n self.h_vc.remove()\n y1, y2 = self.figure_c2.ax.get_ylim()\n self.h_vc = self.figure_c2.ax.vlines(xdata, y1,y2, color = 'green' )\n self.canvas_c2.draw_idle()\n\n\n def set_hcursor(self, event):\n # wrapper for separation of event and ydata\n if event.button == 3:\n self.beam_y_position_on_camera = event.ydata\n self.settings.setValue('beam_y_position_on_camera', self.beam_y_position_on_camera)\n self._set_hcursor()\n\n\n def _set_hcursor(self):\n ydata = self.beam_y_position_on_camera\n if self.h_hc:\n self.h_hc.remove()\n x1, x2 = self.figure_c1.ax.get_xlim()\n self.h_hc = self.figure_c1.ax.hlines(ydata, x1, x2, color='green')\n self.canvas_c1.draw_idle()\n\n\n\n\n\n\n # def set_qr_cursor(self):\n # color = [0.0, 0.7, 0.0]\n # y_lo, y_hi = self.figure_qr.ax.get_xlim()\n # x_lo, x_hi = self.figure_qr.ax.get_ylim()\n # if self.qr_vc:\n # self.qr_vc.remove()\n # if self.qr_hc:\n # self.qr_hc.remove()\n #\n # self.qr_vc = self.figure_qr.ax.vlines(self.spinBox_zero_x.value(), x_lo, x_hi, colors=color, linewidths=0.5)\n # self.qr_hc = self.figure_qr.ax.hlines(self.spinBox_zero_y.value(), y_lo, y_hi, colors=color, linewidths=0.5)\n # self.figure_qr.ax.set_xlim(y_low, y_high)\n # self.figure_qr.ax.set_ylim(x_low, x_high)\n\n\n\n\n\n\n" ]
[ [ "matplotlib.figure.Figure", "matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg", "matplotlib.backends.backend_qt5agg.NavigationToolbar2QT", "numpy.percentile" ] ]
hlin09/metrics
[ "cceced613f4323a1f5124099a969f2cf32a80d7e" ]
[ "tests/classification/test_auc.py" ]
[ "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom collections import namedtuple\nfrom functools import partial\n\nimport numpy as np\nimport pytest\nfrom sklearn.metrics import auc as _sk_auc\nfrom torch import tensor\n\nfrom tests.helpers import seed_all\nfrom tests.helpers.testers import NUM_BATCHES, MetricTester\nfrom torchmetrics.classification.auc import AUC\nfrom torchmetrics.functional import auc\n\nseed_all(42)\n\n\ndef sk_auc(x, y, reorder=False):\n x = x.flatten()\n y = y.flatten()\n if reorder:\n idx = np.argsort(x, kind='stable')\n x = x[idx]\n y = y[idx]\n return _sk_auc(x, y)\n\n\nInput = namedtuple('Input', [\"x\", \"y\"])\n\n_examples = []\n# generate already ordered samples, sorted in both directions\nfor batch_size in (8, 4049):\n for i in range(4):\n x = np.random.rand((NUM_BATCHES * batch_size))\n y = np.random.rand((NUM_BATCHES * batch_size))\n idx = np.argsort(x, kind='stable')\n x = x[idx] if i % 2 == 0 else x[idx[::-1]]\n y = y[idx] if i % 2 == 0 else x[idx[::-1]]\n x = x.reshape(NUM_BATCHES, batch_size)\n y = y.reshape(NUM_BATCHES, batch_size)\n _examples.append(Input(x=tensor(x), y=tensor(y)))\n\n\[email protected](\"x, y\", _examples)\nclass TestAUC(MetricTester):\n\n @pytest.mark.parametrize(\"ddp\", [False])\n @pytest.mark.parametrize(\"dist_sync_on_step\", [True, False])\n def test_auc(self, x, y, ddp, dist_sync_on_step):\n self.run_class_metric_test(\n ddp=ddp,\n preds=x,\n target=y,\n metric_class=AUC,\n sk_metric=sk_auc,\n dist_sync_on_step=dist_sync_on_step,\n )\n\n @pytest.mark.parametrize(\"reorder\", [True, False])\n def test_auc_functional(self, x, y, reorder):\n self.run_functional_metric_test(\n x, y, metric_functional=auc, sk_metric=partial(sk_auc, reorder=reorder), metric_args={\"reorder\": reorder}\n )\n\n\[email protected](['x', 'y', 'expected'], [\n pytest.param([0, 1], [0, 1], 0.5),\n pytest.param([1, 0], [0, 1], 0.5),\n pytest.param([1, 0, 0], [0, 1, 1], 0.5),\n pytest.param([0, 1], [1, 1], 1),\n pytest.param([0, 0.5, 1], [0, 0.5, 1], 0.5),\n])\ndef test_auc(x, y, expected):\n # Test Area Under Curve (AUC) computation\n assert auc(tensor(x), tensor(y), reorder=True) == expected\n" ]
[ [ "sklearn.metrics.auc", "torch.tensor", "numpy.argsort", "numpy.random.rand" ] ]
PEtab-dev/petab_test_suite
[ "1ff2d0c895dec90bd519e72ec226acb7573b54c9" ]
[ "petabtests/cases/0015/0015.py" ]
[ "from petabtests import *\nfrom petab.C import *\nimport petab\n\nimport pandas as pd\n\n\ntest_id = 15\n\n# problem --------------------------------------------------------------------\n\nmodel = DEFAULT_SBML_FILE\n\ncondition_df = pd.DataFrame(data={\n CONDITION_ID: ['c0'],\n}).set_index([CONDITION_ID])\n\nmeasurement_df = pd.DataFrame(data={\n OBSERVABLE_ID: ['obs_a', 'obs_a'],\n SIMULATION_CONDITION_ID: ['c0', 'c0'],\n TIME: [0, 10],\n MEASUREMENT: [0.7, 0.1],\n NOISE_PARAMETERS: ['noise', 'noise']\n})\n\nobservable_df = pd.DataFrame(data={\n OBSERVABLE_ID: ['obs_a'],\n OBSERVABLE_FORMULA: ['A'],\n NOISE_FORMULA: ['noiseParameter1_obs_a']\n}).set_index([OBSERVABLE_ID])\n\nparameter_df = pd.DataFrame(data={\n PARAMETER_ID: ['a0', 'b0', 'k1', 'k2', 'noise'],\n PARAMETER_SCALE: [LIN] * 5,\n LOWER_BOUND: [0] * 5,\n UPPER_BOUND: [10] * 5,\n NOMINAL_VALUE: [1, 0, 0.8, 0.6, 5],\n ESTIMATE: [1] * 5,\n}).set_index(PARAMETER_ID)\n\n\n# solutions ------------------------------------------------------------------\n\nsimulation_df = measurement_df.copy(deep=True).rename(\n columns={MEASUREMENT: SIMULATION})\nsimulation_df[SIMULATION] = [analytical_a(t, 1, 0, 0.8, 0.6)\n for t in simulation_df[TIME]]\n\nchi2 = petab.calculate_chi2(\n measurement_df, simulation_df, observable_df, parameter_df)\n\nllh = petab.calculate_llh(\n measurement_df, simulation_df, observable_df, parameter_df)\nprint(llh)\n" ]
[ [ "pandas.DataFrame" ] ]
shonaka/pytorch_challenge
[ "6e7d357e1ec1f01687664714efa2f04e64014f94" ]
[ "main.py" ]
[ "\"\"\"\nMain file for PyTorch Challenge Final Project\n\"\"\"\nfrom __future__ import print_function, division\nimport json\nimport yaml\nimport time\nimport torch\nimport optuna\nfrom torchvision import transforms\nfrom pathlib import Path\nfrom torchsummary import summary\nfrom torchvision import models\n# Custom functions and classes\nfrom trainer.trainer import train_and_eval, objective\nfrom utils.arg_yaml import get_args, get_parser\nfrom utils.util import download_data, check_dir_and_create\nfrom utils.logfun import set_logger, timer\nfrom utils.visualization import fig_loss_acc\nfrom data_loader.data_loaders import create_dataloader\nfrom model.model import SimpleCNN, Pretrained\n# Just for debugging purpose. You could delete this later.\nimport pdb\n\n\nif __name__ == '__main__':\n # Get the default and specified arguments\n args = get_args(get_parser(\"config.yaml\"))\n\n # Defining a name for the model to be saved\n header = args.trial + '_' + args.model_type\n model_name = header + '.pth.tar'\n\n # Specifying some paths\n DATA_DIR = Path(\"data\")\n RESULTS_DIR = Path(\"results\") / header\n LOG_DIR = RESULTS_DIR / \"logs\"\n FIG_DIR = RESULTS_DIR / \"figures\"\n # Just checking if the directory exists, if not creating\n check_dir_and_create(str(DATA_DIR))\n check_dir_and_create(str(RESULTS_DIR))\n check_dir_and_create(str(LOG_DIR))\n check_dir_and_create(str(FIG_DIR))\n\n # Custom function for logging\n log = set_logger(str(LOG_DIR), args.log_name)\n\n # Using a custom function to download the data\n download_data(data_dir=DATA_DIR, data_name=args.file_name, zip_name=args.zip_name, url=args.url)\n\n # Use GPU if available\n torch_gpu = torch.cuda.is_available()\n\n # Directories to training and validation\n directories = {x: DATA_DIR / args.file_name / x for x in ['train', 'valid']}\n # If you were to use transfer learning on pre-trained network that was trained on\n # ImageNet, you need to specifically use the following normalization parameters\n # https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html\n if args.model_type == 'simplecnn':\n normalization = transforms.Normalize(\n mean=[0.5, 0.5, 0.5],\n std=[0.5, 0.5, 0.5]\n )\n else:\n normalization = transforms.Normalize(\n mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]\n )\n d_size, d_loaders = create_dataloader(normalization, directories, batch_size=args.batch_size)\n\n # Get some other parameters\n num_classes = len(d_loaders['train'].dataset.classes)\n\n # Logging some information\n log.info(\"PyTorch version: {}\".format(torch.__version__))\n log.info(\"Model using: {}\".format(args.model_type))\n log.info(\"Hyperparameter optimization: {}\".format(args.optuna_tune))\n log.info(\"Batch size: {}\".format(args.batch_size))\n log.info(\"Using GPU: {}\".format(str(torch_gpu)))\n log.info(\"Number of training samples: {}\".format(len(d_loaders['train'].dataset.samples)))\n log.info(\"Number of classes: {}\".format(num_classes))\n log.info(\"Dimensions of an image: {}\".format(str(next(iter(d_loaders['train']))[0].shape)))\n\n # Loading labels provided by Udacity\n # https://github.com/udacity/pytorch_challenge\n with open('cat_to_name.json', 'r') as f:\n cat_to_name = json.load(f)\n\n # Building a model\n params = {\n 'nc': num_classes,\n }\n\n # Define the model\n if args.model_type == 'simplecnn':\n model = SimpleCNN(args, params)\n else:\n model = Pretrained(args, params)\n # Make sure to put the model into GPU\n model.cuda() if torch_gpu else model.cpu()\n # Using multiple GPUs\n model = torch.nn.DataParallel(model)\n\n # Good for checking the architecture\n summary(model, input_size=(3, 224, 224), batch_size=args.batch_size)\n\n # A function to perform training and validation\n log.info(\"Start Training\")\n start = time.time()\n if args.optuna_tune:\n # Running hyperparameter optimization using optuna\n # n_warmup_steps = 10 to at least run 10 epochs before deciding to prune\n study = optuna.create_study(pruner=optuna.pruners.MedianPruner(n_warmup_steps=10))\n # use lambda if you want to pass more agruments other than the \"trial\"\n study.optimize(lambda trial: objective(trial, params, d_size, d_loaders, torch_gpu, args),\n n_trials=args.optuna_trials)\n # after the optimization, this is how you get the best parameters\n best_params = study.best_params\n # The best error_rate\n best_error = study.best_value\n log.info(\"Best params are: {}\".format(str(best_params)))\n log.info(\"Best error_rate is: {:.4f}\".format(best_error))\n # now running with the best parameters for saving results purposes\n # TODO: optimize this part a little, I shouldn't have to run twice\n # TODO: make parsing of the best parameters automatic as well\n args.optim_lr = float(best_params['lr'])\n args.optim_type = str(best_params['optimizer'])\n args.optim_amsgrad = bool(best_params['amsgrad'])\n args.optim_weight_decay = float(best_params['weight_decay'])\n log.info(\"Final testing with the best parameters\")\n t_loss, t_acc, v_loss, v_acc = train_and_eval(model,\n d_size,\n d_loaders,\n torch_gpu,\n log,\n args)\n else:\n t_loss, t_acc, v_loss, v_acc = train_and_eval(model,\n d_size,\n d_loaders,\n torch_gpu,\n log,\n args)\n end = time.time()\n log.info(\"Finsihed Training\")\n hours, mins, seconds = timer(start, end)\n log.info(\"Training and testing took: {:0>2} Hours {:0>2} minutes {:05.2f} seconds\".format(int(hours), int(mins), seconds))\n\n # Save the model\n torch.save(model.state_dict(), str(RESULTS_DIR / model_name))\n\n # Log the results and save the figures\n fig_loss_acc(t_loss, v_loss, \"loss\", FIG_DIR)\n fig_loss_acc(t_acc, v_acc, \"acc\", FIG_DIR)\n\n # Log the parameters and results\n dict_params = vars(args)\n dict_params['final_train_loss'] = round(t_loss[-1], 4)\n dict_params['final_train_acc'] = round(t_acc[-1], 4)\n dict_params['final_valid_loss'] = round(v_loss[-1], 4)\n dict_params['final_valid_acc'] = round(v_acc[-1], 4)\n print(type(dict_params))\n print(dict_params)\n with open(str(RESULTS_DIR / \"results.yaml\"), 'w') as output_file:\n yaml.dump(dict_params, output_file, default_flow_style=False)\n with open(str(RESULTS_DIR / \"results.json\"), 'w') as output_file:\n json.dump(dict_params, output_file)\n" ]
[ [ "torch.nn.DataParallel", "torch.cuda.is_available" ] ]
PeterouZh/SemiNAS
[ "41e044b49bc7fbc3cfb832ebef988fb690024b2e" ]
[ "tts/tasks.py" ]
[ "import os\nimport sys\nimport json\nimport logging\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nmatplotlib.use('Agg')\nimport torch\nfrom torch import nn\nimport torch.optim\nimport torch.utils.data\nimport torch.nn.functional as F\nimport utils\nimport logging\nfrom text_encoder import TokenTextEncoder\nfrom preprocessor import _process_utterance\nimport audio\nimport model, model_ws\n\n\ndef collate(samples, pad_idx, eos_idx):\n if len(samples) == 0:\n return {}\n\n id = torch.LongTensor([s['id'] for s in samples])\n utt_id = torch.LongTensor([s['utt_id'] for s in samples]) if samples[0]['utt_id'] is not None else None\n text = [s['text'] for s in samples] if samples[0]['text'] is not None else None\n src_tokens = utils.collate_tokens([s['source'] for s in samples], pad_idx)\n target = utils.collate_mels([s['target'] for s in samples], pad_idx) if samples[0]['target'] is not None else None\n prev_output_mels = utils.collate_mels([s['target'] for s in samples], pad_idx, shift_right=True) if target is not None else None\n # sort by descending source length\n src_lengths = torch.LongTensor([s['source'].numel() for s in samples])\n target_lengths = torch.LongTensor([s['target'].shape[0] for s in samples]) if target is not None else None\n if target is not None and target_lengths is not None:\n target_lengths, sort_order = target_lengths.sort(descending=True)\n target = target.index_select(0, sort_order)\n prev_output_mels = prev_output_mels.index_select(0, sort_order)\n src_tokens = src_tokens.index_select(0, sort_order)\n src_lengths = src_lengths.index_select(0, sort_order)\n else:\n src_lengths, sort_order = src_lengths.sort(descending=True) \n src_tokens = src_tokens.index_select(0, sort_order)\n id = id.index_select(0, sort_order)\n utt_id = utt_id.index_select(0, sort_order) if utt_id is not None else None\n text = [text[i] for i in sort_order] if text is not None else None\n ntokens = sum(len(s['source']) for s in samples)\n nmels = sum(len(s['target']) for s in samples) if target is not None else None\n \n batch = {\n 'id': id,\n 'utt_id': utt_id,\n 'nsamples': len(samples),\n 'ntokens': ntokens,\n 'nmels': nmels,\n 'text': text,\n 'src_tokens': src_tokens,\n 'src_lengths': src_lengths,\n 'targets': target,\n 'target_lengths': target_lengths,\n 'prev_output_mels': prev_output_mels\n }\n return batch\n\n\nclass LJSpeechRawDataset(torch.utils.data.Dataset):\n def __init__(self, data_dir, model_hparams, phone_encoder, utt_ids=None, shuffle=False):\n super().__init__()\n self.model_hparams = model_hparams\n self.phone_encoder = phone_encoder\n self.shuffle = shuffle\n\n self.utt_ids = None\n self.texts = None\n self.phones = None\n self.mels = None\n self.sizes = None \n self.read_data(data_dir, utt_ids)\n\n def produce_result(self, utt_id, text, phone, mel):\n phones = phone.split(\" \")\n phones += ['|']\n phones = ' '.join(phones)\n try:\n utt_id = int(utt_id)\n phone_encoded = torch.LongTensor(self.phone_encoder.encode(phones) + [self.phone_encoder.eos()])\n mel = torch.Tensor(mel.T) #(T*80)\n except Exception as e:\n logging.info('{} {}'.format(e, text))\n return None\n\n return utt_id, text, phone_encoded, mel\n\n def read_data(self, data_dir, utt_ids=None):\n data_df = pd.read_csv(os.path.join(data_dir, 'metadata_phone.csv'))\n self.utt_ids = []\n self.texts = []\n self.phones = []\n self.mels = []\n self.sizes = [] \n if utt_ids is None:\n for idx, r in data_df.iterrows():\n utt_id, text, phone, mel = self.produce_result(idx, r['txt2'], r['phone2'], self.process_wav(data_dir, r['wav'])[1])\n self.utt_ids.append(utt_id)\n self.texts.append(text)\n self.phones.append(phone)\n self.mels.append(mel)\n self.sizes.append(len(mel))\n else:\n for utt_id in utt_ids:\n r = data_df.iloc[utt_id]\n utt_id, text, phone, mel = self.produce_result(utt_id, r['txt2'], r['phone2'], self.process_wav(data_dir, r['wav'])[1])\n self.utt_ids.append(utt_id)\n self.texts.append(text)\n self.phones.append(phone)\n self.mels.append(mel)\n self.sizes.append(len(mel))\n \n def __getitem__(self, index):\n sample = {\"id\": index, \n \"utt_id\": self.utt_ids[index] if self.utt_ids is not None else None,\n \"text\": self.texts[index] if self.texts is not None else None,\n \"source\": self.phones[index] if self.phones is not None else None,\n \"target\": self.mels[index] if self.mels is not None else None}\n return sample\n\n def __len__(self):\n return len(self.sizes)\n\n def collater(self, samples):\n return collate(\n samples, pad_idx=self.phone_encoder.pad(), eos_idx=self.phone_encoder.eos()\n )\n\n def num_tokens(self, index):\n return self.size(index)\n\n def size(self, index):\n \"\"\"Return an example's size as a float or tuple. This value is used when\n filtering a dataset with ``--max-positions``.\"\"\"\n return min(self.sizes[index], self.model_hparams.max_sample_size)\n\n def ordered_indices(self):\n \"\"\"Return an ordered list of indices. Batches will be constructed based\n on this order.\"\"\"\n if self.shuffle:\n indices = np.random.permutation(len(self))\n else:\n indices = np.arange(len(self))\n return indices[np.argsort(np.array(self.sizes)[indices], kind='mergesort')]\n\n\nclass LJSpeechDataset(LJSpeechRawDataset):\n def __init__(self, data_dir, prefix, model_hparams, phone_encoder, shuffle=False):\n super().__init__(data_dir, model_hparams, phone_encoder, prefix, shuffle)\n\n def read_data(self, data_dir, prefix):\n if os.path.exists(os.path.join(data_dir, '{}.idx'.format(prefix))):\n with open(os.path.join(data_dir, '{}.idx'.format(prefix)), 'r') as f:\n self.utt_ids = [int(line) for line in f.readlines()]\n if os.path.exists(os.path.join(data_dir, '{}.text'.format(prefix))):\n with open(os.path.join(data_dir, '{}.text'.format(prefix)), 'r') as f:\n self.texts = [line.strip() for line in f.readlines()]\n if os.path.exists(os.path.join(data_dir, '{}.phone'.format(prefix))):\n with open(os.path.join(data_dir, '{}.phone'.format(prefix)), 'r') as f:\n self.phones = [torch.LongTensor(list(map(int, line.strip().split()))) for line in f.readlines()]\n if os.path.exists(os.path.join(data_dir, '{}.mel'.format(prefix))):\n with open(os.path.join(data_dir, '{}.mel'.format(prefix)), 'rb') as f:\n mels = np.load(f, allow_pickle=True)\n self.mels = [torch.Tensor(mel) for mel in mels]\n\n if self.mels:\n self.sizes = [len(mel) for mel in self.mels]\n else:\n self.sizes =[len(text) for text in self.texts]\n \n\ndef set_ljspeech_hparams(model_hparams):\n model_hparams.max_sample_size = 1500\n model_hparams.symbol_size = None\n model_hparams.save_npz = False\n model_hparams.audio_num_mel_bins = 80\n model_hparams.audio_sample_rate = 22050\n model_hparams.num_freq = 513 # (= n_fft / 2 + 1) only used when adding linear spectrograms post processing network\n model_hparams.hop_size = 256 # For 22050Hz, 275 ~= 12.5 ms (0.0125 * sample_rate)\n model_hparams.win_size = 1024 # For 22050Hz, 1100 ~= 50 ms (If None, win_size = n_fft) (0.05 * sample_rate)\n model_hparams.fmin = 0 # Set this to 55 if your speaker is male! if female, 95 should help taking off noise. (To test depending on dataset. Pitch info: male~[65, 260], female~[100, 525])\n model_hparams.fmax = 8000 # To be increased/reduced depending on data.\n model_hparams.n_fft = 1024 # Extra window size is filled with 0 paddings to match this parameter\n model_hparams.min_level_db = -100\n model_hparams.ref_level_db = 20\n # Griffin Lim\n model_hparams.power = 1.5 # Only used in G&L inversion, usually values between 1.2 and 1.5 are a good choice.\n model_hparams.magnitude_power = 1 # The power of the spectrogram magnitude (1. for energy, 2. for power)\n model_hparams.griffin_lim_iters = 60 # Number of G&L iterations, typically 30 is enough but we use 60 to ensure convergence.\n\n # #M-AILABS (and other datasets) trim params (there parameters are usually correct for any data, but definitely must be tuned for specific speakers)\n model_hparams.trim_fft_size = 512\n model_hparams.trim_hop_size = 128\n model_hparams.trim_top_db = 23\n model_hparams.frame_shift_ms = None # Can replace hop_size parameter. (Recommended: 12.5)\n model_hparams.use_lws = False\n model_hparams.silence_threshold = 2 # silence threshold used for sound trimming for wavenet preprocessing\n model_hparams.trim_silence = True # Whether to clip silence in Audio (at beginning and end of audio only, not the middle)\n model_hparams.vocoder = 'gl'\n model_hparams.preemphasize = False # whether to apply filter\n model_hparams.preemphasis = 0.97 # filter coefficient.\n\n\nclass RSQRTSchedule(object):\n def __init__(self, args, optimizer):\n super().__init__()\n self.optimizer = optimizer\n self.constant_lr = args.lr \n self.warmup_updates = args.warmup_updates\n self.hidden_size = args.hidden_size\n self.lr = args.lr\n for param_group in optimizer.param_groups:\n param_group['lr'] = self.lr\n\n def step(self, num_updates):\n constant_lr = self.constant_lr\n warmup = min(num_updates / self.warmup_updates, 1.0)\n rsqrt_decay = max(self.warmup_updates, num_updates)**-0.5\n rsqrt_hidden = self.hidden_size**-0.5\n self.lr = constant_lr * warmup * rsqrt_decay * rsqrt_hidden\n for param_group in self.optimizer.param_groups:\n param_group['lr'] = self.lr\n return self.lr\n\n def get_lr(self):\n return self.optimizer.param_groups[0]['lr']\n\n\nclass LJSpeechTask(object):\n\n def __init__(self, args):\n #set_ljspeech_hparams(args)\n self.args = args\n self.ws = getattr(args, 'ws', False)\n self.arch = getattr(args, 'arch', None)\n self.data_dir = args.data_dir\n self.output_dir = args.output_dir\n self.max_tokens = args.max_tokens\n self.max_sentences = args.max_sentences\n self.max_eval_tokens = args.max_eval_tokens if getattr(args, 'max_eval_tokens', None) is not None else self.max_tokens\n self.max_eval_sentences = args.max_eval_sentences if getattr(args, 'max_eval_sentences', None) is not None else self.max_sentences\n if isinstance(self.arch, str):\n self.arch = list(map(int, self.arch.strip().split()))\n if self.arch is not None:\n self.num_heads = utils.get_num_heads(self.arch[args.enc_layers:])\n \n def setup_task(self, model_state_dict=None, optimizer_state_dict=None, ws=False):\n self.phone_encoder = self.build_phone_encoder(self.data_dir)\n self.train_dataset, self.valid_dataset, self.test_dataset = self.build_dataset(self.data_dir, self.args.raw_data)\n self.train_queue = self.build_queue(self.train_dataset, True, self.max_tokens, self.max_sentences)\n self.valid_queue = self.build_queue(self.valid_dataset, False, self.max_eval_tokens, self.max_eval_sentences)\n self.test_queue = self.build_queue(self.test_dataset, False, self.max_eval_tokens, self.max_eval_sentences)\n self.model = self.build_model(arch=self.arch, model_state_dict=model_state_dict, ws=self.ws | ws)\n self.optimizer = self.build_optimizer(optimizer_state_dict=optimizer_state_dict)\n self.scheduler = self.build_scheduler()\n self.padding_idx = self.phone_encoder.pad()\n self.eos_idx = self.phone_encoder.eos()\n self.seg_idx = self.phone_encoder.seg()\n #if torch.cuda.device_count() > 1:\n # torch.distributed.init_process_group(backend='nccl')\n\n def setup_search_task(self):\n self.phone_encoder = self.build_phone_encoder(self.data_dir)\n self.train_dataset, self.valid_dataset, self.test_dataset = self.build_dataset(self.data_dir, self.args.raw_data)\n self.train_queue = self.build_queue(self.train_dataset, True, self.max_tokens, self.max_sentences)\n self.valid_queue = self.build_queue(self.valid_dataset, False, self.max_eval_tokens, self.max_eval_sentences)\n self.test_queue = self.build_queue(self.test_dataset, False, self.max_eval_tokens, self.max_eval_sentences)\n self.padding_idx = self.phone_encoder.pad()\n self.eos_idx = self.phone_encoder.eos()\n self.seg_idx = self.phone_encoder.seg()\n\n def build_model(self, arch=None, model_state_dict=None, ws=False):\n if arch is None:\n arch = self.arch\n assert (arch is not None) ^ ws, 'arch and ws are mutual'\n if ws:\n _model = model_ws.NASNetwork(self.args, self.phone_encoder)\n else:\n _model = model.NASNetwork(self.args, arch, self.phone_encoder)\n if model_state_dict is not None:\n _model.load_state_dict(model_state_dict)\n if torch.cuda.is_available():\n if torch.cuda.device_count() > 1:\n _model = nn.DataParallel(_model)\n _model = _model.cuda()\n return _model\n\n def build_optimizer(self, model=None, optimizer_state_dict=None):\n if model is None:\n model = self.model\n optimizer = torch.optim.AdamW(\n model.parameters(),\n lr=self.args.lr,\n betas=(self.args.optimizer_adam_beta1, self.args.optimizer_adam_beta2),\n weight_decay=self.args.weight_decay)\n if optimizer_state_dict is not None:\n optimizer.load_state_dict(optimizer_state_dict)\n return optimizer\n\n def build_scheduler(self, optimizer=None):\n if optimizer is None:\n optimizer = self.optimizer\n return RSQRTSchedule(self.args, optimizer)\n\n def build_phone_encoder(self, data_dir):\n phone_list_file = os.path.join(data_dir, 'phone_set.json')\n phone_list = json.load(open(phone_list_file))\n return TokenTextEncoder(None, vocab_list=phone_list)\n\n def split_train_test_set(self, data_dir, test_num=500):\n data_file_name = 'metadata_phone.csv'\n data_df = pd.read_csv(os.path.join(data_dir, data_file_name))\n total_num = len(data_df.index)\n train_uttids = [i for i in np.arange(0, total_num)]\n test_uttids = []\n for _ in range(test_num):\n random_index = int(np.random.randint(0, len(train_uttids)))\n test_uttids.append(train_uttids[random_index])\n del train_uttids[random_index]\n\n logging.info(\">>test {}\".format(len(test_uttids)))\n logging.info(\">>train {}\".format(len(train_uttids)))\n logging.info(\">>total {}\".format(len(list(set(test_uttids + train_uttids)))))\n return train_uttids, test_uttids\n\n def build_dataset(self, data_dir, raw_data):\n if raw_data:\n train_utt_ids, test_utt_ids = self.split_train_test_set(data_dir)\n train_dataset = LJSpeechRawDataset(data_dir, self.args, self.phone_encoder, utt_ids=train_utt_ids, shuffle=True)\n test_dataset = LJSpeechRawDataset(data_dir, self.args, self.phone_encoder, utt_ids=test_utt_ids, shuffle=False)\n valid_dataset = test_dataset\n else:\n train_dataset = LJSpeechDataset(data_dir, 'train', self.args, self.phone_encoder, shuffle=True)\n valid_dataset = LJSpeechDataset(data_dir, 'valid', self.args, self.phone_encoder, shuffle=False)\n test_dataset = LJSpeechDataset(data_dir, 'test', self.args, self.phone_encoder, shuffle=False)\n return train_dataset, valid_dataset, test_dataset\n\n def build_queue(self, dataset, shuffle, max_tokens=None, max_sentences=None, required_batch_size_multiple=8):\n def shuffle_batches(batches):\n np.random.shuffle(batches)\n return batches\n\n if max_tokens is not None:\n max_tokens *= torch.cuda.device_count()\n if max_sentences is not None:\n max_sentences *= torch.cuda.device_count()\n indices = dataset.ordered_indices()\n batch_sampler = utils.batch_by_size(\n indices, dataset.num_tokens, max_tokens=max_tokens, max_sentences=max_sentences,\n required_batch_size_multiple=required_batch_size_multiple,\n )\n if shuffle:\n batches = shuffle_batches(list(batch_sampler))\n else:\n batches = batch_sampler\n return torch.utils.data.DataLoader(dataset, collate_fn=dataset.collater, batch_sampler=batches, num_workers=8)\n\n def remove_padding(self, x, hit_eos=None):\n if x is None:\n return None\n if len(x.shape) == 1: # wav\n hit_eos = np.sum(~hit_eos)\n hit_eos = (hit_eos - 1) * self.args.hop_size + self.args.win_size\n return x[:hit_eos]\n if x.shape[1] > 1: # mel\n if len(x.shape) == 3:\n x = x[:, :, :1]\n if hit_eos is not None:\n return x[~hit_eos]\n else:\n return x[np.abs(x).sum(1).reshape(-1) != 0]\n else: # text\n if len(np.where(x <= 1)[0]) > 0:\n x = x[:np.where(x <= 1)[0][0]]\n return x\n\n def weights_nonzero_speech(self, target):\n # target : B x T x mel\n # Assign weight 1.0 to all labels except for padding (id=0).\n dim = target.size(-1)\n return target.abs().sum(-1, keepdim=True).ne(0).float().repeat(1, 1, dim)\n\n def make_stop_target(self, target):\n # target : B x T x mel\n seq_mask = target.abs().sum(-1).ne(0).float()\n seq_length = seq_mask.sum(1)\n mask_r = 1 - utils.sequence_mask(seq_length - 1, target.size(1)).float()\n return seq_mask, mask_r\n\n def weighted_cross_entropy_with_logits(self, targets, logits, pos_weight=1):\n x = logits\n z = targets\n q = pos_weight\n l = 1 + (q - 1) * z\n return (1 - z) * x + l * (torch.log(1 + torch.exp(-x.abs())) + F.relu(-x))\n\n def loss(self, decoder_output, target):\n # decoder_output : B x T x (mel+1)\n # target : B x T x mel\n if target is None:\n return {\n 'decoder loss': decoder_output.new(1).fill_(0)[0],\n 'stop loss': decoder_output.new(1).fill_(0)[0],\n }\n\n predicted_mel = decoder_output[:, :, :self.args.audio_num_mel_bins]\n predicted_stop = decoder_output[:, :, -1]\n seq_mask, stop_mask = self.make_stop_target(target)\n\n decoder_loss = F.mse_loss(predicted_mel, target, reduction='none')\n weights = self.weights_nonzero_speech(target)\n decoder_loss = (decoder_loss * weights).sum() / weights.sum()\n stop_loss = (self.weighted_cross_entropy_with_logits(stop_mask, predicted_stop, self.args.stop_token_weight) * seq_mask).sum()\n stop_loss = stop_loss / (seq_mask.sum() + target.size(0) * (self.args.stop_token_weight - 1))\n \n return {\n 'decoder loss': decoder_loss,\n 'stop loss': stop_loss,\n }\n\n def train(self, model=None, optimizer=None, scheduler=None, epoch=1, num_updates=0, arch_pool=None, arch_pool_prob=None):\n if model is None:\n model = self.model\n if optimizer is None:\n optimizer = self.optimizer\n if scheduler is None:\n scheduler = self.scheduler\n \n decoder_loss_obj = utils.AvgrageMeter()\n stop_loss_obj = utils.AvgrageMeter()\n loss_obj = utils.AvgrageMeter()\n model.train()\n for step, sample in enumerate(self.train_queue):\n num_updates += 1\n scheduler.step(num_updates)\n input = utils.move_to_cuda(sample['src_tokens'])\n prev_output_mels = utils.move_to_cuda(sample['prev_output_mels'])\n target = utils.move_to_cuda(sample['targets'])\n optimizer.zero_grad()\n\n if arch_pool is not None:# ws train\n arch = utils.sample_arch(arch_pool, arch_pool_prob)\n output, _ = model(input, prev_output_mels, target, arch)\n else:# normal train\n output, _ = model(input, prev_output_mels, target)\n loss_output = self.loss(output, target)\n decoder_loss = loss_output['decoder loss']\n stop_loss = loss_output['stop loss']\n total_loss = decoder_loss + stop_loss\n total_loss.backward()\n nn.utils.clip_grad_norm_(model.parameters(), self.args.clip_grad_norm)\n optimizer.step()\n\n n = sample['nmels']\n decoder_loss_obj.update(decoder_loss.data, n)\n stop_loss_obj.update(stop_loss.data, n)\n loss_obj.update(total_loss.data, n)\n\n if (step+1) % self.args.log_interval == 0:\n lr = scheduler.get_lr()\n log_output = 'train {}@{} global step {} lr {:.6f} decoder loss {:.6f} stop loss {:.6f} total loss {:.6f}'.format(\n epoch, step+1, num_updates, lr, decoder_loss_obj.avg, stop_loss_obj.avg, loss_obj.avg)\n if arch_pool is not None:\n log_output = 'arch {}\\n'.format(arch) + log_output\n logging.info(log_output)\n\n return decoder_loss_obj.avg, stop_loss_obj.avg, loss_obj.avg, num_updates\n\n def valid(self, model=None):\n if model is None:\n model = self.model\n\n decoder_loss_obj = utils.AvgrageMeter()\n stop_loss_obj = utils.AvgrageMeter()\n loss_obj = utils.AvgrageMeter()\n fr_obj = utils.AvgrageMeter()\n pcr_obj = utils.AvgrageMeter()\n dfr_obj = utils.AvgrageMeter()\n model.eval()\n with torch.no_grad():\n for step, sample in enumerate(self.test_queue):\n input = utils.move_to_cuda(sample['src_tokens'])\n prev_output_mels = utils.move_to_cuda(sample['prev_output_mels'])\n target = utils.move_to_cuda(sample['targets'])\n if target is not None:\n output, attn_logits = model(input, prev_output_mels, target)\n else:\n bsz = input.size(0)\n max_input_len = input.size(1)\n if type(model) is nn.DataParallel:\n model = model.module\n decode_length = self.estimate_decode_length(max_input_len)\n encoder_outputs = model.forward_encoder(input)\n encoder_out = encoder_outputs['encoder_out']\n encoder_padding_mask = encoder_outputs['encoder_padding_mask']\n decoder_input = input.new(bsz, decode_length+1, self.args.audio_num_mel_bins).fill_(self.padding_idx).float()\n output = input.new(bsz, 0, self.args.audio_num_mel_bins+1).fill_(self.padding_idx).float()\n hit_eos = input.new(bsz, 1).fill_(0).bool()\n stop_logits = input.new(bsz, 0).fill_(0).float()\n encdec_attn_logits = []\n num_heads = self.num_heads\n for i in range(self.args.dec_layers):\n encdec_attn_logits.append(input.new(bsz, num_heads[i], 0, max_input_len).fill_(0).float())\n incremental_state = {}\n for step in range(decode_length):\n decoder_output, attn_logits = model.forward_decoder(decoder_input[:, :step+1], encoder_out, encoder_padding_mask, incremental_state=incremental_state)\n next_mel = decoder_output[:, -1:, :self.args.audio_num_mel_bins]\n stop_logit = decoder_output[:, -1:, -1]\n stop_logits = torch.cat((stop_logits, stop_logit), dim=1)\n output = torch.cat((output, decoder_output), dim=1)\n for i in range(self.args.dec_layers):\n encdec_attn_logits[i] = torch.cat((encdec_attn_logits[i], attn_logits[i]), dim=2)\n decoder_input[:, step+1] = next_mel[:, -1]\n attn_logits = encdec_attn_logits\n this_hit_eos = hit_eos[:, -1:]\n this_hit_eos |= torch.sigmoid(stop_logit) > 0.5\n hit_eos = torch.cat((hit_eos, this_hit_eos), dim=1)\n\n\n loss_output = self.loss(output, target)\n decoder_loss = loss_output['decoder loss']\n stop_loss = loss_output['stop loss']\n total_loss = decoder_loss + stop_loss\n \n n = sample['nmels'] if sample['nmels'] is not None else sample['nsamples']\n decoder_loss_obj.update(decoder_loss.data, n)\n stop_loss_obj.update(stop_loss.data, n)\n loss_obj.update(total_loss.data, n)\n \n encdec_attn = utils.select_attn(attn_logits)\n \n src_lengths = utils.move_to_cuda(sample['src_lengths']) #- 1 # exclude eos\n if target is not None:\n target_lengths = utils.move_to_cuda(sample['target_lengths'])\n target_padding_mask = target.abs().sum(-1).eq(self.padding_idx)\n else:\n hit_eos = hit_eos[:, 1:]\n target_lengths = (1.0 - hit_eos.float()).sum(dim=-1)\n target_padding_mask = output[:, :, :self.args.audio_num_mel_bins].abs().sum(-1).eq(self.padding_idx)\n src_padding_mask = input.eq(self.padding_idx)# | input.eq(self.eos_idx) # also exclude eos\n src_seg_mask = input.eq(self.seg_idx)\n focus_rate = utils.get_focus_rate(encdec_attn, src_padding_mask, target_padding_mask).mean()\n phone_coverage_rate = utils.get_phone_coverage_rate(encdec_attn, src_padding_mask, src_seg_mask, target_padding_mask).mean()\n attn_ks = src_lengths.float() / target_lengths.float()\n diagonal_focus_rate = utils.get_diagonal_focus_rate(encdec_attn, attn_ks, target_lengths, src_padding_mask, target_padding_mask).mean()\n\n fr_obj.update(focus_rate.data, sample['nsamples'])\n pcr_obj.update(phone_coverage_rate.data, sample['nsamples'])\n dfr_obj.update(diagonal_focus_rate.data, sample['nsamples'])\n\n return decoder_loss_obj.avg, stop_loss_obj.avg, loss_obj.avg, fr_obj.avg, pcr_obj.avg, dfr_obj.avg\n\n def infer_batch(self, model, sample):\n if model is None:\n model = self.model\n \n model.eval()\n if type(model) is nn.DataParallel:\n model = model.module\n with torch.no_grad():\n input = utils.move_to_cuda(sample['src_tokens'])\n prev_output_mels = utils.move_to_cuda(sample['prev_output_mels'])\n target = utils.move_to_cuda(sample['targets'])\n bsz = input.size(0)\n max_input_len = input.size(1)\n\n if self.args.gta:\n decode_length = target.size(1)\n else:\n decode_length = self.estimate_decode_length(max_input_len)\n \n encoder_outputs = model.forward_encoder(input)\n encoder_out = encoder_outputs['encoder_out']\n encoder_padding_mask = encoder_outputs['encoder_padding_mask']\n\n hit_eos = input.new(bsz, 1).fill_(0).bool()\n stop_logits = input.new(bsz, 0).fill_(0).float()\n stage = 0\n decoder_input = input.new(bsz, decode_length+1, self.args.audio_num_mel_bins).fill_(self.padding_idx).float()\n decoded_mel = input.new(bsz, 0, self.args.audio_num_mel_bins).fill_(self.padding_idx).float()\n encdec_attn_logits = []\n\n for i in range(self.args.dec_layers):\n encdec_attn_logits.append(input.new(bsz, self.num_heads[i], 0, max_input_len).fill_(0).float())\n #encdec_attn_logits = input.new(bsz, self.args.dec_layers, 0, max_input_len).fill_(0).float()\n attn_pos = input.new(bsz).fill_(0).int()\n use_masks = []\n for i in range(self.args.dec_layers):\n use_masks.append(input.new(self.num_heads[i]).fill_(0).float())\n #use_masks = input.new(self.args.dec_layers*2).fill_(0).float()\n \n incremental_state = {}\n step = 0\n if self.args.attn_constraint:\n for i, layer in enumerate(model.decoder.layers):\n enc_dec_attn_constraint_mask = input.new(bsz, self.num_heads[i], max_input_len).fill_(0).int()\n layer.set_buffer('enc_dec_attn_constraint_mask', enc_dec_attn_constraint_mask, incremental_state)\n while True:\n #import pdb; pdb.set_trace()\n if self.is_finished(step, decode_length, hit_eos, stage):\n break\n \n if self.args.gta:\n decoder_input[:, step] = prev_output_mels[:, step]\n\n decoder_output, attn_logits = model.forward_decoder(decoder_input[:, :step+1], encoder_out, encoder_padding_mask, incremental_state=incremental_state)\n next_mel = decoder_output[:, -1:, :self.args.audio_num_mel_bins]\n stop_logit = decoder_output[:, -1:, -1]\n stop_logits = torch.cat((stop_logits, stop_logit), dim=1)\n decoded_mel = torch.cat((decoded_mel, next_mel), dim=1)\n for i in range(self.args.dec_layers):\n encdec_attn_logits[i] = torch.cat((encdec_attn_logits[i], attn_logits[i]), dim=2)\n step += 1\n\n this_hit_eos = hit_eos[:, -1:]\n if self.args.attn_constraint:\n this_hit_eos |= (attn_pos[:, None] >= (encoder_padding_mask < 1.0).float().sum(dim=-1, keepdim=True).int() - 5) & (torch.sigmoid(stop_logit) > 0.5)\n else:\n this_hit_eos |= torch.sigmoid(stop_logit) > 0.5\n hit_eos = torch.cat((hit_eos, this_hit_eos), dim=1)\n\n \n if not self.args.gta:\n decoder_input[:, step] = next_mel[:, -1]\n\n if self.args.attn_constraint:\n stage_change_step = 50\n all_prev_weights = []\n for i in range(self.args.dec_layers):\n all_prev_weights.append(torch.softmax(encdec_attn_logits[i], dim=-1)) # bsz x head x L x L_kv\n\n # if the stage should change\n next_stage = (step == stage_change_step) | (step >= decode_length)\n if not self.args.gta:\n next_stage |= (hit_eos[:, -1].sum() == hit_eos.size(0)).cpu().numpy()\n next_stage &= (stage == 0)\n\n # choose the diagonal attention\n if next_stage:#TODO\n use_masks = []\n for i in range(self.args.dec_layers):\n use_mask = (all_prev_weights[i][:, :, :step].max(dim=-1).values.mean(dim=(0, 2)) > 0.6).float() # [head]\n use_masks.append(use_mask)\n attn_pos = input.new(bsz).fill_(0).int()\n\n # reseet when the stage changes\n for layer in model.decoder.layers:\n layer.clear_buffer(input, encoder_out, encoder_padding_mask, incremental_state)\n \n encdec_attn_logits = []\n for i in range(self.args.dec_layers):\n encdec_attn_logits.append(input.new(bsz, self.num_heads[i], 0, max_input_len).fill_(0).float())\n decoded_mel = input.new(bsz, 0, self.args.audio_num_mel_bins).fill_(0).float()\n decoder_input = input.new(bsz, decode_length+1, self.args.audio_num_mel_bins).fill_(0).float()\n hit_eos = input.new(bsz, 1).fill_(0).bool()\n stage = stage + 1\n step = 0\n\n prev_weights_mask1 = utils.sequence_mask(torch.max(attn_pos - 1, attn_pos.new(attn_pos.size()).fill_(0)).float(), encdec_attn_logits[0].size(-1)).float() # bsz x L_kv\n prev_weights_mask2 = 1.0 - utils.sequence_mask(attn_pos.float() + 4, encdec_attn_logits[0].size(-1)).float() # bsz x L_kv\n enc_dec_attn_constraint_masks = []\n for i in range(self.args.dec_layers):\n mask = (prev_weights_mask1 + prev_weights_mask2)[:, None, :] * use_masks[i][None, :, None] # bsz x head x L_kv\n enc_dec_attn_constraint_masks.append(mask)\n #enc_dec_attn_constraint_masks = (prev_weights_mask1 + prev_weights_mask2)[:, None, None, :] * use_masks[None, :, None, None] # bsz x (n_layers x head) x 1 x L_kv\n\n for i, layer in enumerate(model.decoder.layers):\n enc_dec_attn_constraint_mask = enc_dec_attn_constraint_masks[i]\n layer.set_buffer('enc_dec_attn_constraint_mask', enc_dec_attn_constraint_mask, incremental_state)\n\n def should_move_on():\n prev_weights = []\n for i in range(self.args.dec_layers):\n prev_weight = (all_prev_weights[i] * use_masks[i][None, :, None, None]).sum(dim=1)\n prev_weights.append(prev_weight)\n prev_weights = sum(prev_weights) / sum([mask.sum() for mask in use_masks])\n #prev_weights = (prev_weights * use_masks[None, :, None, None]).sum(dim=1) / use_masks.sum()\n move_on = (prev_weights[:, -3:].mean(dim=1).gather(1, attn_pos[:, None].long())).squeeze() < 0.7\n move_on &= torch.argmax(prev_weights[:, -1], -1) > attn_pos.long()\n return attn_pos + move_on.int()\n \n if step > 3 and stage == 1:\n attn_pos = should_move_on()\n\n #size = encdec_attn_logits.size()\n #encdec_attn_logits = encdec_attn_logits.view(size[0], size[1]*size[2], size[3], size[4])\n encdec_attn = utils.select_attn(encdec_attn_logits)\n\n src_lengths = utils.move_to_cuda(sample['src_lengths']) - 1 # exclude eos\n target_lengths = (1.0 - hit_eos[:, 1:].float()).sum(dim=-1) + 1\n src_padding_mask = input.eq(self.padding_idx) | input.eq(self.eos_idx) # also exclude eos\n src_seg_mask = input.eq(self.seg_idx)\n target_padding_mask = decoded_mel.abs().sum(-1).eq(self.padding_idx)\n focus_rate = utils.get_focus_rate(encdec_attn, src_padding_mask, target_padding_mask)\n phone_coverage_rate = utils.get_phone_coverage_rate(encdec_attn, src_padding_mask, src_seg_mask, target_padding_mask)\n attn_ks = src_lengths.float() / target_lengths.float()\n diagonal_focus_rate = utils.get_diagonal_focus_rate(encdec_attn, attn_ks, target_lengths, src_padding_mask, target_padding_mask)\n\n return decoded_mel, encdec_attn.unsqueeze(1), hit_eos, stop_logits, focus_rate, phone_coverage_rate, diagonal_focus_rate\n\n def is_finished(self, step, decode_length, hit_eos, stage):\n finished = step >= decode_length\n if not self.args.gta:\n finished |= (hit_eos[:, -1].sum() == hit_eos.size(0)).cpu().numpy()\n if self.args.attn_constraint:\n finished &= stage != 0\n return finished\n\n def infer(self, model=None, split='test'):\n if model is None:\n model = self.model\n if split == 'train':\n queue = self.train_queue\n elif split == 'valid':\n queue = self.valid_queue\n else:\n assert split == 'test'\n queue = self.test_queue\n\n nsamples_finished = 0\n for batch, sample in enumerate(queue):\n logging.info('inferring batch {} with {} samples'.format(batch+1, sample['nsamples']))\n decoded_mel, encdec_attn, hit_eos, _, focus_rate, phone_coverage_rate, diagonal_focus_rate = self.infer_batch(model, sample)\n\n hit_eos = hit_eos[:, 1:]\n outputs = decoded_mel\n predict_lengths = (1.0 - hit_eos.float()).sum(dim=-1)\n outputs *= (1.0 - hit_eos.float())[:, :, None]\n\n sample['outputs'] = outputs\n sample['predict_mels'] = decoded_mel\n sample['predict_lengths'] = predict_lengths\n sample['encdec_attn'] = encdec_attn\n sample['focus_rate'] = focus_rate\n sample['phone_coverage_rate'] = phone_coverage_rate\n sample['diagonal_focus_rate'] = diagonal_focus_rate\n self.after_infer(sample)\n nsamples_finished += sample['nsamples']\n \n def valid_for_search(self, model=None, gta=False, arch_pool=None, layer_norm_training=False):\n if model is None:\n model = self.model\n if arch_pool is not None:\n loss_res, fr_res, pcr_res, dfr_res = [], [], [] ,[]\n for arch in arch_pool:\n loss_obj = utils.AvgrageMeter()\n fr_obj = utils.AvgrageMeter()\n pcr_obj = utils.AvgrageMeter()\n dfr_obj = utils.AvgrageMeter()\n for batch, sample in enumerate(self.valid_queue):\n ret = self.valid_for_search_batch(model, sample, gta, arch, layer_norm_training)\n loss_obj.update(ret['loss'], ret['nsamples'])\n fr_obj.update(ret['focus_rate'], ret['nsamples'])\n pcr_obj.update(ret['phone_coverage_rate'], ret['nsamples'])\n dfr_obj.update(ret['diagonal_focus_rate'], ret['nsamples'])\n loss_res.append(loss_obj.avg)\n fr_res.append(fr_obj.avg)\n pcr_res.append(pcr_obj.avg)\n dfr_res.append(dfr_obj.avg)\n return fr_res, pcr_res, dfr_res, loss_res\n \n loss_obj = utils.AvgrageMeter()\n fr_obj = utils.AvgrageMeter()\n pcr_obj = utils.AvgrageMeter()\n dfr_obj = utils.AvgrageMeter()\n for batch, sample in enumerate(self.valid_queue):\n ret = self.valid_for_search_batch(model, sample, gta)\n loss_obj.update(ret['loss'], ret['nsamples'])\n fr_obj.update(ret['focus_rate'], ret['nsamples'])\n pcr_obj.update(ret['phone_coverage_rate'], ret['nsamples'])\n dfr_obj.update(ret['diagonal_focus_rate'], ret['nsamples'])\n return fr_obj.avg, pcr_obj.avg, dfr_obj.avg, loss_obj.avg\n\n def valid_for_search_batch(self, model, sample, gta=False, arch=None, layer_norm_training=False):\n if model is None:\n model = self.model\n model.eval()\n\n with torch.no_grad():\n input = utils.move_to_cuda(sample['src_tokens'])\n prev_output_mels = utils.move_to_cuda(sample['prev_output_mels'])\n target = utils.move_to_cuda(sample['targets'])\n bsz = input.size(0)\n max_input_len = input.size(1)\n\n if gta:\n output, attn_logits = model(input, prev_output_mels, target, arch=arch, layer_norm_training=layer_norm_training)\n encdec_attn_logits = attn_logits\n else:\n if type(model) is nn.DataParallel:\n model = model.module\n decode_length = target.size(1) if target is not None else self.estimate_decode_length(input.size(1))\n encoder_outputs = model.forward_encoder(input, arch=arch, layer_norm_training=layer_norm_training)\n encoder_out = encoder_outputs['encoder_out']\n encoder_padding_mask = encoder_outputs['encoder_padding_mask']\n decoder_input = input.new(bsz, decode_length+1, self.args.audio_num_mel_bins).fill_(self.padding_idx).float()\n output = input.new(bsz, 0, self.args.audio_num_mel_bins+1).fill_(self.padding_idx).float()\n hit_eos = input.new(bsz, 1).fill_(0).bool()\n stop_logits = input.new(bsz, 0).fill_(0).float()\n encdec_attn_logits = []\n if arch is not None: # in ws mode, arch is provided at run\n num_heads = utils.get_num_heads(arch[self.args.enc_layers:])\n else: # in general mode, arch is defined at the begining\n num_heads = self.num_heads\n for i in range(self.args.dec_layers):\n encdec_attn_logits.append(input.new(bsz, num_heads[i], 0, max_input_len).fill_(0).float())\n incremental_state = {}\n for step in range(decode_length):\n decoder_output, attn_logits = model.forward_decoder(decoder_input[:, :step+1], encoder_out, encoder_padding_mask, incremental_state=incremental_state, arch=arch, layer_norm_training=layer_norm_training)\n next_mel = decoder_output[:, -1:, :self.args.audio_num_mel_bins]\n stop_logit = decoder_output[:, -1:, -1]\n stop_logits = torch.cat((stop_logits, stop_logit), dim=1)\n output = torch.cat((output, decoder_output), dim=1)\n for i in range(self.args.dec_layers):\n encdec_attn_logits[i] = torch.cat((encdec_attn_logits[i], attn_logits[i]), dim=2)\n decoder_input[:, step+1] = next_mel[:, -1]\n this_hit_eos = hit_eos[:, -1:]\n this_hit_eos |= torch.sigmoid(stop_logit) > 0.5\n hit_eos = torch.cat((hit_eos, this_hit_eos), dim=1)\n \n loss_output = self.loss(output, target)\n decoder_loss = loss_output['decoder loss']\n stop_loss = loss_output['stop loss']\n total_loss = decoder_loss + stop_loss\n encdec_attn = utils.select_attn(encdec_attn_logits)\n\n src_lengths = utils.move_to_cuda(sample['src_lengths']) - 1 # exclude eos\n if target is not None:\n target_lengths = utils.move_to_cuda(sample['target_lengths'])\n target_padding_mask = target.abs().sum(-1).eq(self.padding_idx)\n else:\n hit_eos = hit_eos[:, 1:]\n target_lengths = (1.0 - hit_eos.float()).sum(dim=-1)\n target_padding_mask = output[:, :, :self.args.audio_num_mel_bins].abs().sum(-1).eq(self.padding_idx)\n src_padding_mask = input.eq(self.padding_idx) | input.eq(self.eos_idx) # also exclude eos\n src_seg_mask = input.eq(self.seg_idx)\n focus_rate = utils.get_focus_rate(encdec_attn, src_padding_mask, target_padding_mask)\n phone_coverage_rate = utils.get_phone_coverage_rate(encdec_attn, src_padding_mask, src_seg_mask, target_padding_mask)\n attn_ks = src_lengths.float() / target_lengths.float()\n diagonal_focus_rate = utils.get_diagonal_focus_rate(encdec_attn, attn_ks, target_lengths, src_padding_mask, target_padding_mask)\n\n ret = {\n 'focus_rate': focus_rate.mean().data,\n 'phone_coverage_rate': phone_coverage_rate.mean().data,\n 'diagonal_focus_rate': diagonal_focus_rate.mean().data,\n 'loss': total_loss.data,\n 'nsamples': sample['nsamples'],\n }\n return ret\n\n def estimate_decode_length(self, input_length):\n return input_length * 5 + 100\n\n def after_infer(self, predictions):\n predictions = utils.unpack_dict_to_list(predictions)\n for num_predictions, prediction in enumerate(predictions):\n for k, v in prediction.items():\n if type(v) is torch.Tensor:\n prediction[k] = v.cpu().numpy()\n\n utt_id = prediction.get('utt_id', None)\n text = prediction.get('text', None)\n src_tokens = prediction.get('src_tokens')\n src_lengths = prediction.get('src_lengths')\n targets = prediction.get(\"targets\", None)\n outputs = prediction[\"outputs\"]\n focus_rate = prediction['focus_rate']\n phone_coverage_rate = prediction['phone_coverage_rate']\n diagonal_focus_rate = prediction['diagonal_focus_rate']\n decoded_inputs_txt = self.phone_encoder.decode(src_tokens, strip_eos=True, strip_padding=True)\n out_wav = audio.inv_mel_spectrogram(outputs.T, self.args)\n prediction['out_wav'] = out_wav\n\n if prediction.get('hit_eos') is None:\n assert prediction.get('predict_lengths') is not None\n prediction['hit_eos'] = np.arange(outputs.shape[0]) >= prediction['predict_lengths']\n \n targets = self.remove_padding(targets) if targets is not None else None # speech\n outputs = self.remove_padding(outputs, prediction.get('hit_eos'))\n if out_wav is not None:\n outputs = self.remove_padding(out_wav, prediction.get('hit_eos'))\n\n prediction['predict_mels'] = self.remove_padding(prediction['predict_mels'], prediction.get('hit_eos'))\n\n if 'encdec_attn' in prediction:\n encdec_attn = prediction['encdec_attn']\n encdec_attn = encdec_attn[encdec_attn.max(-1).sum(-1).argmax(-1)]\n prediction['encdec_attn'] = self.remove_padding(encdec_attn, prediction.get('hit_eos'))\n prediction['encdec_attn'] = prediction['encdec_attn'].T[:src_lengths]\n\n if hasattr(self.args, 'checkpoint_path') and self.args.checkpoint_path is not None:\n steps = os.path.split(self.args.checkpoint_path)[-1].strip().split('checkpoint')[1].split('.pt')[0]\n output_dir = os.path.join(self.args.output_dir, f'generated_{steps}')\n else:\n output_dir = os.path.join(self.args.output_dir, f'generated')\n os.makedirs(output_dir, exist_ok=True)\n\n def log_audio(outputs, prefix, alignment=None, mels=None, decoded_txt=None):\n if len(outputs.shape) == 1:\n wav_out = outputs\n else:\n mel = outputs.reshape(-1, self.args.audio_num_mel_bins)\n wav_out = audio.inv_mel_spectrogram(mel.T, self.args)\n wav_out = audio.inv_preemphasis(wav_out, self.args.preemphasis, self.args.preemphasize)\n #audio.save_wav(wav_out, os.path.join(output_dir, '[W][{}][{}]{}.wav'.format(prefix, utt_id, text.replace(':', '%3A') if text is not None else '')),\n # self.args.audio_sample_rate)\n audio.save_wav(wav_out, os.path.join(output_dir, '[W][{}][{}].wav'.format(prefix, utt_id)),\n self.args.audio_sample_rate)\n #audio.plot_spec(mels.reshape(-1, 80).T,\n # os.path.join(output_dir, '[P][{}][{}]{}.png'.format(prefix, utt_id, text.replace(':', '%3A') if text is not None else '')))\n audio.plot_spec(mels.reshape(-1, 80).T,\n os.path.join(output_dir, '[P][{}][{}].png'.format(prefix, utt_id)))\n if alignment is not None:\n import matplotlib.pyplot as plt\n fig, ax = plt.subplots(figsize=(12, 16))\n im = ax.imshow(alignment, aspect='auto', origin='lower',\n interpolation='none')\n decoded_txt = decoded_txt.split(\" \")\n ax.set_yticks(np.arange(len(decoded_txt)))\n ax.set_yticklabels(list(decoded_txt), fontsize=6)\n\n fig.colorbar(im, ax=ax)\n #fig.savefig(os.path.join(output_dir, '[A][{}][{}]{}.png'.format(prefix, utt_id, text.replace(':', '%3A') if text is not None else '')), format='png')\n fig.savefig(os.path.join(output_dir, '[A][{}][{}].png'.format(prefix, utt_id)), format='png')\n plt.close()\n\n #with open(os.path.join(output_dir, '[A][{}][{}]{}.txt'.format(prefix, utt_id, text.replace(':', '%3A') if text is not None else '')), 'w') as f:\n with open(os.path.join(output_dir, '[A][{}][{}].txt'.format(prefix, utt_id)), 'w') as f:\n f.write('fr %.6f pcr %.6f dfr %.6f' % (focus_rate, phone_coverage_rate, diagonal_focus_rate))\n\n log_audio(outputs, 'pred', prediction.get('encdec_attn', None), prediction[\"predict_mels\"], decoded_inputs_txt)\n logging.info('pred_outputs.shape: {}'.format(prediction['predict_mels'].shape))\n if targets is not None:\n log_audio(targets, 'gt', None, targets[:, :self.args.audio_num_mel_bins], decoded_inputs_txt)\n\n logging.info(\">>> {}\".format(num_predictions+1))\n\n\nclass LJSpeechTaskMB(LJSpeechTask):\n\n def __init__(self, args):\n self.args = args\n self.ws = getattr(args, 'ws', False)\n self.arch = getattr(args, 'arch', None)\n self.data_dir = args.data_dir\n self.output_dir = args.output_dir\n self.max_tokens = args.max_tokens\n self.max_sentences = args.max_sentences\n self.max_eval_tokens = args.max_eval_tokens if getattr(args, 'max_eval_tokens', None) is not None else self.max_tokens\n self.max_eval_sentences = args.max_eval_sentences if getattr(args, 'max_eval_sentences', None) is not None else self.max_sentences\n if isinstance(self.arch, str):\n self.arch = list(map(int, self.arch.strip().split()))\n if self.arch is not None:\n self.num_heads = utils.get_num_heads(self.arch[args.enc_layers*2:])\n \n def setup_task(self, model_state_dict=None, optimizer_state_dict=None, ws=False):\n self.phone_encoder = self.build_phone_encoder(self.data_dir)\n self.train_dataset, self.valid_dataset, self.test_dataset = self.build_dataset(self.data_dir, self.args.raw_data)\n self.train_queue = self.build_queue(self.train_dataset, True, self.max_tokens, self.max_sentences)\n self.valid_queue = self.build_queue(self.valid_dataset, False, self.max_eval_tokens, self.max_eval_sentences)\n self.test_queue = self.build_queue(self.test_dataset, False, self.max_eval_tokens, self.max_eval_sentences)\n self.model = self.build_model(arch=self.arch, model_state_dict=model_state_dict, ws=self.ws | ws)\n self.optimizer = self.build_optimizer(optimizer_state_dict=optimizer_state_dict)\n self.scheduler = self.build_scheduler()\n self.padding_idx = self.phone_encoder.pad()\n self.eos_idx = self.phone_encoder.eos()\n self.seg_idx = self.phone_encoder.seg()\n #if torch.cuda.device_count() > 1:\n # torch.distributed.init_process_group(backend='nccl')\n\n def build_model(self, arch=None, model_state_dict=None, ws=False):\n if arch is None:\n arch = self.arch\n assert (arch is not None) ^ ws, 'arch and ws are mutual'\n if ws:\n _model = model_ws.NASNetwork(self.args, self.phone_encoder)\n else:\n _model = model.NASNetwork(self.args, arch, self.phone_encoder)\n if model_state_dict is not None:\n _model.load_state_dict(model_state_dict)\n if torch.cuda.is_available():\n if torch.cuda.device_count() > 1:\n _model = nn.DataParallel(_model)\n _model = _model.cuda()\n return _model\n\n def infer_batch(self, model, sample):\n if model is None:\n model = self.model\n \n model.eval()\n if type(model) is nn.DataParallel:\n model = model.module\n with torch.no_grad():\n input = utils.move_to_cuda(sample['src_tokens'])\n prev_output_mels = utils.move_to_cuda(sample['prev_output_mels'])\n target = utils.move_to_cuda(sample['targets'])\n bsz = input.size(0)\n max_input_len = input.size(1)\n\n if self.args.gta:\n decode_length = target.size(1)\n else:\n decode_length = self.estimate_decode_length(max_input_len)\n \n encoder_outputs = model.forward_encoder(input)\n encoder_out = encoder_outputs['encoder_out']\n encoder_padding_mask = encoder_outputs['encoder_padding_mask']\n\n hit_eos = input.new(bsz, 1).fill_(0).bool()\n stop_logits = input.new(bsz, 0).fill_(0).float()\n stage = 0\n decoder_input = input.new(bsz, decode_length+1, self.args.audio_num_mel_bins).fill_(self.padding_idx).float()\n decoded_mel = input.new(bsz, 0, self.args.audio_num_mel_bins).fill_(self.padding_idx).float()\n encdec_attn_logits = []\n\n for i in range(self.args.dec_layers):\n encdec_attn_logits.append(input.new(bsz, self.num_heads[2*i], 0, max_input_len).fill_(0).float())\n encdec_attn_logits.append(input.new(bsz, self.num_heads[2*i+1], 0, max_input_len).fill_(0).float())\n #encdec_attn_logits = input.new(bsz, self.args.dec_layers, 0, max_input_len).fill_(0).float()\n attn_pos = input.new(bsz).fill_(0).int()\n use_masks = []\n for i in range(self.args.dec_layers):\n use_masks.append(input.new(self.num_heads[2*i]).fill_(0).float())\n use_masks.append(input.new(self.num_heads[2*i+1]).fill_(0).float())\n #use_masks = input.new(self.args.dec_layers*2).fill_(0).float()\n \n incremental_state = {}\n step = 0\n if self.args.attn_constraint:\n for i, layer in enumerate(model.decoder.layers):\n enc_dec_attn_constraint_mask = input.new(bsz, self.num_heads[2*i], max_input_len).fill_(0).int()\n layer.set_left_buffer('enc_dec_attn_constraint_mask', enc_dec_attn_constraint_mask, incremental_state)\n enc_dec_attn_constraint_mask = input.new(bsz, self.num_heads[2*i+1], max_input_len).fill_(0).int()\n layer.set_right_buffer('enc_dec_attn_constraint_mask', enc_dec_attn_constraint_mask, incremental_state)\n while True:\n #import pdb; pdb.set_trace()\n if self.is_finished(step, decode_length, hit_eos, stage):\n break\n \n if self.args.gta:\n decoder_input[:, step] = prev_output_mels[:, step]\n\n decoder_output, attn_logits = model.forward_decoder(decoder_input[:, :step+1], encoder_out, encoder_padding_mask, incremental_state=incremental_state)\n next_mel = decoder_output[:, -1:, :self.args.audio_num_mel_bins]\n stop_logit = decoder_output[:, -1:, -1]\n stop_logits = torch.cat((stop_logits, stop_logit), dim=1)\n decoded_mel = torch.cat((decoded_mel, next_mel), dim=1)\n for i in range(self.args.dec_layers):\n encdec_attn_logits[2*i] = torch.cat((encdec_attn_logits[2*i], attn_logits[2*i]), dim=2)\n encdec_attn_logits[2*i+1] = torch.cat((encdec_attn_logits[2*i+1], attn_logits[2*i+1]), dim=2)\n step += 1\n\n this_hit_eos = hit_eos[:, -1:]\n if self.args.attn_constraint:\n this_hit_eos |= (attn_pos[:, None] >= (encoder_padding_mask < 1.0).float().sum(dim=-1, keepdim=True).int() - 5) & (torch.sigmoid(stop_logit) > 0.5)\n else:\n this_hit_eos |= torch.sigmoid(stop_logit) > 0.5\n hit_eos = torch.cat((hit_eos, this_hit_eos), dim=1)\n\n \n if not self.args.gta:\n decoder_input[:, step] = next_mel[:, -1]\n\n if self.args.attn_constraint:\n stage_change_step = 50\n all_prev_weights = []\n for i in range(self.args.dec_layers):\n all_prev_weights.append(torch.softmax(encdec_attn_logits[2*i], dim=-1)) # bsz x head x L x L_kv\n all_prev_weights.append(torch.softmax(encdec_attn_logits[2*i+1], dim=-1))\n\n # if the stage should change\n next_stage = (step == stage_change_step) | (step >= decode_length)\n if not self.args.gta:\n next_stage |= (hit_eos[:, -1].sum() == hit_eos.size(0)).cpu().numpy()\n next_stage &= (stage == 0)\n\n # choose the diagonal attention\n if next_stage:#TODO\n use_masks = []\n for i in range(self.args.dec_layers):\n use_mask = (all_prev_weights[2*i][:, :, :step].max(dim=-1).values.mean(dim=(0, 2)) > 0.6).float() # [head]\n use_masks.append(use_mask)\n use_mask = (all_prev_weights[2*i+1][:, :, :step].max(dim=-1).values.mean(dim=(0, 2)) > 0.6).float() # [head]\n use_masks.append(use_mask)\n attn_pos = input.new(bsz).fill_(0).int()\n\n # reset when the stage changes\n for i, layer in enumerate(model.decoder.layers):\n layer.clear_left_buffer(input, encoder_out, encoder_padding_mask, incremental_state)\n layer.clear_right_buffer(input, encoder_out, encoder_padding_mask, incremental_state)\n \n encdec_attn_logits = []\n for i in range(self.args.dec_layers):\n encdec_attn_logits.append(input.new(bsz, self.num_heads[2*i], 0, max_input_len).fill_(0).float())\n encdec_attn_logits.append(input.new(bsz, self.num_heads[2*i+1], 0, max_input_len).fill_(0).float())\n decoded_mel = input.new(bsz, 0, self.args.audio_num_mel_bins).fill_(0).float()\n decoder_input = input.new(bsz, decode_length+1, self.args.audio_num_mel_bins).fill_(0).float()\n hit_eos = input.new(bsz, 1).fill_(0).bool()\n stage = stage + 1\n step = 0\n\n prev_weights_mask1 = utils.sequence_mask(torch.max(attn_pos - 1, attn_pos.new(attn_pos.size()).fill_(0)).float(), encdec_attn_logits[0].size(-1)).float() # bsz x L_kv\n prev_weights_mask2 = 1.0 - utils.sequence_mask(attn_pos.float() + 4, encdec_attn_logits[0].size(-1)).float() # bsz x L_kv\n enc_dec_attn_constraint_masks = []\n for i in range(self.args.dec_layers):\n mask = (prev_weights_mask1 + prev_weights_mask2)[:, None, :] * use_masks[2*i][None, :, None] # bsz x head x L_kv\n enc_dec_attn_constraint_masks.append(mask)\n mask = (prev_weights_mask1 + prev_weights_mask2)[:, None, :] * use_masks[2*i+1][None, :, None] # bsz x head x L_kv\n enc_dec_attn_constraint_masks.append(mask)\n #enc_dec_attn_constraint_masks = (prev_weights_mask1 + prev_weights_mask2)[:, None, None, :] * use_masks[None, :, None, None] # bsz x (n_layers x head) x 1 x L_kv\n\n for i, layer in enumerate(model.decoder.layers):\n enc_dec_attn_constraint_mask = enc_dec_attn_constraint_masks[2*i]\n layer.set_left_buffer('enc_dec_attn_constraint_mask', enc_dec_attn_constraint_mask, incremental_state)\n enc_dec_attn_constraint_mask = enc_dec_attn_constraint_masks[2*i+1]\n layer.set_right_buffer('enc_dec_attn_constraint_mask', enc_dec_attn_constraint_mask, incremental_state)\n\n def should_move_on():\n prev_weights = []\n for i in range(self.args.dec_layers):\n prev_weight = (all_prev_weights[2*i] * use_masks[2*i][None, :, None, None]).sum(dim=1)\n prev_weights.append(prev_weight)\n prev_weight = (all_prev_weights[2*i+1] * use_masks[2*i+1][None, :, None, None]).sum(dim=1)\n prev_weights.append(prev_weight)\n prev_weights = sum(prev_weights) / sum([mask.sum() for mask in use_masks])\n #prev_weights = (prev_weights * use_masks[None, :, None, None]).sum(dim=1) / use_masks.sum()\n move_on = (prev_weights[:, -3:].mean(dim=1).gather(1, attn_pos[:, None].long())).squeeze() < 0.7\n move_on &= torch.argmax(prev_weights[:, -1], -1) > attn_pos.long()\n return attn_pos + move_on.int()\n \n if step > 3 and stage == 1:\n attn_pos = should_move_on()\n\n #size = encdec_attn_logits.size()\n #encdec_attn_logits = encdec_attn_logits.view(size[0], size[1]*size[2], size[3], size[4])\n encdec_attn = utils.select_attn(encdec_attn_logits)\n\n src_lengths = utils.move_to_cuda(sample['src_lengths']) - 1 # exclude eos\n target_lengths = (1.0 - hit_eos[:, 1:].float()).sum(dim=-1) + 1\n src_padding_mask = input.eq(self.padding_idx) | input.eq(self.eos_idx) # also exclude eos\n src_seg_mask = input.eq(self.seg_idx)\n target_padding_mask = decoded_mel.abs().sum(-1).eq(self.padding_idx)\n focus_rate = utils.get_focus_rate(encdec_attn, src_padding_mask, target_padding_mask)\n phone_coverage_rate = utils.get_phone_coverage_rate(encdec_attn, src_padding_mask, src_seg_mask, target_padding_mask)\n attn_ks = src_lengths.float() / target_lengths.float()\n diagonal_focus_rate = utils.get_diagonal_focus_rate(encdec_attn, attn_ks, target_lengths, src_padding_mask, target_padding_mask)\n\n return decoded_mel, encdec_attn.unsqueeze(1), hit_eos, stop_logits, focus_rate, phone_coverage_rate, diagonal_focus_rate\n \n def valid_for_search_batch(self, model, sample, gta=False, arch=None, layer_norm_training=False):\n if model is None:\n model = self.model\n model.eval()\n if type(model) is nn.DataParallel:\n model = model.module\n\n with torch.no_grad():\n input = utils.move_to_cuda(sample['src_tokens'])\n prev_output_mels = utils.move_to_cuda(sample['prev_output_mels'])\n target = utils.move_to_cuda(sample['targets'])\n bsz = input.size(0)\n max_input_len = input.size(1)\n\n if gta:\n output, attn_logits = model(input, prev_output_mels, target, arch=arch, layer_norm_training=layer_norm_training)\n encdec_attn_logits = attn_logits\n else:\n decode_length = target.size(1) if target is not None else self.estimate_decode_length(input.size(1))\n encoder_outputs = model.forward_encoder(input, arch=arch, layer_norm_training=layer_norm_training)\n encoder_out = encoder_outputs['encoder_out']\n encoder_padding_mask = encoder_outputs['encoder_padding_mask']\n decoder_input = input.new(bsz, decode_length+1, self.args.audio_num_mel_bins).fill_(self.padding_idx).float()\n output = input.new(bsz, 0, self.args.audio_num_mel_bins+1).fill_(self.padding_idx).float()\n hit_eos = input.new(bsz, 1).fill_(0).bool()\n stop_logits = input.new(bsz, 0).fill_(0).float()\n encdec_attn_logits = []\n if arch is not None: # in ws mode, arch is provided at run\n num_heads = utils.get_num_heads(arch[2*self.args.enc_layers:])\n else: # in general mode, arch is defined at the begining\n num_heads = self.num_heads\n for i in range(self.args.dec_layers):\n encdec_attn_logits.append(input.new(bsz, num_heads[2*i], 0, max_input_len).fill_(0).float())\n encdec_attn_logits.append(input.new(bsz, num_heads[2*i+1], 0, max_input_len).fill_(0).float())\n incremental_state = {}\n for step in range(decode_length):\n decoder_output, attn_logits = model.forward_decoder(decoder_input[:, :step+1], encoder_out, encoder_padding_mask, incremental_state=incremental_state, arch=arch, layer_norm_training=layer_norm_training)\n next_mel = decoder_output[:, -1:, :self.args.audio_num_mel_bins]\n stop_logit = decoder_output[:, -1:, -1]\n stop_logits = torch.cat((stop_logits, stop_logit), dim=1)\n output = torch.cat((output, decoder_output), dim=1)\n for i in range(self.args.dec_layers):\n encdec_attn_logits[2*i] = torch.cat((encdec_attn_logits[2*i], attn_logits[2*i]), dim=2)\n encdec_attn_logits[2*i+1] = torch.cat((encdec_attn_logits[2*i+1], attn_logits[2*i+1]), dim=2)\n decoder_input[:, step+1] = next_mel[:, -1]\n this_hit_eos = hit_eos[:, -1:]\n this_hit_eos |= torch.sigmoid(stop_logit) > 0.5\n hit_eos = torch.cat((hit_eos, this_hit_eos), dim=1)\n \n loss_output = self.loss(output, target)\n decoder_loss = loss_output['decoder loss']\n stop_loss = loss_output['stop loss']\n total_loss = decoder_loss + stop_loss\n encdec_attn = utils.select_attn(encdec_attn_logits)\n\n src_lengths = utils.move_to_cuda(sample['src_lengths']) - 1 # exclude eos\n src_lengths = utils.move_to_cuda(sample['src_lengths']) - 1 # exclude eos\n if target is not None:\n target_lengths = utils.move_to_cuda(sample['target_lengths'])\n target_padding_mask = target.abs().sum(-1).eq(self.padding_idx)\n else:\n hit_eos = hit_eos[:, 1:]\n target_lengths = (1.0 - hit_eos.float()).sum(dim=-1)\n target_padding_mask = output[:, :, :self.args.audio_num_mel_bins].abs().sum(-1).eq(self.padding_idx)\n src_padding_mask = input.eq(self.padding_idx) | input.eq(self.eos_idx) # also exclude eos\n src_seg_mask = input.eq(self.seg_idx)\n focus_rate = utils.get_focus_rate(encdec_attn, src_padding_mask, target_padding_mask)\n phone_coverage_rate = utils.get_phone_coverage_rate(encdec_attn, src_padding_mask, src_seg_mask, target_padding_mask)\n attn_ks = src_lengths.float() / target_lengths.float()\n diagonal_focus_rate = utils.get_diagonal_focus_rate(encdec_attn, attn_ks, target_lengths, src_padding_mask, target_padding_mask)\n\n ret = {\n 'focus_rate': focus_rate.mean().data,\n 'phone_coverage_rate': phone_coverage_rate.mean().data,\n 'diagonal_focus_rate': diagonal_focus_rate.mean().data,\n 'loss': total_loss.data,\n 'nsamples': sample['nsamples'],\n }\n return ret\n" ]
[ [ "torch.utils.data.DataLoader", "torch.nn.functional.mse_loss", "numpy.sum", "torch.no_grad", "torch.cuda.is_available", "torch.cat", "torch.softmax", "numpy.abs", "torch.cuda.device_count", "matplotlib.use", "numpy.where", "torch.nn.DataParallel", "torch.sigmoid", "torch.Tensor", "numpy.load", "torch.argmax", "matplotlib.pyplot.subplots", "numpy.arange", "matplotlib.pyplot.close", "numpy.random.shuffle", "torch.nn.functional.relu", "numpy.array", "torch.LongTensor" ] ]
elletech/practice_manim
[ "83671e9e801490ce84100da3a684e369860fda37" ]
[ "manim/utils/hashing.py" ]
[ "\"\"\"Utilities for scene caching.\"\"\"\n\nimport json\nimport zlib\nimport inspect\nimport copy\nimport numpy as np\nfrom types import ModuleType, MappingProxyType, FunctionType, MethodType\nfrom time import perf_counter\n\nfrom .. import logger\n\nALREADY_PROCESSED_ID = {}\n\n\nclass CustomEncoder(json.JSONEncoder):\n def default(self, obj):\n \"\"\"\n This method is used to serialize objects to JSON format.\n\n If obj is a function, then it will return a dict with two keys : 'code', for the code source, and 'nonlocals' for all nonlocalsvalues. (including nonlocals functions, that will be serialized as this is recursive.)\n if obj is a np.darray, it converts it into a list.\n if obj is an object with __dict__ attribute, it returns its __dict__.\n Else, will let the JSONEncoder do the stuff, and throw an error if the type is not suitable for JSONEncoder.\n\n Parameters\n ----------\n obj : Any\n Arbitrary object to convert\n\n Returns\n -------\n Any\n Python object that JSON encoder will recognize\n\n \"\"\"\n if not (isinstance(obj, ModuleType)) and isinstance(\n obj, (MethodType, FunctionType)\n ):\n cvars = inspect.getclosurevars(obj)\n cvardict = {**copy.copy(cvars.globals), **copy.copy(cvars.nonlocals)}\n for i in list(cvardict):\n # NOTE : All module types objects are removed, because otherwise it throws ValueError: Circular reference detected if not. TODO\n if isinstance(cvardict[i], ModuleType):\n del cvardict[i]\n try:\n code = inspect.getsource(obj)\n except OSError:\n # This happens when rendering videos included in the documentation\n # within doctests and should be replaced by a solution avoiding\n # hash collision (due to the same, empty, code strings) at some point.\n # See https://github.com/ManimCommunity/manim/pull/402.\n code = \"\"\n return self._check_iterable({\"code\": code, \"nonlocals\": cvardict})\n elif isinstance(obj, np.ndarray):\n if obj.size > 1000:\n obj = np.resize(obj, (100, 100))\n return f\"TRUNCATED ARRAY: {repr(obj)}\"\n # We return the repr and not a list to avoid the JsonEncoder to iterate over it.\n return repr(obj)\n elif hasattr(obj, \"__dict__\"):\n temp = getattr(obj, \"__dict__\")\n # MappingProxy is scene-caching nightmare. It contains all of the object methods and attributes. We skip it as the mechanism will at some point process the object, but instancied\n # Indeed, there is certainly no case where scene-caching will recieve only a non instancied object, as this is never used in the library or encouraged to be used user-side.\n if isinstance(temp, MappingProxyType):\n return \"MappingProxy\"\n return self._check_iterable(temp)\n elif isinstance(obj, np.uint8):\n return int(obj)\n\n return f\"Unsupported type for serializing -> {str(type(obj))}\"\n\n def _handle_already_processed(self, obj):\n \"\"\"Handle if an object has been already processed by checking the id of the object.\n\n This prevents the mechanism to handle an object several times, and is used to prevent any circular reference.\n\n Parameters\n ----------\n obj : Any\n The obj to check.\n\n Returns\n -------\n Any\n \"already_processed\" string if it has been processed, otherwise obj.\n \"\"\"\n global ALREADY_PROCESSED_ID\n if id(obj) in ALREADY_PROCESSED_ID:\n return \"already_processed\"\n if not isinstance(obj, (str, int, bool, float)):\n ALREADY_PROCESSED_ID[id(obj)] = obj\n return obj\n\n def _check_iterable(self, iterable):\n \"\"\"Check for circular reference at each iterable that will go through the JSONEncoder, as well as key of the wrong format.\n\n If a key with a bad format is found (i.e not a int, string, or float), it gets replaced byt its hash using the same process implemented here.\n If a circular reference is found within the iterable, it will be replaced by the string \"already processed\".\n\n Parameters\n ----------\n iterable : Iterable[Any]\n The iterable to check.\n \"\"\"\n\n def _key_to_hash(key):\n return zlib.crc32(json.dumps(key, cls=CustomEncoder).encode())\n\n def _iter_check_list(lst):\n # We have to make a copy, as we don't want to touch to the original list\n # A deepcopy isn't necessary as it is already recursive.\n lst_copy = copy.copy(lst)\n if isinstance(lst, tuple):\n # NOTE: Sometimes a tuple can pass through this function. As a tuple\n # is immutable, we convert it to a list to be able to modify it.\n # It's ok as it is a copy.\n lst_copy = list(lst_copy)\n for i, el in enumerate(lst):\n if not isinstance(lst, tuple):\n lst_copy[i] = self._handle_already_processed(\n el\n ) # ISSUE here, because of copy.\n if isinstance(el, (list, tuple)):\n lst_copy[i] = _iter_check_list(el)\n elif isinstance(el, dict):\n lst_copy[i] = _iter_check_dict(el)\n return lst_copy\n\n def _iter_check_dict(dct):\n # We have to make a copy, as we don't want to touch to the original dict\n # A deepcopy isn't necessary as it is already recursive.\n dct_copy = copy.copy(dct)\n for k, v in dct.items():\n dct_copy[k] = self._handle_already_processed(v)\n # We check if the k is of the right format (supporter by Json)\n if not isinstance(k, (str, int, float, bool)) and k is not None:\n k_new = _key_to_hash(k)\n # We delete the value coupled with the old key, as the value is now coupled with the new key.\n dct_copy[k_new] = dct_copy[k]\n del dct_copy[k]\n else:\n k_new = k\n if isinstance(v, dict):\n dct_copy[k_new] = _iter_check_dict(v)\n elif isinstance(v, (list, tuple)):\n dct_copy[k_new] = _iter_check_list(v)\n return dct_copy\n\n if isinstance(iterable, (list, tuple)):\n return _iter_check_list(iterable)\n elif isinstance(iterable, dict):\n return _iter_check_dict(iterable)\n\n def encode(self, obj):\n \"\"\"Overriding of :meth:`JSONEncoder.encode`, to make our own process.\n\n Parameters\n ----------\n obj: Any\n The object to encode in JSON.\n\n Returns\n -------\n :class:`str`\n The object encoder with the standard json process.\n \"\"\"\n # We need to mark as already processed the first object to go in the process,\n # As after, only objects that come from iterables will be marked as such.\n global ALREADY_PROCESSED_ID\n ALREADY_PROCESSED_ID[id(obj)] = obj\n if isinstance(obj, (dict, list, tuple)):\n return super().encode(self._check_iterable(obj))\n return super().encode(obj)\n\n\ndef get_json(obj):\n \"\"\"Recursively serialize `object` to JSON using the :class:`CustomEncoder` class.\n\n Parameters\n ----------\n dict_config : :class:`dict`\n The dict to flatten\n\n Returns\n -------\n :class:`str`\n The flattened object\n \"\"\"\n return json.dumps(obj, cls=CustomEncoder)\n\n\ndef get_camera_dict_for_hashing(camera_object):\n \"\"\"Remove some keys from `camera_object.__dict__` that are very heavy and useless for the caching functionality.\n\n Parameters\n ----------\n camera_object : :class:`~.Camera`\n The camera object used in the scene\n\n Returns\n -------\n :class:`dict`\n `Camera.__dict__` but cleaned.\n \"\"\"\n camera_object_dict = copy.copy(camera_object.__dict__)\n # We have to clean a little bit of camera_dict, as pixel_array and background are two very big numpy arrays.\n # They are not essential to caching process.\n # We also have to remove pixel_array_to_cairo_context as it contains used memory adress (set randomly). See l.516 get_cached_cairo_context in camera.py\n for to_clean in [\"background\", \"pixel_array\", \"pixel_array_to_cairo_context\"]:\n camera_object_dict.pop(to_clean, None)\n return camera_object_dict\n\n\ndef get_hash_from_play_call(\n scene_object, camera_object, animations_list, current_mobjects_list\n):\n \"\"\"Take the list of animations and a list of mobjects and output their hashes. This is meant to be used for `scene.play` function.\n\n Parameters\n -----------\n scene_object : :class:`~.Scene`\n The scene object.\n\n camera_object : :class:`~.Camera`\n The camera object used in the scene.\n\n animations_list : Iterable[:class:`~.Animation`]\n The list of animations.\n\n current_mobjects_list : Iterable[:class:`~.Mobject`]\n The list of mobjects.\n\n Returns\n -------\n :class:`str`\n A string concatenation of the respective hashes of `camera_object`, `animations_list` and `current_mobjects_list`, separated by `_`.\n \"\"\"\n logger.debug(\"Hashing ...\")\n global ALREADY_PROCESSED_ID\n # We add the scene object within the ALREADY_PROCESSED_ID, as we don't want to process because pretty much all of its attributes will be soon or later processed (in one of the three hashes).\n ALREADY_PROCESSED_ID = {id(scene_object): scene_object}\n t_start = perf_counter()\n camera_json = get_json(get_camera_dict_for_hashing(camera_object))\n animations_list_json = [get_json(x) for x in sorted(animations_list, key=str)]\n current_mobjects_list_json = [get_json(x) for x in current_mobjects_list]\n hash_camera, hash_animations, hash_current_mobjects = [\n zlib.crc32(repr(json_val).encode())\n for json_val in [camera_json, animations_list_json, current_mobjects_list_json]\n ]\n t_end = perf_counter()\n logger.debug(\"Hashing done in %(time)s s.\", {\"time\": str(t_end - t_start)[:8]})\n hash_complete = f\"{hash_camera}_{hash_animations}_{hash_current_mobjects}\"\n # This will reset ALREADY_PROCESSED_ID as all the hashing processus is finished.\n ALREADY_PROCESSED_ID = {}\n logger.debug(\"Hash generated : %(h)s\", {\"h\": hash_complete})\n return hash_complete\n\n\ndef get_hash_from_wait_call(\n scene_object,\n camera_object,\n wait_time,\n stop_condition_function,\n current_mobjects_list,\n):\n \"\"\"Take a wait time, a boolean function as a stop condition and a list of mobjects, and then output their individual hashes. This is meant to be used for `scene.wait` function.\n\n Parameters\n -----------\n scene_object : :class:`~.Scene`\n The scene object.\n camera_object : :class:`~.Camera`\n The camera object.\n wait_time : :class:`float`\n The time to wait\n stop_condition_function : Callable[[...], bool]\n Boolean function used as a stop_condition in `wait`.\n\n Returns\n -------\n :class:`str`\n A concatenation of the respective hashes of `animations_list and `current_mobjects_list`, separated by `_`.\n \"\"\"\n logger.debug(\"Hashing ...\")\n t_start = perf_counter()\n global ALREADY_PROCESSED_ID\n # We add the scene object within the ALREADY_PROCESSED_ID, as we don't want to process because pretty much all of its attributes will be soon or later processed (in one of the three hashes).\n ALREADY_PROCESSED_ID = {id(scene_object): scene_object}\n camera_json = get_json(get_camera_dict_for_hashing(camera_object))\n current_mobjects_list_json = [get_json(x) for x in current_mobjects_list]\n hash_current_mobjects = zlib.crc32(repr(current_mobjects_list_json).encode())\n hash_camera = zlib.crc32(repr(camera_json).encode())\n if stop_condition_function is not None:\n hash_function = zlib.crc32(get_json(stop_condition_function).encode())\n # This will reset ALREADY_PROCESSED_ID as all the hashing processus is finished.\n ALREADY_PROCESSED_ID = {}\n t_end = perf_counter()\n logger.debug(\"Hashing done in %(time)s s.\", {\"time\": str(t_end - t_start)[:8]})\n hash_complete = f\"{hash_camera}_{str(wait_time).replace('.', '-')}{hash_function}_{hash_current_mobjects}\"\n logger.debug(\"Hash generated : %(h)s\", {\"h\": hash_complete})\n return hash_complete\n ALREADY_PROCESSED_ID = {}\n t_end = perf_counter()\n logger.debug(\"Hashing done in %(time)s s.\", {\"time\": str(t_end - t_start)[:8]})\n hash_complete = (\n f\"{hash_camera}_{str(wait_time).replace('.', '-')}_{hash_current_mobjects}\"\n )\n\n logger.debug(\"Hash generated : %(h)s\", {\"h\": hash_complete})\n return hash_complete\n" ]
[ [ "numpy.resize" ] ]
viniciusd/DCO1008---Digital-Signal-Processing
[ "a2756cb577bcdaf8852e2ef766732799cde7f5a3" ]
[ "projeto2/question2.py" ]
[ "import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.io import loadmat\nfrom scipy.interpolate import interp1d\n\n\ndef _load_signal(name):\n try:\n sig = loadmat(name)\n except FileNotFoundError:\n raise\n condition = name.split('_')[-1]\n sig['t'] = sig.pop('t_%s' % condition).flatten()\n sig['hr'] = sig.pop('hr_%s' % condition).flatten()\n # Removes DC component\n sig['hr'] -= np.mean(sig['hr'])\n return sig\n\n\ndef _signal_fix_sample_rate(sig, rate):\n new_sig = dict()\n\n interp, ts = interp1d(sig['t'], sig['hr']), 1/rate\n\n new_sig['t'] = np.arange(sig['t'][0], sig['t'][-1], ts)\n new_sig['hr'] = interp(new_sig['t'])\n return new_sig\n\n\ndef signal_autocorr_plot(name):\n sig = _load_signal(name)\n plt.figure()\n plt.acorr(sig['hr'], usevlines=False, maxlags=35)\n plt.xlabel('Lags')\n plt.ylabel('Autocorrelation')\n plt.savefig('q2_acorr_%s.png' % name)\n\n\ndef signal_psd_plot(name):\n rate = 100\n sig = _signal_fix_sample_rate(\n _load_signal(name),\n rate\n )\n plt.figure()\n plt.psd(sig['hr']**2, Fs=rate)\n plt.savefig('q2_psd_%s.png' % name)\n\nif __name__ == '__main__':\n signal_autocorr_plot('Hr_pre')\n signal_autocorr_plot('Hr_med')\n signal_psd_plot('Hr_pre')\n signal_psd_plot('Hr_med')\n" ]
[ [ "scipy.io.loadmat", "scipy.interpolate.interp1d", "matplotlib.pyplot.figure", "matplotlib.pyplot.savefig", "numpy.arange", "matplotlib.pyplot.acorr", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.psd", "matplotlib.pyplot.xlabel", "numpy.mean" ] ]
danmar3/twodlearn
[ "02b23bf07618d5288e338bd8f312cc38aa58c195" ]
[ "twodlearn/core/autoinit.py" ]
[ "import numpy as np\nimport tensorflow as tf\nfrom . import variable\nfrom .options import global_options\n\n\nclass AutoinitType(object):\n ''' Base class to identify auto initializers '''\n pass\n\n\nclass AutoInit(object):\n ''' Indicates that the property should be auto initialized\n\n Example: ::\n\n TdlModel(prop=AutoInit()) # Runs auto initialization for prop\n\n If the property initializer accepts AutoType, the Type can be provided\n using a tuple: ::\n\n TdlModel(prop=(AutoInit(), AutoType))\n '''\n\n\nclass AutoTensor(AutoinitType):\n ''' auto initialize properties as tensorflow Tensors\n '''\n def __call__(self, value):\n if isinstance(value, tf.Tensor):\n return value\n else:\n return tf.convert_to_tensor(value)\n\n\nclass AutoConstant(AutoinitType):\n ''' auto initialize properties as tensorflow constants\n '''\n def __call__(self, *args, **kargs):\n return tf.constant(*args, **kargs)\n\n\nclass AutoVariable(AutoinitType):\n ''' auto initialize properties as variables\n\n If an initializer is provided, then shape must be specified: ::\n\n init = AutoVariable(initializer=tf.keras.initializer.glorot_uniform())\n var = init(shape=shape)\n\n Otherwise, calling AutoVariable expects an initial value or an initializer\n\n '''\n def __init__(self, initializer=None):\n self.initializer = initializer\n\n def __call__(self, *args, **kargs):\n if self.initializer is not None:\n if 'shape' not in kargs:\n raise TypeError('shape must be specified for an AutoVariable '\n 'that has an initializer.')\n if args:\n raise TypeError('arguments must be explicitly stated when '\n 'AutoVariable with an initializer.')\n shape = kargs['shape']\n kargs = {key: value for key, value in kargs.items()\n if key != 'shape'}\n return variable.variable(self.initializer(shape=shape),\n **kargs)\n else:\n return variable.variable(*args, **kargs)\n\n\nclass AutoConstantVariable(AutoinitType):\n ''' auto initialize properties as non-trainable vairables\n '''\n def __call__(self, *args, **kargs):\n return variable.variable(*args, trainable=False, **kargs)\n\n\nclass AutoTrainable(AutoinitType):\n ''' auto initialize properties as trainable vairables\n '''\n def __call__(self, *args, **kargs):\n return variable.variable(*args, trainable=True, **kargs)\n\n\nclass AutoPlaceholder(AutoinitType):\n def __call__(self, **kargs):\n ''' auto initialize properties as placeholders\n '''\n if 'dtype' not in kargs:\n kargs['dtype'] = global_options.float.tftype\n return tf.placeholder(**kargs)\n\n\nclass AutoZeros(AutoinitType):\n def __call__(self, **kargs):\n ''' auto initialize properties as placeholders\n '''\n if 'dtype' not in kargs:\n kargs['dtype'] = global_options.float.tftype\n return tf.zeros(**kargs)\n\n\nclass AutoNormalVar(AutoinitType):\n def __init__(self, mean, stddev):\n self.mean = mean\n self.stddev = stddev\n\n def __call__(self, shape, **kargs):\n ''' auto initialize properties as variables\n '''\n return variable.variable(\n tf.random_normal(shape=shape, mean=self.mean, stddev=self.stddev),\n **kargs)\n" ]
[ [ "tensorflow.zeros", "tensorflow.placeholder", "tensorflow.convert_to_tensor", "tensorflow.constant", "tensorflow.random_normal" ] ]
kamodulin/TRAILMAP
[ "1700eca3db070b02132ac1d9db8b9a80323d02cb" ]
[ "utilities/utilities.py" ]
[ "import numpy as np\nimport cv2\nimport os\nfrom os import listdir, makedirs\nfrom os.path import join\nfrom PIL import Image\nimport shutil\nimport sys\n\ndef crop_numpy(dim1, dim2, dim3, vol):\n return vol[dim1:vol.shape[0] - dim1, dim2:vol.shape[1] - dim2, dim3:vol.shape[2] - dim3]\n\n\ndef write_tiff_stack(vol, fname):\n im = Image.fromarray(vol[0])\n ims = []\n\n for i in range(1, vol.shape[0]):\n ims.append(Image.fromarray(vol[i]))\n\n im.save(fname, save_all=True, append_images=ims)\n\n\ndef get_dir(path):\n tiffs = [join(path, f) for f in listdir(path) if f[0] != '.']\n return sorted(tiffs)\n\n\ndef crop_cube(x, y, z, vol, cube_length=64):\n # Cube shape\n return crop_box(x, y, z, vol, (cube_length, cube_length, cube_length))\n\n\ndef crop_box(x, y, z, vol, shape):\n return vol[z:z + shape[2], x:x + shape[0], y:y + shape[1]]\n\n\n\"\"\"\nRead images from start_index to end_index from a folder\n\n@param path: The path to the folder\n@param start_index: The index of the image to start reading from inclusive\n@param end_index: The end of the image to stop reading from exclusive\n\n@raise FileNotFoundError: If the path to the folder cannot be found \n\"\"\"\ndef read_folder_section(path, start_index, end_index):\n fnames = get_dir(path)\n vol = []\n\n for f in fnames[start_index: end_index]:\n img = cv2.imread(f, cv2.COLOR_BGR2GRAY)\n vol.append(img)\n\n vol = np.array(vol)\n\n return vol\n\n\ndef read_folder_stack(path):\n fnames = get_dir(path)\n\n fnames.sort()\n vol = cv2.imread(fnames[0], cv2.COLOR_BGR2GRAY)\n\n if len(vol.shape) == 3:\n return vol\n\n vol = []\n\n for f in fnames:\n img = cv2.imread(f, cv2.COLOR_BGR2GRAY)\n vol.append(img)\n\n vol = np.array(vol)\n\n return vol\n\ndef write_folder_stack(vol, path):\n\n if os.path.exists(path):\n print(\"Overwriting \" + path)\n shutil.rmtree(path)\n\n makedirs(path)\n\n for i in range(vol.shape[0]):\n\n fname = os.path.join(path, \"slice\" + str(i).zfill(5) + \".tiff\")\n cv2.imwrite(fname, vol[i])\n\n\ndef read_tiff_stack(path):\n img = Image.open(path)\n images = []\n for i in range(img.n_frames):\n img.seek(i)\n slice = np.array(img)\n images.append(slice)\n\n return np.array(images)\n\n\ndef coordinate_vol(coords, shape):\n vol = np.zeros(shape, dtype=\"uint16\")\n for c in coords:\n vol[c[0], c[1], c[2]] = 1\n return vol\n\n\ndef preprocess(vol):\n return vol / 65535\n\n\ndef preprocess_batch(batch):\n assert len(batch.shape) == 5\n lst = []\n\n for i in range(batch.shape[0]):\n lst.append(preprocess(batch[i]))\n\n return np.array(lst)\n\n\ndef dist(p1, p2):\n sqr = (p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2 + (p1[2] - p2[2]) ** 2\n return sqr ** .5\n\n\n\n\"\"\"\nProgress bar to indicate status of the segment_brain function\n\"\"\"\n\ndef draw_progress_bar(percent, eta=\"\", bar_len = 40):\n # percent float from 0 to 1.\n sys.stdout.write(\"\\r\")\n sys.stdout.write(\"[{:<{}}] {:>3.0f}% {:20}\".format(\"=\" * int(bar_len * percent), bar_len, percent * 100, eta))\n sys.stdout.flush()\n" ]
[ [ "numpy.array", "numpy.zeros" ] ]
pprachas/ABC_dataset
[ "61c915853c0229295e728f869b11b113ee59f098" ]
[ "Domain/subdataset1_domain/subdataset1_mesh.py" ]
[ "import numpy as np\r\n\r\nimport pygmsh\r\nimport meshio\r\n\r\nimport sys\r\n#---------------------Beam Parameters----------------------------#\r\nL = 40 # length of beam\r\nw = 5 # wdith of beam\r\nr_max = w/10\r\nr_min = w/15\r\n#----------------------------------Import Files---------------------#\r\n# Change to directory of dowloaded txt files in folder subdataset1_geo\r\nf_x = 'subdataset1_geometry/x.npy'\r\nf_l = 'subdataset1_geometry/l.npy'\r\n\r\nx = np.load(f_x)\r\nl = np.load(f_l)\r\n\r\nfor ii in range(0,len(x)):\r\n#-----------------------------------pygmsh structure generation-----------------------------#\r\n geom = pygmsh.opencascade.Geometry(characteristic_length_min=r_min,characteristic_length_max=r_max)\r\n block = []\r\n for jj in range(0,len(x[ii])):\r\n block.append(geom.add_rectangle([x[ii][jj]-l[ii][jj],L-(L*(jj+1)/40),0],2*l[ii][jj],L/40))\r\n \r\n unit = geom.boolean_union(block)\r\n\r\n\r\n #----------------------------Add Boundaries----------------------------#\r\n bot = geom.add_rectangle([0.0,0.0,0.0],w,L/40)\r\n top = geom.add_rectangle([0.0,L-L/40,0.0],w,L/40)\r\n \r\n unit = geom.boolean_union([unit,top])\r\n unit = geom.boolean_union([unit,bot])\r\n \r\n #---------------------------Generate Mesh----------------------------------#\r\n mesh = pygmsh.generate_mesh(geom, prune_z_0 = True)\r\n \r\n \r\n fname_mesh = 'mesh/mesh'+str(len(x)*(num)+ii) + '.xml' #directory to save mesh\r\n \r\n print(fname_mesh)\r\n \r\n for cell in mesh.cells:\r\n if cell.type == \"triangle\":\r\n triangle_cells = cell.data\r\n \r\n meshio.write(fname_mesh,meshio.Mesh(points=mesh.points,cells={\"triangle\": triangle_cells}))\r\n" ]
[ [ "numpy.load" ] ]
kimhyeji/Mem2Seq
[ "6e6b7eacb4ae2e26517980c45046b0c519c918b7" ]
[ "models/enc_PTRUNK.py" ]
[ "import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch import optim\nimport torch.nn.functional as F\nfrom utils.masked_cross_entropy import *\nfrom utils.config import *\nimport random\nimport numpy as np\nimport datetime\nfrom utils.measures import wer,moses_multi_bleu\nfrom tqdm import tqdm\nfrom sklearn.metrics import f1_score\nimport math\nimport nsml\n\nclass PTRUNK(nn.Module):\n def __init__(self,hidden_size,max_len,max_r,lang,path,task,lr,n_layers, dropout):\n super(PTRUNK, self).__init__()\n self.name = \"PTRUNK\"\n self.task = task\n self.input_size = lang.n_words\n self.output_size = lang.n_words\n self.hidden_size = hidden_size\n self.max_len = max_len ## max input\n self.max_r = max_r ## max responce len \n self.lang = lang\n self.lr = lr\n self.decoder_learning_ratio = 5.0\n self.n_layers = n_layers\n self.dropout = dropout\n if path:\n if USE_CUDA:\n logging.info(\"MODEL {} LOADED\".format(str(path)))\n self.encoder = torch.load(str(path)+'/enc.th')\n self.decoder = torch.load(str(path)+'/dec.th')\n else:\n logging.info(\"MODEL {} LOADED\".format(str(path)))\n self.encoder = torch.load(str(path)+'/enc.th',lambda storage, loc: storage)\n self.decoder = torch.load(str(path)+'/dec.th',lambda storage, loc: storage)\n self.decoder.viz_arr =[] \n else:\n self.encoder = EncoderRNN(lang.n_words, hidden_size, n_layers,dropout)\n self.decoder = PtrDecoderRNN(hidden_size, lang.n_words, n_layers, dropout)\n # Initialize optimizers and criterion\n self.encoder_optimizer = optim.Adam(self.encoder.parameters(), lr=lr)\n self.decoder_optimizer = optim.Adam(self.decoder.parameters(), lr=lr* self.decoder_learning_ratio)\n self.criterion = nn.MSELoss()\n self.loss = 0\n self.loss_gate = 0\n self.loss_ptr = 0\n self.loss_vac = 0\n self.print_every = 1\n # Move models to GPU\n if USE_CUDA:\n self.encoder.cuda()\n self.decoder.cuda()\n\n def print_loss(self):\n print_loss_avg = self.loss / self.print_every\n print_loss_gate = self.loss_gate / self.print_every\n print_loss_ptr = self.loss_ptr / self.print_every\n print_loss_vac = self.loss_vac / self.print_every\n self.print_every += 1\n return 'L:{:.2f}, VL:{:.2f},GL:{:.2f}, PL:{:.2f}'.format(print_loss_avg,print_loss_vac,print_loss_gate,print_loss_ptr)\n \n def save_model(self,dec_type):\n name_data = \"KVR/\" if self.task=='' else \"BABI/\"\n if USEKB:\n directory = 'save/PTR_KB-'+name_data+str(self.task)+'HDD'+str(self.hidden_size)+'DR'+str(self.dropout)+'L'+str(self.n_layers)+'lr'+str(self.lr)+str(dec_type) \n else:\n directory = 'save/PTR_noKB-'+name_data+str(self.task)+'HDD'+str(self.hidden_size)+'DR'+str(self.dropout)+'L'+str(self.n_layers)+'lr'+str(self.lr)+str(dec_type) \n #directory = 'save/PTR_KVR_KB/'+str(self.task)+'HDD'+str(self.hidden_size)+'DR'+str(self.dropout)+'L'+str(self.n_layers)+'lr'+str(self.lr)+str(dec_type) #+datetime.datetime.now().strftime(\"%I%M%p%B%d%Y\"\n if not os.path.exists(directory):\n os.makedirs(directory)\n torch.save(self.encoder, directory+'/enc.th')\n torch.save(self.decoder, directory+'/dec.th')\n \n def train_batch(self, input_batches, input_lengths, target_batches, \n target_lengths, target_index, target_gate, batch_size, clip,\n teacher_forcing_ratio, reset):\n if reset:\n self.loss = 0\n self.loss_gate = 0\n self.loss_ptr = 0\n self.loss_vac = 0\n self.print_every = 1 \n # Zero gradients of both optimizers\n self.encoder_optimizer.zero_grad()\n self.decoder_optimizer.zero_grad()\n loss_Vocab,loss_Ptr,loss_Gate = 0,0,0\n # Run words through encoder\n encoder_outputs, encoder_hidden = self.encoder(input_batches, input_lengths)\n \n # Prepare input and output variables\n decoder_input = Variable(torch.LongTensor([SOS_token] * batch_size))\n decoder_hidden = (encoder_hidden[0][:self.decoder.n_layers],encoder_hidden[1][:self.decoder.n_layers])\n \n max_target_length = max(target_lengths)\n all_decoder_outputs_vocab = Variable(torch.zeros(max_target_length, batch_size, self.output_size))\n all_decoder_outputs_ptr = Variable(torch.zeros(max_target_length, batch_size, encoder_outputs.size(0)))\n all_decoder_outputs_gate = Variable(torch.zeros(max_target_length, batch_size))\n # Move new Variables to CUDA\n if USE_CUDA:\n all_decoder_outputs_vocab = all_decoder_outputs_vocab.cuda()\n all_decoder_outputs_ptr = all_decoder_outputs_ptr.cuda()\n all_decoder_outputs_gate = all_decoder_outputs_gate.cuda()\n decoder_input = decoder_input.cuda()\n\n # Choose whether to use teacher forcing\n use_teacher_forcing = random.random() < teacher_forcing_ratio\n \n if use_teacher_forcing: \n # Run through decoder one time step at a time\n for t in range(max_target_length):\n decoder_ptr,decoder_vacab,gate,decoder_hidden = self.decoder(\n decoder_input, decoder_hidden, encoder_outputs)\n\n all_decoder_outputs_vocab[t] = decoder_vacab\n all_decoder_outputs_ptr[t] = decoder_ptr.transpose(0,1)\n all_decoder_outputs_gate[t] = gate.squeeze(1)\n decoder_input = target_batches[t] # Next input is current target\n if USE_CUDA: decoder_input = decoder_input.cuda()\n \n else:\n for t in range(max_target_length):\n decoder_ptr,decoder_vacab,gate,decoder_hidden = self.decoder(\n decoder_input, decoder_hidden, encoder_outputs)\n all_decoder_outputs_vocab[t] = decoder_vacab\n all_decoder_outputs_ptr[t] = decoder_ptr.transpose(0,1) #\n all_decoder_outputs_gate[t] = gate.squeeze(1) #\n topv, topvi = decoder_vacab.data.topk(1)\n topp, toppi = decoder_ptr.data.topk(1)\n ## get the correspective word in input\n top_ptr_i = torch.gather(input_batches,0,toppi.view(1, -1))\n next_in = [top_ptr_i.squeeze()[i].data[0] if(gate.squeeze()[i].data[0]>=0.5) else topvi.squeeze()[i] for i in range(batch_size)]\n decoder_input = Variable(torch.LongTensor(next_in)) # Chosen word is next input\n if USE_CUDA: decoder_input = decoder_input.cuda()\n \n #Loss calculation and backpropagation\n loss_Vocab = masked_cross_entropy(\n all_decoder_outputs_vocab.transpose(0, 1).contiguous(), # -> batch x seq\n target_batches.transpose(0, 1).contiguous(), # -> batch x seq\n target_lengths\n )\n loss_Ptr = masked_cross_entropy(\n all_decoder_outputs_ptr.transpose(0, 1).contiguous(), # -> batch x seq\n target_index.transpose(0, 1).contiguous(), # -> batch x seq\n target_lengths\n )\n loss_gate = self.criterion(all_decoder_outputs_gate,target_gate.float())\n\n\n loss = loss_Vocab + loss_Ptr + loss_gate\n loss.backward()\n \n # Clip gradient norms\n ec = torch.nn.utils.clip_grad_norm_(self.encoder.parameters(), clip)\n dc = torch.nn.utils.clip_grad_norm_(self.decoder.parameters(), clip)\n # Update parameters with optimizers\n self.encoder_optimizer.step()\n self.decoder_optimizer.step()\n self.loss += loss.item()\n self.loss_gate += loss_gate.item()\n self.loss_ptr += loss_Ptr.item()\n self.loss_vac += loss_Vocab.item()\n \n \n def evaluate_batch(self,batch_size,input_batches, input_lengths, target_batches, target_lengths, target_index,target_gate,src_plain): \n # Set to not-training mode to disable dropout\n self.encoder.train(False)\n self.decoder.train(False) \n # Run words through encoder\n encoder_outputs, encoder_hidden = self.encoder(input_batches, input_lengths, None)\n # Prepare input and output variables\n decoder_input = Variable(torch.LongTensor([SOS_token] * batch_size))\n decoder_hidden = (encoder_hidden[0][:self.decoder.n_layers],encoder_hidden[1][:self.decoder.n_layers])\n\n decoded_words = []\n all_decoder_outputs_vocab = Variable(torch.zeros(self.max_r, batch_size, self.decoder.output_size))\n all_decoder_outputs_ptr = Variable(torch.zeros(self.max_r, batch_size, encoder_outputs.size(0)))\n all_decoder_outputs_gate = Variable(torch.zeros(self.max_r, batch_size))\n # Move new Variables to CUDA\n\n if USE_CUDA:\n all_decoder_outputs_vocab = all_decoder_outputs_vocab.cuda()\n all_decoder_outputs_ptr = all_decoder_outputs_ptr.cuda()\n all_decoder_outputs_gate = all_decoder_outputs_gate.cuda()\n decoder_input = decoder_input.cuda()\n p = []\n for elm in src_plain:\n p.append(elm.split(' '))\n # Run through decoder one time step at a time\n for t in range(self.max_r):\n decoder_ptr,decoder_vacab,gate,decoder_hidden = self.decoder(\n decoder_input, decoder_hidden, encoder_outputs)\n all_decoder_outputs_vocab[t] = decoder_vacab\n all_decoder_outputs_ptr[t] = decoder_ptr.transpose(0,1)\n all_decoder_outputs_gate[t] = gate.squeeze(1)\n\n topv, topvi = decoder_vacab.data.topk(1)\n topp, toppi = decoder_ptr.data.topk(1)\n top_ptr_i = torch.gather(input_batches,0,toppi.view(1, -1)) \n next_in = [top_ptr_i.squeeze()[i].item() if(gate.squeeze()[i].item()>=0.5) else topvi.squeeze()[i] for i in range(batch_size)]\n decoder_input = Variable(torch.LongTensor(next_in)) \n # Next input is chosen word\n if USE_CUDA: decoder_input = decoder_input.cuda()\n\n temp = []\n for i in range(batch_size):\n if(gate.squeeze()[i].item()>=0.5):\n if(toppi.squeeze()[i] >= len(p[i]) ):\n temp.append('<EOS>')\n else:\n temp.append(p[i][toppi.squeeze()[i]])\n else:\n ind = topvi.squeeze()[i]\n if ind == EOS_token:\n temp.append('<EOS>')\n else:\n temp.append(self.lang.index2word[ind.item()])\n decoded_words.append(temp)\n\n # Set back to training mode\n self.encoder.train(True)\n self.decoder.train(True) \n\n return decoded_words\n\n\n def evaluate(self,dev,avg_best,epoch = 0, BLEU=False):\n logging.info(\"STARTING EVALUATION\")\n acc_avg = 0.0\n wer_avg = 0.0\n acc_G = 0.0\n acc_P = 0.0\n acc_V = 0.0\n microF1_PRED,microF1_PRED_cal,microF1_PRED_nav,microF1_PRED_wet = [],[],[],[]\n microF1_TRUE,microF1_TRUE_cal,microF1_TRUE_nav,microF1_TRUE_wet = [],[],[],[]\n ref = []\n hyp = []\n pred = []\n if nsml.IS_ON_NSML:\n pbar = enumerate(dev)\n else:\n pbar = tqdm(enumerate(dev),total=len(dev))\n for j, data_dev in pbar: \n words = self.evaluate_batch(len(data_dev[1]),data_dev[0],data_dev[1],data_dev[2],data_dev[3],data_dev[4],data_dev[5],data_dev[6]) \n acc=0\n w = 0\n temp_gen = []\n for i, row in enumerate(np.transpose(words)):\n st = ''\n for e in row:\n if e== '<EOS>':\n break\n else:\n st+= e + ' '\n temp_gen.append(st)\n correct = data_dev[7][i]\n ### compute F1 SCORE \n if(len(data_dev)>10):\n f1_true,f1_pred = computeF1(data_dev[8][i],st.lstrip().rstrip(),correct.lstrip().rstrip())\n microF1_TRUE += f1_true\n microF1_PRED += f1_pred\n\n f1_true,f1_pred = computeF1(data_dev[9][i],st.lstrip().rstrip(),correct.lstrip().rstrip())\n microF1_TRUE_cal += f1_true\n microF1_PRED_cal += f1_pred \n\n f1_true,f1_pred = computeF1(data_dev[10][i],st.lstrip().rstrip(),correct.lstrip().rstrip())\n microF1_TRUE_nav += f1_true\n microF1_PRED_nav += f1_pred \n\n f1_true,f1_pred = computeF1(data_dev[11][i],st.lstrip().rstrip(),correct.lstrip().rstrip()) \n microF1_TRUE_wet += f1_true\n microF1_PRED_wet += f1_pred \n \n if (correct.lstrip().rstrip() == st.lstrip().rstrip()):\n acc+=1\n pred.append(\"O\")\n else:\n pred.append(\"X\")\n\n w += wer(correct.lstrip().rstrip(),st.lstrip().rstrip())\n ref.append(str(correct.lstrip().rstrip()))\n hyp.append(str(st.lstrip().rstrip()))\n\n acc_avg += acc/float(len(data_dev[1]))\n wer_avg += w/float(len(data_dev[1]))\n if not nsml.IS_ON_NSML:\n pbar.set_description(\"R:{:.4f},W:{:.4f}\".format(acc_avg/float(len(dev)),wer_avg/float(len(dev))))\n if(len(data_dev)>10):\n logging.info(\"F1 SCORE:\\t\"+str(f1_score(microF1_TRUE, microF1_PRED, average='micro')))\n logging.info(\"F1 CAL:\\t\"+str(f1_score(microF1_TRUE_cal, microF1_PRED_cal, average='micro')))\n logging.info(\"F1 WET:\\t\"+str(f1_score(microF1_TRUE_wet, microF1_PRED_wet, average='micro')))\n logging.info(\"F1 NAV:\\t\"+str(f1_score(microF1_TRUE_nav, microF1_PRED_nav, average='micro')))\n\n if (BLEU): \n bleu_score = moses_multi_bleu(np.array(hyp), np.array(ref), lowercase=True) \n logging.info(\"BLEU SCORE:\"+str(bleu_score)) \n \n if (bleu_score >= avg_best):\n self.save_model(str(self.name)+str(bleu_score))\n logging.info(\"MODEL SAVED\")\n return bleu_score\n else: \n acc_avg = acc_avg/float(len(dev))\n logging.info(\"ACC : {}\".format(str(acc_avg)))\n if (acc_avg >= avg_best):\n if nsml.IS_ON_NSML:\n pass\n else:\n self.save_model(str(self.name) + str(acc_avg))\n logging.info(\"MODEL SAVED\")\n '''\n if acc_avg > 0.33:\n for i in range(len(pred)):\n print(\"{} {} {}\".format(pred[i], ref[i], hyp[i]))\n '''\n return acc_avg\n\ndef computeF1(entity,st,correct):\n y_pred = [0 for z in range(len(entity))]\n y_true = [1 for z in range(len(entity))]\n for k in st.lstrip().rstrip().split(' '):\n if (k in entity):\n y_pred[entity.index(k)] = 1\n return y_true,y_pred\n\nclass EncoderRNN(nn.Module):\n def __init__(self, input_size, hidden_size, n_layers=1, dropout=0.1):\n super(EncoderRNN, self).__init__() \n self.input_size = input_size\n self.hidden_size = hidden_size\n self.n_layers = n_layers\n self.dropout = dropout \n self.embedding = nn.Embedding(input_size, hidden_size)\n self.embedding_dropout = nn.Dropout(dropout) \n self.cell = nn.LSTM(hidden_size, hidden_size, n_layers, dropout=self.dropout)\n if USE_CUDA:\n self.cell = self.cell.cuda()\n self.embedding_dropout = self.embedding_dropout.cuda()\n self.embedding = self.embedding.cuda() \n\n def get_state(self, input):\n \"\"\"Get cell states and hidden states.\"\"\"\n batch_size = input.size(1)\n c0_encoder = Variable(torch.zeros(self.n_layers, batch_size, self.hidden_size)) \n h0_encoder = Variable(torch.zeros(self.n_layers, batch_size, self.hidden_size)) ### * self.num_directions = 2 if bi\n if USE_CUDA:\n h0_encoder = h0_encoder.cuda()\n c0_encoder = c0_encoder.cuda() \n return (h0_encoder, c0_encoder)\n\n def forward(self, input_seqs, input_lengths, hidden=None):\n # Note: we run this all at once (over multiple batches of multiple sequences)\n embedded = self.embedding(input_seqs) # S * B * H\n embedded = self.embedding_dropout(embedded)\n hidden = self.get_state(input_seqs) # N * B * H\n if input_lengths:\n embedded = nn.utils.rnn.pack_padded_sequence(embedded, input_lengths, batch_first=False)\n \n outputs, hidden = self.cell(embedded, hidden)\n if input_lengths:\n outputs, _ = nn.utils.rnn.pad_packed_sequence(outputs, batch_first=False) # Max_S * B * H\n \n return outputs, hidden\n\nclass PtrDecoderRNN(nn.Module):\n def __init__(self, hidden_size, output_size, n_layers=1, dropout=0.1):\n super(PtrDecoderRNN, self).__init__()\n self.hidden_size = hidden_size\n self.output_size = output_size ### Vocab size\n self.n_layers = n_layers\n self.dropout = dropout\n self.embedding = nn.Embedding(output_size, hidden_size)\n self.embedding_dropout = nn.Dropout(dropout)\n self.cell = nn.LSTM(2*hidden_size, hidden_size, n_layers, dropout=dropout)\n self.W1 = nn.Linear(2*hidden_size, hidden_size)\n v = torch.rand(hidden_size)\n stdv = 1. / math.sqrt(v.size(0))\n v = v.data.normal_(mean=0, std=stdv)\n self.concat = nn.Linear(hidden_size * 2, hidden_size) \n self.U = nn.Linear(hidden_size, output_size)\n self.W = nn.Linear(hidden_size, 1)\n\n if USE_CUDA:\n self.embedding = self.embedding.cuda()\n self.embedding_dropout = self.embedding_dropout.cuda()\n self.cell = self.cell.cuda()\n self.W1 = self.W1.cuda() \n v = v.cuda()\n self.U = self.U.cuda() \n self.W = self.W.cuda()\n\n self.v = nn.Parameter(v)\n def forward(self, input_seq, last_hidden, encoder_outputs):\n # Note: we run this one step at a time \n # Get the embedding of the current input word (last output word)\n max_len = encoder_outputs.size(0) # MaxS\n batch_size = input_seq.size(0)\n input_seq = input_seq # B (word)\n encoder_outputs = encoder_outputs.transpose(0,1)\n \n word_embedded = self.embedding(input_seq) # S=1 x B x H\n word_embedded = self.embedding_dropout(word_embedded)\n\n ## ATTENTION CALCULATION \n s_t = last_hidden[0][-1].unsqueeze(0)\n H = s_t.repeat(max_len,1,1).transpose(0,1) # B * MaxS * H\n\n energy = F.tanh(self.W1(torch.cat([H,encoder_outputs], 2))) # B * MaxS * H\n energy = energy.transpose(2,1) # B * H * MaxS\n\n # NORMALIZATION\n v = self.v.repeat(encoder_outputs.data.shape[0],1).unsqueeze(1) #[B*1*H]\n p_ptr = torch.bmm(v,energy) # [B*1*MaxS]\n \n a = F.softmax(p_ptr)\n context = a.bmm(encoder_outputs) # B * 1 * H (encoder_output : B * MaxS * H)\n\n # Combine embedded input word and attended context, run through RNN\n if word_embedded.size() != context.squeeze().size():\n print(word_embedded.size(), context.squeeze().size())\n rnn_input = torch.cat((word_embedded, context.squeeze()), 1).unsqueeze(0)\n output, hidden = self.cell(rnn_input, last_hidden)\n \n p_vacab = self.U(output) # 1 * B * output_size\n \n gate = F.sigmoid(self.W(hidden[0][-1])) # B * 1\n\n return p_ptr,p_vacab,gate,hidden\n" ]
[ [ "torch.nn.LSTM", "torch.nn.Linear", "torch.nn.MSELoss", "torch.nn.utils.rnn.pack_padded_sequence", "torch.nn.utils.rnn.pad_packed_sequence", "numpy.transpose", "torch.nn.functional.softmax", "torch.rand", "torch.save", "numpy.array", "torch.nn.Embedding", "torch.nn.Parameter", "sklearn.metrics.f1_score", "torch.cat", "torch.zeros", "torch.LongTensor", "torch.bmm", "torch.nn.Dropout" ] ]
m0r13/pytorch-ssd
[ "c92dc5228f8e12df907f0e6f06646e9a2ec94a73" ]
[ "vision/ssd/predictor.py" ]
[ "import torch\n\nfrom ..utils import box_utils\nfrom .data_preprocessing import PredictionTransform\nfrom ..utils.misc import Timer\n\n\nclass Predictor:\n def __init__(self, net, size, mean=0.0, std=1.0, nms_method=None,\n iou_threshold=0.45, filter_threshold=0.01, candidate_size=200, sigma=0.5, device=None):\n self.net = net\n self.transform = PredictionTransform(size, mean, std)\n self.iou_threshold = iou_threshold\n self.filter_threshold = filter_threshold\n self.candidate_size = candidate_size\n self.nms_method = nms_method\n\n self.sigma = sigma\n if device:\n self.device = device\n else:\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n self.net.to(self.device)\n self.net.eval()\n\n self.timer = Timer()\n\n def predict(self, image, top_k=-1, prob_threshold=None):\n cpu_device = torch.device(\"cpu\")\n height, width, _ = image.shape\n image = self.transform(image)\n images = image.unsqueeze(0)\n images = images.to(self.device)\n with torch.no_grad():\n self.timer.start()\n scores, boxes = self.net.forward(images)\n #print(\"Inference time: \", self.timer.end())\n boxes = boxes[0]\n scores = scores[0]\n if not prob_threshold:\n prob_threshold = self.filter_threshold\n # this version of nms is slower on GPU, so we move data to CPU.\n boxes = boxes.to(cpu_device)\n scores = scores.to(cpu_device)\n picked_box_probs = []\n picked_labels = []\n for class_index in range(1, scores.size(1)):\n probs = scores[:, class_index]\n mask = probs > prob_threshold\n probs = probs[mask]\n if probs.size(0) == 0:\n continue\n subset_boxes = boxes[mask, :]\n box_probs = torch.cat([subset_boxes, probs.reshape(-1, 1)], dim=1)\n box_probs = box_utils.nms(box_probs, self.nms_method,\n score_threshold=prob_threshold,\n iou_threshold=self.iou_threshold,\n sigma=self.sigma,\n top_k=top_k,\n candidate_size=self.candidate_size)\n picked_box_probs.append(box_probs)\n picked_labels.extend([class_index] * box_probs.size(0))\n if not picked_box_probs:\n return torch.tensor([]), torch.tensor([]), torch.tensor([])\n picked_box_probs = torch.cat(picked_box_probs)\n picked_box_probs[:, 0] *= width\n picked_box_probs[:, 1] *= height\n picked_box_probs[:, 2] *= width\n picked_box_probs[:, 3] *= height\n return picked_box_probs[:, :4], torch.tensor(picked_labels), picked_box_probs[:, 4]" ]
[ [ "torch.no_grad", "torch.tensor", "torch.cuda.is_available", "torch.device", "torch.cat" ] ]
TorchSpatiotemporal/tsl
[ "da13493b0cf83826bf41fe78a67e8d4ce1d7a8a0" ]
[ "tsl/nn/base/dense.py" ]
[ "from torch import nn\n\nfrom tsl.nn.utils import utils\n\n\nclass Dense(nn.Module):\n r\"\"\"\n A simple fully-connected layer.\n\n Args:\n input_size (int): Size of the input.\n output_size (int): Size of the output.\n activation (str, optional): Activation function.\n dropout (float, optional): Dropout rate.\n bias (bool, optional): Whether to use a bias.\n \"\"\"\n def __init__(self, input_size, output_size, activation='linear', dropout=0., bias=True):\n super(Dense, self).__init__()\n self.layer = nn.Sequential(\n nn.Linear(input_size, output_size, bias=bias),\n utils.get_layer_activation(activation)(),\n nn.Dropout(dropout) if dropout > 0. else nn.Identity()\n )\n\n def forward(self, x):\n return self.layer(x)\n" ]
[ [ "torch.nn.Linear", "torch.nn.Dropout", "torch.nn.Identity" ] ]
sjk0709/Cartpole-DQN-pytorch041
[ "439e5be4bd7b44dd923c46f24e62b46b7dadfba4" ]
[ "CartPole_DQN2015_tf140/network.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\n\nimport gym \nfrom gym.envs.registration import register\nimport sys, os\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random as pr\n\n \nclass DQN:\n \n def __init__(self, session, input_size, output_size, name=\"policy\"):\n \n self.sess = session\n self.input_size = input_size\n self.output_size = output_size\n self.net_name = name\n \n self.kernel_regularizer = tf.contrib.layers.l2_regularizer(scale=1e-5)\n \n self.build_network()\n \n def build_network(self, h_size=16, learning_rate=1e-1):\n with tf.variable_scope(self.net_name):\n self.state = tf.placeholder(shape=[None, self.input_size], dtype=tf.float32, name=\"state\")\n self.action = tf.placeholder(shape=[None], dtype=tf.int32, name=\"action\" )\n \n dense1 = tf.layers.dense(inputs=self.state, units=h_size, activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n kernel_regularizer=self.kernel_regularizer)\n \n dense2 = tf.layers.dense(inputs=dense1, units=h_size, activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n kernel_regularizer=self.kernel_regularizer)\n \n# dense3 = tf.layers.dense(inputs=dense2, units=h_size, activation=tf.nn.relu,\n# kernel_initializer=tf.contrib.layers.xavier_initializer(),\n# kernel_regularizer=self.kernel_regularizer)\n \n self.output = tf.layers.dense(inputs=dense2, units=self.output_size, \n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n kernel_regularizer=self.kernel_regularizer)\n \n# # First layer of weights\n# W1 = tf.get_variable(\"W1\", shape=[self.input_size, h_size], initializer=tf.contrib.layers.xavier_initializer())\n# b1 = tf.Variable(tf.constant(0.1, shape=[h_size]))\n# layer1 = tf.nn.tanh(tf.matmul(self._X, W1)+b1)\n# \n# # Second layer of weights\n# W2 = tf.get_variable(\"W2\", shape=[h_size, h_size], initializer=tf.contrib.layers.xavier_initializer())\n# b2 = tf.Variable(tf.constant(0.1, shape=[h_size]))\n# layer2 = tf.nn.relu(tf.matmul(layer1, W2)+b2)\n# \n# W3 = tf.get_variable(\"W3\", shape=[h_size, self.output_size], initializer=tf.contrib.layers.xavier_initializer())\n# b3 = tf.Variable(tf.constant(0.1, shape=[self.output_size]))\n# # Q prediction\n# self._Qpred = tf.matmul(layer2, W3, name=\"Q\")+b3\n \n self.one_hot = tf.one_hot(self.action, self.output_size)\n# print(self.one_hot)\n self.Q = tf.reduce_sum(self.output*self.one_hot , axis=1)\n \n self.prob = tf.nn.softmax(self.output, name=\"prob\")\n # we need to define the parts of the network needed for learning a\n \n # policy\n self.Y = tf.placeholder(shape=[None], dtype=tf.float32)\n \n # Loss function\n self.loss = tf.reduce_mean(tf.square(self.Y - self.Q))\n \n # Learning\n self.train = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(self.loss)\n \n def predict(self, state):\n state = np.reshape(state, [-1, self.input_size])\n return self.sess.run(self.output, feed_dict={self.state: state})\n \n def update(self, state, action, y):\n return self.sess.run([self.loss, self.train], feed_dict={self.state: state, self.action: action, self.Y: y})\n \n" ]
[ [ "tensorflow.placeholder", "numpy.reshape", "tensorflow.train.AdamOptimizer", "tensorflow.variable_scope", "tensorflow.contrib.layers.l2_regularizer", "tensorflow.one_hot", "tensorflow.square", "tensorflow.contrib.layers.xavier_initializer", "tensorflow.nn.softmax", "tensorflow.reduce_sum" ] ]
goerz-forks/qutip
[ "759759e85f61e3619b37253a6f981f71abc442d6" ]
[ "qutip/qobj.py" ]
[ "# This file is part of QuTiP: Quantum Toolbox in Python.\n#\n# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names\n# of its contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n###############################################################################\n\"\"\"The Quantum Object (Qobj) class, for representing quantum states and\noperators, and related functions.\n\"\"\"\n\n__all__ = ['Qobj', 'qobj_list_evaluate', 'ptrace', 'dag', 'isequal',\n 'issuper', 'isoper', 'isoperket', 'isoperbra', 'isket', 'isbra',\n 'isherm', 'shape', 'dims']\n\nimport warnings\nimport types\n\ntry:\n import builtins\nexcept:\n import __builtin__ as builtins\n\n# import math functions from numpy.math: required for td string evaluation\nfrom numpy import (arccos, arccosh, arcsin, arcsinh, arctan, arctan2, arctanh,\n ceil, copysign, cos, cosh, degrees, e, exp, expm1, fabs,\n floor, fmod, frexp, hypot, isinf, isnan, ldexp, log, log10,\n log1p, modf, pi, radians, sin, sinh, sqrt, tan, tanh, trunc)\n\nimport numpy as np\nimport scipy.sparse as sp\nimport scipy.linalg as la\nimport qutip.settings as settings\nfrom qutip import __version__\nfrom qutip.fastsparse import fast_csr_matrix, fast_identity\nfrom qutip.cy.ptrace import _ptrace\nfrom qutip.permute import _permute\nfrom qutip.sparse import (sp_eigs, sp_expm, sp_fro_norm, sp_max_norm,\n sp_one_norm, sp_L2_norm)\nfrom qutip.dimensions import type_from_dims, enumerate_flat, collapse_dims_super\nfrom qutip.cy.spmath import (zcsr_transpose, zcsr_adjoint, zcsr_isherm,\n zcsr_trace, zcsr_proj, zcsr_inner)\nfrom qutip.cy.spmatfuncs import zcsr_mat_elem\nfrom qutip.cy.sparse_utils import cy_tidyup\nimport sys\nif sys.version_info.major >= 3:\n from itertools import zip_longest\nelif sys.version_info.major < 3:\n from itertools import izip_longest\n zip_longest = izip_longest\n\n#OPENMP stuff\nfrom qutip.cy.openmp.utilities import use_openmp\nif settings.has_openmp:\n from qutip.cy.openmp.omp_sparse_utils import omp_tidyup\n\n\nclass Qobj(object):\n \"\"\"A class for representing quantum objects, such as quantum operators\n and states.\n\n The Qobj class is the QuTiP representation of quantum operators and state\n vectors. This class also implements math operations +,-,* between Qobj\n instances (and / by a C-number), as well as a collection of common\n operator/state operations. The Qobj constructor optionally takes a\n dimension ``list`` and/or shape ``list`` as arguments.\n\n Parameters\n ----------\n inpt : array_like\n Data for vector/matrix representation of the quantum object.\n dims : list\n Dimensions of object used for tensor products.\n shape : list\n Shape of underlying data structure (matrix shape).\n copy : bool\n Flag specifying whether Qobj should get a copy of the\n input data, or use the original.\n fast : bool\n Flag for fast qobj creation when running ode solvers.\n This parameter is used internally only.\n\n\n Attributes\n ----------\n data : array_like\n Sparse matrix characterizing the quantum object.\n dims : list\n List of dimensions keeping track of the tensor structure.\n shape : list\n Shape of the underlying `data` array.\n type : str\n Type of quantum object: 'bra', 'ket', 'oper', 'operator-ket',\n 'operator-bra', or 'super'.\n superrep : str\n Representation used if `type` is 'super'. One of 'super'\n (Liouville form) or 'choi' (Choi matrix with tr = dimension).\n isherm : bool\n Indicates if quantum object represents Hermitian operator.\n isunitary : bool\n Indictaes if quantum object represents unitary operator.\n iscp : bool\n Indicates if the quantum object represents a map, and if that map is\n completely positive (CP).\n ishp : bool\n Indicates if the quantum object represents a map, and if that map is\n hermicity preserving (HP).\n istp : bool\n Indicates if the quantum object represents a map, and if that map is\n trace preserving (TP).\n iscptp : bool\n Indicates if the quantum object represents a map that is completely\n positive and trace preserving (CPTP).\n isket : bool\n Indicates if the quantum object represents a ket.\n isbra : bool\n Indicates if the quantum object represents a bra.\n isoper : bool\n Indicates if the quantum object represents an operator.\n issuper : bool\n Indicates if the quantum object represents a superoperator.\n isoperket : bool\n Indicates if the quantum object represents an operator in column vector\n form.\n isoperbra : bool\n Indicates if the quantum object represents an operator in row vector\n form.\n\n Methods\n -------\n copy()\n Create copy of Qobj\n conj()\n Conjugate of quantum object.\n cosm()\n Cosine of quantum object.\n dag()\n Adjoint (dagger) of quantum object.\n dnorm()\n Diamond norm of quantum operator.\n dual_chan()\n Dual channel of quantum object representing a CP map.\n eigenenergies(sparse=False, sort='low', eigvals=0, tol=0, maxiter=100000)\n Returns eigenenergies (eigenvalues) of a quantum object.\n eigenstates(sparse=False, sort='low', eigvals=0, tol=0, maxiter=100000)\n Returns eigenenergies and eigenstates of quantum object.\n expm()\n Matrix exponential of quantum object.\n full(order='C')\n Returns dense array of quantum object `data` attribute.\n groundstate(sparse=False, tol=0, maxiter=100000)\n Returns eigenvalue and eigenket for the groundstate of a quantum\n object.\n matrix_element(bra, ket)\n Returns the matrix element of operator between `bra` and `ket` vectors.\n norm(norm='tr', sparse=False, tol=0, maxiter=100000)\n Returns norm of a ket or an operator.\n permute(order)\n Returns composite qobj with indices reordered.\n proj()\n Computes the projector for a ket or bra vector.\n ptrace(sel)\n Returns quantum object for selected dimensions after performing\n partial trace.\n sinm()\n Sine of quantum object.\n sqrtm()\n Matrix square root of quantum object.\n tidyup(atol=1e-12)\n Removes small elements from quantum object.\n tr()\n Trace of quantum object.\n trans()\n Transpose of quantum object.\n transform(inpt, inverse=False)\n Performs a basis transformation defined by `inpt` matrix.\n trunc_neg(method='clip')\n Removes negative eigenvalues and returns a new Qobj that is\n a valid density operator.\n unit(norm='tr', sparse=False, tol=0, maxiter=100000)\n Returns normalized quantum object.\n\n \"\"\"\n __array_priority__ = 100 # sets Qobj priority above numpy arrays\n\n def __init__(self, inpt=None, dims=[[], []], shape=[],\n type=None, isherm=None, copy=True,\n fast=False, superrep=None, isunitary=None):\n \"\"\"\n Qobj constructor.\n \"\"\"\n self._isherm = isherm\n self._type = type\n self.superrep = superrep\n self._isunitary = isunitary\n\n if fast == 'mc':\n # fast Qobj construction for use in mcsolve with ket output\n self._data = inpt\n self.dims = dims\n self._isherm = False\n return\n\n if fast == 'mc-dm':\n # fast Qobj construction for use in mcsolve with dm output\n self._data = inpt\n self.dims = dims\n self._isherm = True\n return\n\n if isinstance(inpt, Qobj):\n # if input is already Qobj then return identical copy\n\n self._data = fast_csr_matrix((inpt.data.data, inpt.data.indices,\n inpt.data.indptr),\n shape=inpt.shape, copy=copy)\n\n if not np.any(dims):\n # Dimensions of quantum object used for keeping track of tensor\n # components\n self.dims = inpt.dims\n else:\n self.dims = dims\n\n self.superrep = inpt.superrep\n self._isunitary = inpt._isunitary\n\n elif inpt is None:\n # initialize an empty Qobj with correct dimensions and shape\n\n if any(dims):\n N, M = np.prod(dims[0]), np.prod(dims[1])\n self.dims = dims\n\n elif shape:\n N, M = shape\n self.dims = [[N], [M]]\n\n else:\n N, M = 1, 1\n self.dims = [[N], [M]]\n\n self._data = fast_csr_matrix(shape=(N, M))\n\n elif isinstance(inpt, list) or isinstance(inpt, tuple):\n # case where input is a list\n data = np.array(inpt)\n if len(data.shape) == 1:\n # if list has only one dimension (i.e [5,4])\n data = data.transpose()\n\n _tmp = sp.csr_matrix(data, dtype=complex)\n self._data = fast_csr_matrix((_tmp.data, _tmp.indices, _tmp.indptr),\n shape=_tmp.shape)\n if not np.any(dims):\n self.dims = [[int(data.shape[0])], [int(data.shape[1])]]\n else:\n self.dims = dims\n\n elif isinstance(inpt, np.ndarray) or sp.issparse(inpt):\n # case where input is array or sparse\n if inpt.ndim == 1:\n inpt = inpt[:, np.newaxis]\n\n do_copy = copy\n if not isinstance(inpt, fast_csr_matrix):\n _tmp = sp.csr_matrix(inpt, dtype=complex, copy=do_copy)\n _tmp.sort_indices() #Make sure indices are sorted.\n do_copy = 0\n else:\n _tmp = inpt\n self._data = fast_csr_matrix((_tmp.data, _tmp.indices, _tmp.indptr),\n shape=_tmp.shape, copy=do_copy)\n\n if not np.any(dims):\n self.dims = [[int(inpt.shape[0])], [int(inpt.shape[1])]]\n else:\n self.dims = dims\n\n elif isinstance(inpt, (int, float, complex,\n np.integer, np.floating, np.complexfloating)):\n # if input is int, float, or complex then convert to array\n _tmp = sp.csr_matrix([[inpt]], dtype=complex)\n self._data = fast_csr_matrix((_tmp.data, _tmp.indices, _tmp.indptr),\n shape=_tmp.shape)\n if not np.any(dims):\n self.dims = [[1], [1]]\n else:\n self.dims = dims\n\n else:\n warnings.warn(\"Initializing Qobj from unsupported type: %s\" %\n builtins.type(inpt))\n inpt = np.array([[0]])\n _tmp = sp.csr_matrix(inpt, dtype=complex, copy=copy)\n self._data = fast_csr_matrix((_tmp.data, _tmp.indices, _tmp.indptr),\n shape = _tmp.shape)\n self.dims = [[int(inpt.shape[0])], [int(inpt.shape[1])]]\n\n if type == 'super':\n # Type is not super, i.e. dims not explicitly passed, but oper shape\n if dims== [[], []] and self.shape[0] == self.shape[1]:\n sub_shape = np.sqrt(self.shape[0])\n # check if root of shape is int\n if (sub_shape % 1) != 0:\n raise Exception('Invalid shape for a super operator.')\n else:\n sub_shape = int(sub_shape)\n self.dims = [[[sub_shape], [sub_shape]]]*2\n\n\n if superrep:\n self.superrep = superrep\n else:\n if self.type == 'super' and self.superrep is None:\n self.superrep = 'super'\n\n # clear type cache\n self._type = None\n\n def copy(self):\n \"\"\"Create identical copy\"\"\"\n return Qobj(inpt=self)\n\n def get_data(self):\n return self._data\n #Here we perfrom a check of the csr matrix type during setting of Q.data\n def set_data(self, data):\n if not isinstance(data, fast_csr_matrix):\n raise TypeError('Qobj data must be in fast_csr format.')\n else:\n self._data = data\n data = property(get_data, set_data)\n\n def __add__(self, other):\n \"\"\"\n ADDITION with Qobj on LEFT [ ex. Qobj+4 ]\n \"\"\"\n self._isunitary = None\n\n if isinstance(other, eseries):\n return other.__radd__(self)\n\n if not isinstance(other, Qobj):\n if isinstance(other, (int, float, complex, np.integer, np.floating,\n np.complexfloating, np.ndarray, list, tuple)) \\\n or sp.issparse(other):\n other = Qobj(other)\n else:\n return NotImplemented\n\n if np.prod(other.shape) == 1 and np.prod(self.shape) != 1:\n # case for scalar quantum object\n dat = other.data[0, 0]\n if dat == 0:\n return self\n\n out = Qobj()\n\n if self.type in ['oper', 'super']:\n out.data = self.data + dat * fast_identity(\n self.shape[0])\n else:\n out.data = self.data\n out.data.data = out.data.data + dat\n\n out.dims = self.dims\n\n if settings.auto_tidyup: out.tidyup()\n\n if isinstance(dat, (int, float)):\n out._isherm = self._isherm\n else:\n # We use _isherm here to prevent recalculating on self and\n # other, relying on that bool(None) == False.\n out._isherm = (True if self._isherm and other._isherm\n else out.isherm)\n\n out.superrep = self.superrep\n\n return out\n\n elif np.prod(self.shape) == 1 and np.prod(other.shape) != 1:\n # case for scalar quantum object\n dat = self.data[0, 0]\n if dat == 0:\n return other\n\n out = Qobj()\n if other.type in ['oper', 'super']:\n out.data = dat * fast_identity(other.shape[0]) + other.data\n else:\n out.data = other.data\n out.data.data = out.data.data + dat\n out.dims = other.dims\n\n if settings.auto_tidyup: out.tidyup()\n\n if isinstance(dat, complex):\n out._isherm = out.isherm\n else:\n out._isherm = self._isherm\n\n out.superrep = self.superrep\n\n return out\n\n elif self.dims != other.dims:\n raise TypeError('Incompatible quantum object dimensions')\n\n elif self.shape != other.shape:\n raise TypeError('Matrix shapes do not match')\n\n else: # case for matching quantum objects\n out = Qobj()\n out.data = self.data + other.data\n out.dims = self.dims\n if settings.auto_tidyup: out.tidyup()\n\n if self.type in ['ket', 'bra', 'operator-ket', 'operator-bra']:\n out._isherm = False\n elif self._isherm is None or other._isherm is None:\n out._isherm = out.isherm\n elif not self._isherm and not other._isherm:\n out._isherm = out.isherm\n else:\n out._isherm = self._isherm and other._isherm\n\n if self.superrep and other.superrep:\n if self.superrep != other.superrep:\n msg = (\"Adding superoperators with different \" +\n \"representations\")\n warnings.warn(msg)\n\n out.superrep = self.superrep\n\n return out\n\n def __radd__(self, other):\n \"\"\"\n ADDITION with Qobj on RIGHT [ ex. 4+Qobj ]\n \"\"\"\n return self + other\n\n def __sub__(self, other):\n \"\"\"\n SUBTRACTION with Qobj on LEFT [ ex. Qobj-4 ]\n \"\"\"\n return self + (-other)\n\n def __rsub__(self, other):\n \"\"\"\n SUBTRACTION with Qobj on RIGHT [ ex. 4-Qobj ]\n \"\"\"\n return (-self) + other\n\n def __mul__(self, other):\n \"\"\"\n MULTIPLICATION with Qobj on LEFT [ ex. Qobj*4 ]\n \"\"\"\n self._isunitary = None\n\n if isinstance(other, Qobj):\n if self.dims[1] == other.dims[0]:\n out = Qobj()\n out.data = self.data * other.data\n dims = [self.dims[0], other.dims[1]]\n out.dims = dims\n if settings.auto_tidyup: out.tidyup()\n if (settings.auto_tidyup_dims\n and not isinstance(dims[0][0], list)\n and not isinstance(dims[1][0], list)):\n # If neither left or right is a superoperator,\n # we should implicitly partial trace over\n # matching dimensions of 1.\n # Using izip_longest allows for the left and right dims\n # to have uneven length (non-square Qobjs).\n # We use None as padding so that it doesn't match anything,\n # and will never cause a partial trace on the other side.\n mask = [l == r == 1 for l, r in zip_longest(dims[0], dims[1],\n fillvalue=None)]\n # To ensure that there are still any dimensions left, we\n # use max() to add a dimensions list of [1] if all matching dims\n # are traced out of that side.\n out.dims = [max([1],\n [dim for dim, m in zip(dims[0], mask)\n if not m]),\n max([1],\n [dim for dim, m in zip(dims[1], mask)\n if not m])]\n\n else:\n out.dims = dims\n\n out._isherm = None\n\n if self.superrep and other.superrep:\n if self.superrep != other.superrep:\n msg = (\"Multiplying superoperators with different \" +\n \"representations\")\n warnings.warn(msg)\n\n out.superrep = self.superrep\n\n return out\n\n elif np.prod(self.shape) == 1:\n out = Qobj(other)\n out.data *= self.data[0, 0]\n out.superrep = other.superrep\n return out.tidyup() if settings.auto_tidyup else out\n\n elif np.prod(other.shape) == 1:\n out = Qobj(self)\n out.data *= other.data[0, 0]\n out.superrep = self.superrep\n return out.tidyup() if settings.auto_tidyup else out\n\n else:\n raise TypeError(\"Incompatible Qobj shapes\")\n\n elif isinstance(other, np.ndarray):\n if other.dtype=='object':\n return np.array([self * item for item in other],\n dtype=object)\n else:\n return self.data * other\n\n\n elif isinstance(other, list):\n # if other is a list, do element-wise multiplication\n return np.array([self * item for item in other],\n dtype=object)\n\n elif isinstance(other, eseries):\n return other.__rmul__(self)\n\n elif isinstance(other, (int, float, complex,\n np.integer, np.floating, np.complexfloating)):\n out = Qobj()\n out.data = self.data * other\n out.dims = self.dims\n out.superrep = self.superrep\n if settings.auto_tidyup: out.tidyup()\n if isinstance(other, complex):\n out._isherm = out.isherm\n else:\n out._isherm = self._isherm\n\n return out\n\n else:\n return NotImplemented\n\n def __rmul__(self, other):\n \"\"\"\n MULTIPLICATION with Qobj on RIGHT [ ex. 4*Qobj ]\n \"\"\"\n if isinstance(other, np.ndarray):\n if other.dtype=='object':\n return np.array([item * self for item in other],\n dtype=object)\n else:\n return other * self.data\n\n elif isinstance(other, list):\n # if other is a list, do element-wise multiplication\n return np.array([item * self for item in other],\n dtype=object)\n\n elif isinstance(other, eseries):\n return other.__mul__(self)\n\n elif isinstance(other, (int, float, complex,\n np.integer, np.floating, np.complexfloating)):\n out = Qobj()\n out.data = other * self.data\n out.dims = self.dims\n out.superrep = self.superrep\n if settings.auto_tidyup: out.tidyup()\n if isinstance(other, complex):\n out._isherm = out.isherm\n else:\n out._isherm = self._isherm\n\n return out\n\n else:\n raise TypeError(\"Incompatible object for multiplication\")\n\n def __truediv__(self, other):\n return self.__div__(other)\n\n def __div__(self, other):\n \"\"\"\n DIVISION (by numbers only)\n \"\"\"\n if isinstance(other, Qobj): # if both are quantum objects\n raise TypeError(\"Incompatible Qobj shapes \" +\n \"[division with Qobj not implemented]\")\n\n if isinstance(other, (int, float, complex,\n np.integer, np.floating, np.complexfloating)):\n out = Qobj()\n out.data = self.data / other\n out.dims = self.dims\n if settings.auto_tidyup: out.tidyup()\n if isinstance(other, complex):\n out._isherm = out.isherm\n else:\n out._isherm = self._isherm\n\n out.superrep = self.superrep\n\n return out\n\n else:\n raise TypeError(\"Incompatible object for division\")\n\n def __neg__(self):\n \"\"\"\n NEGATION operation.\n \"\"\"\n out = Qobj()\n out.data = -self.data\n out.dims = self.dims\n out.superrep = self.superrep\n if settings.auto_tidyup: out.tidyup()\n out._isherm = self._isherm\n out._isunitary = self._isunitary\n return out\n\n def __getitem__(self, ind):\n \"\"\"\n GET qobj elements.\n \"\"\"\n out = self.data[ind]\n if sp.issparse(out):\n return np.asarray(out.todense())\n else:\n return out\n\n def __eq__(self, other):\n \"\"\"\n EQUALITY operator.\n \"\"\"\n if (isinstance(other, Qobj) and\n self.dims == other.dims and\n not np.any(np.abs((self.data - other.data).data) >\n settings.atol)):\n return True\n else:\n return False\n\n def __ne__(self, other):\n \"\"\"\n INEQUALITY operator.\n \"\"\"\n return not (self == other)\n\n def __pow__(self, n, m=None): # calculates powers of Qobj\n \"\"\"\n POWER operation.\n \"\"\"\n if self.type not in ['oper', 'super']:\n raise Exception(\"Raising a qobj to some power works only for \" +\n \"operators and super-operators (square matrices).\")\n\n if m is not None:\n raise NotImplementedError(\"modulo is not implemented for Qobj\")\n\n try:\n data = self.data ** n\n out = Qobj(data, dims=self.dims)\n out.superrep = self.superrep\n return out.tidyup() if settings.auto_tidyup else out\n\n except:\n raise ValueError('Invalid choice of exponent.')\n\n def __abs__(self):\n return abs(self.data)\n\n def __str__(self):\n s = \"\"\n t = self.type\n shape = self.shape\n if self.type in ['oper', 'super']:\n s += (\"Quantum object: \" +\n \"dims = \" + str(self.dims) +\n \", shape = \" + str(shape) +\n \", type = \" + t +\n \", isherm = \" + str(self.isherm) +\n (\n \", superrep = {0.superrep}\".format(self)\n if t == \"super\" and self.superrep != \"super\"\n else \"\"\n ) + \"\\n\")\n else:\n s += (\"Quantum object: \" +\n \"dims = \" + str(self.dims) +\n \", shape = \" + str(shape) +\n \", type = \" + t + \"\\n\")\n s += \"Qobj data =\\n\"\n\n if shape[0] > 10000 or shape[1] > 10000:\n # if the system is huge, don't attempt to convert to a\n # dense matrix and then to string, because it is pointless\n # and is likely going to produce memory errors. Instead print the\n # sparse data string representation\n s += str(self.data)\n\n elif all(np.imag(self.data.data) == 0):\n s += str(np.real(self.full()))\n\n else:\n s += str(self.full())\n\n return s\n\n def __repr__(self):\n # give complete information on Qobj without print statement in\n # command-line we cant realistically serialize a Qobj into a string,\n # so we simply return the informal __str__ representation instead.)\n return self.__str__()\n\n def __call__(self, other):\n \"\"\"\n Acts this Qobj on another Qobj either by left-multiplication,\n or by vectorization and devectorization, as\n appropriate.\n \"\"\"\n if not isinstance(other, Qobj):\n raise TypeError(\"Only defined for quantum objects.\")\n\n if self.type == \"super\":\n if other.type == \"ket\":\n other = qutip.states.ket2dm(other)\n\n if other.type == \"oper\":\n return qutip.superoperator.vector_to_operator(\n self * qutip.superoperator.operator_to_vector(other)\n )\n else:\n raise TypeError(\"Can only act super on oper or ket.\")\n\n elif self.type == \"oper\":\n if other.type == \"ket\":\n return self * other\n else:\n raise TypeError(\"Can only act oper on ket.\")\n\n def __getstate__(self):\n # defines what happens when Qobj object gets pickled\n self.__dict__.update({'qutip_version': __version__[:5]})\n return self.__dict__\n\n def __setstate__(self, state):\n # defines what happens when loading a pickled Qobj\n if 'qutip_version' in state.keys():\n del state['qutip_version']\n (self.__dict__).update(state)\n\n def _repr_latex_(self):\n \"\"\"\n Generate a LaTeX representation of the Qobj instance. Can be used for\n formatted output in ipython notebook.\n \"\"\"\n t = self.type\n shape = self.shape\n s = r''\n if self.type in ['oper', 'super']:\n s += (\"Quantum object: \" +\n \"dims = \" + str(self.dims) +\n \", shape = \" + str(shape) +\n \", type = \" + t +\n \", isherm = \" + str(self.isherm) +\n (\n \", superrep = {0.superrep}\".format(self)\n if t == \"super\" and self.superrep != \"super\"\n else \"\"\n ))\n else:\n s += (\"Quantum object: \" +\n \"dims = \" + str(self.dims) +\n \", shape = \" + str(shape) +\n \", type = \" + t)\n\n M, N = self.data.shape\n\n s += r'\\begin{equation*}\\left(\\begin{array}{*{11}c}'\n\n def _format_float(value):\n if value == 0.0:\n return \"0.0\"\n elif abs(value) > 1000.0 or abs(value) < 0.001:\n return (\"%.3e\" % value).replace(\"e\", r\"\\times10^{\") + \"}\"\n elif abs(value - int(value)) < 0.001:\n return \"%.1f\" % value\n else:\n return \"%.3f\" % value\n\n def _format_element(m, n, d):\n s = \" & \" if n > 0 else \"\"\n if type(d) == str:\n return s + d\n else:\n if abs(np.imag(d)) < settings.atol:\n return s + _format_float(np.real(d))\n elif abs(np.real(d)) < settings.atol:\n return s + _format_float(np.imag(d)) + \"j\"\n else:\n s_re = _format_float(np.real(d))\n s_im = _format_float(np.imag(d))\n if np.imag(d) > 0.0:\n return (s + \"(\" + s_re + \"+\" + s_im + \"j)\")\n else:\n return (s + \"(\" + s_re + s_im + \"j)\")\n\n if M > 10 and N > 10:\n # truncated matrix output\n for m in range(5):\n for n in range(5):\n s += _format_element(m, n, self.data[m, n])\n s += r' & \\cdots'\n for n in range(N - 5, N):\n s += _format_element(m, n, self.data[m, n])\n s += r'\\\\'\n\n for n in range(5):\n s += _format_element(m, n, r'\\vdots')\n s += r' & \\ddots'\n for n in range(N - 5, N):\n s += _format_element(m, n, r'\\vdots')\n s += r'\\\\'\n\n for m in range(M - 5, M):\n for n in range(5):\n s += _format_element(m, n, self.data[m, n])\n s += r' & \\cdots'\n for n in range(N - 5, N):\n s += _format_element(m, n, self.data[m, n])\n s += r'\\\\'\n\n elif M > 10 and N <= 10:\n # truncated vertically elongated matrix output\n for m in range(5):\n for n in range(N):\n s += _format_element(m, n, self.data[m, n])\n s += r'\\\\'\n\n for n in range(N):\n s += _format_element(m, n, r'\\vdots')\n s += r'\\\\'\n\n for m in range(M - 5, M):\n for n in range(N):\n s += _format_element(m, n, self.data[m, n])\n s += r'\\\\'\n\n elif M <= 10 and N > 10:\n # truncated horizontally elongated matrix output\n for m in range(M):\n for n in range(5):\n s += _format_element(m, n, self.data[m, n])\n s += r' & \\cdots'\n for n in range(N - 5, N):\n s += _format_element(m, n, self.data[m, n])\n s += r'\\\\'\n\n else:\n # full output\n for m in range(M):\n for n in range(N):\n s += _format_element(m, n, self.data[m, n])\n s += r'\\\\'\n\n s += r'\\end{array}\\right)\\end{equation*}'\n return s\n\n def dag(self):\n \"\"\"Adjoint operator of quantum object.\n \"\"\"\n out = Qobj()\n out.data = zcsr_adjoint(self.data)\n out.dims = [self.dims[1], self.dims[0]]\n out._isherm = self._isherm\n out.superrep = self.superrep\n return out\n\n def dual_chan(self):\n \"\"\"Dual channel of quantum object representing a completely positive\n map.\n \"\"\"\n # Uses the technique of Johnston and Kribs (arXiv:1102.0948), which\n # is only valid for completely positive maps.\n if not self.iscp:\n raise ValueError(\"Dual channels are only implemented for CP maps.\")\n J = sr.to_choi(self)\n tensor_idxs = enumerate_flat(J.dims)\n J_dual = tensor.tensor_swap(J, *(\n list(zip(tensor_idxs[0][1], tensor_idxs[0][0])) +\n list(zip(tensor_idxs[1][1], tensor_idxs[1][0]))\n )).trans()\n J_dual.superrep = 'choi'\n return J_dual\n\n\n def conj(self):\n \"\"\"Conjugate operator of quantum object.\n \"\"\"\n out = Qobj()\n out.data = self.data.conj()\n out.dims = [self.dims[0], self.dims[1]]\n return out\n\n def norm(self, norm=None, sparse=False, tol=0, maxiter=100000):\n \"\"\"Norm of a quantum object.\n\n Default norm is L2-norm for kets and trace-norm for operators.\n Other ket and operator norms may be specified using the `norm` and\n argument.\n\n Parameters\n ----------\n norm : str\n Which norm to use for ket/bra vectors: L2 'l2', max norm 'max',\n or for operators: trace 'tr', Frobius 'fro', one 'one', or max\n 'max'.\n\n sparse : bool\n Use sparse eigenvalue solver for trace norm. Other norms are not\n affected by this parameter.\n\n tol : float\n Tolerance for sparse solver (if used) for trace norm. The sparse\n solver may not converge if the tolerance is set too low.\n\n maxiter : int\n Maximum number of iterations performed by sparse solver (if used)\n for trace norm.\n\n Returns\n -------\n norm : float\n The requested norm of the operator or state quantum object.\n\n\n Notes\n -----\n The sparse eigensolver is much slower than the dense version.\n Use sparse only if memory requirements demand it.\n\n \"\"\"\n if self.type in ['oper', 'super']:\n if norm is None or norm == 'tr':\n _op = self*self.dag()\n vals = sp_eigs(_op.data, _op.isherm, vecs=False,\n sparse=sparse, tol=tol, maxiter=maxiter)\n return np.sum(np.sqrt(np.abs(vals)))\n elif norm == 'fro':\n return sp_fro_norm(self.data)\n elif norm == 'one':\n return sp_one_norm(self.data)\n elif norm == 'max':\n return sp_max_norm(self.data)\n else:\n raise ValueError(\n \"For matrices, norm must be 'tr', 'fro', 'one', or 'max'.\")\n else:\n if norm is None or norm == 'l2':\n return sp_L2_norm(self.data)\n elif norm == 'max':\n return sp_max_norm(self.data)\n else:\n raise ValueError(\"For vectors, norm must be 'l2', or 'max'.\")\n\n def proj(self):\n \"\"\"Form the projector from a given ket or bra vector.\n\n Parameters\n ----------\n Q : :class:`qutip.Qobj`\n Input bra or ket vector\n\n Returns\n -------\n P : :class:`qutip.Qobj`\n Projection operator.\n \"\"\"\n if self.isket:\n _out = zcsr_proj(self.data,1)\n _dims = [self.dims[0],self.dims[0]]\n elif self.isbra:\n _out = zcsr_proj(self.data,0)\n _dims = [self.dims[1],self.dims[1]]\n else:\n raise TypeError('Projector can only be formed from a bra or ket.')\n\n return Qobj(_out,dims=_dims)\n\n\n def tr(self):\n \"\"\"Trace of a quantum object.\n\n Returns\n -------\n trace : float\n Returns ``real`` if operator is Hermitian, returns ``complex``\n otherwise.\n\n \"\"\"\n return zcsr_trace(self.data, self.isherm)\n\n def full(self, order='C', squeeze=False):\n \"\"\"Dense array from quantum object.\n\n Parameters\n ----------\n order : str {'C', 'F'}\n Return array in C (default) or Fortran ordering.\n squeeze : bool {False, True}\n Squeeze output array.\n\n Returns\n -------\n data : array\n Array of complex data from quantum objects `data` attribute.\n \"\"\"\n if squeeze:\n return self.data.toarray(order=order).squeeze()\n else:\n return self.data.toarray(order=order)\n\n def __array__(self, *arg, **kwarg):\n \"\"\"Numpy array from Qobj\n For compatibility with np.array\n \"\"\"\n return self.full()\n\n def diag(self):\n \"\"\"Diagonal elements of quantum object.\n\n Returns\n -------\n diags : array\n Returns array of ``real`` values if operators is Hermitian,\n otherwise ``complex`` values are returned.\n\n \"\"\"\n out = self.data.diagonal()\n if np.any(np.imag(out) > settings.atol) or not self.isherm:\n return out\n else:\n return np.real(out)\n\n def expm(self, method='dense'):\n \"\"\"Matrix exponential of quantum operator.\n\n Input operator must be square.\n\n Parameters\n ----------\n method : str {'dense', 'sparse'}\n Use set method to use to calculate the matrix exponentiation. The\n available choices includes 'dense' and 'sparse'. Since the\n exponential of a matrix is nearly always dense, method='dense'\n is set as default.s\n\n Returns\n -------\n oper : :class:`qutip.Qobj`\n Exponentiated quantum operator.\n\n Raises\n ------\n TypeError\n Quantum operator is not square.\n\n \"\"\"\n if self.dims[0][0] != self.dims[1][0]:\n raise TypeError('Invalid operand for matrix exponential')\n\n if method == 'dense':\n F = sp_expm(self.data, sparse=False)\n\n elif method == 'sparse':\n F = sp_expm(self.data, sparse=True)\n\n else:\n raise ValueError(\"method must be 'dense' or 'sparse'.\")\n\n out = Qobj(F, dims=self.dims)\n return out.tidyup() if settings.auto_tidyup else out\n\n def check_herm(self):\n \"\"\"Check if the quantum object is hermitian.\n\n Returns\n -------\n isherm : bool\n Returns the new value of isherm property.\n \"\"\"\n self._isherm = None\n return self.isherm\n\n def sqrtm(self, sparse=False, tol=0, maxiter=100000):\n \"\"\"Sqrt of a quantum operator.\n\n Operator must be square.\n\n Parameters\n ----------\n sparse : bool\n Use sparse eigenvalue/vector solver.\n tol : float\n Tolerance used by sparse solver (0 = machine precision).\n maxiter : int\n Maximum number of iterations used by sparse solver.\n\n Returns\n -------\n oper : :class:`qutip.Qobj`\n Matrix square root of operator.\n\n Raises\n ------\n TypeError\n Quantum object is not square.\n\n Notes\n -----\n The sparse eigensolver is much slower than the dense version.\n Use sparse only if memory requirements demand it.\n\n \"\"\"\n if self.dims[0][0] == self.dims[1][0]:\n evals, evecs = sp_eigs(self.data, self.isherm, sparse=sparse,\n tol=tol, maxiter=maxiter)\n numevals = len(evals)\n dV = sp.spdiags(np.sqrt(evals, dtype=complex), 0, numevals,\n numevals, format='csr')\n if self.isherm:\n spDv = dV.dot(evecs.T.conj().T)\n else:\n spDv = dV.dot(np.linalg.inv(evecs.T))\n\n out = Qobj(evecs.T.dot(spDv), dims=self.dims)\n return out.tidyup() if settings.auto_tidyup else out\n\n else:\n raise TypeError('Invalid operand for matrix square root')\n\n\n def cosm(self):\n \"\"\"Cosine of a quantum operator.\n\n Operator must be square.\n\n Returns\n -------\n oper : :class:`qutip.Qobj`\n Matrix cosine of operator.\n\n Raises\n ------\n TypeError\n Quantum object is not square.\n\n Notes\n -----\n Uses the Q.expm() method.\n\n \"\"\"\n if self.dims[0][0] == self.dims[1][0]:\n return 0.5 * ((1j * self).expm() + (-1j * self).expm())\n else:\n raise TypeError('Invalid operand for matrix square root')\n\n\n def sinm(self):\n \"\"\"Sine of a quantum operator.\n\n Operator must be square.\n\n Returns\n -------\n oper : :class:`qutip.Qobj`\n Matrix sine of operator.\n\n Raises\n ------\n TypeError\n Quantum object is not square.\n\n Notes\n -----\n Uses the Q.expm() method.\n\n \"\"\"\n if self.dims[0][0] == self.dims[1][0]:\n return -0.5j * ((1j * self).expm() - (-1j * self).expm())\n else:\n raise TypeError('Invalid operand for matrix square root')\n\n\n\n def unit(self, inplace=False,\n norm=None, sparse=False,\n tol=0, maxiter=100000):\n \"\"\"Operator or state normalized to unity.\n\n Uses norm from Qobj.norm().\n\n Parameters\n ----------\n inplace : bool\n Do an in-place normalization\n norm : str\n Requested norm for states / operators.\n sparse : bool\n Use sparse eigensolver for trace norm. Does not affect other norms.\n tol : float\n Tolerance used by sparse eigensolver.\n maxiter : int\n Number of maximum iterations performed by sparse eigensolver.\n\n Returns\n -------\n oper : :class:`qutip.Qobj`\n Normalized quantum object if not in-place,\n else None.\n\n \"\"\"\n if inplace:\n nrm = self.norm(norm=norm, sparse=sparse,\n tol=tol, maxiter=maxiter)\n\n self.data /= nrm\n elif not inplace:\n out = self / self.norm(norm=norm, sparse=sparse,\n tol=tol, maxiter=maxiter)\n if settings.auto_tidyup:\n return out.tidyup()\n else:\n return out\n else:\n raise Exception('inplace kwarg must be bool.')\n\n def ptrace(self, sel):\n \"\"\"Partial trace of the quantum object.\n\n Parameters\n ----------\n sel : int/list\n An ``int`` or ``list`` of components to keep after partial trace.\n\n Returns\n -------\n oper : :class:`qutip.Qobj`\n Quantum object representing partial trace with selected components\n remaining.\n\n Notes\n -----\n This function is identical to the :func:`qutip.qobj.ptrace` function\n that has been deprecated.\n\n \"\"\"\n q = Qobj()\n q.data, q.dims, _ = _ptrace(self, sel)\n return q.tidyup() if settings.auto_tidyup else q\n\n def permute(self, order):\n \"\"\"Permutes a composite quantum object.\n\n Parameters\n ----------\n order : list/array\n List specifying new tensor order.\n\n Returns\n -------\n P : :class:`qutip.Qobj`\n Permuted quantum object.\n\n \"\"\"\n q = Qobj()\n q.data, q.dims = _permute(self, order)\n return q.tidyup() if settings.auto_tidyup else q\n\n def tidyup(self, atol=settings.auto_tidyup_atol):\n \"\"\"Removes small elements from the quantum object.\n\n Parameters\n ----------\n atol : float\n Absolute tolerance used by tidyup. Default is set\n via qutip global settings parameters.\n\n Returns\n -------\n oper : :class:`qutip.Qobj`\n Quantum object with small elements removed.\n\n \"\"\"\n if self.data.nnz:\n #This does the tidyup and returns True if\n #The sparse data needs to be shortened\n if use_openmp() and self.data.nnz > 500:\n if omp_tidyup(self.data.data,atol,self.data.nnz,\n settings.num_cpus):\n self.data.eliminate_zeros()\n else:\n if cy_tidyup(self.data.data,atol,self.data.nnz):\n self.data.eliminate_zeros()\n return self\n else:\n return self\n\n def transform(self, inpt, inverse=False, sparse=True):\n \"\"\"Basis transform defined by input array.\n\n Input array can be a ``matrix`` defining the transformation,\n or a ``list`` of kets that defines the new basis.\n\n\n Parameters\n ----------\n inpt : array_like\n A ``matrix`` or ``list`` of kets defining the transformation.\n inverse : bool\n Whether to return inverse transformation.\n sparse : bool\n Use sparse matrices when possible. Can be slower.\n\n Returns\n -------\n oper : :class:`qutip.Qobj`\n Operator in new basis.\n\n Notes\n -----\n This function is still in development.\n\n\n \"\"\"\n if isinstance(inpt, list) or (isinstance(inpt, np.ndarray) and\n len(inpt.shape) == 1):\n if len(inpt) != max(self.shape):\n raise TypeError(\n 'Invalid size of ket list for basis transformation')\n if sparse:\n S = sp.hstack([psi.data for psi in inpt],\n format='csr', dtype=complex).conj().T\n else:\n S = np.hstack([psi.full() for psi in inpt],\n dtype=complex).conj().T\n elif isinstance(inpt, Qobj) and inpt.isoper:\n S = inpt.data\n elif isinstance(inpt, np.ndarray):\n S = inpt.conj()\n sparse = False\n else:\n raise TypeError('Invalid operand for basis transformation')\n\n\n # transform data\n if inverse:\n if self.isket:\n data = (S.conj().T) * self.data\n elif self.isbra:\n data = self.data.dot(S)\n else:\n if sparse:\n data = (S.conj().T) * self.data * S\n else:\n data = (S.conj().T).dot(self.data.dot(S))\n else:\n if self.isket:\n data = S * self.data\n elif self.isbra:\n data = self.data.dot(S.conj().T)\n else:\n if sparse:\n data = S * self.data * (S.conj().T)\n else:\n data = S.dot(self.data.dot(S.conj().T))\n\n out = Qobj(data, dims=self.dims)\n out._isherm = self._isherm\n out.superrep = self.superrep\n\n if settings.auto_tidyup:\n return out.tidyup()\n else:\n return out\n\n\n\n def trunc_neg(self, method=\"clip\"):\n \"\"\"Truncates negative eigenvalues and renormalizes.\n\n Returns a new Qobj by removing the negative eigenvalues\n of this instance, then renormalizing to obtain a valid density\n operator.\n\n\n Parameters\n ----------\n method : str\n Algorithm to use to remove negative eigenvalues. \"clip\"\n simply discards negative eigenvalues, then renormalizes.\n \"sgs\" uses the SGS algorithm (doi:10/bb76) to find the\n positive operator that is nearest in the Shatten 2-norm.\n\n Returns\n -------\n oper : :class:`qutip.Qobj`\n A valid density operator.\n\n \"\"\"\n if not self.isherm:\n raise ValueError(\"Must be a Hermitian operator to remove negative \"\n \"eigenvalues.\")\n\n if method not in ('clip', 'sgs'):\n raise ValueError(\"Method {} not recognized.\".format(method))\n\n eigvals, eigstates = self.eigenstates()\n if all([eigval >= 0 for eigval in eigvals]):\n # All positive, so just renormalize.\n return self.unit()\n idx_nonzero = eigvals != 0\n eigvals = eigvals[idx_nonzero]\n eigstates = eigstates[idx_nonzero]\n\n if method == 'clip':\n eigvals[eigvals < 0] = 0\n elif method == 'sgs':\n eigvals = eigvals[::-1]\n eigstates = eigstates[::-1]\n\n acc = 0.0\n dim = self.shape[0]\n n_eigs = len(eigvals)\n\n for idx in reversed(range(n_eigs)):\n if eigvals[idx] + acc / (idx + 1) >= 0:\n break\n else:\n acc += eigvals[idx]\n eigvals[idx] = 0.0\n\n eigvals[:idx+1] += acc / (idx + 1)\n\n return sum([\n val * qutip.states.ket2dm(state)\n for val, state in zip(eigvals, eigstates)\n ], Qobj(np.zeros(self.shape), dims=self.dims)\n ).unit()\n\n\n def matrix_element(self, bra, ket):\n \"\"\"Calculates a matrix element.\n\n Gives the matrix element for the quantum object sandwiched between a\n `bra` and `ket` vector.\n\n Parameters\n -----------\n bra : :class:`qutip.Qobj`\n Quantum object of type 'bra' or 'ket'\n\n ket : :class:`qutip.Qobj`\n Quantum object of type 'ket'.\n\n Returns\n -------\n elem : complex\n Complex valued matrix element.\n\n Note\n ----\n It is slightly more computationally efficient to use a ket\n vector for the 'bra' input.\n\n \"\"\"\n if not self.isoper:\n raise TypeError(\"Can only get matrix elements for an operator.\")\n\n else:\n if bra.isbra and ket.isket:\n return zcsr_mat_elem(self.data,bra.data,ket.data,1)\n\n elif bra.isket and ket.isket:\n return zcsr_mat_elem(self.data,bra.data,ket.data,0)\n else:\n raise TypeError(\"Can only calculate matrix elements for bra and ket vectors.\")\n\n def overlap(self, other):\n \"\"\"Overlap between two state vectors or two operators.\n\n Gives the overlap (inner product) between the current bra or ket Qobj\n and and another bra or ket Qobj. It gives the Hilbert-Schmidt overlap\n when one of the Qobj is an operator/density matrix.\n\n Parameters\n -----------\n other : :class:`qutip.Qobj`\n Quantum object for a state vector of type 'ket', 'bra' or density\n matrix.\n\n Returns\n -------\n overlap : complex\n Complex valued overlap.\n\n Raises\n ------\n TypeError\n Can only calculate overlap between a bra, ket and density matrix\n quantum objects.\n\n Notes\n -----\n Since QuTiP mainly deals with ket vectors, the most efficient inner\n product call is the ket-ket version that computes the product\n <self|other> with both vectors expressed as kets.\n \"\"\"\n\n if isinstance(other, Qobj):\n\n if self.isbra:\n if other.isket:\n return zcsr_inner(self.data, other.data, 1)\n elif other.isbra:\n #Since we deal mainly with ket vectors, the bra-bra combo\n #is not common, and not optimized.\n return zcsr_inner(self.data, other.dag().data, 1)\n elif other.isoper:\n return (qutip.states.ket2dm(self).dag() * other).tr()\n else:\n raise TypeError(\"Can only calculate overlap for state vector Qobjs\")\n\n elif self.isket:\n if other.isbra:\n return zcsr_inner(other.data, self.data, 1)\n elif other.isket:\n return zcsr_inner(self.data, other.data, 0)\n elif other.isoper:\n return (qutip.states.ket2dm(self).dag() * other).tr()\n else:\n raise TypeError(\"Can only calculate overlap for state vector Qobjs\")\n\n elif self.isoper:\n if other.isket or other.isbra:\n return (self.dag() * qutip.states.ket2dm(other)).tr()\n elif other.isoper:\n return (self.dag() * other).tr()\n else:\n raise TypeError(\"Can only calculate overlap for state vector Qobjs\")\n\n\n raise TypeError(\"Can only calculate overlap for state vector Qobjs\")\n\n\n def eigenstates(self, sparse=False, sort='low',\n eigvals=0, tol=0, maxiter=100000):\n \"\"\"Eigenstates and eigenenergies.\n\n Eigenstates and eigenenergies are defined for operators and\n superoperators only.\n\n Parameters\n ----------\n sparse : bool\n Use sparse Eigensolver\n\n sort : str\n Sort eigenvalues (and vectors) 'low' to high, or 'high' to low.\n\n eigvals : int\n Number of requested eigenvalues. Default is all eigenvalues.\n\n tol : float\n Tolerance used by sparse Eigensolver (0 = machine precision).\n The sparse solver may not converge if the tolerance is set too low.\n\n maxiter : int\n Maximum number of iterations performed by sparse solver (if used).\n\n Returns\n -------\n eigvals : array\n Array of eigenvalues for operator.\n\n eigvecs : array\n Array of quantum operators representing the oprator eigenkets.\n Order of eigenkets is determined by order of eigenvalues.\n\n Notes\n -----\n The sparse eigensolver is much slower than the dense version.\n Use sparse only if memory requirements demand it.\n\n \"\"\"\n evals, evecs = sp_eigs(self.data, self.isherm, sparse=sparse,\n sort=sort, eigvals=eigvals, tol=tol,\n maxiter=maxiter)\n new_dims = [self.dims[0], [1] * len(self.dims[0])]\n ekets = np.array([Qobj(vec, dims=new_dims) for vec in evecs],\n dtype=object)\n norms = np.array([ket.norm() for ket in ekets])\n return evals, ekets / norms\n\n\n def eigenenergies(self, sparse=False, sort='low',\n eigvals=0, tol=0, maxiter=100000):\n \"\"\"Eigenenergies of a quantum object.\n\n Eigenenergies (eigenvalues) are defined for operators or superoperators\n only.\n\n Parameters\n ----------\n sparse : bool\n Use sparse Eigensolver\n sort : str\n Sort eigenvalues 'low' to high, or 'high' to low.\n eigvals : int\n Number of requested eigenvalues. Default is all eigenvalues.\n tol : float\n Tolerance used by sparse Eigensolver (0=machine precision).\n The sparse solver may not converge if the tolerance is set too low.\n maxiter : int\n Maximum number of iterations performed by sparse solver (if used).\n\n Returns\n -------\n eigvals : array\n Array of eigenvalues for operator.\n\n Notes\n -----\n The sparse eigensolver is much slower than the dense version.\n Use sparse only if memory requirements demand it.\n\n \"\"\"\n return sp_eigs(self.data, self.isherm, vecs=False, sparse=sparse,\n sort=sort, eigvals=eigvals, tol=tol, maxiter=maxiter)\n\n def groundstate(self, sparse=False, tol=0, maxiter=100000, safe=True):\n \"\"\"Ground state Eigenvalue and Eigenvector.\n\n Defined for quantum operators or superoperators only.\n\n Parameters\n ----------\n sparse : bool\n Use sparse Eigensolver\n tol : float\n Tolerance used by sparse Eigensolver (0 = machine precision).\n The sparse solver may not converge if the tolerance is set too low.\n maxiter : int\n Maximum number of iterations performed by sparse solver (if used).\n safe : bool (default=True)\n Check for degenerate ground state\n\n Returns\n -------\n eigval : float\n Eigenvalue for the ground state of quantum operator.\n eigvec : :class:`qutip.Qobj`\n Eigenket for the ground state of quantum operator.\n\n Notes\n -----\n The sparse eigensolver is much slower than the dense version.\n Use sparse only if memory requirements demand it.\n\n \"\"\"\n if safe:\n evals = 2\n else:\n evals = 1\n grndval, grndvec = sp_eigs(self.data, self.isherm, sparse=sparse,\n eigvals=evals, tol=tol, maxiter=maxiter)\n if safe:\n if tol == 0: tol = 1e-15\n if (grndval[1]-grndval[0]) <= 10*tol:\n print(\"WARNING: Ground state may be degenerate. \"\n \"Use Q.eigenstates()\")\n new_dims = [self.dims[0], [1] * len(self.dims[0])]\n grndvec = Qobj(grndvec[0], dims=new_dims)\n grndvec = grndvec / grndvec.norm()\n return grndval[0], grndvec\n\n def trans(self):\n \"\"\"Transposed operator.\n\n Returns\n -------\n oper : :class:`qutip.Qobj`\n Transpose of input operator.\n\n \"\"\"\n out = Qobj()\n out.data = zcsr_transpose(self.data)\n out.dims = [self.dims[1], self.dims[0]]\n return out\n\n def extract_states(self, states_inds, normalize=False):\n \"\"\"Qobj with states in state_inds only.\n\n Parameters\n ----------\n states_inds : list of integer\n The states that should be kept.\n\n normalize : True / False\n Weather or not the new Qobj instance should be normalized (default\n is False). For Qobjs that represents density matrices or state\n vectors normalized should probably be set to True, but for Qobjs\n that represents operators in for example an Hamiltonian, normalize\n should be False.\n\n Returns\n -------\n q : :class:`qutip.Qobj`\n A new instance of :class:`qutip.Qobj` that contains only the states\n corresponding to the indices in `state_inds`.\n\n Notes\n -----\n Experimental.\n\n \"\"\"\n if self.isoper:\n q = Qobj(self.data[states_inds, :][:, states_inds])\n elif self.isket:\n q = Qobj(self.data[states_inds, :])\n elif self.isbra:\n q = Qobj(self.data[:, states_inds])\n else:\n raise TypeError(\"Can only eliminate states from operators or \" +\n \"state vectors\")\n\n return q.unit() if normalize else q\n\n def eliminate_states(self, states_inds, normalize=False):\n \"\"\"Creates a new quantum object with states in state_inds eliminated.\n\n Parameters\n ----------\n states_inds : list of integer\n The states that should be removed.\n\n normalize : True / False\n Weather or not the new Qobj instance should be normalized (default\n is False). For Qobjs that represents density matrices or state\n vectors normalized should probably be set to True, but for Qobjs\n that represents operators in for example an Hamiltonian, normalize\n should be False.\n\n Returns\n -------\n q : :class:`qutip.Qobj`\n A new instance of :class:`qutip.Qobj` that contains only the states\n corresponding to indices that are **not** in `state_inds`.\n\n Notes\n -----\n Experimental.\n\n \"\"\"\n keep_indices = np.array([s not in states_inds\n for s in range(self.shape[0])]).nonzero()[0]\n\n return self.extract_states(keep_indices, normalize=normalize)\n\n def dnorm(self, B=None):\n \"\"\"Calculates the diamond norm, or the diamond distance to another\n operator.\n\n Parameters\n ----------\n B : :class:`qutip.Qobj` or None\n If B is not None, the diamond distance d(A, B) = dnorm(A - B) between\n this operator and B is returned instead of the diamond norm.\n\n Returns\n -------\n d : float\n Either the diamond norm of this operator, or the diamond distance\n from this operator to B.\n\n \"\"\"\n return mts.dnorm(self, B)\n\n\n @property\n def ishp(self):\n # FIXME: this needs to be cached in the same ways as isherm.\n if self.type in [\"super\", \"oper\"]:\n try:\n J = sr.to_choi(self)\n return J.isherm\n except:\n return False\n else:\n return False\n\n @property\n def iscp(self):\n # FIXME: this needs to be cached in the same ways as isherm.\n if self.type in [\"super\", \"oper\"]:\n try:\n J = (\n self\n # We can test with either Choi or chi, since the basis\n # transformation between them is unitary and hence\n # preserves the CP and TP conditions.\n if self.superrep in ('choi', 'chi')\n else sr.to_choi(self)\n )\n # If J isn't hermitian, then that could indicate either\n # that J is not normal, or is normal, but has complex eigenvalues.\n # In either case, it makes no sense to then demand that the\n # eigenvalues be non-negative.\n if not J.isherm:\n return False\n eigs = J.eigenenergies()\n return all(eigs >= -settings.atol)\n except:\n return False\n else:\n return False\n\n @property\n def istp(self):\n import qutip.superop_reps as sr\n if self.type in [\"super\", \"oper\"]:\n try:\n # Normalize to a super of type choi or chi.\n # We can test with either Choi or chi, since the basis\n # transformation between them is unitary and hence\n # preserves the CP and TP conditions.\n if self.type == \"super\" and self.superrep in ('choi', 'chi'):\n qobj = self\n else:\n qobj = sr.to_choi(self)\n\n # Possibly collapse dims.\n if any([len(index) > 1 for super_index in qobj.dims\n for index in super_index]):\n qobj = Qobj(qobj, dims=collapse_dims_super(qobj.dims))\n else:\n qobj = qobj\n\n # We use the condition from John Watrous' lecture notes,\n # Tr_1(J(Phi)) = identity_2.\n tr_oper = qobj.ptrace([0])\n ident = ops.identity(tr_oper.shape[0])\n return isequal(tr_oper, ident)\n except:\n return False\n else:\n return False\n\n @property\n def iscptp(self):\n from qutip.superop_reps import to_choi\n if self.type == \"super\" or self.type == \"oper\":\n reps = ('choi', 'chi')\n q_oper = to_choi(self) if self.superrep not in reps else self\n return q_oper.iscp and q_oper.istp\n else:\n return False\n\n @property\n def isherm(self):\n\n if self._isherm is not None:\n # used previously computed value\n return self._isherm\n\n self._isherm = bool(zcsr_isherm(self.data))\n\n return self._isherm\n\n @isherm.setter\n def isherm(self, isherm):\n self._isherm = isherm\n\n def check_isunitary(self):\n \"\"\"\n Checks whether qobj is a unitary matrix\n \"\"\"\n if self.isoper:\n eye_data = fast_identity(self.shape[0])\n return not (np.any(np.abs((self.data*self.dag().data\n - eye_data).data)\n > settings.atol)\n or\n np.any(np.abs((self.dag().data*self.data\n - eye_data).data) >\n settings.atol)\n )\n\n else:\n return False\n\n @property\n def isunitary(self):\n if self._isunitary is not None:\n # used previously computed value\n return self._isunitary\n\n self._isunitary = self.check_isunitary()\n\n return self._isunitary\n\n @isunitary.setter\n def isunitary(self, isunitary):\n self._isunitary = isunitary\n\n @property\n def type(self):\n if not self._type:\n self._type = type_from_dims(self.dims)\n\n return self._type\n\n @property\n def shape(self):\n if self.data.shape == (1, 1):\n return tuple([np.prod(self.dims[0]), np.prod(self.dims[1])])\n else:\n return tuple(self.data.shape)\n\n @property\n def isbra(self):\n return self.type == 'bra'\n\n @property\n def isket(self):\n return self.type == 'ket'\n\n @property\n def isoperbra(self):\n return self.type == 'operator-bra'\n\n @property\n def isoperket(self):\n return self.type == 'operator-ket'\n\n @property\n def isoper(self):\n return self.type == 'oper'\n\n @property\n def issuper(self):\n return self.type == 'super'\n\n @staticmethod\n def evaluate(qobj_list, t, args):\n \"\"\"Evaluate a time-dependent quantum object in list format. For\n example,\n\n qobj_list = [H0, [H1, func_t]]\n\n is evaluated to\n\n Qobj(t) = H0 + H1 * func_t(t, args)\n\n and\n\n qobj_list = [H0, [H1, 'sin(w * t)']]\n\n is evaluated to\n\n Qobj(t) = H0 + H1 * sin(args['w'] * t)\n\n Parameters\n ----------\n qobj_list : list\n A nested list of Qobj instances and corresponding time-dependent\n coefficients.\n t : float\n The time for which to evaluate the time-dependent Qobj instance.\n args : dictionary\n A dictionary with parameter values required to evaluate the\n time-dependent Qobj intance.\n\n Returns\n -------\n output : :class:`qutip.Qobj`\n A Qobj instance that represents the value of qobj_list at time t.\n\n \"\"\"\n\n q_sum = 0\n if isinstance(qobj_list, Qobj):\n q_sum = qobj_list\n elif isinstance(qobj_list, list):\n for q in qobj_list:\n if isinstance(q, Qobj):\n q_sum += q\n elif (isinstance(q, list) and len(q) == 2 and\n isinstance(q[0], Qobj)):\n if isinstance(q[1], types.FunctionType):\n q_sum += q[0] * q[1](t, args)\n elif isinstance(q[1], str):\n args['t'] = t\n q_sum += q[0] * float(eval(q[1], globals(), args))\n else:\n raise TypeError('Unrecognized format for ' +\n 'specification of time-dependent Qobj')\n else:\n raise TypeError('Unrecognized format for specification ' +\n 'of time-dependent Qobj')\n else:\n raise TypeError(\n 'Unrecongized format for specification of time-dependent Qobj')\n\n return q_sum\n\n\n# -----------------------------------------------------------------------------\n# This functions evaluates a time-dependent quantum object on the list-string\n# and list-function formats that are used by the time-dependent solvers.\n# Although not used directly in by those solvers, it can for test purposes be\n# conventient to be able to evaluate the expressions passed to the solver for\n# arbitrary value of time. This function provides this functionality.\n#\ndef qobj_list_evaluate(qobj_list, t, args):\n \"\"\"\n Depracated: See Qobj.evaluate\n \"\"\"\n warnings.warn(\"Deprecated: Use Qobj.evaluate\", DeprecationWarning)\n return Qobj.evaluate(qobj_list, t, args)\n\n\n# -----------------------------------------------------------------------------\n#\n# A collection of tests used to determine the type of quantum objects, and some\n# functions for increased compatibility with quantum optics toolbox.\n#\n\ndef dag(A):\n \"\"\"Adjont operator (dagger) of a quantum object.\n\n Parameters\n ----------\n A : :class:`qutip.Qobj`\n Input quantum object.\n\n Returns\n -------\n oper : :class:`qutip.Qobj`\n Adjoint of input operator\n\n Notes\n -----\n This function is for legacy compatibility only. It is recommended to use\n the ``dag()`` Qobj method.\n\n \"\"\"\n if not isinstance(A, Qobj):\n raise TypeError(\"Input is not a quantum object\")\n\n return A.dag()\n\n\ndef ptrace(Q, sel):\n \"\"\"Partial trace of the Qobj with selected components remaining.\n\n Parameters\n ----------\n Q : :class:`qutip.Qobj`\n Composite quantum object.\n sel : int/list\n An ``int`` or ``list`` of components to keep after partial trace.\n\n Returns\n -------\n oper : :class:`qutip.Qobj`\n Quantum object representing partial trace with selected components\n remaining.\n\n Notes\n -----\n This function is for legacy compatibility only. It is recommended to use\n the ``ptrace()`` Qobj method.\n\n \"\"\"\n if not isinstance(Q, Qobj):\n raise TypeError(\"Input is not a quantum object\")\n\n return Q.ptrace(sel)\n\n\ndef dims(inpt):\n \"\"\"Returns the dims attribute of a quantum object.\n\n Parameters\n ----------\n inpt : :class:`qutip.Qobj`\n Input quantum object.\n\n Returns\n -------\n dims : list\n A ``list`` of the quantum objects dimensions.\n\n Notes\n -----\n This function is for legacy compatibility only. Using the `Qobj.dims`\n attribute is recommended.\n\n \"\"\"\n if isinstance(inpt, Qobj):\n return inpt.dims\n else:\n raise TypeError(\"Input is not a quantum object\")\n\n\ndef shape(inpt):\n \"\"\"Returns the shape attribute of a quantum object.\n\n Parameters\n ----------\n inpt : :class:`qutip.Qobj`\n Input quantum object.\n\n Returns\n -------\n shape : list\n A ``list`` of the quantum objects shape.\n\n Notes\n -----\n This function is for legacy compatibility only. Using the `Qobj.shape`\n attribute is recommended.\n\n \"\"\"\n if isinstance(inpt, Qobj):\n return Qobj.shape\n else:\n return np.shape(inpt)\n\n\ndef isket(Q):\n \"\"\"\n Determines if given quantum object is a ket-vector.\n\n Parameters\n ----------\n Q : :class:`qutip.Qobj`\n Quantum object\n\n Returns\n -------\n isket : bool\n True if qobj is ket-vector, False otherwise.\n\n Examples\n --------\n >>> psi = basis(5,2)\n >>> isket(psi)\n True\n\n Notes\n -----\n This function is for legacy compatibility only. Using the `Qobj.isket`\n attribute is recommended.\n\n \"\"\"\n return True if isinstance(Q, Qobj) and Q.isket else False\n\n\ndef isbra(Q):\n \"\"\"Determines if given quantum object is a bra-vector.\n\n Parameters\n ----------\n Q : :class:`qutip.Qobj`\n Quantum object\n\n Returns\n -------\n isbra : bool\n True if Qobj is bra-vector, False otherwise.\n\n Examples\n --------\n >>> psi = basis(5,2)\n >>> isket(psi)\n False\n\n Notes\n -----\n This function is for legacy compatibility only. Using the `Qobj.isbra`\n attribute is recommended.\n\n \"\"\"\n return True if isinstance(Q, Qobj) and Q.isbra else False\n\n\ndef isoperket(Q):\n \"\"\"Determines if given quantum object is an operator in column vector form\n (operator-ket).\n\n Parameters\n ----------\n Q : :class:`qutip.Qobj`\n Quantum object\n\n Returns\n -------\n isoperket : bool\n True if Qobj is operator-ket, False otherwise.\n\n Notes\n -----\n This function is for legacy compatibility only. Using the `Qobj.isoperket`\n attribute is recommended.\n\n \"\"\"\n return True if isinstance(Q, Qobj) and Q.isoperket else False\n\n\ndef isoperbra(Q):\n \"\"\"Determines if given quantum object is an operator in row vector form\n (operator-bra).\n\n Parameters\n ----------\n Q : :class:`qutip.Qobj`\n Quantum object\n\n Returns\n -------\n isoperbra : bool\n True if Qobj is operator-bra, False otherwise.\n\n Notes\n -----\n This function is for legacy compatibility only. Using the `Qobj.isoperbra`\n attribute is recommended.\n\n \"\"\"\n return True if isinstance(Q, Qobj) and Q.isoperbra else False\n\n\ndef isoper(Q):\n \"\"\"Determines if given quantum object is a operator.\n\n Parameters\n ----------\n Q : :class:`qutip.Qobj`\n Quantum object\n\n Returns\n -------\n isoper : bool\n True if Qobj is operator, False otherwise.\n\n Examples\n --------\n >>> a = destroy(5)\n >>> isoper(a)\n True\n\n Notes\n -----\n This function is for legacy compatibility only. Using the `Qobj.isoper`\n attribute is recommended.\n\n \"\"\"\n return True if isinstance(Q, Qobj) and Q.isoper else False\n\n\ndef issuper(Q):\n \"\"\"Determines if given quantum object is a super-operator.\n\n Parameters\n ----------\n Q : :class:`qutip.Qobj`\n Quantum object\n\n Returns\n -------\n issuper : bool\n True if Qobj is superoperator, False otherwise.\n\n Notes\n -----\n This function is for legacy compatibility only. Using the `Qobj.issuper`\n attribute is recommended.\n\n \"\"\"\n return True if isinstance(Q, Qobj) and Q.issuper else False\n\n\ndef isequal(A, B, tol=None):\n \"\"\"Determines if two qobj objects are equal to within given tolerance.\n\n Parameters\n ----------\n A : :class:`qutip.Qobj`\n Qobj one\n B : :class:`qutip.Qobj`\n Qobj two\n tol : float\n Tolerence for equality to be valid\n\n Returns\n -------\n isequal : bool\n True if qobjs are equal, False otherwise.\n\n Notes\n -----\n This function is for legacy compatibility only. Instead, it is recommended\n to use the equality operator of Qobj instances instead: A == B.\n\n \"\"\"\n if tol is None:\n tol = settings.atol\n\n if not isinstance(A, Qobj) or not isinstance(B, Qobj):\n return False\n\n if A.dims != B.dims:\n return False\n\n Adat = A.data\n Bdat = B.data\n elems = (Adat - Bdat).data\n if np.any(np.abs(elems) > tol):\n return False\n\n return True\n\n\ndef isherm(Q):\n \"\"\"Determines if given operator is Hermitian.\n\n Parameters\n ----------\n Q : :class:`qutip.Qobj`\n Quantum object\n\n Returns\n -------\n isherm : bool\n True if operator is Hermitian, False otherwise.\n\n Examples\n --------\n >>> a = destroy(4)\n >>> isherm(a)\n False\n\n Notes\n -----\n This function is for legacy compatibility only. Using the `Qobj.isherm`\n attribute is recommended.\n\n \"\"\"\n return True if isinstance(Q, Qobj) and Q.isherm else False\n\n\n# TRAILING IMPORTS\n# We do a few imports here to avoid circular dependencies.\nfrom qutip.eseries import eseries\nimport qutip.superop_reps as sr\nimport qutip.tensor as tensor\nimport qutip.operators as ops\nimport qutip.metrics as mts\nimport qutip.states\nimport qutip.superoperator\n" ]
[ [ "numpy.zeros", "scipy.sparse.issparse", "numpy.linalg.inv", "numpy.any", "numpy.abs", "scipy.sparse.csr_matrix", "numpy.shape", "numpy.prod", "numpy.sqrt", "scipy.sparse.hstack", "numpy.array", "numpy.real", "numpy.imag" ] ]
biologioholic/sktime
[ "9d0391a04b11d22bd783b452f01aa5b4529b41a2", "9d0391a04b11d22bd783b452f01aa5b4529b41a2" ]
[ "sktime/classification/interval_based/tests/test_drcif.py", "sktime/annotation/adapters/_pyod.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"DrCIF test code.\"\"\"\nimport numpy as np\nfrom sklearn.metrics import accuracy_score\n\nfrom sktime.classification.interval_based import DrCIF\nfrom sktime.datasets import load_unit_test\n\n\ndef test_drcif_train_estimate():\n \"\"\"Test of DrCIF on unit test data.\"\"\"\n # load unit test data\n X_train, y_train = load_unit_test(split=\"train\")\n\n # train DrCIF\n drcif = DrCIF(\n n_estimators=2,\n n_intervals=2,\n att_subsample_size=2,\n random_state=0,\n save_transformed_data=True,\n )\n drcif.fit(X_train, y_train)\n\n # test train estimate\n train_probas = drcif._get_train_probs(X_train, y_train)\n assert train_probas.shape == (20, 2)\n train_preds = drcif.classes_[np.argmax(train_probas, axis=1)]\n assert accuracy_score(y_train, train_preds) >= 0.6\n\n\ndef test_contracted_drcif():\n \"\"\"Test of contracted DrCIF on unit test data.\"\"\"\n # load unit test data\n X_train, y_train = load_unit_test(split=\"train\")\n\n # train contracted DrCIF\n drcif = DrCIF(\n time_limit_in_minutes=0.25,\n contract_max_n_estimators=2,\n n_intervals=2,\n att_subsample_size=2,\n random_state=0,\n )\n drcif.fit(X_train, y_train)\n\n assert len(drcif.estimators_) > 1\n", "#!/usr/bin/env python3 -u\n# -*- coding: utf-8 -*-\n# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)\n\"\"\"Implements outlier detection from pyOD.\"\"\"\n\nimport numpy as np\nfrom sklearn.base import clone\n\nfrom sktime.annotation.base._base import BaseSeriesAnnotator\n\n__author__ = [\"mloning\", \"satya-pattnaik\", \"fkiraly\"]\n\nimport pandas as pd\n\n\nclass PyODAnnotator(BaseSeriesAnnotator):\n \"\"\"Transformer that applies outlier detector from pyOD.\n\n Parameters\n ----------\n estimator : PyOD estimator\n See ``https://pyod.readthedocs.io/en/latest/`` documentation for a detailed\n description of all options.\n fmt : str {\"dense\", \"sparse\"}, optional (default=\"dense\")\n Annotation output format:\n * If \"sparse\", a sub-series of labels for only the outliers in X is returned,\n * If \"dense\", a series of labels for all values in X is returned.\n labels : str {\"indicator\", \"score\"}, optional (default=\"indicator\")\n Annotation output labels:\n * If \"indicator\", returned values are boolean, indicating whether a value is an\n outlier,\n * If \"score\", returned values are floats, giving the outlier score.\n \"\"\"\n\n def __init__(self, estimator, fmt=\"dense\", labels=\"indicator\"):\n self.estimator = estimator # pyod estimator\n super(PyODAnnotator, self).__init__(fmt=fmt, labels=labels)\n\n def _fit(self, X, Y=None):\n \"\"\"Fit to training data.\n\n core logic\n\n Parameters\n ----------\n X : pd.DataFrame\n training data to fit model to, time series\n Y : pd.Series, optional\n ground truth annotations for training if annotator is supervised\n Returns\n -------\n self : returns a reference to self\n\n Notes\n -----\n Create fitted model that sets attributes ending in \"_\".\n \"\"\"\n X_np = X.to_numpy()\n\n if len(X_np.shape) == 1:\n X_np = X_np.reshape(-1, 1)\n\n self.estimator_ = clone(self.estimator)\n self.estimator_.fit(X_np)\n\n return self\n\n def _predict(self, X):\n \"\"\"Create annotations on test/deployment data.\n\n Parameters\n ----------\n X : pd.DataFrame - data to annotate, time series\n\n Returns\n -------\n Y : pd.Series - annotations for sequence X\n exact format depends on annotation type\n \"\"\"\n fmt = self.fmt\n labels = self.labels\n\n X_np = X.to_numpy()\n\n if len(X_np.shape) == 1:\n X_np = X_np.reshape(-1, 1)\n\n Y_np = self.estimator_.predict(X_np)\n\n if labels == \"score\":\n Y_val_np = self.estimator_.decision_function(X_np)\n elif labels == \"indicator\":\n Y_val_np = Y_np\n\n if fmt == \"dense\":\n Y = pd.Series(Y_val_np, index=X.index)\n elif fmt == \"sparse\":\n Y_loc = np.where(Y_np)\n Y = pd.Series(Y_val_np[Y_loc], index=X.index[Y_loc])\n\n return Y\n" ]
[ [ "sklearn.metrics.accuracy_score", "numpy.argmax" ], [ "numpy.where", "pandas.Series", "sklearn.base.clone" ] ]
sasmirnov/numba-dppy
[ "6ec41a5adab3034ddcfba2df312117afd6e2327b" ]
[ "numba_dppy/dpnp_glue/dpnp_array_creations_impl.py" ]
[ "# Copyright 2021 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numba_dppy.dpnp_glue.dpnpimpl as dpnp_ext\nfrom numba import types\nfrom numba.core.typing import signature\nfrom . import stubs\nimport numba_dppy.dpnp_glue as dpnp_lowering\nfrom numba.core.extending import overload, register_jitable\nimport numpy as np\nfrom numba_dppy import dpctl_functions\nimport numba_dppy\n\n\n@register_jitable\ndef common_impl(a, b, out, dpnp_func, PRINT_DEBUG):\n if a.size == 0:\n raise ValueError(\"Passed Empty array\")\n\n sycl_queue = dpctl_functions.get_current_queue()\n\n b_usm = dpctl_functions.malloc_shared(b.size * b.itemsize, sycl_queue)\n dpctl_functions.queue_memcpy(sycl_queue, b_usm, b.ctypes, b.size * b.itemsize)\n\n out_usm = dpctl_functions.malloc_shared(out.size * out.itemsize, sycl_queue)\n\n dpnp_func(out_usm, b_usm, a.size)\n\n dpctl_functions.queue_memcpy(\n sycl_queue, out.ctypes, out_usm, out.size * out.itemsize\n )\n\n dpctl_functions.free_with_queue(b_usm, sycl_queue)\n dpctl_functions.free_with_queue(out_usm, sycl_queue)\n\n dpnp_ext._dummy_liveness_func([a.size, out.size])\n\n if PRINT_DEBUG:\n print(\"dpnp implementation\")\n\n\n@register_jitable\ndef common_shape_impl(a, out, dpnp_func, PRINT_DEBUG):\n if a.size == 0:\n raise ValueError(\"Passed Empty array\")\n\n sycl_queue = dpctl_functions.get_current_queue()\n\n a_usm = dpctl_functions.malloc_shared(a.size * a.itemsize, sycl_queue)\n dpctl_functions.queue_memcpy(sycl_queue, a_usm, a.ctypes, a.size * a.itemsize)\n\n out_usm = dpctl_functions.malloc_shared(out.size * out.itemsize, sycl_queue)\n\n dpnp_func(a_usm, out_usm, a.shapeptr, a.ndim)\n\n dpctl_functions.queue_memcpy(\n sycl_queue, out.ctypes, out_usm, out.size * out.itemsize\n )\n\n dpctl_functions.free_with_queue(a_usm, sycl_queue)\n dpctl_functions.free_with_queue(out_usm, sycl_queue)\n\n dpnp_ext._dummy_liveness_func([a.size, out.size])\n\n if PRINT_DEBUG:\n print(\"dpnp implementation\")\n\n\n@overload(stubs.dpnp.zeros_like)\ndef dpnp_zeros_like_impl(a, dtype=None):\n name = \"zeros_like\"\n dpnp_lowering.ensure_dpnp(name)\n\n ret_type = types.void\n \"\"\"\n dpnp source:\n https://github.com/IntelPython/dpnp/blob/0.5.1/dpnp/backend/kernels/dpnp_krnl_common.cpp#L224\n\n Function declaration:\n void dpnp_initval_c(void* result1, void* value, size_t size)\n\n \"\"\"\n res_dtype = dtype\n if dtype == types.none:\n res_dtype = a.dtype\n name_dtype = res_dtype.name\n else:\n name_dtype = res_dtype.dtype.name\n\n sig = signature(ret_type, types.voidptr, types.voidptr, types.intp)\n dpnp_func = dpnp_ext.dpnp_func(\"dpnp_\" + name, [name_dtype, \"NONE\"], sig)\n\n PRINT_DEBUG = dpnp_lowering.DEBUG\n\n def dpnp_impl(a, dtype=None):\n b = np.zeros(1, dtype=res_dtype)\n out = np.zeros(a.shape, dtype=res_dtype)\n common_impl(a, b, out, dpnp_func, PRINT_DEBUG)\n return out\n\n return dpnp_impl\n\n\n@overload(stubs.dpnp.ones_like)\ndef dpnp_ones_like_impl(a, dtype=None):\n name = \"ones_like\"\n dpnp_lowering.ensure_dpnp(name)\n\n ret_type = types.void\n \"\"\"\n dpnp source:\n https://github.com/IntelPython/dpnp/blob/0.5.1/dpnp/backend/kernels/dpnp_krnl_common.cpp#L224\n\n Function declaration:\n void dpnp_initval_c(void* result1, void* value, size_t size)\n\n \"\"\"\n res_dtype = dtype\n if dtype == types.none:\n res_dtype = a.dtype\n name_dtype = res_dtype.name\n else:\n name_dtype = res_dtype.dtype.name\n\n sig = signature(ret_type, types.voidptr, types.voidptr, types.intp)\n dpnp_func = dpnp_ext.dpnp_func(\"dpnp_\" + name, [name_dtype, \"NONE\"], sig)\n\n PRINT_DEBUG = dpnp_lowering.DEBUG\n\n def dpnp_impl(a, dtype=None):\n b = np.ones(1, dtype=res_dtype)\n out = np.ones(a.shape, dtype=res_dtype)\n common_impl(a, b, out, dpnp_func, PRINT_DEBUG)\n return out\n\n return dpnp_impl\n\n\n@overload(stubs.dpnp.full_like)\ndef dpnp_full_like_impl(a, b):\n name = \"full_like\"\n dpnp_lowering.ensure_dpnp(name)\n\n ret_type = types.void\n \"\"\"\n dpnp source:\n https://github.com/IntelPython/dpnp/blob/0.5.1/dpnp/backend/kernels/dpnp_krnl_common.cpp#L224\n\n Function declaration:\n void dpnp_initval_c(void* result1, void* value, size_t size)\n\n \"\"\"\n sig = signature(ret_type, types.voidptr, types.voidptr, types.intp)\n dpnp_func = dpnp_ext.dpnp_func(\"dpnp_\" + name, [b.dtype.name, \"NONE\"], sig)\n\n res_dtype = b.dtype\n PRINT_DEBUG = dpnp_lowering.DEBUG\n\n def dpnp_impl(a, b):\n out = np.ones(a.shape, dtype=res_dtype)\n common_impl(a, b, out, dpnp_func, PRINT_DEBUG)\n return out\n\n return dpnp_impl\n\n\n# TODO: This implementation is incorrect\n@overload(stubs.dpnp.full)\ndef dpnp_full_impl(a, b):\n name = \"full\"\n dpnp_lowering.ensure_dpnp(name)\n\n ret_type = types.void\n \"\"\"\n dpnp source:\n https://github.com/IntelPython/dpnp/blob/0.5.1/dpnp/backend/kernels/dpnp_krnl_arraycreation.cpp#L70\n\n Function declaration:\n void dpnp_full_c(void* array_in, void* result, const size_t size)\n\n \"\"\"\n sig = signature(ret_type, types.voidptr, types.voidptr, types.intp)\n dpnp_func = dpnp_ext.dpnp_func(\"dpnp_\" + name, [b.dtype.name, \"NONE\"], sig)\n\n res_dtype = b.dtype\n PRINT_DEBUG = dpnp_lowering.DEBUG\n\n def dpnp_impl(a, b):\n if a.size == 0:\n raise ValueError(\"Passed Empty array\")\n\n sycl_queue = dpctl_functions.get_current_queue()\n\n b_usm = dpctl_functions.malloc_shared(b.size * b.itemsize, sycl_queue)\n dpctl_functions.queue_memcpy(sycl_queue, b_usm, b.ctypes, b.size * b.itemsize)\n\n out = np.arange(a.size, dtype=res_dtype)\n out_usm = dpctl_functions.malloc_shared(out.size * out.itemsize, sycl_queue)\n\n dpnp_func(b_usm, out_usm, a.size)\n\n dpctl_functions.queue_memcpy(\n sycl_queue, out.ctypes, out_usm, out.size * out.itemsize\n )\n\n dpctl_functions.free_with_queue(b_usm, sycl_queue)\n dpctl_functions.free_with_queue(out_usm, sycl_queue)\n\n dpnp_ext._dummy_liveness_func([a.size, out.size])\n\n if PRINT_DEBUG:\n print(\"dpnp implementation\")\n return out\n\n return dpnp_impl\n\n\n@overload(stubs.dpnp.trace)\ndef dpnp_trace_impl(a):\n name = \"trace\"\n dpnp_lowering.ensure_dpnp(name)\n\n ret_type = types.void\n \"\"\"\n dpnp source:\n https://github.com/IntelPython/dpnp/blob/0.6.2/dpnp/backend/kernels/dpnp_krnl_arraycreation.cpp#L218\n\n Function declaration:\n void dpnp_trace_c(const void* array1_in, void* result1, const size_t* shape_, const size_t ndim)\n\n \"\"\"\n sig = signature(ret_type, types.voidptr, types.voidptr, types.voidptr, types.intp)\n dpnp_func = dpnp_ext.dpnp_func(\"dpnp_\" + name, [a.dtype.name, \"NONE\"], sig)\n\n PRINT_DEBUG = dpnp_lowering.DEBUG\n\n def dpnp_impl(a):\n diag_arr = numba_dppy.dpnp.diagonal(a, 0)\n out = np.zeros(diag_arr.shape[:-1], dtype=a.dtype)\n common_shape_impl(diag_arr, out, dpnp_func, PRINT_DEBUG)\n return out\n\n return dpnp_impl\n" ]
[ [ "numpy.arange", "numpy.ones", "numpy.zeros" ] ]
computerwala/tensorflow
[ "97164413d009aa6506f269eff7fb78411419146d", "766eb63f2f3e43cd8b23c1cbb05fe63dd918ffa3" ]
[ "tensorflow/python/ops/ragged/ragged_math_ops.py", "tensorflow/python/autograph/impl/api.py" ]
[ "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Support for ragged tensors.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import check_ops\nfrom tensorflow.python.ops import gen_ragged_math_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops.ragged import ragged_functional_ops\nfrom tensorflow.python.ops.ragged import ragged_tensor\nfrom tensorflow.python.ops.ragged import ragged_util\nfrom tensorflow.python.ops.ragged import segment_id_ops\n\n\n#===============================================================================\n# ragged.range\n#===============================================================================\n# pylint: disable=redefined-builtin\ndef range(starts, limits=None, deltas=1, dtype=None, name=None):\n \"\"\"Returns a `RaggedTensor` containing the specified sequences of numbers.\n\n Each row of the returned `RaggedTensor` contains a single sequence:\n\n ```python\n ragged.range(starts, limits, deltas)[i] ==\n tf.range(starts[i], limits[i], deltas[i])\n ```\n\n If `start[i] < limits[i] and deltas[i] > 0`, then `output[i]` will be an\n empty list. Similarly, if `start[i] > limits[i] and deltas[i] < 0`, then\n `output[i]` will be an empty list. This behavior is consistent with the\n Python `range` function, but differs from the `tf.range` op, which returns\n an error for these cases.\n\n Examples:\n\n ```python\n >>> ragged.range([3, 5, 2]).eval().tolist()\n [[0, 1, 2], [0, 1, 2, 3, 4], [0, 1]]\n >>> ragged.range([0, 5, 8], [3, 3, 12]).eval().tolist()\n [[0, 1, 2], [], [8, 9, 10, 11]]\n >>> ragged.range([0, 5, 8], [3, 3, 12], 2).eval().tolist()\n [[0, 2], [], [8, 10]]\n ```\n\n The input tensors `starts`, `limits`, and `deltas` may be scalars or vectors.\n The vector inputs must all have the same size. Scalar inputs are broadcast\n to match the size of the vector inputs.\n\n Args:\n starts: Vector or scalar `Tensor`. Specifies the first entry for each range\n if `limits` is not `None`; otherwise, specifies the range limits, and the\n first entries default to `0`.\n limits: Vector or scalar `Tensor`. Specifies the exclusive upper limits for\n each range.\n deltas: Vector or scalar `Tensor`. Specifies the increment for each range.\n Defaults to `1`.\n dtype: The type of the elements of the resulting tensor. If not specified,\n then a value is chosen based on the other args.\n name: A name for the operation.\n\n Returns:\n A `RaggedTensor` of type `dtype` with `ragged_rank=1`.\n \"\"\"\n if limits is None:\n starts, limits = 0, starts\n\n with ops.name_scope(name, 'RaggedRange', [starts, limits, deltas]) as name:\n starts = ops.convert_to_tensor(starts, dtype=dtype, name='starts')\n limits = ops.convert_to_tensor(limits, dtype=dtype, name='limits')\n deltas = ops.convert_to_tensor(deltas, dtype=dtype, name='deltas')\n\n # infer dtype if not explicitly provided\n if dtype is None:\n starts, limits, deltas = _infer_matching_dtype(\n [starts, limits, deltas],\n [dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64])\n\n result = gen_ragged_math_ops.ragged_range(starts, limits, deltas, name=name)\n return ragged_tensor.RaggedTensor.from_row_splits(result.rt_dense_values,\n result.rt_nested_splits)\n\n\ndef _infer_matching_dtype(tensors, dtype_hierarchy):\n \"\"\"Infers a matching dtype for tensors, and casts them to that dtype.\"\"\"\n assert all(t.dtype in dtype_hierarchy for t in tensors)\n inferred_dtype = max([t.dtype for t in tensors], key=dtype_hierarchy.index)\n return [math_ops.cast(t, inferred_dtype) for t in tensors]\n\n\n#===============================================================================\n# ragged_segment_<AGGREGATE>\n#===============================================================================\n\n# Docstring template used for the raggged_segment_<AGGREGATE> ops.\n_RAGGED_SEGMENT_DOCSTRING = \"\"\"\\\nComputes the %(combination)s along segments of a RaggedTensor.\n\n Returns a RaggedTensor `output` with `num_segments` rows, where the row\n `output[i]` is formed by taking the %(combination)s of all rows of `data`\n whose corresponding `segment_id` is `i`.\n\n The length of the row `output[i]` will be the maximum of the lengths of\n all rows of `data` whose corresponding `segment_id` is `i`. If no `data`\n rows correspond to a given segment ID, then the output row for that segment\n ID will be empty.\n\n Args:\n data: A `RaggedTensor` containing the values to combine.\n segment_ids: A `Tensor` or `RaggedTensor`. Must have type `int64` or\n `int32`. `segment_ids.shape` must be a prefix of `data.shape`.\n Must be greater than or equal to zero, and less than `num_segments`.\n `segment_ids` is not required to be sorted.\n num_segments: An `int32` or `int64` scalar specifying the number of\n distinct segment ids.\n name: A name prefix for the returned tensor (optional).\n Returns:\n A `RaggedTensor` containing the %(combined)s values. The returned tensor\n has the same dtype as `data`, and its shape is\n `[num_segments] + data.shape[segment_ids.rank:]`.\n Raises:\n ValueError: If `segment_ids.shape` is not a prefix of `data.shape`.\n\"\"\"\n\n\ndef _ragged_segment_aggregate(unsorted_segment_op,\n data,\n segment_ids,\n num_segments,\n name=None):\n \"\"\"Aggregates along segments of a RaggedTensor using `unsorted_segment_op`.\n\n Returns a RaggedTensor `output` with `num_segments` rows, where the row\n `output[i]` is formed by combining all rows of `data` whose corresponding\n `segment_id` is `i`. The values in each row are combined using\n `unsorted_segment_op`.\n\n The length of the row `output[i]` will be the maximum of the lengths of\n all rows of `data` whose corresponding `segment_id` is `i`. If no `data`\n rows correspond to a given segment ID, then the output row for that segment\n ID will be empty.\n\n Args:\n unsorted_segment_op: The tensorflow `op` that should be used to combine\n values in each row. Must have the same signature and basic behavior as\n `unsorted_segment_sum`, `unsorted_segment_max`, etc.\n data: A `RaggedTensor` containing the values to be combined.\n segment_ids: A `Tensor` or `RaggedTensor`. Must have type `int64` or\n `int32`. `segment_ids.shape` must be a prefix of `data.shape`.\n `segment_ids` is not required to be sorted.\n num_segments: An `int32` or `int64` scalar.\n name: A name prefix for the returned tensor (optional).\n\n Returns:\n A `RaggedTensor` containing the aggregated values. The returned tensor\n has the same dtype as `data`, and its shape is\n `[num_segments] + data.shape[segment_ids.rank:]`.\n Raises:\n ValueError: If segment_ids.shape is not a prefix of data.shape.\n \"\"\"\n if not (ragged_tensor.is_ragged(data) or\n ragged_tensor.is_ragged(segment_ids)):\n return unsorted_segment_op(data, segment_ids, num_segments, name)\n\n with ops.name_scope(name, 'RaggedSegment',\n [data, segment_ids, num_segments]) as name:\n data = ragged_tensor.convert_to_tensor_or_ragged_tensor(data, name='data')\n segment_ids = ragged_tensor.convert_to_tensor_or_ragged_tensor(\n segment_ids, name='segment_ids')\n\n if ragged_tensor.is_ragged(segment_ids):\n if not ragged_tensor.is_ragged(data):\n raise ValueError('segment_ids.shape must be a prefix of data.shape, '\n 'but segment_ids is ragged and data is not.')\n check_splits = check_ops.assert_equal(\n segment_ids.row_splits,\n data.row_splits,\n message='segment_ids.shape must be a prefix of data.shape')\n with ops.control_dependencies([check_splits]):\n return _ragged_segment_aggregate(unsorted_segment_op, data.values,\n segment_ids.values, num_segments, name)\n\n segment_ids = math_ops.cast(segment_ids, dtypes.int64)\n\n # Find the length of each row in data. (dtype=int64, shape=[data_nrows])\n data_row_lengths = data.row_splits[1:] - data.row_splits[:-1]\n\n # Find the length that each output row will have. The length of the row\n # corresponding to segment `id` is `max(data_row_lengths[i])` where\n # `segment_ids[i]=id`. (dtype=int64, shape=[output_nrows])\n output_row_lengths = math_ops.maximum(\n math_ops.unsorted_segment_max(data_row_lengths, segment_ids,\n num_segments), 0)\n assert output_row_lengths.dtype == dtypes.int64\n\n # Build the splits tensor for the output RaggedTensor.\n output_splits = array_ops.concat([\n array_ops.zeros([1], dtypes.int64),\n math_ops.cumsum(output_row_lengths)\n ],\n axis=0)\n\n # For each row in `data`, find the start & limit position where that row's\n # values will be aggregated in output.values.\n data_row_to_out_row_start = array_ops.gather(output_splits, segment_ids)\n data_row_to_out_row_limit = data_row_to_out_row_start + data_row_lengths\n\n # For each value in `data.values`, find the position where it will\n # aggregated in `output.values`.\n # Get the target output values index for each data values index.\n data_val_to_out_val_index = range(data_row_to_out_row_start,\n data_row_to_out_row_limit).values\n\n # Recursively aggregate the values.\n output_values = _ragged_segment_aggregate(unsorted_segment_op, data.values,\n data_val_to_out_val_index,\n output_splits[-1])\n return ragged_tensor.RaggedTensor.from_row_splits(output_values,\n output_splits)\n\n\ndef segment_sum(data, segment_ids, num_segments, name=None):\n # For docs, see: _RAGGED_SEGMENT_DOCSTRING\n return _ragged_segment_aggregate(math_ops.unsorted_segment_sum, data,\n segment_ids, num_segments, name or\n 'RaggedSegmentSum')\n\n\ndef segment_prod(data, segment_ids, num_segments, name=None):\n # For docs, see: _RAGGED_SEGMENT_DOCSTRING\n return _ragged_segment_aggregate(math_ops.unsorted_segment_prod, data,\n segment_ids, num_segments, name or\n 'RaggedSegmentProd')\n\n\ndef segment_min(data, segment_ids, num_segments, name=None):\n # For docs, see: _RAGGED_SEGMENT_DOCSTRING\n return _ragged_segment_aggregate(math_ops.unsorted_segment_min, data,\n segment_ids, num_segments, name or\n 'RaggedSegmentMin')\n\n\ndef segment_max(data, segment_ids, num_segments, name=None):\n # For docs, see: _RAGGED_SEGMENT_DOCSTRING\n return _ragged_segment_aggregate(math_ops.unsorted_segment_max, data,\n segment_ids, num_segments, name or\n 'RaggedSegmentMax')\n\n\ndef segment_mean(data, segment_ids, num_segments, name=None):\n \"\"\"For docs, see: _RAGGED_SEGMENT_DOCSTRING.\"\"\"\n with ops.name_scope(name, 'RaggedSegmentMean',\n [data, segment_ids, num_segments]):\n total = segment_sum(data, segment_ids, num_segments)\n ones = ragged_tensor.RaggedTensor.from_nested_row_splits(\n array_ops.ones_like(data.flat_values), data.nested_row_splits)\n count = segment_sum(ones, segment_ids, num_segments)\n if ragged_tensor.is_ragged(total):\n return total.with_flat_values(total.flat_values / count.flat_values)\n else:\n return total / count\n\n\ndef segment_sqrt_n(data, segment_ids, num_segments, name=None):\n \"\"\"For docs, see: _RAGGED_SEGMENT_DOCSTRING.\"\"\"\n with ops.name_scope(name, 'RaggedSegmentSqrtN',\n [data, segment_ids, num_segments]):\n total = segment_sum(data, segment_ids, num_segments)\n ones = ragged_tensor.RaggedTensor.from_nested_row_splits(\n array_ops.ones_like(data.flat_values), data.nested_row_splits)\n count = segment_sum(ones, segment_ids, num_segments)\n if ragged_tensor.is_ragged(total):\n return total.with_flat_values(\n total.flat_values / math_ops.sqrt(count.flat_values))\n else:\n return total / math_ops.sqrt(count)\n\n\ndef _set_ragged_segment_docstring(func, combination, combined):\n func.__doc__ = _RAGGED_SEGMENT_DOCSTRING % dict(\n combination=combination, combined=combined)\n\n\n_set_ragged_segment_docstring(segment_sum, 'sum', 'summed')\n_set_ragged_segment_docstring(segment_prod, 'product', 'multiplied')\n_set_ragged_segment_docstring(segment_min, 'minimum', 'minimized')\n_set_ragged_segment_docstring(segment_max, 'maximum', 'maximized')\n_set_ragged_segment_docstring(segment_mean, 'mean', 'averaged')\n_set_ragged_segment_docstring(segment_sqrt_n, 'sum divided by sqrt(N)',\n 'summed')\n\n#===============================================================================\n# ragged_reduce_<AGGREGATE>\n#===============================================================================\n\n# Docstring template used for ragged_reduce_<AGGREGATE> ops.\n_RAGGED_REDUCE_DOCSTRING = \"\"\"\\\nComputes the %(combination)s of elements across dimensions of a `RaggedTensor`.\n\n Reduces `input_tensor` along the dimensions given in `axis` by taking the\n %(combination)s of values. If a reduced dimension has no elements for\n some index, then the value for that index will be %(default)s.\n\n The rank of the tensor is reduced by `1` for each entry in `axis`. If\n `axis` is not specified, then all dimensions are reduced, and a scalar\n value is returned.\n Args:\n input_tensor: A `RaggedTensor` containing the values to be %(combined)s.\n axis: The dimensions to reduce. May be `None` (to reduce all axes), an\n `int` (to reduce a single axis), a `list` or `tuple` of `int` (to reduce\n a given set of axes), or a `Tensor` with a constant value. Must be in\n the range `[0, input_tensor.rank]`.\n name: A name prefix for the returned tensor (optional).\n Returns:\n A `RaggedTensor` containing the %(combined)s values. The returned tensor\n has the same dtype as `data`, and its shape is given by removing the\n dimensions specified in `axis` from `input_tensor.shape`. The `ragged_rank`\n of the returned tensor is given by substracting any ragged dimensions\n specified in `axis` from `input_tensor.ragged_rank`.\n Raises:\n ValueError: If `axis` contains a `Tensor` whose value is not constant.\n ####Example:\n ```python%(example)s ```\n\"\"\"\n_RAGGED_REDUCE_SUM_EXAMPLE = \"\"\"\n >>> rt = ragged.constant([[3, 1, 4], [1, 5], [9], [2, 6]])\n >>> ragged.reduce_sum(rt, axis=0).eval().tolist()\n [15, 12, 4] # = [3+1+9+2, 1+5+6, 4]\n >>> ragged.reduce_sum(rt, axis=1).eval().tolist()\n [8, 6, 9, 8] # = [3+1+4, 1+5, 9, 2+6]\n\"\"\"\n_RAGGED_REDUCE_PROD_EXAMPLE = \"\"\"\n >>> rt = ragged.constant([[3, 1, 4], [1, 5], [9], [2, 6]])\n >>> ragged.reduce_prod(rt, axis=0).eval().tolist()\n [54, 30, 4] # = [3*1*9*2, 1*5*6, 4]\n >>> ragged.reduce_prod(rt, axis=1).eval().tolist()\n [12, 5, 9, 12] # = [3*1*4, 1*5, 9, 2*6]\n\"\"\"\n_RAGGED_REDUCE_MIN_EXAMPLE = \"\"\"\n >>> rt = ragged.constant([[3, 1, 4], [1, 5], [9], [2, 6]])\n >>> ragged.reduce_min(rt, axis=0).eval().tolist()\n [1, 1, 4] # = [min(3, 1, 9, 2), min(1, 5, 6), 4]\n >>> ragged.reduce_min(rt, axis=1).eval().tolist()\n [1, 1, 9, 2] # = [min(3, 1, 4), min(1, 5), 9, min(2, 6)]\n\"\"\"\n_RAGGED_REDUCE_MAX_EXAMPLE = \"\"\"\n >>> rt = ragged.constant([[3, 1, 4], [1, 5], [9], [2, 6]])\n >>> ragged.reduce_max(rt, axis=0).eval().tolist()\n [9, 6, 4] # = [max(3, 1, 9, 2), max(1, 5, 6), 4]\n >>> ragged.reduce_max(rt, axis=1).eval().tolist()\n [4, 5, 9, 6] # = [max(3, 1, 4), max(1, 5), 9, max(2, 6)]\n\"\"\"\n_RAGGED_REDUCE_MEAN_EXAMPLE = \"\"\"\n >>> rt = ragged.constant([[3, 1, 4], [1, 5], [9], [2, 6]])\n >>> ragged.reduce_mean(rt, axis=0).eval().tolist()\n [3.75, 4, 4] # = [mean(3, 1, 9, 2), mean(1, 5, 6), 4]\n >>> ragged.reduce_mean(rt, axis=1).eval().tolist()\n [2.66666, 3, 9, 4] # = [mean(3, 1, 4), mean(1, 5), 9, mean(2, 6)]\n\"\"\"\n_RAGGED_REDUCE_ALL_EXAMPLE = \"\"\"\n >>> rt = ragged.constant([[True, True], [True, True, False, True], [False, True]])\n >>> ragged.reduce_all(rt, axis=0).eval().tolist()\n [False, True, False, True]\n >>> ragged.reduce_all(rt, axis=1).eval().tolist()\n [True, False, False]\n\"\"\"\n_RAGGED_REDUCE_ANY_EXAMPLE = \"\"\"\n >>> rt = ragged.constant([[True, True], [True, True, False, True], [False, True]])\n >>> ragged.reduce_any(rt, axis=0).eval().tolist()\n [True, True, False, True]\n >>> ragged.reduce_any(rt, axis=1).eval().tolist()\n [True, True, True]\n\"\"\"\n\n\ndef _ragged_reduce_aggregate(reduce_op,\n unsorted_segment_op,\n rt_input,\n axis,\n keepdims,\n name=None):\n \"\"\"Aggregates across axes of a RaggedTensor using the given `Tensor` ops.\n\n Reduces `rt_input` along the dimensions given in `axis`. The rank of the\n tensor is reduced by 1 for each entry in `axis`. If `axis` is not specified,\n then all dimensions are reduced, and a scalar value is returned.\n\n This op assumes that `reduce_op` and `unsorted_segment_op` are associative;\n if not, then reducing multiple axes will return incorrect results. (In\n particular, reducing multiple axes is currently implemented by reducing the\n axes one at a time.)\n\n Args:\n reduce_op: The tensorflow `op` that should be used to reduce values in\n uniform dimensions. Must have the same signature and basic behavior as\n `reduce_sum`, `reduce_max`, etc.\n unsorted_segment_op: The tensorflow `op` that should be used to combine\n values in ragged dimensions. Must have the same signature and basic\n behavior as `unsorted_segment_sum`, `unsorted_segment_max`, etc.\n rt_input: A `Tensor` or `RaggedTensor` containing the values to be reduced.\n axis: The axis or axes to reduce. May be `None` (to reduce all axes), an\n `int` (to reduce a single axis), a `list` or `tuple` of `int` (to reduce a\n given set of axes), or a `Tensor` with a constant value. Must be in the\n range `[0, rt_input.rank)`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name prefix for the returned tensor (optional).\n\n Returns:\n A `RaggedTensor` containing the reduced values. The returned tensor\n has the same dtype as `data`, and its shape is given by removing the\n dimensions specified in `axis` from `rt_input.shape`. The `ragged_rank`\n of the returned tensor is given by substracting any ragged dimensions\n specified in `axis` from `rt_input.ragged_rank`.\n Raises:\n ValueError: If `axis` contains a `Tensor` whose value is not constant.\n \"\"\"\n if not ragged_tensor.is_ragged(rt_input):\n return reduce_op(rt_input, axis, name=name)\n\n if keepdims:\n raise ValueError('keepdims=True is not supported for RaggedTensors.')\n\n if isinstance(axis, ops.Tensor):\n axis = tensor_util.constant_value(axis)\n if axis is None:\n raise ValueError('axis must be known at graph construction time.')\n if isinstance(axis, np.ndarray):\n axis = axis.tolist()\n\n # When reducing all axes, just ignore splits & reduce the inner values.\n if axis is None:\n return reduce_op(rt_input.flat_values, None, name=name)\n\n with ops.name_scope(name, 'RaggedReduce', [rt_input, axis]):\n if isinstance(axis, (tuple, list)):\n if not axis:\n return rt_input\n elif len(axis) == 1:\n axis = axis[0]\n else:\n # When reducing multiple axes, just reduce one at a time. This is less\n # efficient, and only works for associative ops. (In particular, it\n # does not work for reduce_mean.) However, reducing multiple axes at\n # once will probably require a nontrivial c++ op.\n axis = sorted(axis)\n inner_reduced = _ragged_reduce_aggregate(reduce_op, unsorted_segment_op,\n rt_input, axis[-1], keepdims)\n return _ragged_reduce_aggregate(reduce_op, unsorted_segment_op,\n inner_reduced, axis[:-1], keepdims)\n\n rt_input = ragged_tensor.convert_to_tensor_or_ragged_tensor(\n rt_input, name='rt_input')\n\n axis = ragged_util.get_positive_axis(axis, rt_input.shape.ndims)\n\n if axis == 0:\n # out[i_1, i_2, ..., i_N] = sum_{j} rt_input[j, i_1, i_2, ..., i_N]\n row_lengths = rt_input.row_splits[1:] - rt_input.row_splits[:-1]\n num_segments = math_ops.maximum(math_ops.reduce_max(row_lengths), 0)\n segment_ids = range(row_lengths).values\n return _ragged_segment_aggregate(unsorted_segment_op, rt_input.values,\n segment_ids, num_segments)\n elif axis == 1:\n # out[i_0, i_1, i_2, ..., i_N] = sum_{j} rt_input[i_0, j, i_2, ..., i_N]\n num_segments = array_ops.shape(rt_input.row_splits)[0] - 1\n segment_ids = segment_id_ops.row_splits_to_segment_ids(\n rt_input.row_splits)\n return _ragged_segment_aggregate(unsorted_segment_op, rt_input.values,\n segment_ids, num_segments)\n else:\n # out[i_0, ..., i_[axis-1], i_axis+1], ..., i_N] =\n # sum_{j} rt_input [i_0, ..., i_[axis-1], j, i_axis+1], ..., i_N]\n return rt_input.with_values(\n _ragged_reduce_aggregate(reduce_op, unsorted_segment_op,\n rt_input.values, axis - 1, keepdims))\n\n\ndef reduce_sum(input_tensor, axis=None, keepdims=None, name=None):\n \"\"\"For docs, see: _RAGGED_REDUCE_DOCSTRING.\"\"\"\n return _ragged_reduce_aggregate(math_ops.reduce_sum,\n math_ops.unsorted_segment_sum, input_tensor,\n axis, keepdims, name or 'RaggedReduceSum')\n\n\ndef reduce_prod(input_tensor, axis=None, keepdims=None, name=None):\n \"\"\"For docs, see: _RAGGED_REDUCE_DOCSTRING.\"\"\"\n return _ragged_reduce_aggregate(math_ops.reduce_prod,\n math_ops.unsorted_segment_prod, input_tensor,\n axis, keepdims, name or 'RaggedReduceProd')\n\n\ndef reduce_min(input_tensor, axis=None, keepdims=None, name=None):\n \"\"\"For docs, see: _RAGGED_REDUCE_DOCSTRING.\"\"\"\n return _ragged_reduce_aggregate(math_ops.reduce_min,\n math_ops.unsorted_segment_min, input_tensor,\n axis, keepdims, name or 'RaggedReduceMin')\n\n\ndef reduce_max(input_tensor, axis=None, keepdims=None, name=None):\n \"\"\"For docs, see: _RAGGED_REDUCE_DOCSTRING.\"\"\"\n return _ragged_reduce_aggregate(math_ops.reduce_max,\n math_ops.unsorted_segment_max, input_tensor,\n axis, keepdims, name or 'RaggedReduceMax')\n\n\ndef reduce_mean(input_tensor, axis=None, keepdims=None, name=None):\n \"\"\"For docs, see: _RAGGED_REDUCE_DOCSTRING.\"\"\"\n with ops.name_scope(name, 'RaggedReduceMean', [input_tensor, axis]):\n total = reduce_sum(input_tensor, axis, keepdims)\n if ragged_tensor.is_ragged(input_tensor):\n ones = ragged_tensor.RaggedTensor.from_nested_row_splits(\n array_ops.ones_like(input_tensor.flat_values),\n input_tensor.nested_row_splits)\n else:\n ones = array_ops.ones_like(input_tensor)\n count = reduce_sum(ones, axis, keepdims)\n if ragged_tensor.is_ragged(total):\n return ragged_tensor.RaggedTensor.from_nested_row_splits(\n total.flat_values / count.flat_values, total.nested_row_splits)\n else:\n return total / count\n\n\ndef _cast(input_tensor, dtype):\n return ragged_functional_ops.map_flat_values(math_ops.cast, input_tensor,\n dtype)\n\n\ndef reduce_all(input_tensor, axis=None, keepdims=None, name=None):\n \"\"\"For docs, see: _RAGGED_REDUCE_DOCSTRING.\"\"\"\n with ops.name_scope(name, 'RaggedReduceAll', [input_tensor, axis]):\n return _cast(\n reduce_prod(_cast(input_tensor, dtypes.int32), axis, keepdims),\n dtypes.bool)\n\n\ndef reduce_any(input_tensor, axis=None, keepdims=None, name=None):\n \"\"\"For docs, see: _RAGGED_REDUCE_DOCSTRING.\"\"\"\n with ops.name_scope(name, 'RaggedReduceAny', [input_tensor, axis]):\n return _cast(\n reduce_sum(_cast(input_tensor, dtypes.int32), axis, keepdims),\n dtypes.bool)\n\n\ndef _set_ragged_reduce_docstring(func, combination, combined, default, example):\n func.__doc__ = _RAGGED_REDUCE_DOCSTRING % dict(\n combination=combination,\n combined=combined,\n default=default,\n example=example)\n\n\n_set_ragged_reduce_docstring(reduce_sum, 'sum', 'summed', '0',\n _RAGGED_REDUCE_SUM_EXAMPLE)\n_set_ragged_reduce_docstring(reduce_prod, 'product', 'multiplied', '1',\n _RAGGED_REDUCE_PROD_EXAMPLE)\n_set_ragged_reduce_docstring(reduce_min, 'minimum', 'minimized',\n '`input_tensor.dtype.min`',\n _RAGGED_REDUCE_MIN_EXAMPLE)\n_set_ragged_reduce_docstring(reduce_max, 'maximum', 'maximized',\n '`input_tensor.dtype.max`',\n _RAGGED_REDUCE_MAX_EXAMPLE)\n_set_ragged_reduce_docstring(reduce_mean, 'mean', 'averaged', 'NaN',\n _RAGGED_REDUCE_MEAN_EXAMPLE)\n\n_set_ragged_reduce_docstring(reduce_all, 'logical and', 'and-ed', 'True',\n _RAGGED_REDUCE_ALL_EXAMPLE)\n_set_ragged_reduce_docstring(reduce_any, 'logical or', 'or-ed', 'False',\n _RAGGED_REDUCE_ANY_EXAMPLE)\n", "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"This module contains the user-facing API for AutoGraph.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport sys\n\nfrom enum import Enum\n\n# pylint:disable=g-bad-import-order\nimport numpy as np\n# pylint:enable=g-bad-import-order\n\n\nfrom tensorflow.python.autograph.core import config\nfrom tensorflow.python.autograph.core import converter\nfrom tensorflow.python.autograph.impl import conversion\nfrom tensorflow.python.autograph.operators import py_builtins\nfrom tensorflow.python.autograph.pyct import compiler\nfrom tensorflow.python.autograph.pyct import inspect_utils\nfrom tensorflow.python.autograph.utils import py_func\nfrom tensorflow.python.data.util import nest\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util import tf_decorator\nfrom tensorflow.python.util import tf_inspect\n\n# TODO(mdan): Properly document the type hints.\n# TODO(mdan): Reduce the type hint information to (module, type).\n# (currently we require (module + class name, type))\n\n\n# TODO(mdan): This should behave like to_graph (e.g. convert statically).\n# TODO(znado): Make an alias so can write Verbosity directly without needing\n# to write converter.\ndef convert(\n recursive=False,\n verbose=converter.Verbosity.BRIEF,\n optional_features=converter.Feature.ALL):\n \"\"\"Decorator that compiles a function to use TensorFlow ops.\n\n The decorator is dynamic - it recompiles the target whenever the decorated\n function is called. This means the parameter values are known at conversion.\n It also means that repeated calls with different types of parameters will be\n correctly processed.\n\n Args:\n recursive: bool, whether to recursively convert any functions or classes\n that the converted function may use.\n verbose: converter.Verbosity, the level of verbosity.\n optional_features: converted.Feature, allows toggling optional or\n experimental features. When set to None, only the core features are\n enabled.\n\n Returns:\n Callable, a decorator that converts the given function into an equivalent\n function that uses TensorFlow ops.\n \"\"\"\n\n def decorator(f):\n \"\"\"Decorator implementation.\"\"\"\n\n @functools.wraps(f)\n def wrapper(*args, **kwargs):\n return converted_call(\n f, None,\n converter.ConversionOptions(\n recursive=recursive,\n verbose=verbose,\n force_conversion=True,\n optional_features=optional_features,\n ), *args, **kwargs)\n\n wrapper = tf_decorator.make_decorator(f, wrapper)\n\n # Sometimes the decorator is just desugared, making it impossible to detect.\n # This attribute makes detection easier.\n setattr(wrapper, '__ag_compiled', True)\n return wrapper\n\n return decorator\n\n\nclass RunMode(Enum):\n \"\"\"Specifies the way a converted function or method should be executed in TF.\n\n Attributes:\n * GRAPH: Call this function directly, as-is. This is suitable for functions\n that were already designed for TF graphs and contain ops.\n * PY_FUNC: Wrap this function into a py_func op. This is suitable for code\n that will only run correctly in Python, for example code that renders\n to the display, reads keyboard input, etc.\n \"\"\"\n GRAPH = 1\n PY_FUNC = 2\n\n\ndef do_not_convert(run_as=RunMode.GRAPH, return_dtypes=None):\n \"\"\"Decorator that suppresses the conversion of a function.\n\n See also: docs/pyfunc_dtypes.md\n\n Args:\n run_as: RunMode, specifies how to use the function in TensorFlow.\n return_dtypes: Optional[Iterable[ Union[tf.DType,\n utils.py_func.MatchDType]]], the return data types of the converted\n function, if run_as is RunMode.PY_FUNC. Ignored otherwise. May be set to\n None if the function has no return values.\n\n Returns:\n Callable, a decorator that wraps the original function.\n \"\"\"\n\n def decorator(f):\n \"\"\"Decorator implementation.\"\"\"\n\n @functools.wraps(f)\n def graph_wrapper(*args, **kwargs):\n return f(*args, **kwargs)\n\n @functools.wraps(f)\n def py_func_wrapper(*args, **kwargs):\n if kwargs:\n raise NotImplementedError('RunMode.PY_FUNC does not yet support kwargs')\n # TODO(mdan): Add support for kwargs.\n return py_func.wrap_py_func(\n f, return_dtypes, args, kwargs, use_dummy_return=not return_dtypes)\n\n if run_as == RunMode.GRAPH:\n wrapper = graph_wrapper\n elif run_as == RunMode.PY_FUNC:\n wrapper = py_func_wrapper\n else:\n raise ValueError('unknown value for run_as: %s' % run_as)\n\n # Sometimes the decorator is just desugared, making it impossible to detect.\n # This attribute makes detection easier.\n setattr(wrapper, '__ag_compiled', True)\n return wrapper\n\n return decorator\n\n\n# TODO(mdan): Move to a private, undocumented module.\ndef converted_call(f, owner, options, *args, **kwargs):\n \"\"\"Compiles a function call inline. For internal use only.\"\"\"\n if options.verbose >= converter.Verbosity.VERBOSE:\n logging.info('Converted call: {}; owner: {}'.format(f, owner))\n\n if owner is not None:\n if not isinstance(f, str):\n raise ValueError(\n 'When owner is specified, the function name must be specified as'\n ' a string: {}'.format(f))\n\n # Special case when the owner is a 'super' object. In that case lookups of\n # dynamic attributes won't work. See\n # inspect_utils.SuperWrapperForDynamicAttrs.\n if isinstance(owner, super):\n owner = inspect_utils.SuperWrapperForDynamicAttrs(owner)\n\n f = getattr(owner, f)\n\n if inspect_utils.isbuiltin(f):\n return py_builtins.overload_of(f)(*args, **kwargs)\n\n # TODO(mdan): This needs cleanup.\n # In particular, we may want to avoid renaming functions altogether.\n if not options.force_conversion and conversion.is_whitelisted_for_graph(f):\n\n # Args typically include `self`, as required by the conversion process.\n # When conversion is skipped, `self` is not necessary, because the\n # original bound method is being executed. This code removes it.\n if tf_inspect.ismethod(f) and args:\n f_class = inspect_utils.getmethodclass(f)\n if args[0] is f_class:\n args = args[1:]\n\n return f(*args, **kwargs)\n\n # internal_convert_user_code is for example turned off when issuing a dynamic\n # call conversion from generated code while in nonrecursive mode. In that\n # case we evidently don't want to recurse, but we still have to convert\n # things like builtins.\n if not options.internal_convert_user_code:\n return f(*args, **kwargs)\n\n # Unwrap functools.partial objects\n # TODO(allenl, mdan): Consider sharing unwrapping logic with tf_inspect.\n while isinstance(f, functools.partial):\n args = f.args + args\n new_kwargs = {}\n if f.keywords is not None:\n new_kwargs.update(f.keywords)\n new_kwargs.update(kwargs)\n kwargs = new_kwargs\n f = f.func\n\n if tf_inspect.isfunction(f) or tf_inspect.ismethod(f):\n # Regular functions\n target_entity = f\n arg_map_target = f\n f_class = inspect_utils.getmethodclass(f)\n\n # TODO(b/119246461): This may be more elegantly handled using __get__?\n if f_class is not None:\n # If this is a method call, it may or may not include self.\n #\n # Example when self is included:\n # converted_call(to_graph(foo.bar), foo)\n #\n # Example when self is not included:\n # super(...).foo(args)\n #\n if owner is not None and (not args or args[0] is not owner):\n effective_args = (owner,) + args\n else:\n # When the owner is not specified, use the result of\n # inspect_utils.getmethodclass.\n # TODO(b/119246461): Make sure an owner is always specified.\n if not args or args[0] is not f_class:\n effective_args = (f_class,) + args\n else:\n effective_args = (f_class,) + args[1:]\n partial_types = (f_class,)\n else:\n effective_args = args\n partial_types = ()\n\n elif tf_inspect.isclass(f):\n # Constructors\n target_entity = f\n arg_map_target = f.__init__\n effective_args = args\n partial_types = ()\n\n elif hasattr(f, '__call__') and hasattr(f, '__class__'):\n # Callable objects\n target_entity = f.__call__\n arg_map_target = f.__call__\n effective_args = (f,) + args\n partial_types = (f.__class__,)\n\n else:\n NotImplementedError('unknown callable type \"%s\"' % type(f))\n\n arg_values = tf_inspect.getcallargs(arg_map_target, *args, **kwargs)\n arg_types = {}\n for name, arg in arg_values.items():\n arg_class = arg.__class__\n arg_types[name] = (arg_class.__name__, arg_class)\n\n # When called from within a decorator, this is the only indication that\n # the function is a method - it appears that the decorator is applied\n # before the method is bound.\n if not partial_types:\n if 'self' in arg_values:\n if tf_inspect.isclass(arg_values['self'].__class__):\n partial_types = (arg_values['self'].__class__,)\n elif 'cls' in arg_values:\n if tf_inspect.isclass(arg_values['cls']):\n partial_types = (arg_values['cls'],)\n\n converted_f = to_graph(\n target_entity,\n recursive=options.recursive,\n verbose=options.verbose,\n arg_values=arg_values,\n arg_types=arg_types,\n partial_types=partial_types,\n strip_decorators=options.strip_decorators,\n optional_features=options.optional_features)\n\n result = converted_f(*effective_args, **kwargs)\n\n # The converted function's closure is simply inserted into the function's\n # module __dict__. Since modules are permanently cached, that results in\n # leaking the entire closure.\n # Normally, it's not safe to delete the module because that may release said\n # closure as well. However, in the case of converted_call we are certain the\n # function will not be executed again, so the closure should no longer be\n # needed so long as the function doesn't return any executable code.\n # TODO(mdan): Attach the closure properly, using cells.\n if all(map(_is_not_callable, nest.flatten(result))):\n del sys.modules[converted_f.__module__]\n\n return result\n\n\ndef _is_not_callable(obj):\n # TODO(brianklee): Handle case when obj is a tensor dependent on a py_func.\n if isinstance(obj, (int, float, complex, str, bool)):\n return True\n if isinstance(obj, (np.ndarray, np.generic)):\n return True\n if tensor_util.is_tensor(obj):\n return True\n return False\n\n\n# TODO(mdan): Rename: to_ops?\n# TODO(mdan): Look into overloading as function and decorator, like tfe.defun?\n# TODO(mdan): Remove partial_types.\ndef to_graph(e,\n recursive=True,\n verbose=converter.Verbosity.VERBOSE,\n arg_values=None,\n arg_types=None,\n partial_types=None,\n strip_decorators=None,\n optional_features=converter.Feature.ALL):\n \"\"\"Converts a Python entity into equivalent code that uses TensorFlow ops.\n\n Supported Python entities include:\n * functions\n * classes\n\n Classes are converted by converting all their methods into a new class.\n\n Args:\n e: Union[Callable, Type], the Python entity to convert.\n recursive: bool, whether to recursively convert any functions that the\n converted function may call.\n verbose: converter.Verbosity, the level of printing verbosity to use.\n arg_values: Optional[Dict[Text, Any]], value hints for symbols including\n function arguments.\n arg_types: Optional[Dict[Text, Type]], type hints for symbols including\n function arguments.\n partial_types: Set[Type], reserved for internal use.\n strip_decorators: Tuple[Callable], same as\n ConversionOptions.strip_decorators.\n optional_features: Union[Feature, Set[Feature]], same as\n ConversionOptions.optional_features.\n\n Returns:\n Union[Callable, Type], the converted entity, which is the same kind as e\n (that is, a function is e is a function, a class if e is a class, etc.) but\n its code has been converted to use TF ops.\n\n Raises:\n ValueError: If the entity could not be converted.\n \"\"\"\n if strip_decorators is None:\n strip_decorators = ()\n strip_decorators += (convert, do_not_convert, converted_call)\n\n program_ctx = converter.ProgramContext(\n options=converter.ConversionOptions(\n recursive=recursive,\n verbose=verbose,\n strip_decorators=strip_decorators,\n optional_features=optional_features),\n partial_types=partial_types,\n autograph_module=tf_inspect.getmodule(to_graph),\n uncompiled_modules=config.DEFAULT_UNCOMPILED_MODULES)\n _, name, namespace = conversion.entity_to_graph(e, program_ctx, arg_values,\n arg_types)\n\n nodes = []\n for dep in reversed(program_ctx.conversion_order):\n nodes.extend(program_ctx.dependency_cache[dep])\n\n compiled_module, _ = compiler.ast_to_object(\n nodes,\n source_prefix=program_ctx.required_imports,\n include_source_map=True)\n\n # The compiled code should see everything the entry entity saw.\n # TODO(mdan): This might not work well if the call tree spans modules?\n for key, val in namespace.items():\n # Avoid overwriting entities that have been transformed.\n if key not in compiled_module.__dict__:\n compiled_module.__dict__[key] = val\n compiled = getattr(compiled_module, name)\n\n if tf_inspect.isfunction(e):\n compiled.__defaults__ = e.__defaults__\n\n if hasattr(compiled, '__globals__'):\n # Remove self to avoid circular references. This will probably only work\n # so long as the function is not reentrant.\n del compiled.__globals__[name]\n\n # Need this so the source_mapping attribute is available for the context\n # manager to access for runtime errors.\n #\n # Note that compiler.ast_to_object attaches the source map 'ag_source_map__'\n # symbol to the compiled module.\n # TODO(mdan): Record this statically in the generated code.\n # TODO(mdan): Rename this attribute to 'autograph_info__'\n source_map_attribute_name = 'ag_source_map'\n if getattr(compiled, source_map_attribute_name, None) is not None:\n raise ValueError('cannot convert %s because is has an attribute '\n '\"%s\", which is reserved for AutoGraph.' %\n (compiled, source_map_attribute_name))\n setattr(compiled, source_map_attribute_name,\n compiled_module.__dict__['ag_source_map__'])\n\n return compiled\n\n\ndef to_code(e,\n recursive=True,\n arg_values=None,\n arg_types=None,\n partial_types=None,\n indentation=' '):\n \"\"\"Returns the equivalent code that uses TensorFlow ops.\n\n Also see: `to_graph`, `convert`\n\n Args:\n e: Union[Callable, Type], the Python entity to convert.\n recursive: bool, whether to recursively convert any functions that the\n converted function may call.\n arg_values: Optional[Dict[Text, Any]], value hints for symbols including\n function arguments.\n arg_types: Optional[Dict[Text, Type]], type hints for symbols including\n function arguments.\n partial_types: Set[Type], reserved for internal use.\n indentation: Text, when to use for each level of indentation.\n\n Returns:\n Text, the converted code.\n \"\"\"\n program_ctx = converter.ProgramContext(\n options=converter.ConversionOptions(\n recursive=recursive,\n strip_decorators=(convert, do_not_convert, converted_call)),\n partial_types=partial_types,\n autograph_module=tf_inspect.getmodule(to_graph),\n uncompiled_modules=config.DEFAULT_UNCOMPILED_MODULES)\n conversion.entity_to_graph(e, program_ctx, arg_values, arg_types)\n\n code = '\\n'.join(\n compiler.ast_to_source(program_ctx.dependency_cache[dep], indentation)\n for dep in reversed(program_ctx.conversion_order))\n\n return program_ctx.required_imports + '\\n\\n' + code\n" ]
[ [ "tensorflow.python.ops.ragged.ragged_util.get_positive_axis", "tensorflow.python.ops.ragged.ragged_tensor.RaggedTensor.from_row_splits", "tensorflow.python.ops.ragged.ragged_tensor.RaggedTensor.from_nested_row_splits", "tensorflow.python.ops.ragged.segment_id_ops.row_splits_to_segment_ids", "tensorflow.python.framework.tensor_util.constant_value", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.math_ops.unsorted_segment_max", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.ops.ragged.ragged_functional_ops.map_flat_values", "tensorflow.python.ops.array_ops.gather", "tensorflow.python.ops.ragged.ragged_tensor.convert_to_tensor_or_ragged_tensor", "tensorflow.python.ops.gen_ragged_math_ops.ragged_range", "tensorflow.python.ops.math_ops.reduce_max", "tensorflow.python.ops.math_ops.sqrt", "tensorflow.python.ops.ragged.ragged_tensor.is_ragged", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.ops.check_ops.assert_equal", "tensorflow.python.ops.array_ops.ones_like", "tensorflow.python.ops.math_ops.cumsum" ], [ "tensorflow.python.data.util.nest.flatten", "tensorflow.python.autograph.impl.conversion.entity_to_graph", "tensorflow.python.autograph.operators.py_builtins.overload_of", "tensorflow.python.autograph.pyct.inspect_utils.SuperWrapperForDynamicAttrs", "tensorflow.python.util.tf_inspect.getmodule", "tensorflow.python.autograph.pyct.inspect_utils.isbuiltin", "tensorflow.python.util.tf_inspect.getcallargs", "tensorflow.python.util.tf_inspect.ismethod", "tensorflow.python.util.tf_inspect.isfunction", "tensorflow.python.util.tf_decorator.make_decorator", "tensorflow.python.autograph.impl.conversion.is_whitelisted_for_graph", "tensorflow.python.autograph.pyct.inspect_utils.getmethodclass", "tensorflow.python.util.tf_inspect.isclass", "tensorflow.python.autograph.pyct.compiler.ast_to_source", "tensorflow.python.autograph.core.converter.ConversionOptions", "tensorflow.python.autograph.utils.py_func.wrap_py_func", "tensorflow.python.autograph.pyct.compiler.ast_to_object", "tensorflow.python.framework.tensor_util.is_tensor" ] ]
makoziol0/pyne
[ "660b1bdd608d9b227d6a432737303f7e82af4a25" ]
[ "pyne/transmute/origen22.py" ]
[ "\"\"\"This module implements an ORIGEN v2.2 transmutation solver.\n\"\"\"\nfrom __future__ import print_function, division\n\nimport os\nimport subprocess\nimport tempfile\nfrom collections import Mapping\nfrom warnings import warn\nfrom pyne.utils import QAWarning\n\nimport numpy as np\n\nfrom pyne import data\nfrom pyne import rxname\nfrom pyne import nucname\nfrom pyne import nuc_data\nfrom pyne import origen22\nfrom pyne import utils\nfrom pyne.material import Material, from_atom_frac\nfrom pyne.xs.data_source import NullDataSource, SimpleDataSource, EAFDataSource\nfrom pyne.xs.cache import XSCache\n\nwarn(__name__ + \" is not yet QA compliant.\", QAWarning)\n\nclass Transmuter(object):\n \"\"\"A class for transmuting materials using ORIGEN v2.2.\"\"\"\n\n def __init__(self, t=0.0, phi=0.0, temp=300.0, tol=1e-7, cwd='',\n base_tape9=origen22.BASE_TAPE9, xscache=None, \n o2exe='o2_therm_linux.exe', *args, **kwargs):\n \"\"\"Parameters\n ----------\n t : float\n Transmutations time [sec].\n phi : float or array of floats\n Neutron flux vector [n/cm^2/sec]. Currently this must either be \n a scalar or match the group structure of EAF.\n temp : float, optional\n Temperature [K] of material, defaults to 300.0.\n tol : float\n Tolerance level for chain truncation.\n cwd : str, optional\n Current working directory for origen runs. Defaults to this dir.\n base_tape9 : str or dict, optional\n A base TAPE9.INP file. If this is a str it is interpreted as a path \n to a file, which is then read in and parsed. If this is a dict, it is\n assumed to be in the format described in the main origen22 module.\n xscache : XSCache, optional\n A cross section cache to generate cross sections with.\n o2exe : str, optional\n Name or path to ORIGEN 2.2 executable.\n args : tuple, optional\n Other arguments ignored for compatibility with other Transmuters.\n kwargs : dict, optional\n Other keyword arguments ignored for compatibility with other Transmuters.\n \"\"\"\n if not isinstance(base_tape9, Mapping):\n base_tape9 = origen22.parse_tape9(tape9=base_tape9)\n self.base_tape9 = base_tape9\n\n if xscache is None:\n eafds = EAFDataSource()\n eafds.load(temp=temp)\n gs = np.array([eafds.src_group_struct[0], eafds.src_group_struct[-1]])\n eafds.dst_group_struct = gs\n xscache = XSCache(group_struct=gs, data_source_classes=[SimpleDataSource, \n NullDataSource])\n xscache.load(temp=temp)\n xscache.data_sources.insert(0, eafds)\n self.xscache = xscache\n\n self.t = t\n self._phi = None\n self.phi = phi\n self.temp = temp\n self.tol = tol\n self.cwd = os.path.abspath(cwd)\n self.o2exe = o2exe\n\n @property\n def phi(self):\n return self._phi\n\n @phi.setter\n def phi(self, flux):\n \"\"\"Ensures that the flux is correctly formatted.\"\"\"\n flux = np.asarray(flux)\n if flux.ndim == 0:\n _ = np.empty(175, float)\n _.fill(flux / 175.0)\n flux = _\n elif flux.ndim == 1 and flux.shape[0] != 175:\n raise ValueError(\"Group structure must match EAF.\")\n elif flux.ndim > 1:\n raise ValueError(\"The flux vector must be 0- or 1-dimensional.\")\n if not np.all(flux >= 0.0):\n raise ValueError(\"Flux entries must be non-negative.\")\n for ds in self.xscache.data_sources:\n ds.src_phi_g = flux\n self.xscache['phi_g'] = np.array([flux.sum()])\n self._phi = flux\n\n def transmute(self, x, t=None, phi=None, tol=None, cwd=None, xscache=None, \n o2exe=None, *args, **kwargs):\n \"\"\"Transmutes a material into its daughters.\n\n Parameters\n ----------\n x : Material or similar\n Input material for transmutation.\n t : float\n Transmutations time [sec].\n phi : float or array of floats\n Neutron flux vector [n/cm^2/sec]. Currently this must either be \n a scalar or match the group structure of EAF.\n tol : float\n Tolerance level for chain truncation.\n cwd : str, optional\n Current working directory for origen runs. Defaults to this dir.\n xscache : XSCache, optional\n A cross section cache to generate cross sections with.\n o2exe : str, optional\n Name or path to ORIGEN 2.2 executable.\n\n Returns\n -------\n y : Material\n The output material post-transmutation.\n\n \"\"\"\n if not isinstance(x, Material):\n x = Material(x)\n if t is not None:\n self.t = t\n if phi is not None:\n self.phi = phi\n if tol is not None:\n self.tol = tol\n if cwd is not None:\n self.cwd = os.path.abspath(cwd)\n if xscache is not None:\n self.xscache = xscache\n if o2exe is not None:\n self.o2exe = o2exe\n\n # prepare new tape9\n nucs = set(x.comp.keys())\n base_tape9 = self.base_tape9\n decay_nlb, xsfpy_nlb = origen22.nlbs(base_tape9)\n new_tape9 = origen22.xslibs(nucs=nucs, xscache=self.xscache, nlb=xsfpy_nlb)\n t9 = origen22.merge_tape9([new_tape9, base_tape9])\n\n # write out files\n origen22.write_tape4(x, outfile=os.path.join(self.cwd, 'TAPE4.INP'))\n origen22.write_tape5_irradiation('IRF', self.t/86400.0, self.xscache['phi_g'][0], \n outfile=os.path.join(self.cwd, 'TAPE5.INP'), decay_nlb=decay_nlb, \n xsfpy_nlb=xsfpy_nlb, cut_off=self.tol)\n origen22.write_tape9(t9, outfile=os.path.join(self.cwd, 'TAPE9.INP'))\n\n # run origen & get results\n f = tempfile.NamedTemporaryFile()\n try:\n subprocess.check_call([self.o2exe], cwd=self.cwd, stdout=f, stderr=f)\n except subprocess.CalledProcessError:\n f.seek(0)\n print(\"ORIGEN output:\\n\\n{0}\".format(f.read()))\n raise\n finally:\n f.close()\n t6 = origen22.parse_tape6(tape6=os.path.join(self.cwd, 'TAPE6.OUT'))\n y = t6['materials'][-1]\n return y\n\n" ]
[ [ "numpy.array", "numpy.empty", "numpy.all", "numpy.asarray" ] ]
SkyAndCloud/Coursera-AndrewNG-ML-Python
[ "586edffdcc3e0811ac186a00b78897b0a75a07d0" ]
[ "ex7/computeCentroids.py" ]
[ "import numpy as np\n\n\ndef computeCentroids(X, idx, K):\n \"\"\"returns the new centroids by\n computing the means of the data points assigned to each centroid. It is\n given a dataset X where each row is a single data point, a vector\n idx of centroid assignments (i.e. each entry in range [1..K]) for each\n example, and K, the number of centroids. You should return a matrix\n centroids, where each row of centroids is the mean of the data points\n assigned to it.\n \"\"\"\n\n# Useful variables\n m, n = X.shape\n\n# You need to return the following variables correctly.\n centroids = np.zeros((K, X.shape[1]))\n\n# ====================== YOUR CODE HERE ======================\n# Instructions: Go over every centroid and compute mean of all points that\n# belong to it. Concretely, the row vector centroids(i, :)\n# should contain the mean of the data points assigned to\n# centroid i.\n#\n# Note: You can use a for-loop over the centroids to compute this.\n# \n idx_count = np.bincount(idx)\n for k in xrange(K):\n if k < len(idx_count):\n centroids[k] = np.sum(X[idx == k,:], axis=0) / float(idx_count[k])\n\n# =============================================================\n\n return centroids\n\n# if __name__ == '__main__':\n# print computeCentroids(\n# np.array([[1, 2, 3, 4], [4, 3, 2, 1]]),\n# np.array([0, 0]),\n# 2\n# )" ]
[ [ "numpy.sum", "numpy.bincount", "numpy.zeros" ] ]
YaxinCui/TorchSSL
[ "5603d16dfcb62e558c298f999a613f6f9d2c49de" ]
[ "pimodel.py" ]
[ "# import needed library\nimport os\nimport logging\nimport random\nimport warnings\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\n\nfrom utils import net_builder, get_logger, count_parameters, over_write_args_from_file\nfrom train_utils import TBLog, get_optimizer, get_cosine_schedule_with_warmup\nfrom models.pimodel.pimodel import PiModel\nfrom datasets.ssl_dataset import SSL_Dataset\nfrom datasets.data_utils import get_data_loader\n\n\ndef main(args):\n '''\n For (Distributed)DataParallelism,\n main(args) spawn each process (main_worker) to each GPU.\n '''\n\n save_path = os.path.join(args.save_dir, args.save_name)\n if os.path.exists(save_path) and not args.overwrite:\n raise Exception('already existing model: {}'.format(save_path))\n if args.resume:\n if args.load_path is None:\n raise Exception('Resume of training requires --load_path in the args')\n if os.path.abspath(save_path) == os.path.abspath(args.load_path) and not args.overwrite:\n raise Exception('Saving & Loading pathes are same. \\\n If you want over-write, give --overwrite in the argument.')\n\n if args.seed is not None:\n warnings.warn('You have chosen to seed training. '\n 'This will turn on the CUDNN deterministic setting, '\n 'which can slow down your training considerably! '\n 'You may see unexpected behavior when restarting '\n 'from checkpoints.')\n\n if args.gpu is not None:\n warnings.warn('You have chosen a specific GPU. This will completely '\n 'disable data parallelism.')\n\n if args.dist_url == \"env://\" and args.world_size == -1:\n args.world_size = int(os.environ[\"WORLD_SIZE\"])\n\n # distributed: true if manually selected or if world_size > 1\n args.distributed = args.world_size > 1 or args.multiprocessing_distributed\n ngpus_per_node = torch.cuda.device_count() # number of gpus of each node\n\n if args.multiprocessing_distributed:\n # now, args.world_size means num of total processes in all nodes\n args.world_size = ngpus_per_node * args.world_size\n\n # args=(,) means the arguments of main_worker\n mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args))\n else:\n main_worker(args.gpu, ngpus_per_node, args)\n\n\ndef main_worker(gpu, ngpus_per_node, args):\n '''\n main_worker is conducted on each GPU.\n '''\n\n global best_acc1\n args.gpu = gpu\n\n # random seed has to be set for the syncronization of labeled data sampling in each process.\n assert args.seed is not None\n random.seed(args.seed)\n torch.manual_seed(args.seed)\n np.random.seed(args.seed)\n cudnn.deterministic = True\n\n # SET UP FOR DISTRIBUTED TRAINING\n if args.distributed:\n if args.dist_url == \"env://\" and args.rank == -1:\n args.rank = int(os.environ[\"RANK\"])\n if args.multiprocessing_distributed:\n args.rank = args.rank * ngpus_per_node + gpu # compute global rank\n\n # set distributed group:\n dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,\n world_size=args.world_size, rank=args.rank)\n\n # SET save_path and logger\n save_path = os.path.join(args.save_dir, args.save_name)\n logger_level = \"WARNING\"\n tb_log = None\n if args.rank % ngpus_per_node == 0:\n tb_log = TBLog(save_path, 'tensorboard', use_tensorboard=args.use_tensorboard)\n logger_level = \"INFO\"\n\n logger = get_logger(args.save_name, save_path, logger_level)\n logger.warning(f\"USE GPU: {args.gpu} for training\")\n\n args.bn_momentum = 1.0 - 0.999\n if 'imagenet' in args.dataset.lower():\n _net_builder = net_builder('ResNet50', False, None, is_remix=False)\n else:\n _net_builder = net_builder(args.net,\n args.net_from_name,\n {'first_stride': 2 if 'stl' in args.dataset else 1,\n 'depth': args.depth,\n 'widen_factor': args.widen_factor,\n 'leaky_slope': args.leaky_slope,\n 'bn_momentum': args.bn_momentum,\n 'dropRate': args.dropout,\n 'use_embed': False,\n 'is_remix': False},\n )\n\n model = PiModel(_net_builder,\n args.num_classes,\n args.ulb_loss_ratio,\n num_eval_iter=args.num_eval_iter,\n tb_log=tb_log,\n ema_m=args.ema_m,\n logger=logger)\n\n logger.info(f'Number of Trainable Params: {count_parameters(model.model)}')\n\n # SET Optimizer & LR Scheduler\n ## construct SGD and cosine lr scheduler\n optimizer = get_optimizer(model.model, args.optim, args.lr, args.momentum, args.weight_decay)\n scheduler = get_cosine_schedule_with_warmup(optimizer,\n args.num_train_iter,\n num_warmup_steps=args.num_train_iter * 0)\n ## set SGD and cosine lr\n model.set_optimizer(optimizer, scheduler)\n\n # SET Devices for (Distributed) DataParallel\n if not torch.cuda.is_available():\n raise Exception('ONLY GPU TRAINING IS SUPPORTED')\n elif args.distributed:\n if args.gpu is not None:\n torch.cuda.set_device(args.gpu)\n\n '''\n batch_size: batch_size per node -> batch_size per gpu\n workers: workers per node -> workers per gpu\n '''\n args.batch_size = int(args.batch_size / ngpus_per_node)\n model.model.cuda(args.gpu)\n model.model = torch.nn.parallel.DistributedDataParallel(model.model,\n device_ids=[args.gpu],\n broadcast_buffers=False,\n find_unused_parameters=True)\n\n else:\n # if arg.gpu is None, DDP will divide and allocate batch_size\n # to all available GPUs if device_ids are not set.\n model.cuda()\n model = torch.nn.parallel.DistributedDataParallel(model)\n\n elif args.gpu is not None:\n torch.cuda.set_device(args.gpu)\n model.model = model.model.cuda(args.gpu)\n\n else:\n model.model = torch.nn.DataParallel(model.model).cuda()\n\n logger.info(f\"model_arch: {model}\")\n logger.info(f\"Arguments: {args}\")\n\n cudnn.benchmark = True\n\n # Construct Dataset & DataLoader\n train_dset = SSL_Dataset(args, alg='pimodel', name=args.dataset, train=True,\n num_classes=args.num_classes, data_dir=args.data_dir)\n lb_dset, ulb_dset = train_dset.get_ssl_dset(args.num_labels)\n\n _eval_dset = SSL_Dataset(args, alg='pimodel', name=args.dataset, train=False,\n num_classes=args.num_classes, data_dir=args.data_dir)\n eval_dset = _eval_dset.get_dset()\n\n loader_dict = {}\n dset_dict = {'train_lb': lb_dset, 'train_ulb': ulb_dset, 'eval': eval_dset}\n\n loader_dict['train_lb'] = get_data_loader(dset_dict['train_lb'],\n args.batch_size,\n data_sampler=args.train_sampler,\n num_iters=args.num_train_iter,\n num_workers=args.num_workers,\n distributed=args.distributed)\n\n loader_dict['train_ulb'] = get_data_loader(dset_dict['train_ulb'],\n args.batch_size * args.uratio,\n data_sampler=args.train_sampler,\n num_iters=args.num_train_iter,\n num_workers=4 * args.num_workers,\n distributed=args.distributed)\n\n loader_dict['eval'] = get_data_loader(dset_dict['eval'],\n args.eval_batch_size,\n num_workers=args.num_workers,\n drop_last=False)\n\n ## set DataLoader\n model.set_data_loader(loader_dict)\n\n # If args.resume, load checkpoints from args.load_path\n if args.resume:\n model.load_model(args.load_path)\n\n # START TRAINING\n trainer = model.train\n for epoch in range(args.epoch):\n trainer(args)\n\n if not args.multiprocessing_distributed or \\\n (args.multiprocessing_distributed and args.rank % ngpus_per_node == 0):\n model.save_model('latest_model.pth', save_path)\n\n logging.warning(f\"GPU {args.rank} training is FINISHED\")\n\n\ndef str2bool(v):\n if isinstance(v, bool):\n return v\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser(description='')\n\n '''\n Saving & loading of the model.\n '''\n parser.add_argument('--save_dir', type=str, default='./saved_models')\n parser.add_argument('--save_name', type=str, default='pimodel')\n parser.add_argument('--resume', type=str2bool, default=False)\n parser.add_argument('--load_path', type=str, default=None)\n parser.add_argument('--overwrite', type=str2bool, default=False)\n parser.add_argument('--use_tensorboard', action='store_true', help='Use tensorboard to plot and save curves, otherwise save the curves locally.')\n\n '''\n Training Configuration of PiModel\n '''\n\n parser.add_argument('--epoch', type=int, default=1)\n parser.add_argument('--num_train_iter', type=int, default=2 ** 20,\n help='total number of training iterations')\n parser.add_argument('--num_eval_iter', type=int, default=1000,\n help='evaluation frequency')\n parser.add_argument('--unsup_warmup_pos', type=float, default=0.4,\n help='Relative position at which constraint loss warmup ends.')\n parser.add_argument('--num_labels', type=int, default=4000)\n parser.add_argument('--batch_size', type=int, default=64,\n help='total number of batch size of labeled data')\n parser.add_argument('--uratio', type=int, default=1,\n help='the ratio of unlabeled data to labeld data in each mini-batch')\n parser.add_argument('--eval_batch_size', type=int, default=1024,\n help='batch size of evaluation data loader (it does not affect the accuracy)')\n\n parser.add_argument('--ema_m', type=float, default=0.999)\n parser.add_argument('--ulb_loss_ratio', type=float, default=10.0)\n '''\n Optimizer configurations\n '''\n parser.add_argument('--optim', type=str, default='SGD')\n parser.add_argument('--lr', type=float, default=3e-2)\n parser.add_argument('--momentum', type=float, default=0.9)\n parser.add_argument('--weight_decay', type=float, default=5e-4)\n parser.add_argument('--amp', type=str2bool, default=False, help='use mixed precision training or not')\n parser.add_argument('--clip', type=float, default=0)\n\n '''\n Backbone Net Configurations\n '''\n parser.add_argument('--net', type=str, default='WideResNet')\n parser.add_argument('--net_from_name', type=str2bool, default=False)\n parser.add_argument('--depth', type=int, default=28)\n parser.add_argument('--widen_factor', type=int, default=2)\n parser.add_argument('--leaky_slope', type=float, default=0.1)\n parser.add_argument('--dropout', type=float, default=0.0)\n\n '''\n Data Configurations\n '''\n\n parser.add_argument('--data_dir', type=str, default='./data')\n parser.add_argument('--dataset', type=str, default='cifar10')\n parser.add_argument('--train_sampler', type=str, default='RandomSampler')\n parser.add_argument('--num_classes', type=int, default=10)\n parser.add_argument('--num_workers', type=int, default=1)\n\n '''\n multi-GPUs & Distrbitued Training\n '''\n\n ## args for distributed training (from https://github.com/pytorch/examples/blob/master/imagenet/main.py)\n parser.add_argument('--world-size', default=1, type=int,\n help='number of nodes for distributed training')\n parser.add_argument('--rank', default=0, type=int,\n help='**node rank** for distributed training')\n parser.add_argument('--dist-url', default='tcp://127.0.0.1:10002', type=str,\n help='url used to set up distributed training')\n parser.add_argument('--dist-backend', default='nccl', type=str,\n help='distributed backend')\n parser.add_argument('--seed', default=0, type=int,\n help='seed for initializing training. ')\n parser.add_argument('--gpu', default=None, type=int,\n help='GPU id to use.')\n parser.add_argument('--multiprocessing-distributed', type=str2bool, default=True,\n help='Use multi-processing distributed training to launch '\n 'N processes per node, which has N GPUs. This is the '\n 'fastest way to use PyTorch for either single node or '\n 'multi node data parallel training')\n\n # config file\n parser.add_argument('--c', type=str, default='')\n\n args = parser.parse_args()\n over_write_args_from_file(args, args.c)\n main(args)\n" ]
[ [ "torch.multiprocessing.spawn", "torch.manual_seed", "torch.distributed.init_process_group", "numpy.random.seed", "torch.cuda.device_count", "torch.nn.parallel.DistributedDataParallel", "torch.cuda.is_available", "torch.nn.DataParallel", "torch.cuda.set_device" ] ]
ioam/topographica
[ "1e097e2df9938a6ce9f48cefbf25672cbbf9a4db" ]
[ "topo/tests/unit/testplot.py" ]
[ "\"\"\"\nTest for the Plot class.\n\"\"\"\n\n\nimport unittest\nfrom topo.base.sheet import *\n#from testsheetview import ImageGenerator\n\nSHOW_PLOTS = False\n\n### JC: My new imports\nfrom topo.plotting.plot import make_template_plot\nimport numpy as np\n\nimport param\n\nfrom holoviews.core import BoundingBox, NdMapping\nfrom holoviews.interface.collector import AttrDict\nfrom holoviews import Image\n\n\n### This function is defined here, where it might be useful for testing\n### Plot\ndef matrix_hsv_to_rgb(hMapArray,sMapArray,vMapArray):\n \"\"\"\n First matrix sets the Hue (Color).\n Second marix sets the Sauration (How much color)\n Third matrix sets the Value (How bright the pixel will be)\n\n The three input matrices should all be the same size, and have\n been normalized to 1. There should be no side-effects on the\n original input matrices.\n \"\"\"\n\n shape = hMapArray.shape\n rmat = np.array(hMapArray,dtype=np.float)\n gmat = np.array(sMapArray,dtype=np.float)\n bmat = np.array(vMapArray,dtype=np.float)\n\n ## This code should never be seen. It means that calling code did\n ## not take the precaution of clipping the input matrices.\n if max(rmat.ravel()) > 1 or max(gmat.ravel()) > 1 or max(bmat.ravel()) > 1:\n param.Parameterized().warning('HSVBitmap inputs exceed 1. Clipping to 1.0')\n if max(rmat.ravel()) > 0: rmat = clip(rmat,0.0,1.0)\n if max(gmat.ravel()) > 0: gmat = clip(gmat,0.0,1.0)\n if max(bmat.ravel()) > 0: bmat = clip(bmat,0.0,1.0)\n\n # List comprehensions were not used because they were slower.\n for j in range(shape[0]):\n for i in range(shape[1]):\n rgb = hsv_to_rgb(rmat[j,i],gmat[j,i],bmat[j,i])\n rmat[j,i] = rgb[0]\n gmat[j,i] = rgb[1]\n bmat[j,i] = rgb[2]\n\n return (rmat, gmat, bmat)\n\n\n\n### JCALERT !he file should be rewritten according to new changes in Plot.\n\nclass TestPlot(unittest.TestCase):\n\n def setUp(self):\n ### Simple case: we only pass a dictionary to Plot()\n ### that does not belong to a Sheet:\n views = {}\n\n time = 0\n metadata = AttrDict(timestamp=time)\n\n ### SheetView1:\n ### Find a way to assign randomly the matrix.\n self.matrix1 = np.zeros((10,10),dtype=np.float) + np.random.random((10,10))\n self.bounds1 = BoundingBox(points=((-0.5,-0.5),(0.5,0.5)))\n im = Image(self.matrix1, self.bounds1)\n im.metadata=metadata\n self.sheet_view1 = NdMapping((None, im))\n self.sheet_view1.metadata = AttrDict(src_name='TestInputParam',\n precedence=0.1, row_precedence=0.1,\n cyclic_range=None, timestamp=time)\n self.key1 = 'IM1'\n views[self.key1] = self.sheet_view1\n\n ### SheetView2:\n ### Find a way to assign randomly the matrix.\n self.matrix2 = np.zeros((10,10),dtype=np.float) + 0.3\n self.bounds2 = BoundingBox(points=((-0.5,-0.5),(0.5,0.5)))\n im = Image(self.matrix2, self.bounds2)\n im.metadata=metadata\n self.sheet_view2 = NdMapping((None, im))\n self.sheet_view2.metadata = AttrDict(src_name='TestInputParam',\n precedence=0.2, row_precedence=0.2,\n cyclic_range=None, timestamp=time)\n self.key2 = 'IM2'\n views[self.key2] = self.sheet_view2\n\n ### SheetView3:\n ### Find a way to assign randomly the matrix.\n self.matrix3 = np.zeros((10,10),dtype=np.float) + np.random.random((10,10))\n self.bounds3 = BoundingBox(points=((-0.5,-0.5),(0.5,0.5)))\n im = Image(self.matrix3, self.bounds3)\n im.metadata=metadata\n self.sheet_view3 = NdMapping((None, im))\n self.sheet_view3.metadata = AttrDict(src_name='TestInputParam',\n precedence=0.3, row_precedence=0.3,\n cyclic_range=None, timestamp=time)\n self.key3 = 'IM3'\n views[self.key3] = self.sheet_view3\n\n ### SheetView4: for testing clipping + different bounding box\n ### Find a way to assign randomly the matrix.\n self.matrix4 = np.zeros((10,10),dtype=np.float) + 1.6\n self.bounds4 = BoundingBox(points=((-0.7,-0.7),(0.7,0.7)))\n im = Image(self.matrix4, self.bounds4)\n im.metadata=metadata\n self.sheet_view4 = NdMapping((None, im))\n self.sheet_view4.metadata = AttrDict(src_name='TestInputParam',\n precedence=0.4, row_precedence=0.4,\n cyclic_range=None, timestamp=time)\n self.key4 = 'IM4'\n views[self.key4] = self.sheet_view4\n\n self.view_dict = {'Strength': views, 'Hue': views, 'Confidence': views}\n\n ### JCALERT! for the moment we can only pass a triple when creating plot\n ### adding more sheetView to test when plot will be fixed for accepting\n ### as much as you want.\n\n # plot0: empty plot + no sheetviewdict passed: error or empty plot?\n ### JCALERT! It has to be fixed what to do in this case in plot..\n ### disabled test for the moment.\n #self.plot0 = Plot((None,None,None),None,name='plot0')\n ### CATCH EXCEPTION\n\n plot_channels1 = {'Strength':None,'Hue':None,'Confidence':None}\n # plot1: empty plot\n self.plot1 = make_template_plot(plot_channels1,self.view_dict,density=10.0,name='plot1')\n\n plot_channels2 = {'Strength':self.key1,'Hue':None,'Confidence':None}\n # plot2: sheetView 1, no normalize, no clipping\n self.plot2 = make_template_plot(plot_channels2,self.view_dict,density=10.0,name='plot2')\n\n plot_channels3 = {'Strength':self.key1,'Hue':self.key2,'Confidence':None}\n # plot3: sheetView 1+2, no normalize, no clipping\n self.plot3 = make_template_plot(plot_channels3,self.view_dict,density=10.0,name='plot3')\n\n plot_channels4 = {'Strength':self.key1,'Hue':self.key2,'Confidence':self.key3}\n # plot4: sheetView 1+2+3, no normalize , no clipping\n self.plot4 = make_template_plot(plot_channels4,self.view_dict,density=10.0,name='plot4')\n\n plot_channels5 = {'Strength':self.key1,'Hue':None,'Confidence':self.key3}\n # plot5: sheetView 1+3, no normalize, no clipping\n self.plot5 = make_template_plot(plot_channels5,self.view_dict,density=10.0,name='plot5')\n\n plot_channels6 = {'Strength':None,'Hue':self.key2,'Confidence':self.key3}\n # plot6: sheetView 2+3, no normalize , no clipping\n self.plot6 = make_template_plot(plot_channels6,self.view_dict,density=10.0,name='plot6')\n\n plot_channels7 = {'Strength':self.key4,'Hue':self.key2,'Confidence':self.key3}\n # plot7: sheetView 1+2+3, no normalize , clipping\n self.plot7 = make_template_plot(plot_channels7,self.view_dict,density=10.0,name='plot7')\n\n plot_channels8 = {'Strength':self.key1,'Hue':self.key2,'Confidence':self.key3}\n # plot8: sheetView 1+2+3, normalize , no clipping\n self.plot8 = make_template_plot(plot_channels8,self.view_dict,density=10.0,normalize=True,name='plot8')\n\n ### JCALERT! FOR THE MOMENT I TAKE THE DEFAULT FOR NORMALIZE.\n ### WE WILL SEE IF IT REMAINS IN PLOT FIRST.\n\n ### also makes a sheet to test realease_sheetviews\n\n self.sheet = Sheet()\n self.sheet.views.Maps[self.key1]=self.sheet_view1\n self.sheet.views.Maps[self.key2]=self.sheet_view2\n self.sheet.views.Maps[self.key3]=self.sheet_view3\n self.sheet.views.Maps[self.key4]=self.sheet_view4\n\n plot_channels9 = {'Strength':self.key1,'Hue':self.key2,'Confidence':self.key3}\n self.plot9 = make_template_plot(plot_channels9,self.sheet.views.Maps,density=10.0,name='plot9')\n\n\n\n\n def test_plot(self):\n pass\n\n# ### JCALERT! make a test for plot0\n\n# # plot 1\n# test = None\n# self.assertEqual(self.plot1,test)\n\n# # plot 2\n# sat = np.zeros((10,10),dtype=np.float)\n# hue = np.zeros((10,10),dtype=np.float)\n# val = self.matrix1\n\n# test = matrix_hsv_to_rgb(hue,sat,val)\n# for each1,each2 in zip(self.plot2.rgb_matrices,test):\n# for each3,each4 in zip(each1.ravel(),each2.ravel()):\n# self.assertAlmostEqual(each3,each4)\n\n# # plot 3\n# sat = ones((10,10),dtype=np.float)\n# hue = np.zeros((10,10),dtype=np.float) + 0.3\n# val = self.matrix1\n\n# test = matrix_hsv_to_rgb(hue,sat,val)\n# for each1,each2 in zip(self.plot3.rgb_matrices,test):\n# for each3,each4 in zip(each1.ravel(),each2.ravel()):\n# self.assertAlmostEqual(each3,each4)\n\n# # plot 4\n# sat = self.matrix3\n# hue = np.zeros((10,10),dtype=np.float) + 0.3\n# val = self.matrix1\n\n# test = matrix_hsv_to_rgb(hue,sat,val)\n# for each1,each2 in zip(self.plot4.rgb_matrices,test):\n# for each3,each4 in zip(each1.ravel(),each2.ravel()):\n# self.assertAlmostEqual(each3,each4)\n\n# # plot 5\n# sat = np.zeros((10,10),dtype=np.float)\n# hue = np.zeros((10,10),dtype=np.float)\n# val = self.matrix1\n\n# test = matrix_hsv_to_rgb(hue,sat,val)\n# for each1,each2 in zip(self.plot5.rgb_matrices,test):\n# for each3,each4 in zip(each1.ravel(),each2.ravel()):\n# self.assertAlmostEqual(each3,each4)\n\n# # plot 6\n# sat = self.matrix3\n# hue = np.zeros((10,10),dtype=np.float) + 0.3\n# val = ones((10,10),dtype=np.float)\n\n# test = matrix_hsv_to_rgb(hue,sat,val)\n# for each1,each2 in zip(self.plot6.rgb_matrices,test):\n# for each3,each4 in zip(each1.ravel(),each2.ravel()):\n# self.assertAlmostEqual(each3,each4)\n\n# # plot 7\n# sat = self.matrix3\n# hue = np.zeros((10,10),dtype=np.float) + 0.3\n# val = self.matrix4\n\n# val = MLab.clip(val,0.0,1.0)\n\n# test = matrix_hsv_to_rgb(hue,sat,val)\n# for each1,each2 in zip(self.plot7.rgb_matrices,test):\n# for each3,each4 in zip(each1.ravel(),each2.ravel()):\n# self.assertAlmostEqual(each3,each4)\n\n\n# # plot 8\n# sat = self.matrix3\n# hue = np.zeros((10,10),dtype=np.float) + 0.3\n# val = self.matrix1\n\n# val = divide(val,float(max(val.ravel())))\n\n# test = matrix_hsv_to_rgb(hue,sat,val)\n\n# for each1,each2 in zip(self.plot8.rgb_matrices,test):\n# for each3,each4 in zip(each1.ravel(),each2.ravel()):\n# self.assertAlmostEqual(each3,each4)\n\n\n\n\n# # plot 9\n# sat = self.matrix3\n# hue = np.zeros((10,10),dtype=np.float) + 0.3\n# val = self.matrix1\n\n# test = matrix_hsv_to_rgb(hue,sat,val)\n# for each1,each2 in zip(self.plot9.rgb_matrices,test):\n# for each3,each4 in zip(each1.ravel(),each2.ravel()):\n# self.assertAlmostEqual(each3,each4)\n\n# #### Think about doing a plot test using sheet_dict and a sheet?\n# ### Ask Jim if it is really necessary...\n\n# def test_release_sheetviews(self):\n\n# self.plot9.release_sheetviews()\n\n# test=self.sheet.sheet_views.get(self.key1,None)\n# self.assertEqual(test,None)\n# test=self.sheet.sheet_views.get(self.key2,None)\n# self.assertEqual(test,None)\n# test=self.sheet.sheet_views.get(self.key3,None)\n# self.assertEqual(test,None)\n# test=self.sheet.sheet_views.get(self.key4,None)\n# self.assertEqual(test,self.sheet_view4)\n\n\n# def test_matrix_hsv_to_rgb(self):\n# a = [j for i in range(256) for j in range(256)]\n# b = [i for i in range(256) for j in range(256)]\n# c = [max(i,j) for i in range(256) for j in range(256)]\n# a = Numeric.reshape(a,(256,256)) / 255.0\n# b = Numeric.reshape(b,(256,256)) / 255.0\n# c = Numeric.reshape(c,(256,256)) / 255.0\n# (h,s,v) = matrix_hsv_to_rgb(a,b,c)\n# rgb = RGBMap(h,s,v)\n# # rgb.show()\n\n# def test_matrix_hsv_to_rgb2(self):\n# h = Numeric.np.array([[0.0,0.0],[0.0,0.0]])\n# s = Numeric.np.array([[0.0,0.0],[0.0,0.0]])\n# v = Numeric.np.array([[0.5,0.5],[0.5,0.5]])\n# h_orig = Numeric.np.array(h)\n# s_orig = Numeric.np.array(s)\n# v_orig = Numeric.np.array(v)\n# r,g,b = matrix_hsv_to_rgb(h,s,v)\n# rgb_target = Numeric.np.array([[0.5,0.5],[0.5,0.5]])\n# self.assertEqual(h,h_orig)\n# self.assertEqual(s,s_orig)\n# self.assertEqual(v,v_orig)\n\n\n### JC: THIS CODE IS LEFT TEMPORARY IN CASE IT IS OF ANY USE IN NEAR FUTURE\n\n# x = plot.Plot(('Activity',None,None),plot.COLORMAP,self.s2)\n# for o in dir():\n# # pprint(o)\n# if isinstance(o,plot.Plot):\n# o.warning('Found ', o.name)\n\n# input = ImageGenerator(filename='topo/tests/testsheetview.ppm',\n# density=100,\n# bounds=BoundingBox(points=((-0.8,-0.8),(0.8,0.8))))\n# sv = input.sheet_view('Activity')\n\n# # Defined sheetview in the R channel\n# plot1 = plot.Plot((None,None,sv),plot.COLORMAP)\n# p_tuple = plot1.plot()\n# (r, g, b) = p_tuple.matrices\n# map = RGBMap(r,g,b)\n# if SHOW_PLOTS: map.show()\n\n\n# def test_HSV_plot(self):\n# input = ImageGenerator(filename='topo/tests/testsheetview.ppm',\n# density=100,\n# bounds=BoundingBox(points=((-0.8,-0.8),(0.8,0.8))))\n# sv = input.sheet_view('Activity')\n\n# # Defined sheetview in the R channel\n# plot1 = plot.Plot((sv,sv,sv),plot.HSV)\n# p_tuple = plot1.plot()\n# (r, g, b) = p_tuple.matrices\n# map = HSVMap(r,g,b)\n# if SHOW_PLOTS: map.show()\n\n# def test_plottemplate(self):\n# pt = plot.PlotTemplate()\n# pt = plot.PlotTemplate({'Strength' : None,\n# 'Hue' : 'HueP',\n# 'Confidence' : None})\n# pt = plot.PlotTemplate(channels={'Strength' : None,\n# 'Hue' : 'HueP',\n# 'Confidence' : None})\n\nif __name__ == \"__main__\":\n\timport nose\n\tnose.runmodule()\n\n" ]
[ [ "numpy.array", "numpy.zeros", "numpy.random.random" ] ]
workprinond/Anti-Alignment
[ "12783fcc7f3c208007bf15d750a3659fd92506f0" ]
[ "anti_alignment/algo/graph_construction/search_tree.py" ]
[ "import numpy as np\nimport networkx as nx\n\n\nclass SearchTree:\n\n def __init__(self,net,i_m, f_m):\n self.net = net\n self.i_m = i_m\n self.f_m = f_m\n\n def compute_incidence_matrix(self,net):\n \"\"\"\n We compute the incidence matrix of a Petri Net. It provides us with the firing requirements of a transition and its\n outcome. The matrix has rows equals to the number of places and columns equals to the the number of transition.\n As a result, the columns represent the firing information for each transition.\n :return: Numpy Matrix representing the incidence matrix.\n \"\"\"\n incidence_matrix=np.zeros((len(self.net.places), len(self.net.transitions)))\n transitions=list(self.net.transitions)\n places=list(self.net.places)\n i=0\n while i<len(transitions):\n transition=transitions[i]\n for ingoing_arc in transition.in_arcs:\n #A transition consumes a token from its input places. Therefore, we have to subtract 1.\n incidence_matrix[places.index(ingoing_arc.source), i] -= ingoing_arc.weight\n for outgoing_arc in transition.out_arcs:\n #A transition produces one token for each of its \"destination\" places. Therefore, we have to add 1.\n incidence_matrix[places.index(outgoing_arc.target), i] +=outgoing_arc.weight\n i+=1\n return incidence_matrix\n\n def requirement_firing(self,net):\n \"\"\"\n Computes how many tokens in which place are needed for a transition to fire.\n :param net: PM4Py Petri Net object\n :return: dictionary, whereby the keys are the transition, the values are a np.array which only marks where tokens are consumed for the respective transtion.\n \"\"\"\n place_list=list(net.places)\n transition_dict={}\n for transition in net.transitions:\n temp=np.zeros(len(place_list))\n for arc in transition.in_arcs:\n temp[place_list.index(arc.source)]-=arc.weight\n transition_dict[transition]=temp\n return transition_dict\n\n def transition_firing_information(self,incidence_matrix, net):\n \"\"\"\n We transform the information that is available in the incidence in a more readable form. This means that we\n contruct a dictionary, whereby a key is the name of a\n :param incidence_matrix: Incidence Matrix of a Petri Net\n :param net: Petri Net\n :return: Dictionary\n \"\"\"\n firing_dict = {}\n i=0\n transitions=list(net.transitions)\n while i < len(transitions):\n firing_dict[transitions[i]] = incidence_matrix[: , i]\n i+=1\n return firing_dict\n\n def get_post_firing_marking(self,marking, firing_dict, requirement_dict):\n \"\"\"\n We compute all possible markings after all fireable transition have been fired.\n :param marking: current marking\n :param firing_dict: Dictionary which provides us with the firing infomation whereby the key is the transition\n :param requirement_dict: Dict, whereby keys are transitions, key np.array that marks from which places amount of tokens is needed to fire\n :return: List of tuples, whereby the first element is the new marking, the second element is the transition that\n was used to reach the new marking.\n \"\"\"\n firing_result = []\n for transition,requirement in requirement_dict.items():\n if all(np.greater_equal(marking, requirement.copy()*-1)):\n firing_result.append((marking+firing_dict[transition], transition))\n return firing_result\n \n def convert_marking(self, net, marking):\n \"\"\"\n Since we are working with numpy arrays as representation of marking, we need no transform the initial marking\n to such a representation\n :param marking: Marking which is returned from discovery algorithms of PM4Py\n :return: numpy array that represents the initial marking\n \"\"\"\n places=list(net.places)\n conv=np.zeros(len(places))\n i=0\n while i<len(places):\n if places[i] in marking:\n conv[i]=marking[places[i]]\n i+=1\n return conv\n\n def construct_reachability_graph(self,initial_marking, net, n):\n \"\"\"\n We construct a reachability graph. Important to note is that we only expand nodes/marking, which can be reached in\n at most n not-tau transitions.\n :param initial_marking: inital marking of Petri Net, already coverted into a np.array representation\n :param net: Petri Net Object\n :param n: How many not tau transitions are considered\n :return: Networkx Multi-Directed Graph object\n \"\"\"\n #compute incidence matrix\n incidence_matrix=self.compute_incidence_matrix(net)\n \n #compute requirment_dict\n requirement_dict=self.requirement_firing(net)\n\n #compute firing dict\n firing_dict=self.transition_firing_information(incidence_matrix,net)\n\n #output graph is a MulitDiGraph to represent self-loops and parallel edges\n graph=nx.MultiDiGraph()\n #the inital marking is node 0. We add the marking as data to the node\n j=0\n graph.add_node(j, marking=initial_marking, distance_from_source=0)\n\n #the reference table reveals the node-number a particular marking has\n reference_table={}\n reference_table[np.array2string(initial_marking)]=j\n\n #our set of nodes which has to be extended in the reachability graph\n work=set()\n work.add(j)\n j+=1\n while len(work)>0:\n #This set contains nodes that are during the computation of the graph faster reachable\n updated_nodes = set()\n #select a random marking and remove it from the work set\n mark=work.pop()\n #a list of marking that are reachble by firing transition which are currently available\n reachable_markings=self.get_post_firing_marking(graph.nodes[mark]['marking'], firing_dict, requirement_dict)\n for marking in reachable_markings:\n if np.array2string(marking[0]) not in reference_table:\n #the first element of marking represent the numpy representation of that marking, the second the\n # transition that was taken\n #If the marking is not in the graph yet, we add it\n reference_table[np.array2string(marking[0])]=j\n graph.add_node(j, marking=marking[0])\n if marking[1].label == None:\n #if the transition that fires, we need an edge of weight 0. This is done because we only care about\n # the projected run/trace at the end\n graph.add_edge(mark, j, transition=marking[1], weight=0)\n graph.nodes[j]['distance_from_source'] = graph.nodes[mark]['distance_from_source']\n else:\n #If a non-tau transition fires, we need a weight of 1\n graph.add_edge(mark,j, transition=marking[1], weight=1)\n graph.nodes[j]['distance_from_source'] = graph.nodes[mark]['distance_from_source']+1\n if graph.nodes[j]['distance_from_source']<=n:\n #only if the distance is not exceed, we add the node to our work set to expand it\n work.add(j)\n j+=1\n else:\n #The marking is in the graph. However, we have to add the edge.\n observerable_marking=reference_table[np.array2string(marking[0])]\n if marking[1].label == None:\n graph.add_edge(mark, observerable_marking, transition=marking[1], weight=0)\n else:\n graph.add_edge(mark, observerable_marking, transition=marking[1], weight=1)\n min=np.inf\n #since there might be multiple arcs beetween states, we want to get the minimum weight to have a minimum distance between these\n for arc in graph.get_edge_data(mark, observerable_marking):\n if graph.get_edge_data(mark, observerable_marking)[arc]['weight']<min:\n min=graph.get_edge_data(mark, observerable_marking)[arc]['weight']\n distance_from_source_over_m=graph.nodes[mark]['distance_from_source']+min\n if distance_from_source_over_m<graph.nodes[observerable_marking]['distance_from_source']:\n graph.nodes[observerable_marking]['distance_from_source']=distance_from_source_over_m\n updated_nodes.add((observerable_marking, graph.nodes[observerable_marking]['distance_from_source']-distance_from_source_over_m))\n for el in updated_nodes:\n #since we have an directed graph, bfs returns us every successor and even their sucessors. These\n #are the nodes which distance have to be updated due a shorter path\n edges = nx.bfs_edges(graph, el[0])\n for (v,w) in edges:\n min = np.inf\n #since there might be multiple arcs beetween states, we want to get the minimum weight to have a minimum distance between these\n for arc in graph.get_edge_data(v, w):\n if graph.get_edge_data(v, w)[arc]['weight'] < min:\n min = graph.get_edge_data(v, w)[arc]['weight']\n if graph.nodes[v]['distance_from_source']+min<graph.nodes[w]['distance_from_source']:\n #if there is shorter path than before, we have to chek if the sucessor had previously a distance greater than n\n if graph.nodes[w]['distance_from_source'] > n and graph.nodes[v]['distance_from_source']+min<n:\n # If the \"new\" distance after eding edges/nodes is smaller and the old distance exceed our limit,\n # we need to consider the node in the work set for expansion\n work.add(w)\n #We have to update the distance value due a shorter path\n graph.nodes[w]['distance_from_source'] =graph.nodes[v]['distance_from_source']+min\n return graph\n\n def annotate_distance_to_sink(self,graph,final_marking):\n \"\"\"\n Each node gets annotated with the the distance to the final marking. Distance means the number of non-tau\n transitions to reach the final marking\n :param graph: Reachability graph, networkx MultiDiGraph object\n :return: Networkx MultiDiGraph whereby each node gets an additional attribute 'distance_to_sink'\n \"\"\"\n for node in graph.nodes: \n if np.array_equal(graph.nodes[node]['marking'],final_marking):\n sink=node\n break\n for node in graph.nodes:\n #it is possible that the final marking cannot be reached from a node\n try:\n graph.nodes[node]['distance_to_sink'] = nx.shortest_path_length(graph, source=node, target=sink, weight='weight')\n except nx.NetworkXNoPath:\n #if the final marking cannot be reached, we remove the node from the reachbility graph\n graph.remove_node(node)\n return graph\n\n def apply(self,depth):#,net, i_m, f_m, \n \"\"\"\n Apply method. Use from outside to get an reachbility graph.\n The reachability graph consist of the following attributes:\n For nodes:\n marking: np.arrray representation of the marking\n distance_from_source: number of non-tau transitions to get to the marking of the node, starting from the initial\n distance_to_sink: number of non-tau transitions to get to the final marking\n For edges:\n transition: transition object of the given Petri Net that is fired\n weight: If a tau-tranisiton has fired, the weight is 0; else 1. Since we are interested in the projected trace,\n we need to distinguish.\n :param net: PM4Py Petri Net object\n :param i_m: initial marking of the Petri Net object\n :param f_m: final marking of the Petri Net object\n :param depth: Depth of the reachability graph, meaning, maximum of non-tau transitions to the final marking\n :return: 3-tupel, consisting of two nodes and a networkx MultiDigraph object. The first node contains the initial\n marking, the second node contains the final marking\n \"\"\"\n initial_marking = self.convert_marking(self.net,self.i_m)\n final_marking = self.convert_marking(self.net,self.f_m)\n reachability_graph =self.construct_reachability_graph(initial_marking, self.net, depth)\n reachability_graph = self.annotate_distance_to_sink(reachability_graph, final_marking)\n #Due the construction of the graph, we know that the initial marking is observerable in node 0\n inital_marking_node = 0\n for node in reachability_graph.nodes:\n if np.array_equal(reachability_graph.nodes[node]['marking'], final_marking):\n final_marking_node = node\n return (inital_marking_node, final_marking_node, reachability_graph)\n" ]
[ [ "numpy.array2string", "numpy.array_equal" ] ]
jkulhanek/viewformer
[ "9ad2c5a2f7abe4b7ff490ced0132bf3d2f07e29c" ]
[ "viewformer/evaluate/evaluate_transformer_multictx_allimg.py" ]
[ "from aparse import click, ConditionalType\nimport os\nimport tqdm\nimport json\nimport numpy as np\nfrom PIL import Image\nfrom typing import Optional\nfrom typing import List\nfrom viewformer.utils.tensorflow import load_model\nfrom viewformer.data.loaders import get_loaders\nimport tensorflow as tf\nfrom viewformer.evaluate.evaluate_transformer_multictx import MultiContextEvaluator, print_metrics, to_relative_cameras, resize_tf, normalize_cameras, from_relative_cameras\n\n\ndef transformer_predict(cameras, codes, *, transformer_model):\n if transformer_model.config.augment_poses == 'relative':\n # Rotate poses for relative augment\n cameras, transform = to_relative_cameras(cameras)\n cameras = normalize_cameras(cameras)\n\n # Generate image tokens\n with tf.name_scope('transformer_generate_images'):\n # Remove prediction information\n input_ids = tf.concat([codes[:, :-1], tf.fill(tf.shape(codes[:, :1]),\n tf.constant(transformer_model.mask_token, dtype=codes.dtype))], 1)\n context_cameras = tf.concat([cameras[:, :-1], tf.zeros_like(cameras[:, :1])], 1)\n\n # Task specific outputs\n image_generation_query_cameras = tf.tile(cameras[:, -1:], [1, tf.shape(cameras)[1], 1])\n localization_query_tokens = tf.tile(codes[:, -1:], [1, tf.shape(cameras)[1], 1, 1])\n\n # Generate outputs\n output = transformer_model(dict(input_ids=input_ids,\n poses=context_cameras,\n localization_tokens=localization_query_tokens,\n output_poses=image_generation_query_cameras), training=False)\n\n # Format output\n generated_codes = tf.argmax(output['logits'], -1)\n generated_cameras = transformer_model.reduce_cameras(output['pose_prediction'], -2)\n\n # Erase relative transform\n if transformer_model.config.augment_poses == 'relative':\n generated_cameras = from_relative_cameras(generated_cameras, transform)\n return generated_cameras, generated_codes\n\n\ndef run_with_batchsize(fn, batch_size, *args, **kwargs):\n total = len(args[0])\n splits = [min(batch_size, (total - i * batch_size)) for i in range((total + batch_size - 1) // batch_size)]\n outs = []\n for i, bs in enumerate(splits):\n largs = [x[i * batch_size: (i+1) * batch_size] for x in args]\n louts = fn(*largs, **kwargs)\n outs.append(louts)\n if isinstance(outs[0], tuple):\n return tuple(tf.concat([x[i] for x in outs], 0) for i in range(len(outs[0])))\n else:\n return tf.concat(outs, 0)\n\n\ndef encode_images(frames, *, codebook_model):\n with tf.name_scope('encode'):\n def encode(images):\n fimages = resize_tf(images, codebook_model.config.image_size)\n fimages = tf.image.convert_image_dtype(fimages, tf.float32)\n fimages = fimages * 2 - 1\n codes = codebook_model.encode(fimages)[-1] # [N, H', W']\n codes = tf.cast(codes, dtype=tf.int32)\n return codes\n\n # codes = tf.ragged.map_flat_values(encode, codes)\n batch_size, seq_len, *im_dim = tf.unstack(tf.shape(frames), 5)\n codes = encode(tf.reshape(frames, [batch_size * seq_len] + list(im_dim)))\n code_len = tf.shape(codes)[-1]\n codes = tf.reshape(codes, [batch_size, seq_len, code_len, code_len])\n return codes\n\n\ndef decode_code(generated_codes, *, codebook_model):\n with tf.name_scope('decode_images'):\n batch_size, seq_len, token_image_shape = tf.split(tf.shape(generated_codes), (1, 1, 2), 0)\n generated_images = codebook_model.decode_code(tf.reshape(generated_codes, tf.concat((batch_size * seq_len, token_image_shape), 0)))\n generated_images = tf.clip_by_value(generated_images, -1, 1)\n generated_images = tf.image.convert_image_dtype(generated_images / 2 + 0.5, tf.uint8)\n generated_images = tf.reshape(generated_images, tf.concat((batch_size, seq_len, tf.shape(generated_images)[-3:]), 0))\n return generated_images\n\n\n#\n# Types used in argument parsing\n#\ndef _loader_switch_cls(cls):\n class Loader(cls):\n # Disable arguments in loader classes\n def __init__(self, *args, image_size=None, shuffle=None, shuffle_sequence_items=None, shuffle_sequences=None, **kwargs):\n raise NotImplementedError()\n\n def __new__(_cls, *args, **kwargs):\n # Return callback to construct Loader on the Fly\n return lambda image_size: cls(*args, **kwargs, image_size=image_size, shuffle_sequences=False, shuffle_sequence_items=False)\n return Loader\n\n\nLoaderSwitch = ConditionalType('Loader', {k: _loader_switch_cls(v) for k, v in get_loaders().items()}, default='dataset')\n\n\[email protected]('evaluate-allimg')\ndef main(loader: LoaderSwitch,\n transformer_model: str,\n codebook_model: str,\n job_dir: str,\n context_views: List[int] = None,\n pose_multiplier: Optional[float] = None,\n image_size: Optional[int] = None):\n transformer_config = dict()\n if pose_multiplier is not None:\n transformer_config['pose_multiplier'] = pose_multiplier\n transformer_model = load_model(transformer_model, **transformer_config)\n codebook_model = load_model(codebook_model)\n loader = loader(codebook_model.config.image_size)\n n_context_views = len(context_views) if context_views is not None else (transformer_model.config.sequence_size - 1)\n evaluator = MultiContextEvaluator(n_context_views + 1, image_size=image_size)\n rng = np.random.default_rng(42)\n\n with tqdm.tqdm(total=len(loader)) as progress:\n for seq in loader:\n c_context_views = context_views\n if c_context_views is None:\n c_context_views = list(rng.choice(len(seq['frames']), (n_context_views,), replace=False))\n frames = np.array(seq['frames'])[np.newaxis, ...]\n cameras = np.stack(seq['cameras'])[np.newaxis, ...].astype('float32')\n frames, cameras = tf.convert_to_tensor(frames), tf.convert_to_tensor(cameras)\n codes = encode_images(frames, codebook_model=codebook_model)\n generated_cameras, generated_codes = [], []\n tcodes = np.concatenate([np.stack([codes[:, j] for j in c_context_views + [i]], 1) for i in range(len(seq['frames']))], 0)\n tcameras = np.concatenate([np.stack([cameras[:, j] for j in c_context_views + [i]], 1) for i in range(len(seq['frames']))], 0)\n generated_cameras, generated_codes = run_with_batchsize(transformer_predict, 128, tcameras, tcodes, transformer_model=transformer_model)\n\n # Decode images\n generated_images = run_with_batchsize(decode_code, 64, generated_codes, codebook_model=codebook_model)\n eval_frames = [x for x in range(len(generated_images)) if x not in c_context_views]\n evaluator.update_state(\n ground_truth_cameras=tf.stack([cameras[0, x] for x in eval_frames], 0),\n ground_truth_images=tf.stack([frames[0, x] for x in eval_frames], 0),\n generated_images=tf.stack([generated_images[x] for x in eval_frames], 0),\n generated_cameras=tf.stack([generated_cameras[x] for x in eval_frames], 0))\n for i in range(0, 1 + len(c_context_views)):\n os.makedirs(os.path.join(job_dir, 'gen_images', seq['sequence_id'], f'gen-{i:02}'), exist_ok=True)\n os.makedirs(os.path.join(job_dir, 'gen_images', seq['sequence_id'], 'gt'), exist_ok=True)\n os.makedirs(os.path.join(job_dir, 'gen_images', seq['sequence_id'], 'ctx'), exist_ok=True)\n for i, c in enumerate(c_context_views):\n Image.fromarray(frames[0, c].numpy()).save(os.path.join(job_dir, 'gen_images', seq['sequence_id'], 'ctx', f'{i:02}-{c:03}.png'))\n for i, c in enumerate(frames[0]):\n Image.fromarray(c.numpy()).save(os.path.join(job_dir, 'gen_images', seq['sequence_id'], 'gt', f'{i:03}.png'))\n for i, c in enumerate(generated_images):\n for j, d in enumerate(c):\n Image.fromarray(d.numpy()).save(os.path.join(job_dir, 'gen_images', seq['sequence_id'], f'gen-{j:02}', f'{i:03}.png'))\n progress.set_postfix(evaluator.get_progress_bar_info())\n progress.update()\n\n result = evaluator.result()\n with open(os.path.join(job_dir, 'results.json'), 'w+') as f:\n json.dump(result, f)\n print('Results:')\n print_metrics(result)\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "tensorflow.stack", "numpy.random.default_rng", "tensorflow.reshape", "tensorflow.shape", "numpy.stack", "tensorflow.zeros_like", "tensorflow.cast", "tensorflow.name_scope", "tensorflow.image.convert_image_dtype", "tensorflow.clip_by_value", "tensorflow.concat", "tensorflow.argmax", "numpy.array", "tensorflow.convert_to_tensor", "tensorflow.constant" ] ]
kdorichev/text2speech
[ "082ed9c222fa346f6c5ad6375477807df44ed45a" ]
[ "fastpitch/transformer_jit.py" ]
[ "# Adapted from\n# https://github.com/NVIDIA/DeepLearningExamples/tree/master/PyTorch/SpeechSynthesis/FastPitch\n\n# Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import List, Optional\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom common.utils import mask_from_lens\nfrom common.text.symbols import pad_idx, symbols\n\n\nclass NoOp(nn.Module):\n def forward(self, x):\n return x\n\n\nclass PositionalEmbedding(nn.Module):\n def __init__(self, demb):\n super(PositionalEmbedding, self).__init__()\n self.demb = demb\n inv_freq = 1 / (10000 ** (torch.arange(0.0, demb, 2.0) / demb))\n self.register_buffer('inv_freq', inv_freq)\n\n def forward(self, pos_seq, bsz: Optional[int] = None):\n sinusoid_inp = torch.ger(pos_seq, self.inv_freq)\n pos_emb = torch.cat([sinusoid_inp.sin(), sinusoid_inp.cos()], dim=1)\n if bsz is not None:\n return pos_emb[None, :, :].expand(bsz, -1, -1)\n else:\n return pos_emb[None, :, :]\n\n\nclass PositionwiseFF(nn.Module):\n def __init__(self, d_model, d_inner, dropout, pre_lnorm=False):\n super(PositionwiseFF, self).__init__()\n\n self.d_model = d_model\n self.d_inner = d_inner\n self.dropout = dropout\n\n self.CoreNet = nn.Sequential(\n nn.Linear(d_model, d_inner), nn.ReLU(),\n nn.Dropout(dropout),\n nn.Linear(d_inner, d_model),\n nn.Dropout(dropout),\n )\n\n self.layer_norm = nn.LayerNorm(d_model)\n self.pre_lnorm = pre_lnorm\n\n def forward(self, inp):\n if self.pre_lnorm:\n # layer normalization + positionwise feed-forward\n core_out = self.CoreNet(self.layer_norm(inp))\n\n # residual connection\n output = core_out + inp\n else:\n # positionwise feed-forward\n core_out = self.CoreNet(inp)\n\n # residual connection + layer normalization\n output = self.layer_norm(inp + core_out)\n\n return output\n\n\nclass PositionwiseConvFF(nn.Module):\n def __init__(self, d_model, d_inner, kernel_size, dropout, pre_lnorm=False):\n super(PositionwiseConvFF, self).__init__()\n\n self.d_model = d_model\n self.d_inner = d_inner\n self.dropout = dropout\n\n self.CoreNet = nn.Sequential(\n nn.Conv1d(d_model, d_inner, kernel_size, 1, (kernel_size // 2)),\n nn.ReLU(),\n # nn.Dropout(dropout), # worse convergence\n nn.Conv1d(d_inner, d_model, kernel_size, 1, (kernel_size // 2)),\n nn.Dropout(dropout),\n )\n self.layer_norm = nn.LayerNorm(d_model)\n self.pre_lnorm = pre_lnorm\n\n def forward(self, inp):\n if self.pre_lnorm:\n # layer normalization + positionwise feed-forward\n core_out = inp.transpose(1, 2)\n core_out = self.CoreNet(self.layer_norm(core_out))\n core_out = core_out.transpose(1, 2)\n\n # residual connection\n output = core_out + inp\n else:\n # positionwise feed-forward\n core_out = inp.transpose(1, 2)\n core_out = self.CoreNet(core_out)\n core_out = core_out.transpose(1, 2)\n\n # residual connection + layer normalization\n output = self.layer_norm(inp + core_out)\n\n return output\n\n\nclass MultiHeadAttn(nn.Module):\n def __init__(self, n_head, d_model, d_head, dropout, dropatt=0.1,\n pre_lnorm=False):\n super(MultiHeadAttn, self).__init__()\n\n self.n_head = n_head\n self.d_model = d_model\n self.d_head = d_head\n self.scale = 1 / (d_head ** 0.5)\n self.dropout = dropout\n self.pre_lnorm = pre_lnorm\n\n self.qkv_net = nn.Linear(d_model, 3 * n_head * d_head)\n self.drop = nn.Dropout(dropout)\n self.dropatt = nn.Dropout(dropatt)\n self.o_net = nn.Linear(n_head * d_head, d_model, bias=False)\n self.layer_norm = nn.LayerNorm(d_model)\n\n\n def forward(self, inp, attn_mask: Optional[torch.Tensor] = None):\n residual = inp\n\n if self.pre_lnorm:\n # layer normalization\n inp = self.layer_norm(inp)\n\n n_head, d_head = self.n_head, self.d_head\n\n head_q, head_k, head_v = torch.chunk(self.qkv_net(inp), 3, dim=-1)\n head_q = head_q.view(inp.size(0), inp.size(1), n_head, d_head)\n head_k = head_k.view(inp.size(0), inp.size(1), n_head, d_head)\n head_v = head_v.view(inp.size(0), inp.size(1), n_head, d_head)\n\n q = head_q.permute(0, 2, 1, 3).reshape(-1, inp.size(1), d_head)\n k = head_k.permute(0, 2, 1, 3).reshape(-1, inp.size(1), d_head)\n v = head_v.permute(0, 2, 1, 3).reshape(-1, inp.size(1), d_head)\n\n attn_score = torch.bmm(q, k.transpose(1, 2))\n attn_score.mul_(self.scale)\n\n if attn_mask is not None:\n attn_mask = attn_mask.unsqueeze(1)\n attn_mask = attn_mask.repeat(n_head, attn_mask.size(2), 1)\n attn_score.masked_fill_(attn_mask, -float('inf'))\n\n attn_prob = F.softmax(attn_score, dim=2)\n attn_prob = self.dropatt(attn_prob)\n attn_vec = torch.bmm(attn_prob, v)\n\n attn_vec = attn_vec.view(n_head, inp.size(0), inp.size(1), d_head)\n attn_vec = attn_vec.permute(1, 2, 0, 3).contiguous().view(\n inp.size(0), inp.size(1), n_head * d_head)\n\n # linear projection\n attn_out = self.o_net(attn_vec)\n attn_out = self.drop(attn_out)\n\n if self.pre_lnorm:\n # residual connection\n output = residual + attn_out\n else:\n # residual connection + layer normalization\n\n # XXX Running TorchScript on 20.02 and 20.03 containers crashes here\n # XXX Works well with 20.01-py3 container.\n # XXX dirty fix is:\n # XXX output = self.layer_norm(residual + attn_out).half()\n output = self.layer_norm(residual + attn_out)\n\n return output\n\n # disabled; slower\n def forward_einsum(self, h, attn_mask=None):\n # multihead attention\n # [hlen x bsz x n_head x d_head]\n\n c = h\n\n if self.pre_lnorm:\n # layer normalization\n c = self.layer_norm(c)\n\n head_q = self.q_net(h)\n head_k, head_v = torch.chunk(self.kv_net(c), 2, -1)\n\n head_q = head_q.view(h.size(0), h.size(1), self.n_head, self.d_head)\n head_k = head_k.view(c.size(0), c.size(1), self.n_head, self.d_head)\n head_v = head_v.view(c.size(0), c.size(1), self.n_head, self.d_head)\n\n # [bsz x n_head x qlen x klen]\n # attn_score = torch.einsum('ibnd,jbnd->bnij', (head_q, head_k))\n attn_score = torch.einsum('bind,bjnd->bnij', (head_q, head_k))\n attn_score.mul_(self.scale)\n if attn_mask is not None and attn_mask.any().item():\n attn_score.masked_fill_(attn_mask[:, None, None, :], -float('inf'))\n\n # [bsz x qlen x klen x n_head]\n attn_prob = F.softmax(attn_score, dim=3)\n attn_prob = self.dropatt(attn_prob)\n\n # [bsz x n_head x qlen x klen] * [klen x bsz x n_head x d_head] \n # -> [qlen x bsz x n_head x d_head]\n attn_vec = torch.einsum('bnij,bjnd->bind', (attn_prob, head_v))\n attn_vec = attn_vec.contiguous().view(\n attn_vec.size(0), attn_vec.size(1), self.n_head * self.d_head)\n\n # linear projection\n attn_out = self.o_net(attn_vec)\n attn_out = self.drop(attn_out)\n\n if self.pre_lnorm:\n # residual connection\n output = h + attn_out\n else:\n # residual connection + layer normalization\n output = self.layer_norm(h + attn_out)\n\n return output\n\n\nclass TransformerLayer(nn.Module):\n def __init__(self, n_head, d_model, d_head, d_inner, kernel_size, dropout,\n **kwargs):\n super(TransformerLayer, self).__init__()\n\n self.dec_attn = MultiHeadAttn(n_head, d_model, d_head, dropout, **kwargs)\n self.pos_ff = PositionwiseConvFF(d_model, d_inner, kernel_size, dropout,\n pre_lnorm=kwargs.get('pre_lnorm'))\n\n def forward(self, dec_inp, mask):\n output = self.dec_attn(dec_inp, attn_mask=~mask.squeeze(2))\n output *= mask\n output = self.pos_ff(output)\n output *= mask\n return output\n\n\nclass FFTransformer(nn.Module):\n pad_idx = 0 # XXX\n\n def __init__(self, n_layer, n_head, d_model, d_head, d_inner, kernel_size,\n dropout, dropatt, dropemb=0.0, embed_input=True, d_embed=None,\n pre_lnorm=False):\n super(FFTransformer, self).__init__()\n self.d_model = d_model\n self.n_head = n_head\n self.d_head = d_head\n\n self.embed_input = embed_input\n if embed_input:\n self.word_emb = nn.Embedding(len(symbols), d_embed or d_model,\n padding_idx=FFTransformer.pad_idx)\n else:\n self.word_emb = NoOp()\n\n self.pos_emb = PositionalEmbedding(self.d_model)\n self.drop = nn.Dropout(dropemb)\n self.layers = nn.ModuleList()\n\n for _ in range(n_layer):\n self.layers.append(\n TransformerLayer(\n n_head, d_model, d_head, d_inner, kernel_size, dropout,\n dropatt=dropatt, pre_lnorm=pre_lnorm)\n )\n\n def forward(self, dec_inp, seq_lens: Optional[torch.Tensor] = None):\n if self.embed_input:\n inp = self.word_emb(dec_inp)\n # [bsz x L x 1]\n # mask = (dec_inp != FFTransformer.pad_idx).unsqueeze(2)\n mask = (dec_inp != 0).unsqueeze(2)\n else:\n inp = dec_inp\n assert seq_lens is not None\n mask = mask_from_lens(seq_lens).unsqueeze(2)\n pos_seq = torch.arange(inp.size(1), device=inp.device, dtype=inp.dtype)\n pos_emb = self.pos_emb(pos_seq) * mask\n out = self.drop(inp + pos_emb)\n\n for layer in self.layers:\n out = layer(out, mask=mask)\n\n # out = self.drop(out)\n return out, mask\n" ]
[ [ "torch.nn.Linear", "torch.nn.functional.softmax", "torch.nn.ReLU", "torch.nn.Conv1d", "torch.nn.LayerNorm", "torch.nn.ModuleList", "torch.arange", "torch.einsum", "torch.bmm", "torch.nn.Dropout", "torch.ger" ] ]
a-chumagin/great_expectations
[ "969dacbd4e0fce74ce515e5f1dcd0918785bcd21" ]
[ "great_expectations/expectations/metrics/map_metric_provider.py" ]
[ "import logging\nfrom functools import wraps\nfrom typing import Any, Callable, Dict, List, Optional, Type, Union\n\nimport numpy as np\n\nimport great_expectations.exceptions as ge_exceptions\nfrom great_expectations.core import ExpectationConfiguration\nfrom great_expectations.core.util import convert_to_json_serializable\nfrom great_expectations.execution_engine import (\n ExecutionEngine,\n PandasExecutionEngine,\n SparkDFExecutionEngine,\n SqlAlchemyExecutionEngine,\n)\nfrom great_expectations.execution_engine.execution_engine import (\n MetricDomainTypes,\n MetricFunctionTypes,\n MetricPartialFunctionTypes,\n)\nfrom great_expectations.execution_engine.sqlalchemy_execution_engine import (\n OperationalError,\n)\nfrom great_expectations.expectations.metrics import MetaMetricProvider\nfrom great_expectations.expectations.metrics.import_manager import F, Window, sa\nfrom great_expectations.expectations.metrics.metric_provider import (\n MetricProvider,\n metric_partial,\n)\nfrom great_expectations.expectations.metrics.util import Engine, Insert, Label, Select\nfrom great_expectations.expectations.registry import (\n get_metric_provider,\n register_metric,\n)\nfrom great_expectations.util import generate_temporary_table_name\nfrom great_expectations.validator.metric_configuration import MetricConfiguration\n\nlogger = logging.getLogger(__name__)\n\n\ndef column_function_partial(\n engine: Type[ExecutionEngine],\n partial_fn_type: str = None,\n **kwargs,\n):\n \"\"\"Provides engine-specific support for authoring a metric_fn with a simplified signature.\n\n A metric function that is decorated as a column_function_partial will be called with the engine-specific column type\n and any value_kwargs associated with the Metric for which the provider function is being declared.\n\n Args:\n engine:\n partial_fn_type:\n **kwargs:\n\n Returns:\n An annotated metric_function which will be called with a simplified signature.\n\n \"\"\"\n domain_type = MetricDomainTypes.COLUMN\n if issubclass(engine, PandasExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_SERIES\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type != MetricPartialFunctionTypes.MAP_SERIES:\n raise ValueError(\n \"PandasExecutionEngine only supports map_series for column_function_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: PandasExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n filter_column_isnull = kwargs.get(\n \"filter_column_isnull\", getattr(cls, \"filter_column_isnull\", False)\n )\n\n (\n df,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n domain_kwargs=metric_domain_kwargs, domain_type=domain_type\n )\n\n column_name = accessor_domain_kwargs[\"column\"]\n\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n if filter_column_isnull:\n df = df[df[column_name].notnull()]\n\n values = metric_fn(\n cls,\n df[column_name],\n **metric_value_kwargs,\n _metrics=metrics,\n )\n return values, compute_domain_kwargs, accessor_domain_kwargs\n\n return inner_func\n\n return wrapper\n\n elif issubclass(engine, SqlAlchemyExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_FN\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type not in [MetricPartialFunctionTypes.MAP_FN]:\n raise ValueError(\n \"SqlAlchemyExecutionEngine only supports map_fn for column_function_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: SqlAlchemyExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n filter_column_isnull = kwargs.get(\n \"filter_column_isnull\", getattr(cls, \"filter_column_isnull\", False)\n )\n if filter_column_isnull:\n compute_domain_kwargs = execution_engine.add_column_row_condition(\n metric_domain_kwargs\n )\n else:\n # We do not copy here because if compute domain is different, it will be copied by get_compute_domain\n compute_domain_kwargs = metric_domain_kwargs\n (\n selectable,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n domain_kwargs=compute_domain_kwargs, domain_type=domain_type\n )\n\n column_name = accessor_domain_kwargs[\"column\"]\n\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n dialect = execution_engine.dialect_module\n column_function = metric_fn(\n cls,\n sa.column(column_name),\n **metric_value_kwargs,\n _dialect=dialect,\n _table=selectable,\n _metrics=metrics,\n )\n return column_function, compute_domain_kwargs, accessor_domain_kwargs\n\n return inner_func\n\n return wrapper\n\n elif issubclass(engine, SparkDFExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_FN\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type not in [\n MetricPartialFunctionTypes.MAP_FN,\n MetricPartialFunctionTypes.WINDOW_FN,\n ]:\n raise ValueError(\n \"SparkDFExecutionEngine only supports map_fn and window_fn for column_function_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: SparkDFExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n filter_column_isnull = kwargs.get(\n \"filter_column_isnull\", getattr(cls, \"filter_column_isnull\", False)\n )\n\n if filter_column_isnull:\n compute_domain_kwargs = execution_engine.add_column_row_condition(\n metric_domain_kwargs\n )\n else:\n # We do not copy here because if compute domain is different, it will be copied by get_compute_domain\n compute_domain_kwargs = metric_domain_kwargs\n\n (\n data,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n domain_kwargs=compute_domain_kwargs, domain_type=domain_type\n )\n\n column_name = accessor_domain_kwargs[\"column\"]\n\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n column = data[column_name]\n column_function = metric_fn(\n cls,\n column=column,\n **metric_value_kwargs,\n _metrics=metrics,\n _compute_domain_kwargs=compute_domain_kwargs,\n )\n return column_function, compute_domain_kwargs, accessor_domain_kwargs\n\n return inner_func\n\n return wrapper\n\n else:\n raise ValueError(\"Unsupported engine for column_function_partial\")\n\n\ndef column_condition_partial(\n engine: Type[ExecutionEngine],\n partial_fn_type: Optional[Union[str, MetricPartialFunctionTypes]] = None,\n **kwargs,\n):\n \"\"\"Provides engine-specific support for authoring a metric_fn with a simplified signature.\n\n A column_condition_partial must provide a map function that evaluates to a boolean value; it will be used to provide\n supplemental metrics, such as the unexpected_value count, unexpected_values, and unexpected_rows.\n\n A metric function that is decorated as a column_condition_partial will be called with the engine-specific column\n type and any value_kwargs associated with the Metric for which the provider function is being declared.\n\n\n\n Args:\n engine:\n partial_fn_type:\n **kwargs:\n\n Returns:\n An annotated metric_function which will be called with a simplified signature.\n\n \"\"\"\n domain_type = MetricDomainTypes.COLUMN\n if issubclass(engine, PandasExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_CONDITION_SERIES\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type not in [MetricPartialFunctionTypes.MAP_CONDITION_SERIES]:\n raise ValueError(\n \"PandasExecutionEngine only supports map_condition_series for column_condition_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: PandasExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n filter_column_isnull = kwargs.get(\n \"filter_column_isnull\", getattr(cls, \"filter_column_isnull\", True)\n )\n\n (\n df,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n domain_kwargs=metric_domain_kwargs, domain_type=domain_type\n )\n\n column_name = accessor_domain_kwargs[\"column\"]\n\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n if filter_column_isnull:\n df = df[df[column_name].notnull()]\n\n meets_expectation_series = metric_fn(\n cls,\n df[column_name],\n **metric_value_kwargs,\n _metrics=metrics,\n )\n return (\n ~meets_expectation_series,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n )\n\n return inner_func\n\n return wrapper\n\n elif issubclass(engine, SqlAlchemyExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_CONDITION_FN\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type not in [\n MetricPartialFunctionTypes.MAP_CONDITION_FN,\n MetricPartialFunctionTypes.WINDOW_CONDITION_FN,\n ]:\n raise ValueError(\n \"SqlAlchemyExecutionEngine only supports map_condition_fn and window_condition_fn for column_condition_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: SqlAlchemyExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n filter_column_isnull = kwargs.get(\n \"filter_column_isnull\", getattr(cls, \"filter_column_isnull\", True)\n )\n\n (\n selectable,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n metric_domain_kwargs, domain_type=domain_type\n )\n\n column_name = accessor_domain_kwargs[\"column\"]\n\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n sqlalchemy_engine: Engine = execution_engine.engine\n\n dialect = execution_engine.dialect_module\n expected_condition = metric_fn(\n cls,\n sa.column(column_name),\n **metric_value_kwargs,\n _dialect=dialect,\n _table=selectable,\n _sqlalchemy_engine=sqlalchemy_engine,\n _metrics=metrics,\n )\n if filter_column_isnull:\n # If we \"filter\" (ignore) nulls then we allow null as part of our new expected condition\n unexpected_condition = sa.and_(\n sa.not_(sa.column(column_name).is_(None)),\n sa.not_(expected_condition),\n )\n else:\n unexpected_condition = sa.not_(expected_condition)\n return (\n unexpected_condition,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n )\n\n return inner_func\n\n return wrapper\n\n elif issubclass(engine, SparkDFExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_CONDITION_FN\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type not in [\n MetricPartialFunctionTypes.MAP_CONDITION_FN,\n MetricPartialFunctionTypes.WINDOW_CONDITION_FN,\n ]:\n raise ValueError(\n \"SparkDFExecutionEngine only supports map_condition_fn and window_condition_fn for column_condition_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: SparkDFExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n filter_column_isnull = kwargs.get(\n \"filter_column_isnull\", getattr(cls, \"filter_column_isnull\", True)\n )\n\n (\n data,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n domain_kwargs=metric_domain_kwargs, domain_type=domain_type\n )\n\n column_name = accessor_domain_kwargs[\"column\"]\n\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n column = data[column_name]\n expected_condition = metric_fn(\n cls,\n column,\n **metric_value_kwargs,\n _table=data,\n _metrics=metrics,\n _compute_domain_kwargs=compute_domain_kwargs,\n _accessor_domain_kwargs=accessor_domain_kwargs,\n )\n if partial_fn_type == MetricPartialFunctionTypes.WINDOW_CONDITION_FN:\n if filter_column_isnull:\n compute_domain_kwargs = (\n execution_engine.add_column_row_condition(\n compute_domain_kwargs, column_name=column_name\n )\n )\n unexpected_condition = ~expected_condition\n else:\n if filter_column_isnull:\n unexpected_condition = column.isNotNull() & ~expected_condition\n else:\n unexpected_condition = ~expected_condition\n return (\n unexpected_condition,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n )\n\n return inner_func\n\n return wrapper\n else:\n raise ValueError(\"Unsupported engine for column_condition_partial\")\n\n\ndef column_pair_function_partial(\n engine: Type[ExecutionEngine], partial_fn_type: str = None, **kwargs\n):\n \"\"\"Provides engine-specific support for authoring a metric_fn with a simplified signature.\n\n A metric function that is decorated as a column_pair_function_partial will be called with the engine-specific\n column_list type and any value_kwargs associated with the Metric for which the provider function is being declared.\n\n Args:\n engine:\n partial_fn_type:\n **kwargs:\n\n Returns:\n An annotated metric_function which will be called with a simplified signature.\n\n \"\"\"\n domain_type = MetricDomainTypes.COLUMN_PAIR\n if issubclass(engine, PandasExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_SERIES\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type != MetricPartialFunctionTypes.MAP_SERIES:\n raise ValueError(\n \"PandasExecutionEngine only supports map_series for column_pair_function_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: PandasExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n (\n df,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n domain_kwargs=metric_domain_kwargs, domain_type=domain_type\n )\n\n # noinspection PyPep8Naming\n column_A_name = accessor_domain_kwargs[\"column_A\"]\n # noinspection PyPep8Naming\n column_B_name = accessor_domain_kwargs[\"column_B\"]\n\n column_list = [column_A_name, column_B_name]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n values = metric_fn(\n cls,\n df[column_A_name],\n df[column_B_name],\n **metric_value_kwargs,\n _metrics=metrics,\n )\n return values, compute_domain_kwargs, accessor_domain_kwargs\n\n return inner_func\n\n return wrapper\n\n elif issubclass(engine, SqlAlchemyExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_FN\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type != MetricPartialFunctionTypes.MAP_FN:\n raise ValueError(\n \"SqlAlchemyExecutionEngine only supports map_fn for column_pair_function_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: SqlAlchemyExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n (\n selectable,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n domain_kwargs=metric_domain_kwargs, domain_type=domain_type\n )\n\n # noinspection PyPep8Naming\n column_A_name = accessor_domain_kwargs[\"column_A\"]\n # noinspection PyPep8Naming\n column_B_name = accessor_domain_kwargs[\"column_B\"]\n\n column_list = [column_A_name, column_B_name]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n column_pair_function = metric_fn(\n cls,\n sa.column(column_A_name),\n sa.column(column_B_name),\n **metric_value_kwargs,\n _metrics=metrics,\n )\n return (\n column_pair_function,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n )\n\n return inner_func\n\n return wrapper\n\n elif issubclass(engine, SparkDFExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_FN\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type != MetricPartialFunctionTypes.MAP_FN:\n raise ValueError(\n \"SparkDFExecutionEngine only supports map_fn for column_pair_function_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: SparkDFExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n (\n data,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n domain_kwargs=metric_domain_kwargs, domain_type=domain_type\n )\n\n # noinspection PyPep8Naming\n column_A_name = accessor_domain_kwargs[\"column_A\"]\n # noinspection PyPep8Naming\n column_B_name = accessor_domain_kwargs[\"column_B\"]\n\n column_list = [column_A_name, column_B_name]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n column_pair_function = metric_fn(\n cls,\n data[column_A_name],\n data[column_B_name],\n **metric_value_kwargs,\n _metrics=metrics,\n )\n return (\n column_pair_function,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n )\n\n return inner_func\n\n return wrapper\n\n else:\n raise ValueError(\"Unsupported engine for column_pair_function_partial\")\n\n\ndef column_pair_condition_partial(\n engine: Type[ExecutionEngine],\n partial_fn_type: Optional[Union[str, MetricPartialFunctionTypes]] = None,\n **kwargs,\n):\n \"\"\"Provides engine-specific support for authoring a metric_fn with a simplified signature. A\n column_pair_condition_partial must provide a map function that evaluates to a boolean value; it will be used to\n provide supplemental metrics, such as the unexpected_value count, unexpected_values, and unexpected_rows.\n\n A metric function that is decorated as a column_pair_condition_partial will be called with the engine-specific\n column_list type and any value_kwargs associated with the Metric for which the provider function is being declared.\n\n Args:\n engine:\n partial_fn_type:\n **kwargs:\n\n Returns:\n An annotated metric_function which will be called with a simplified signature.\n\n \"\"\"\n domain_type = MetricDomainTypes.COLUMN_PAIR\n if issubclass(engine, PandasExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_CONDITION_SERIES\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type not in [MetricPartialFunctionTypes.MAP_CONDITION_SERIES]:\n raise ValueError(\n \"PandasExecutionEngine only supports map_condition_series for column_pair_condition_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: PandasExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n (\n df,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n domain_kwargs=metric_domain_kwargs, domain_type=domain_type\n )\n\n # noinspection PyPep8Naming\n column_A_name = accessor_domain_kwargs[\"column_A\"]\n # noinspection PyPep8Naming\n column_B_name = accessor_domain_kwargs[\"column_B\"]\n\n column_list = [column_A_name, column_B_name]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n meets_expectation_series = metric_fn(\n cls,\n df[column_A_name],\n df[column_B_name],\n **metric_value_kwargs,\n _metrics=metrics,\n )\n return (\n ~meets_expectation_series,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n )\n\n return inner_func\n\n return wrapper\n\n elif issubclass(engine, SqlAlchemyExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_CONDITION_FN\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type not in [\n MetricPartialFunctionTypes.MAP_CONDITION_FN,\n MetricPartialFunctionTypes.WINDOW_CONDITION_FN,\n ]:\n raise ValueError(\n \"SqlAlchemyExecutionEngine only supports map_condition_fn and window_condition_fn for column_pair_condition_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: SqlAlchemyExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n (\n selectable,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n domain_kwargs=metric_domain_kwargs, domain_type=domain_type\n )\n\n # noinspection PyPep8Naming\n column_A_name = accessor_domain_kwargs[\"column_A\"]\n # noinspection PyPep8Naming\n column_B_name = accessor_domain_kwargs[\"column_B\"]\n\n column_list = [column_A_name, column_B_name]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n sqlalchemy_engine: Engine = execution_engine.engine\n\n dialect = execution_engine.dialect_module\n expected_condition = metric_fn(\n cls,\n sa.column(column_A_name),\n sa.column(column_B_name),\n **metric_value_kwargs,\n _dialect=dialect,\n _table=selectable,\n _sqlalchemy_engine=sqlalchemy_engine,\n _metrics=metrics,\n )\n\n unexpected_condition = sa.not_(expected_condition)\n return (\n unexpected_condition,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n )\n\n return inner_func\n\n return wrapper\n\n elif issubclass(engine, SparkDFExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_CONDITION_FN\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type not in [\n MetricPartialFunctionTypes.MAP_CONDITION_FN,\n MetricPartialFunctionTypes.WINDOW_CONDITION_FN,\n ]:\n raise ValueError(\n \"SparkDFExecutionEngine only supports map_condition_fn and window_condition_fn for column_pair_condition_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: SparkDFExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n (\n data,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n domain_kwargs=metric_domain_kwargs, domain_type=domain_type\n )\n\n # noinspection PyPep8Naming\n column_A_name = accessor_domain_kwargs[\"column_A\"]\n # noinspection PyPep8Naming\n column_B_name = accessor_domain_kwargs[\"column_B\"]\n\n column_list = [column_A_name, column_B_name]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n expected_condition = metric_fn(\n cls,\n data[column_A_name],\n data[column_B_name],\n **metric_value_kwargs,\n _metrics=metrics,\n )\n return (\n ~expected_condition,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n )\n\n return inner_func\n\n return wrapper\n\n else:\n raise ValueError(\"Unsupported engine for column_pair_condition_partial\")\n\n\ndef multicolumn_function_partial(\n engine: Type[ExecutionEngine], partial_fn_type: str = None, **kwargs\n):\n \"\"\"Provides engine-specific support for authoring a metric_fn with a simplified signature.\n\n A metric function that is decorated as a multicolumn_function_partial will be called with the engine-specific\n column_list type and any value_kwargs associated with the Metric for which the provider function is being declared.\n\n Args:\n engine:\n partial_fn_type:\n **kwargs:\n\n Returns:\n An annotated metric_function which will be called with a simplified signature.\n\n \"\"\"\n domain_type = MetricDomainTypes.MULTICOLUMN\n if issubclass(engine, PandasExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_SERIES\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type != MetricPartialFunctionTypes.MAP_SERIES:\n raise ValueError(\n \"PandasExecutionEngine only supports map_series for multicolumn_function_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: PandasExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n (\n df,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n domain_kwargs=metric_domain_kwargs, domain_type=domain_type\n )\n\n column_list = accessor_domain_kwargs[\"column_list\"]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n values = metric_fn(\n cls,\n df[column_list],\n **metric_value_kwargs,\n _metrics=metrics,\n )\n return values, compute_domain_kwargs, accessor_domain_kwargs\n\n return inner_func\n\n return wrapper\n\n elif issubclass(engine, SqlAlchemyExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_FN\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type != MetricPartialFunctionTypes.MAP_FN:\n raise ValueError(\n \"SqlAlchemyExecutionEngine only supports map_fn for multicolumn_function_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: SqlAlchemyExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n (\n selectable,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n domain_kwargs=metric_domain_kwargs, domain_type=domain_type\n )\n\n column_list = accessor_domain_kwargs[\"column_list\"]\n\n table_columns = metrics[\"table.columns\"]\n\n for column_name in column_list:\n if column_name not in table_columns:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n sqlalchemy_engine: Engine = execution_engine.engine\n\n column_selector = [\n sa.column(column_name) for column_name in column_list\n ]\n dialect = execution_engine.dialect_module\n multicolumn_function = metric_fn(\n cls,\n column_selector,\n **metric_value_kwargs,\n _column_names=column_list,\n _table_columns=table_columns,\n _dialect=dialect,\n _table=selectable,\n _sqlalchemy_engine=sqlalchemy_engine,\n _metrics=metrics,\n )\n return (\n multicolumn_function,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n )\n\n return inner_func\n\n return wrapper\n\n elif issubclass(engine, SparkDFExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_FN\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type != MetricPartialFunctionTypes.MAP_FN:\n raise ValueError(\n \"SparkDFExecutionEngine only supports map_fn for multicolumn_function_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: SparkDFExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n (\n data,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n domain_kwargs=metric_domain_kwargs, domain_type=domain_type\n )\n\n column_list = accessor_domain_kwargs[\"column_list\"]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n multicolumn_function = metric_fn(\n cls,\n data[column_list],\n **metric_value_kwargs,\n _metrics=metrics,\n )\n return (\n multicolumn_function,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n )\n\n return inner_func\n\n return wrapper\n\n else:\n raise ValueError(\"Unsupported engine for multicolumn_function_partial\")\n\n\ndef multicolumn_condition_partial(\n engine: Type[ExecutionEngine],\n partial_fn_type: Optional[Union[str, MetricPartialFunctionTypes]] = None,\n **kwargs,\n):\n \"\"\"Provides engine-specific support for authoring a metric_fn with a simplified signature. A\n multicolumn_condition_partial must provide a map function that evaluates to a boolean value; it will be used to\n provide supplemental metrics, such as the unexpected_value count, unexpected_values, and unexpected_rows.\n\n A metric function that is decorated as a multicolumn_condition_partial will be called with the engine-specific\n column_list type and any value_kwargs associated with the Metric for which the provider function is being declared.\n\n Args:\n engine:\n partial_fn_type:\n **kwargs:\n\n Returns:\n An annotated metric_function which will be called with a simplified signature.\n\n \"\"\"\n domain_type = MetricDomainTypes.MULTICOLUMN\n if issubclass(engine, PandasExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_CONDITION_SERIES\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type not in [MetricPartialFunctionTypes.MAP_CONDITION_SERIES]:\n raise ValueError(\n \"PandasExecutionEngine only supports map_condition_series for multicolumn_condition_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: PandasExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n (\n df,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n domain_kwargs=metric_domain_kwargs, domain_type=domain_type\n )\n\n column_list = accessor_domain_kwargs[\"column_list\"]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n meets_expectation_series = metric_fn(\n cls,\n df[column_list],\n **metric_value_kwargs,\n _metrics=metrics,\n )\n return (\n ~meets_expectation_series,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n )\n\n return inner_func\n\n return wrapper\n\n elif issubclass(engine, SqlAlchemyExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_CONDITION_FN\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type not in [\n MetricPartialFunctionTypes.MAP_CONDITION_FN,\n MetricPartialFunctionTypes.WINDOW_CONDITION_FN,\n ]:\n raise ValueError(\n \"SqlAlchemyExecutionEngine only supports map_condition_fn and window_condition_fn for multicolumn_condition_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: SqlAlchemyExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n (\n selectable,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n domain_kwargs=metric_domain_kwargs, domain_type=domain_type\n )\n\n column_list = accessor_domain_kwargs[\"column_list\"]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n sqlalchemy_engine: Engine = execution_engine.engine\n\n column_selector = [\n sa.column(column_name) for column_name in column_list\n ]\n dialect = execution_engine.dialect_module\n expected_condition = metric_fn(\n cls,\n column_selector,\n **metric_value_kwargs,\n _dialect=dialect,\n _table=selectable,\n _sqlalchemy_engine=sqlalchemy_engine,\n _metrics=metrics,\n )\n\n unexpected_condition = sa.not_(expected_condition)\n return (\n unexpected_condition,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n )\n\n return inner_func\n\n return wrapper\n\n elif issubclass(engine, SparkDFExecutionEngine):\n if partial_fn_type is None:\n partial_fn_type = MetricPartialFunctionTypes.MAP_CONDITION_FN\n partial_fn_type = MetricPartialFunctionTypes(partial_fn_type)\n if partial_fn_type not in [\n MetricPartialFunctionTypes.MAP_CONDITION_FN,\n MetricPartialFunctionTypes.WINDOW_CONDITION_FN,\n ]:\n raise ValueError(\n \"SparkDFExecutionEngine only supports map_condition_fn and window_condition_fn for multicolumn_condition_partial partial_fn_type\"\n )\n\n def wrapper(metric_fn: Callable):\n @metric_partial(\n engine=engine,\n partial_fn_type=partial_fn_type,\n domain_type=domain_type,\n **kwargs,\n )\n @wraps(metric_fn)\n def inner_func(\n cls,\n execution_engine: SparkDFExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n runtime_configuration: Dict,\n ):\n (\n data,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = execution_engine.get_compute_domain(\n domain_kwargs=metric_domain_kwargs, domain_type=domain_type\n )\n\n column_list = accessor_domain_kwargs[\"column_list\"]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n expected_condition = metric_fn(\n cls,\n data[column_list],\n **metric_value_kwargs,\n _metrics=metrics,\n )\n return (\n ~expected_condition,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n )\n\n return inner_func\n\n return wrapper\n\n else:\n raise ValueError(\"Unsupported engine for multicolumn_condition_partial\")\n\n\ndef _pandas_map_condition_unexpected_count(\n cls,\n execution_engine: PandasExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Returns unexpected count for MapExpectations\"\"\"\n return np.count_nonzero(metrics[\"unexpected_condition\"][0])\n\n\ndef _pandas_column_map_condition_values(\n cls,\n execution_engine: PandasExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Return values from the specified domain that match the map-style metric in the metrics dictionary.\"\"\"\n (\n boolean_mapped_unexpected_values,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = metrics[\"unexpected_condition\"]\n df = execution_engine.get_domain_records(\n domain_kwargs=compute_domain_kwargs,\n )\n\n ###\n # NOTE: 20201111 - JPC - in the map_series / map_condition_series world (pandas), we\n # currently handle filter_column_isnull differently than other map_fn / map_condition\n # cases.\n ###\n filter_column_isnull = kwargs.get(\n \"filter_column_isnull\", getattr(cls, \"filter_column_isnull\", False)\n )\n\n if \"column\" not in accessor_domain_kwargs:\n raise ValueError(\n \"\"\"No \"column\" found in provided metric_domain_kwargs, but it is required for a column map metric\n(_pandas_column_map_condition_values).\n\"\"\"\n )\n\n column_name = accessor_domain_kwargs[\"column\"]\n\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n if filter_column_isnull:\n df = df[df[column_name].notnull()]\n\n domain_values = df[column_name]\n\n domain_values = domain_values[boolean_mapped_unexpected_values == True]\n\n result_format = metric_value_kwargs[\"result_format\"]\n\n if result_format[\"result_format\"] == \"COMPLETE\":\n return list(domain_values)\n else:\n return list(domain_values[: result_format[\"partial_unexpected_count\"]])\n\n\ndef _pandas_column_pair_map_condition_values(\n cls,\n execution_engine: PandasExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Return values from the specified domain that match the map-style metric in the metrics dictionary.\"\"\"\n (\n boolean_mapped_unexpected_values,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = metrics[\"unexpected_condition\"]\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n df = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n if not (\"column_A\" in domain_kwargs and \"column_B\" in domain_kwargs):\n raise ValueError(\n \"\"\"No \"column_A\" and \"column_B\" found in provided metric_domain_kwargs, but it is required for a column pair map metric\n(_pandas_column_pair_map_condition_values).\n\"\"\"\n )\n\n # noinspection PyPep8Naming\n column_A_name = accessor_domain_kwargs[\"column_A\"]\n # noinspection PyPep8Naming\n column_B_name = accessor_domain_kwargs[\"column_B\"]\n\n column_list = [column_A_name, column_B_name]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n domain_values = df[column_list]\n\n domain_values = domain_values[boolean_mapped_unexpected_values == True]\n\n result_format = metric_value_kwargs[\"result_format\"]\n\n unexpected_list = [\n value_pair\n for value_pair in zip(\n domain_values[column_A_name].values, domain_values[column_B_name].values\n )\n ]\n if result_format[\"result_format\"] == \"COMPLETE\":\n return unexpected_list\n else:\n return unexpected_list[: result_format[\"partial_unexpected_count\"]]\n\n\ndef _pandas_column_pair_map_condition_filtered_row_count(\n cls,\n execution_engine: PandasExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Return record counts from the specified domain that match the map-style metric in the metrics dictionary.\"\"\"\n _, compute_domain_kwargs, accessor_domain_kwargs = metrics[\"unexpected_condition\"]\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n df = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n if not (\"column_A\" in domain_kwargs and \"column_B\" in domain_kwargs):\n raise ValueError(\n \"\"\"No \"column_A\" and \"column_B\" found in provided metric_domain_kwargs, but it is required for a column pair map metric\n(_pandas_column_pair_map_condition_filtered_row_count).\n\"\"\"\n )\n\n # noinspection PyPep8Naming\n column_A_name = accessor_domain_kwargs[\"column_A\"]\n # noinspection PyPep8Naming\n column_B_name = accessor_domain_kwargs[\"column_B\"]\n\n column_list = [column_A_name, column_B_name]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n return df.shape[0]\n\n\ndef _pandas_multicolumn_map_condition_values(\n cls,\n execution_engine: PandasExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Return values from the specified domain that match the map-style metric in the metrics dictionary.\"\"\"\n (\n boolean_mapped_unexpected_values,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = metrics[\"unexpected_condition\"]\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n df = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n if \"column_list\" not in accessor_domain_kwargs:\n raise ValueError(\n \"\"\"No \"column_list\" found in provided metric_domain_kwargs, but it is required for a multicolumn map metric\n(_pandas_multicolumn_map_condition_values).\n\"\"\"\n )\n\n column_list = accessor_domain_kwargs[\"column_list\"]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n domain_values = df[column_list]\n\n domain_values = domain_values[boolean_mapped_unexpected_values == True]\n\n result_format = metric_value_kwargs[\"result_format\"]\n\n if result_format[\"result_format\"] == \"COMPLETE\":\n return domain_values.to_dict(\"records\")\n else:\n return domain_values[: result_format[\"partial_unexpected_count\"]].to_dict(\n \"records\"\n )\n\n\ndef _pandas_multicolumn_map_condition_filtered_row_count(\n cls,\n execution_engine: PandasExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Return record counts from the specified domain that match the map-style metric in the metrics dictionary.\"\"\"\n _, compute_domain_kwargs, accessor_domain_kwargs = metrics[\"unexpected_condition\"]\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n df = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n if \"column_list\" not in accessor_domain_kwargs:\n raise ValueError(\n \"\"\"No \"column_list\" found in provided metric_domain_kwargs, but it is required for a multicolumn map metric\n(_pandas_multicolumn_map_condition_filtered_row_count).\n\"\"\"\n )\n\n column_list = accessor_domain_kwargs[\"column_list\"]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n return df.shape[0]\n\n\ndef _pandas_column_map_series_and_domain_values(\n cls,\n execution_engine: PandasExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Return values from the specified domain that match the map-style metric in the metrics dictionary.\"\"\"\n (\n boolean_mapped_unexpected_values,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = metrics[\"unexpected_condition\"]\n (\n map_series,\n compute_domain_kwargs_2,\n accessor_domain_kwargs_2,\n ) = metrics[\"metric_partial_fn\"]\n assert (\n compute_domain_kwargs == compute_domain_kwargs_2\n ), \"map_series and condition must have the same compute domain\"\n assert (\n accessor_domain_kwargs == accessor_domain_kwargs_2\n ), \"map_series and condition must have the same accessor kwargs\"\n df = execution_engine.get_domain_records(\n domain_kwargs=compute_domain_kwargs,\n )\n\n ###\n # NOTE: 20201111 - JPC - in the map_series / map_condition_series world (pandas), we\n # currently handle filter_column_isnull differently than other map_fn / map_condition\n # cases.\n ###\n filter_column_isnull = kwargs.get(\n \"filter_column_isnull\", getattr(cls, \"filter_column_isnull\", False)\n )\n\n if \"column\" not in accessor_domain_kwargs:\n raise ValueError(\n \"\"\"No \"column\" found in provided metric_domain_kwargs, but it is required for a column map metric\n(_pandas_column_map_series_and_domain_values).\n\"\"\"\n )\n\n column_name = accessor_domain_kwargs[\"column\"]\n\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n if filter_column_isnull:\n df = df[df[column_name].notnull()]\n\n domain_values = df[column_name]\n\n domain_values = domain_values[boolean_mapped_unexpected_values == True]\n map_series = map_series[boolean_mapped_unexpected_values == True]\n\n result_format = metric_value_kwargs[\"result_format\"]\n\n if result_format[\"result_format\"] == \"COMPLETE\":\n return (\n list(domain_values),\n list(map_series),\n )\n else:\n return (\n list(domain_values[: result_format[\"partial_unexpected_count\"]]),\n list(map_series[: result_format[\"partial_unexpected_count\"]]),\n )\n\n\ndef _pandas_map_condition_index(\n cls,\n execution_engine: PandasExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n (\n boolean_mapped_unexpected_values,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = metrics.get(\"unexpected_condition\")\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n df = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n ###\n # NOTE: 20201111 - JPC - in the map_series / map_condition_series world (pandas), we\n # currently handle filter_column_isnull differently than other map_fn / map_condition\n # cases.\n ###\n filter_column_isnull = kwargs.get(\n \"filter_column_isnull\", getattr(cls, \"filter_column_isnull\", False)\n )\n\n if \"column\" in accessor_domain_kwargs:\n column_name = accessor_domain_kwargs[\"column\"]\n\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n if filter_column_isnull:\n df = df[df[column_name].notnull()]\n\n elif \"column_list\" in accessor_domain_kwargs:\n column_list = accessor_domain_kwargs[\"column_list\"]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n result_format = metric_value_kwargs[\"result_format\"]\n\n df = df[boolean_mapped_unexpected_values]\n\n if result_format[\"result_format\"] == \"COMPLETE\":\n return list(df.index)\n\n return list(df.index[: result_format[\"partial_unexpected_count\"]])\n\n\ndef _pandas_column_map_condition_value_counts(\n cls,\n execution_engine: PandasExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Returns respective value counts for distinct column values\"\"\"\n (\n boolean_mapped_unexpected_values,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = metrics.get(\"unexpected_condition\")\n df = execution_engine.get_domain_records(\n domain_kwargs=compute_domain_kwargs,\n )\n\n ###\n # NOTE: 20201111 - JPC - in the map_series / map_condition_series world (pandas), we\n # currently handle filter_column_isnull differently than other map_fn / map_condition\n # cases.\n ###\n filter_column_isnull = kwargs.get(\n \"filter_column_isnull\", getattr(cls, \"filter_column_isnull\", False)\n )\n\n column_name = accessor_domain_kwargs[\"column\"]\n\n if \"column\" not in accessor_domain_kwargs:\n raise ValueError(\n \"\"\"No \"column\" found in provided metric_domain_kwargs, but it is required for a column map metric\n(_pandas_column_map_condition_value_counts).\n\"\"\"\n )\n\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n if filter_column_isnull:\n df = df[df[column_name].notnull()]\n\n domain_values = df[column_name]\n\n result_format = metric_value_kwargs[\"result_format\"]\n value_counts = None\n try:\n value_counts = domain_values[boolean_mapped_unexpected_values].value_counts()\n except ValueError:\n try:\n value_counts = (\n domain_values[boolean_mapped_unexpected_values]\n .apply(tuple)\n .value_counts()\n )\n except ValueError:\n pass\n\n if not value_counts:\n raise ge_exceptions.MetricComputationError(\"Unable to compute value counts\")\n\n if result_format[\"result_format\"] == \"COMPLETE\":\n return value_counts\n else:\n return value_counts[result_format[\"partial_unexpected_count\"]]\n\n\ndef _pandas_map_condition_rows(\n cls,\n execution_engine: PandasExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Return values from the specified domain (ignoring the column constraint) that match the map-style metric in the metrics dictionary.\"\"\"\n (\n boolean_mapped_unexpected_values,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = metrics.get(\"unexpected_condition\")\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n df = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n ###\n # NOTE: 20201111 - JPC - in the map_series / map_condition_series world (pandas), we\n # currently handle filter_column_isnull differently than other map_fn / map_condition\n # cases.\n ###\n filter_column_isnull = kwargs.get(\n \"filter_column_isnull\", getattr(cls, \"filter_column_isnull\", False)\n )\n\n if \"column\" in accessor_domain_kwargs:\n column_name = accessor_domain_kwargs[\"column\"]\n\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n if filter_column_isnull:\n df = df[df[column_name].notnull()]\n\n elif \"column_list\" in accessor_domain_kwargs:\n column_list = accessor_domain_kwargs[\"column_list\"]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n result_format = metric_value_kwargs[\"result_format\"]\n\n df = df[boolean_mapped_unexpected_values]\n\n if result_format[\"result_format\"] == \"COMPLETE\":\n return df\n\n return df.iloc[: result_format[\"partial_unexpected_count\"]]\n\n\ndef _sqlalchemy_map_condition_unexpected_count_aggregate_fn(\n cls,\n execution_engine: SqlAlchemyExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Returns unexpected count for MapExpectations\"\"\"\n unexpected_condition, compute_domain_kwargs, accessor_domain_kwargs = metrics.get(\n \"unexpected_condition\"\n )\n\n return (\n sa.func.sum(\n sa.case(\n [(unexpected_condition, 1)],\n else_=0,\n )\n ),\n compute_domain_kwargs,\n accessor_domain_kwargs,\n )\n\n\ndef _sqlalchemy_map_condition_unexpected_count_value(\n cls,\n execution_engine: SqlAlchemyExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Returns unexpected count for MapExpectations. This is a *value* metric, which is useful for\n when the unexpected_condition is a window function.\n \"\"\"\n unexpected_condition, compute_domain_kwargs, accessor_domain_kwargs = metrics.get(\n \"unexpected_condition\"\n )\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n selectable = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n # The integral values are cast to SQL Numeric in order to avoid a bug in AWS Redshift (converted to integer later).\n count_case_statement: List[Label] = sa.case(\n [\n (\n unexpected_condition,\n sa.sql.expression.cast(1, sa.Numeric),\n )\n ],\n else_=sa.sql.expression.cast(0, sa.Numeric),\n ).label(\"condition\")\n\n count_selectable: Select = sa.select([count_case_statement])\n if not MapMetricProvider.is_sqlalchemy_metric_selectable(map_metric_provider=cls):\n count_selectable = count_selectable.select_from(selectable)\n\n try:\n if execution_engine.engine.dialect.name.lower() == \"mssql\":\n temp_table_name: str = generate_temporary_table_name(\n default_table_name_prefix=\"#ge_temp_\"\n )\n\n with execution_engine.engine.begin():\n metadata: sa.MetaData = sa.MetaData(execution_engine.engine)\n temp_table_obj: sa.Table = sa.Table(\n temp_table_name,\n metadata,\n sa.Column(\n \"condition\", sa.Integer, primary_key=False, nullable=False\n ),\n )\n temp_table_obj.create(execution_engine.engine, checkfirst=True)\n\n inner_case_query: Insert = temp_table_obj.insert().from_select(\n [count_case_statement],\n count_selectable,\n )\n execution_engine.engine.execute(inner_case_query)\n\n count_selectable = temp_table_obj\n\n unexpected_count_query: Select = (\n sa.select(\n [\n sa.func.sum(sa.column(\"condition\")).label(\"unexpected_count\"),\n ]\n )\n .select_from(count_selectable)\n .alias(\"UnexpectedCountSubquery\")\n )\n\n unexpected_count: Union[float, int] = execution_engine.engine.execute(\n sa.select(\n [\n unexpected_count_query.c.unexpected_count,\n ]\n )\n ).scalar()\n unexpected_count = int(unexpected_count)\n except OperationalError as oe:\n exception_message: str = f\"An SQL execution Exception occurred: {str(oe)}.\"\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=exception_message\n )\n\n return convert_to_json_serializable(unexpected_count)\n\n\ndef _sqlalchemy_column_map_condition_values(\n cls,\n execution_engine: SqlAlchemyExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"\n Particularly for the purpose of finding unexpected values, returns all the metric values which do not meet an\n expected Expectation condition for ColumnMapExpectation Expectations.\n \"\"\"\n unexpected_condition, compute_domain_kwargs, accessor_domain_kwargs = metrics.get(\n \"unexpected_condition\"\n )\n selectable = execution_engine.get_domain_records(\n domain_kwargs=compute_domain_kwargs,\n )\n\n if \"column\" not in accessor_domain_kwargs:\n raise ValueError(\n \"\"\"No \"column\" found in provided metric_domain_kwargs, but it is required for a column map metric\n(_sqlalchemy_column_map_condition_values).\n\"\"\"\n )\n\n column_name = accessor_domain_kwargs[\"column\"]\n\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n query = sa.select([sa.column(column_name).label(\"unexpected_values\")]).where(\n unexpected_condition\n )\n if not MapMetricProvider.is_sqlalchemy_metric_selectable(map_metric_provider=cls):\n query = query.select_from(selectable)\n\n result_format = metric_value_kwargs[\"result_format\"]\n if result_format[\"result_format\"] != \"COMPLETE\":\n query = query.limit(result_format[\"partial_unexpected_count\"])\n\n return [\n val.unexpected_values\n for val in execution_engine.engine.execute(query).fetchall()\n ]\n\n\ndef _sqlalchemy_column_pair_map_condition_values(\n cls,\n execution_engine: SqlAlchemyExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Return values from the specified domain that match the map-style metric in the metrics dictionary.\"\"\"\n (\n boolean_mapped_unexpected_values,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = metrics[\"unexpected_condition\"]\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n selectable = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n # noinspection PyPep8Naming\n column_A_name = accessor_domain_kwargs[\"column_A\"]\n # noinspection PyPep8Naming\n column_B_name = accessor_domain_kwargs[\"column_B\"]\n\n column_list = [column_A_name, column_B_name]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n query = sa.select(\n sa.column(column_A_name).label(\"unexpected_values_A\"),\n sa.column(column_B_name).label(\"unexpected_values_B\"),\n ).where(boolean_mapped_unexpected_values)\n if not MapMetricProvider.is_sqlalchemy_metric_selectable(map_metric_provider=cls):\n query = query.select_from(selectable)\n\n result_format = metric_value_kwargs[\"result_format\"]\n if result_format[\"result_format\"] != \"COMPLETE\":\n query = query.limit(result_format[\"partial_unexpected_count\"])\n\n unexpected_list = [\n (val.unexpected_values_A, val.unexpected_values_B)\n for val in execution_engine.engine.execute(query).fetchall()\n ]\n return unexpected_list\n\n\ndef _sqlalchemy_column_pair_map_condition_filtered_row_count(\n cls,\n execution_engine: SqlAlchemyExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Return record counts from the specified domain that match the map-style metric in the metrics dictionary.\"\"\"\n _, compute_domain_kwargs, accessor_domain_kwargs = metrics[\"unexpected_condition\"]\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n selectable = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n # noinspection PyPep8Naming\n column_A_name = accessor_domain_kwargs[\"column_A\"]\n # noinspection PyPep8Naming\n column_B_name = accessor_domain_kwargs[\"column_B\"]\n\n column_list = [column_A_name, column_B_name]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n return execution_engine.engine.execute(\n sa.select([sa.func.count()]).select_from(selectable)\n ).scalar()\n\n\ndef _sqlalchemy_multicolumn_map_condition_values(\n cls,\n execution_engine: SqlAlchemyExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Return values from the specified domain that match the map-style metric in the metrics dictionary.\"\"\"\n (\n boolean_mapped_unexpected_values,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = metrics[\"unexpected_condition\"]\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n selectable = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n if \"column_list\" not in accessor_domain_kwargs:\n raise ValueError(\n \"\"\"No \"column_list\" found in provided metric_domain_kwargs, but it is required for a multicolumn map metric\n(_sqlalchemy_multicolumn_map_condition_values).\n\"\"\"\n )\n\n column_list = accessor_domain_kwargs[\"column_list\"]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n column_selector = [sa.column(column_name) for column_name in column_list]\n\n query = sa.select(column_selector).where(boolean_mapped_unexpected_values)\n if not MapMetricProvider.is_sqlalchemy_metric_selectable(map_metric_provider=cls):\n query = query.select_from(selectable)\n\n result_format = metric_value_kwargs[\"result_format\"]\n if result_format[\"result_format\"] != \"COMPLETE\":\n query = query.limit(result_format[\"partial_unexpected_count\"])\n\n return [dict(val) for val in execution_engine.engine.execute(query).fetchall()]\n\n\ndef _sqlalchemy_multicolumn_map_condition_filtered_row_count(\n cls,\n execution_engine: SqlAlchemyExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Return record counts from the specified domain that match the map-style metric in the metrics dictionary.\"\"\"\n _, compute_domain_kwargs, accessor_domain_kwargs = metrics[\"unexpected_condition\"]\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n selectable = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n if \"column_list\" not in accessor_domain_kwargs:\n raise ValueError(\n \"\"\"No \"column_list\" found in provided metric_domain_kwargs, but it is required for a multicolumn map metric\n(_sqlalchemy_multicolumn_map_condition_filtered_row_count).\n\"\"\"\n )\n\n column_list = accessor_domain_kwargs[\"column_list\"]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n return execution_engine.engine.execute(\n sa.select([sa.func.count()]).select_from(selectable)\n ).scalar()\n\n\ndef _sqlalchemy_column_map_condition_value_counts(\n cls,\n execution_engine: SqlAlchemyExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"\n Returns value counts for all the metric values which do not meet an expected Expectation condition for instances\n of ColumnMapExpectation.\n \"\"\"\n unexpected_condition, compute_domain_kwargs, accessor_domain_kwargs = metrics.get(\n \"unexpected_condition\"\n )\n selectable = execution_engine.get_domain_records(\n domain_kwargs=compute_domain_kwargs,\n )\n\n if \"column\" not in accessor_domain_kwargs:\n raise ValueError(\n \"\"\"No \"column\" found in provided metric_domain_kwargs, but it is required for a column map metric\n(_sqlalchemy_column_map_condition_value_counts).\n\"\"\"\n )\n\n column_name = accessor_domain_kwargs[\"column\"]\n\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n column: sa.Column = sa.column(column_name)\n\n query = (\n sa.select([column, sa.func.count(column)])\n .where(unexpected_condition)\n .group_by(column)\n )\n if not MapMetricProvider.is_sqlalchemy_metric_selectable(map_metric_provider=cls):\n query = query.select_from(selectable)\n\n return execution_engine.engine.execute(query).fetchall()\n\n\ndef _sqlalchemy_map_condition_rows(\n cls,\n execution_engine: SqlAlchemyExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"\n Returns all rows of the metric values which do not meet an expected Expectation condition for instances\n of ColumnMapExpectation.\n \"\"\"\n unexpected_condition, compute_domain_kwargs, accessor_domain_kwargs = metrics.get(\n \"unexpected_condition\"\n )\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n selectable = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n table_columns = metrics.get(\"table.columns\")\n column_selector = [sa.column(column_name) for column_name in table_columns]\n query = sa.select(column_selector).where(unexpected_condition)\n if not MapMetricProvider.is_sqlalchemy_metric_selectable(map_metric_provider=cls):\n query = query.select_from(selectable)\n\n result_format = metric_value_kwargs[\"result_format\"]\n if result_format[\"result_format\"] != \"COMPLETE\":\n query = query.limit(result_format[\"partial_unexpected_count\"])\n try:\n return execution_engine.engine.execute(query).fetchall()\n except OperationalError as oe:\n exception_message: str = f\"An SQL execution Exception occurred: {str(oe)}.\"\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=exception_message\n )\n\n\ndef _spark_map_condition_unexpected_count_aggregate_fn(\n cls,\n execution_engine: SparkDFExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n unexpected_condition, compute_domain_kwargs, accessor_domain_kwargs = metrics.get(\n \"unexpected_condition\"\n )\n return (\n F.sum(F.when(unexpected_condition, 1).otherwise(0)),\n compute_domain_kwargs,\n accessor_domain_kwargs,\n )\n\n\ndef _spark_map_condition_unexpected_count_value(\n cls,\n execution_engine: SparkDFExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n # fn_domain_kwargs maybe updated to reflect null filtering\n unexpected_condition, compute_domain_kwargs, accessor_domain_kwargs = metrics.get(\n \"unexpected_condition\"\n )\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n df = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n # withColumn is required to transform window functions returned by some metrics to boolean mask\n data = df.withColumn(\"__unexpected\", unexpected_condition)\n filtered = data.filter(F.col(\"__unexpected\") == True).drop(F.col(\"__unexpected\"))\n\n return filtered.count()\n\n\ndef _spark_column_map_condition_values(\n cls,\n execution_engine: SparkDFExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Return values from the specified domain that match the map-style metric in the metrics dictionary.\"\"\"\n unexpected_condition, compute_domain_kwargs, accessor_domain_kwargs = metrics.get(\n \"unexpected_condition\"\n )\n df = execution_engine.get_domain_records(\n domain_kwargs=compute_domain_kwargs,\n )\n\n if \"column\" not in accessor_domain_kwargs:\n raise ValueError(\n \"\"\"No \"column\" found in provided metric_domain_kwargs, but it is required for a column map metric\n(_spark_column_map_condition_values).\n\"\"\"\n )\n\n column_name = accessor_domain_kwargs[\"column\"]\n\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n # withColumn is required to transform window functions returned by some metrics to boolean mask\n data = df.withColumn(\"__unexpected\", unexpected_condition)\n filtered = data.filter(F.col(\"__unexpected\") == True).drop(F.col(\"__unexpected\"))\n\n result_format = metric_value_kwargs[\"result_format\"]\n if result_format[\"result_format\"] == \"COMPLETE\":\n rows = filtered.select(F.col(column_name)).collect()\n else:\n rows = (\n filtered.select(F.col(column_name))\n .limit(result_format[\"partial_unexpected_count\"])\n .collect()\n )\n return [row[column_name] for row in rows]\n\n\ndef _spark_column_map_condition_value_counts(\n cls,\n execution_engine: SparkDFExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n unexpected_condition, compute_domain_kwargs, accessor_domain_kwargs = metrics.get(\n \"unexpected_condition\"\n )\n df = execution_engine.get_domain_records(\n domain_kwargs=compute_domain_kwargs,\n )\n\n if \"column\" not in accessor_domain_kwargs:\n raise ValueError(\n \"\"\"No \"column\" found in provided metric_domain_kwargs, but it is required for a column map metric\n(_spark_column_map_condition_value_counts).\n\"\"\"\n )\n\n column_name = accessor_domain_kwargs[\"column\"]\n\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n # withColumn is required to transform window functions returned by some metrics to boolean mask\n data = df.withColumn(\"__unexpected\", unexpected_condition)\n filtered = data.filter(F.col(\"__unexpected\") == True).drop(F.col(\"__unexpected\"))\n\n result_format = metric_value_kwargs[\"result_format\"]\n\n value_counts = filtered.groupBy(F.col(column_name)).count()\n if result_format[\"result_format\"] == \"COMPLETE\":\n rows = value_counts.collect()\n else:\n rows = value_counts.collect()[: result_format[\"partial_unexpected_count\"]]\n return rows\n\n\ndef _spark_map_condition_rows(\n cls,\n execution_engine: SparkDFExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n unexpected_condition, compute_domain_kwargs, accessor_domain_kwargs = metrics.get(\n \"unexpected_condition\"\n )\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n df = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n # withColumn is required to transform window functions returned by some metrics to boolean mask\n data = df.withColumn(\"__unexpected\", unexpected_condition)\n filtered = data.filter(F.col(\"__unexpected\") == True).drop(F.col(\"__unexpected\"))\n\n result_format = metric_value_kwargs[\"result_format\"]\n\n if result_format[\"result_format\"] == \"COMPLETE\":\n return filtered.collect()\n else:\n return filtered.limit(result_format[\"partial_unexpected_count\"]).collect()\n\n\ndef _spark_column_pair_map_condition_values(\n cls,\n execution_engine: SparkDFExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Return values from the specified domain that match the map-style metric in the metrics dictionary.\"\"\"\n (\n unexpected_condition,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = metrics[\"unexpected_condition\"]\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n df = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n # noinspection PyPep8Naming\n column_A_name = accessor_domain_kwargs[\"column_A\"]\n # noinspection PyPep8Naming\n column_B_name = accessor_domain_kwargs[\"column_B\"]\n\n column_list = [column_A_name, column_B_name]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n # withColumn is required to transform window functions returned by some metrics to boolean mask\n data = df.withColumn(\"__unexpected\", unexpected_condition)\n filtered = data.filter(F.col(\"__unexpected\") == True).drop(F.col(\"__unexpected\"))\n\n result_format = metric_value_kwargs[\"result_format\"]\n if result_format[\"result_format\"] == \"COMPLETE\":\n rows = filtered.select([F.col(column_A_name), F.col(column_B_name)]).collect()\n else:\n rows = (\n filtered.select([F.col(column_A_name), F.col(column_B_name)])\n .limit(result_format[\"partial_unexpected_count\"])\n .collect()\n )\n\n unexpected_list = [(row[column_A_name], row[column_B_name]) for row in rows]\n return unexpected_list\n\n\ndef _spark_column_pair_map_condition_filtered_row_count(\n cls,\n execution_engine: SparkDFExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Return record counts from the specified domain that match the map-style metric in the metrics dictionary.\"\"\"\n _, compute_domain_kwargs, accessor_domain_kwargs = metrics[\"unexpected_condition\"]\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n df = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n # noinspection PyPep8Naming\n column_A_name = accessor_domain_kwargs[\"column_A\"]\n # noinspection PyPep8Naming\n column_B_name = accessor_domain_kwargs[\"column_B\"]\n\n column_list = [column_A_name, column_B_name]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n return df.count()\n\n\ndef _spark_multicolumn_map_condition_values(\n cls,\n execution_engine: SqlAlchemyExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Return values from the specified domain that match the map-style metric in the metrics dictionary.\"\"\"\n (\n unexpected_condition,\n compute_domain_kwargs,\n accessor_domain_kwargs,\n ) = metrics[\"unexpected_condition\"]\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n df = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n if \"column_list\" not in accessor_domain_kwargs:\n raise ValueError(\n \"\"\"No \"column_list\" found in provided metric_domain_kwargs, but it is required for a multicolumn map metric\n(_spark_multicolumn_map_condition_values).\n\"\"\"\n )\n\n column_list = accessor_domain_kwargs[\"column_list\"]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n # withColumn is required to transform window functions returned by some metrics to boolean mask\n data = df.withColumn(\"__unexpected\", unexpected_condition)\n filtered = data.filter(F.col(\"__unexpected\") == True).drop(F.col(\"__unexpected\"))\n\n column_selector = [F.col(column_name) for column_name in column_list]\n\n domain_values = filtered.select(column_selector)\n\n result_format = metric_value_kwargs[\"result_format\"]\n if result_format[\"result_format\"] == \"COMPLETE\":\n domain_values = (\n domain_values.select(column_selector).toPandas().to_dict(\"records\")\n )\n else:\n domain_values = (\n domain_values.select(column_selector)\n .limit(result_format[\"partial_unexpected_count\"])\n .toPandas()\n .to_dict(\"records\")\n )\n\n return domain_values\n\n\ndef _spark_multicolumn_map_condition_filtered_row_count(\n cls,\n execution_engine: SparkDFExecutionEngine,\n metric_domain_kwargs: Dict,\n metric_value_kwargs: Dict,\n metrics: Dict[str, Any],\n **kwargs,\n):\n \"\"\"Return record counts from the specified domain that match the map-style metric in the metrics dictionary.\"\"\"\n _, compute_domain_kwargs, accessor_domain_kwargs = metrics[\"unexpected_condition\"]\n \"\"\"\n In order to invoke the \"ignore_row_if\" filtering logic, \"execution_engine.get_domain_records()\" must be supplied\n with all of the available \"domain_kwargs\" keys.\n \"\"\"\n domain_kwargs = dict(**compute_domain_kwargs, **accessor_domain_kwargs)\n df = execution_engine.get_domain_records(\n domain_kwargs=domain_kwargs,\n )\n\n if \"column_list\" not in accessor_domain_kwargs:\n raise ValueError(\n \"\"\"No \"column_list\" found in provided metric_domain_kwargs, but it is required for a multicolumn map metric\n(_spark_multicolumn_map_condition_filtered_row_count).\n\"\"\"\n )\n\n column_list = accessor_domain_kwargs[\"column_list\"]\n\n for column_name in column_list:\n if column_name not in metrics[\"table.columns\"]:\n raise ge_exceptions.InvalidMetricAccessorDomainKwargsKeyError(\n message=f'Error: The column \"{column_name}\" in BatchData does not exist.'\n )\n\n return df.count()\n\n\nclass MapMetricProvider(MetricProvider):\n condition_domain_keys = (\n \"batch_id\",\n \"table\",\n \"row_condition\",\n \"condition_parser\",\n )\n function_domain_keys = (\n \"batch_id\",\n \"table\",\n \"row_condition\",\n \"condition_parser\",\n )\n condition_value_keys = tuple()\n function_value_keys = tuple()\n filter_column_isnull = True\n\n SQLALCHEMY_SELECTABLE_METRICS = {\n \"compound_columns.count\",\n \"compound_columns.unique\",\n }\n\n @classmethod\n def _register_metric_functions(cls):\n if not hasattr(cls, \"function_metric_name\") and not hasattr(\n cls, \"condition_metric_name\"\n ):\n return\n\n for attr, candidate_metric_fn in cls.__dict__.items():\n if not hasattr(candidate_metric_fn, \"metric_engine\"):\n # This is not a metric\n continue\n metric_fn_type = getattr(candidate_metric_fn, \"metric_fn_type\")\n engine = candidate_metric_fn.metric_engine\n if not issubclass(engine, ExecutionEngine):\n raise ValueError(\n \"metric functions must be defined with an Execution Engine\"\n )\n\n if metric_fn_type in [\n MetricPartialFunctionTypes.MAP_CONDITION_SERIES,\n MetricPartialFunctionTypes.MAP_CONDITION_FN,\n MetricPartialFunctionTypes.WINDOW_CONDITION_FN,\n ]:\n if not hasattr(cls, \"condition_metric_name\"):\n raise ValueError(\n \"A MapMetricProvider must have a metric_condition_name to have a decorated column_condition_partial method.\"\n )\n\n condition_provider = candidate_metric_fn\n # noinspection PyUnresolvedReferences\n metric_name = cls.condition_metric_name\n metric_domain_keys = cls.condition_domain_keys\n metric_value_keys = cls.condition_value_keys\n metric_definition_kwargs = getattr(\n condition_provider, \"metric_definition_kwargs\", {}\n )\n domain_type = getattr(\n condition_provider,\n \"domain_type\",\n metric_definition_kwargs.get(\n \"domain_type\", MetricDomainTypes.TABLE\n ),\n )\n if issubclass(engine, PandasExecutionEngine):\n register_metric(\n metric_name=metric_name + \".condition\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=metric_value_keys,\n execution_engine=engine,\n metric_class=cls,\n metric_provider=condition_provider,\n metric_fn_type=metric_fn_type,\n )\n register_metric(\n metric_name=metric_name + \".unexpected_count\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=metric_value_keys,\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_pandas_map_condition_unexpected_count,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n register_metric(\n metric_name=metric_name + \".unexpected_index_list\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_pandas_map_condition_index,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n register_metric(\n metric_name=metric_name + \".unexpected_rows\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_pandas_map_condition_rows,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n if domain_type == MetricDomainTypes.COLUMN:\n register_metric(\n metric_name=metric_name + \".unexpected_values\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_pandas_column_map_condition_values,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n register_metric(\n metric_name=metric_name + \".unexpected_value_counts\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_pandas_column_map_condition_value_counts,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n elif domain_type == MetricDomainTypes.COLUMN_PAIR:\n register_metric(\n metric_name=metric_name + \".unexpected_values\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_pandas_column_pair_map_condition_values,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n register_metric(\n metric_name=metric_name + \".filtered_row_count\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_pandas_column_pair_map_condition_filtered_row_count,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n elif domain_type == MetricDomainTypes.MULTICOLUMN:\n register_metric(\n metric_name=metric_name + \".unexpected_values\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_pandas_multicolumn_map_condition_values,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n register_metric(\n metric_name=metric_name + \".filtered_row_count\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_pandas_multicolumn_map_condition_filtered_row_count,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n elif issubclass(engine, SqlAlchemyExecutionEngine):\n register_metric(\n metric_name=metric_name + \".condition\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=metric_value_keys,\n execution_engine=engine,\n metric_class=cls,\n metric_provider=condition_provider,\n metric_fn_type=metric_fn_type,\n )\n register_metric(\n metric_name=metric_name + \".unexpected_rows\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_sqlalchemy_map_condition_rows,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n if metric_fn_type == MetricPartialFunctionTypes.MAP_CONDITION_FN:\n if domain_type == MetricDomainTypes.COLUMN:\n register_metric(\n metric_name=metric_name\n + \".unexpected_count.aggregate_fn\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=metric_value_keys,\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_sqlalchemy_map_condition_unexpected_count_aggregate_fn,\n metric_fn_type=MetricPartialFunctionTypes.AGGREGATE_FN,\n )\n register_metric(\n metric_name=metric_name + \".unexpected_count\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=metric_value_keys,\n execution_engine=engine,\n metric_class=cls,\n metric_provider=None,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n else:\n register_metric(\n metric_name=metric_name + \".unexpected_count\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=metric_value_keys,\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_sqlalchemy_map_condition_unexpected_count_value,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n elif (\n metric_fn_type == MetricPartialFunctionTypes.WINDOW_CONDITION_FN\n ):\n register_metric(\n metric_name=metric_name + \".unexpected_count\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=metric_value_keys,\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_sqlalchemy_map_condition_unexpected_count_value,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n if domain_type == MetricDomainTypes.COLUMN:\n register_metric(\n metric_name=metric_name + \".unexpected_values\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_sqlalchemy_column_map_condition_values,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n register_metric(\n metric_name=metric_name + \".unexpected_value_counts\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_sqlalchemy_column_map_condition_value_counts,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n elif domain_type == MetricDomainTypes.COLUMN_PAIR:\n register_metric(\n metric_name=metric_name + \".unexpected_values\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_sqlalchemy_column_pair_map_condition_values,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n register_metric(\n metric_name=metric_name + \".filtered_row_count\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_sqlalchemy_column_pair_map_condition_filtered_row_count,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n elif domain_type == MetricDomainTypes.MULTICOLUMN:\n register_metric(\n metric_name=metric_name + \".unexpected_values\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_sqlalchemy_multicolumn_map_condition_values,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n register_metric(\n metric_name=metric_name + \".filtered_row_count\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_sqlalchemy_multicolumn_map_condition_filtered_row_count,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n elif issubclass(engine, SparkDFExecutionEngine):\n register_metric(\n metric_name=metric_name + \".condition\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=metric_value_keys,\n execution_engine=engine,\n metric_class=cls,\n metric_provider=condition_provider,\n metric_fn_type=metric_fn_type,\n )\n register_metric(\n metric_name=metric_name + \".unexpected_rows\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_spark_map_condition_rows,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n if metric_fn_type == MetricPartialFunctionTypes.MAP_CONDITION_FN:\n if domain_type == MetricDomainTypes.COLUMN:\n register_metric(\n metric_name=metric_name\n + \".unexpected_count.aggregate_fn\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=metric_value_keys,\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_spark_map_condition_unexpected_count_aggregate_fn,\n metric_fn_type=MetricPartialFunctionTypes.AGGREGATE_FN,\n )\n register_metric(\n metric_name=metric_name + \".unexpected_count\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=metric_value_keys,\n execution_engine=engine,\n metric_class=cls,\n metric_provider=None,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n else:\n register_metric(\n metric_name=metric_name + \".unexpected_count\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=metric_value_keys,\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_spark_map_condition_unexpected_count_value,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n elif (\n metric_fn_type == MetricPartialFunctionTypes.WINDOW_CONDITION_FN\n ):\n register_metric(\n metric_name=metric_name + \".unexpected_count\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=metric_value_keys,\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_spark_map_condition_unexpected_count_value,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n if domain_type == MetricDomainTypes.COLUMN:\n register_metric(\n metric_name=metric_name + \".unexpected_values\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_spark_column_map_condition_values,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n register_metric(\n metric_name=metric_name + \".unexpected_value_counts\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_spark_column_map_condition_value_counts,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n elif domain_type == MetricDomainTypes.COLUMN_PAIR:\n register_metric(\n metric_name=metric_name + \".unexpected_values\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_spark_column_pair_map_condition_values,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n register_metric(\n metric_name=metric_name + \".filtered_row_count\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_spark_column_pair_map_condition_filtered_row_count,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n elif domain_type == MetricDomainTypes.MULTICOLUMN:\n register_metric(\n metric_name=metric_name + \".unexpected_values\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_spark_multicolumn_map_condition_values,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n register_metric(\n metric_name=metric_name + \".filtered_row_count\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=(*metric_value_keys, \"result_format\"),\n execution_engine=engine,\n metric_class=cls,\n metric_provider=_spark_multicolumn_map_condition_filtered_row_count,\n metric_fn_type=MetricFunctionTypes.VALUE,\n )\n elif metric_fn_type in [\n MetricPartialFunctionTypes.MAP_SERIES,\n MetricPartialFunctionTypes.MAP_FN,\n MetricPartialFunctionTypes.WINDOW_FN,\n ]:\n if not hasattr(cls, \"function_metric_name\"):\n raise ValueError(\n \"A MapMetricProvider must have a function_metric_name to have a decorated column_function_partial method.\"\n )\n map_function_provider = candidate_metric_fn\n # noinspection PyUnresolvedReferences\n metric_name = cls.function_metric_name\n metric_domain_keys = cls.function_domain_keys\n metric_value_keys = cls.function_value_keys\n register_metric(\n metric_name=metric_name + \".map\",\n metric_domain_keys=metric_domain_keys,\n metric_value_keys=metric_value_keys,\n execution_engine=engine,\n metric_class=cls,\n metric_provider=map_function_provider,\n metric_fn_type=metric_fn_type,\n )\n\n @classmethod\n def _get_evaluation_dependencies(\n cls,\n metric: MetricConfiguration,\n configuration: Optional[ExpectationConfiguration] = None,\n execution_engine: Optional[ExecutionEngine] = None,\n runtime_configuration: Optional[dict] = None,\n ):\n metric_name = metric.metric_name\n base_metric_value_kwargs = {\n k: v for k, v in metric.metric_value_kwargs.items() if k != \"result_format\"\n }\n dependencies = {}\n\n metric_suffix = \".unexpected_count\"\n if metric_name.endswith(metric_suffix):\n try:\n _ = get_metric_provider(metric_name + \".aggregate_fn\", execution_engine)\n has_aggregate_fn = True\n except ge_exceptions.MetricProviderError:\n has_aggregate_fn = False\n if has_aggregate_fn:\n dependencies[\"metric_partial_fn\"] = MetricConfiguration(\n metric_name + \".aggregate_fn\",\n metric.metric_domain_kwargs,\n base_metric_value_kwargs,\n )\n else:\n dependencies[\"unexpected_condition\"] = MetricConfiguration(\n metric_name[: -len(metric_suffix)] + \".condition\",\n metric.metric_domain_kwargs,\n base_metric_value_kwargs,\n )\n\n # MapMetric uses the condition to build unexpected_count.aggregate_fn as well\n metric_suffix = \".unexpected_count.aggregate_fn\"\n if metric_name.endswith(metric_suffix):\n dependencies[\"unexpected_condition\"] = MetricConfiguration(\n metric_name[: -len(metric_suffix)] + \".condition\",\n metric.metric_domain_kwargs,\n base_metric_value_kwargs,\n )\n\n for metric_suffix in [\n \".unexpected_values\",\n \".unexpected_value_counts\",\n \".unexpected_index_list\",\n \".unexpected_rows\",\n \".filtered_row_count\",\n ]:\n if metric_name.endswith(metric_suffix):\n dependencies[\"unexpected_condition\"] = MetricConfiguration(\n metric_name[: -len(metric_suffix)] + \".condition\",\n metric.metric_domain_kwargs,\n base_metric_value_kwargs,\n )\n\n try:\n _ = get_metric_provider(metric_name + \".map\", execution_engine)\n dependencies[\"metric_map_fn\"] = MetricConfiguration(\n metric_name + \".map\",\n metric.metric_domain_kwargs,\n metric.metric_value_kwargs,\n )\n except ge_exceptions.MetricProviderError:\n pass\n\n return dependencies\n\n @staticmethod\n def is_sqlalchemy_metric_selectable(\n map_metric_provider: MetaMetricProvider,\n ) -> bool:\n \"\"\"\n :param map_metric_provider: object of type \"MapMetricProvider\", whose SQLAlchemy implementation is inspected\n :return: boolean indicating whether or not the returned value of a method implementing the metric resolves all\n columns -- hence the caller must not use \"select_from\" clause as part of its own SQLAlchemy query; otherwise an\n unwanted selectable (e.g., table) will be added to \"FROM\", leading to duplicated and/or erroneous results.\n \"\"\"\n # noinspection PyUnresolvedReferences\n return (\n hasattr(map_metric_provider, \"condition_metric_name\")\n and map_metric_provider.condition_metric_name\n in MapMetricProvider.SQLALCHEMY_SELECTABLE_METRICS\n ) or (\n hasattr(map_metric_provider, \"function_metric_name\")\n and map_metric_provider.function_metric_name\n in MapMetricProvider.SQLALCHEMY_SELECTABLE_METRICS\n )\n\n\nclass ColumnMapMetricProvider(MapMetricProvider):\n condition_domain_keys = (\n \"batch_id\",\n \"table\",\n \"column\",\n \"row_condition\",\n \"condition_parser\",\n )\n function_domain_keys = (\n \"batch_id\",\n \"table\",\n \"column\",\n \"row_condition\",\n \"condition_parser\",\n )\n condition_value_keys = tuple()\n function_value_keys = tuple()\n\n @classmethod\n def _get_evaluation_dependencies(\n cls,\n metric: MetricConfiguration,\n configuration: Optional[ExpectationConfiguration] = None,\n execution_engine: Optional[ExecutionEngine] = None,\n runtime_configuration: Optional[dict] = None,\n ):\n dependencies: dict = super()._get_evaluation_dependencies(\n metric=metric,\n configuration=configuration,\n execution_engine=execution_engine,\n runtime_configuration=runtime_configuration,\n )\n table_domain_kwargs: dict = {\n k: v for k, v in metric.metric_domain_kwargs.items() if k != \"column\"\n }\n dependencies[\"table.columns\"] = MetricConfiguration(\n metric_name=\"table.columns\",\n metric_domain_kwargs=table_domain_kwargs,\n metric_value_kwargs=None,\n metric_dependencies=None,\n )\n return dependencies\n\n\nclass ColumnPairMapMetricProvider(MapMetricProvider):\n condition_domain_keys = (\n \"batch_id\",\n \"table\",\n \"column_A\",\n \"column_B\",\n \"row_condition\",\n \"condition_parser\",\n \"ignore_row_if\",\n )\n function_domain_keys = (\n \"batch_id\",\n \"table\",\n \"column_A\",\n \"column_B\",\n \"row_condition\",\n \"condition_parser\",\n \"ignore_row_if\",\n )\n condition_value_keys = tuple()\n function_value_keys = tuple()\n\n @classmethod\n def _get_evaluation_dependencies(\n cls,\n metric: MetricConfiguration,\n configuration: Optional[ExpectationConfiguration] = None,\n execution_engine: Optional[ExecutionEngine] = None,\n runtime_configuration: Optional[dict] = None,\n ):\n dependencies: dict = super()._get_evaluation_dependencies(\n metric=metric,\n configuration=configuration,\n execution_engine=execution_engine,\n runtime_configuration=runtime_configuration,\n )\n table_domain_kwargs: dict = {\n k: v\n for k, v in metric.metric_domain_kwargs.items()\n if k not in [\"column_A\", \"column_B\", \"ignore_row_if\"]\n }\n dependencies[\"table.columns\"] = MetricConfiguration(\n metric_name=\"table.columns\",\n metric_domain_kwargs=table_domain_kwargs,\n metric_value_kwargs=None,\n metric_dependencies=None,\n )\n return dependencies\n\n\nclass MulticolumnMapMetricProvider(MapMetricProvider):\n condition_domain_keys = (\n \"batch_id\",\n \"table\",\n \"column_list\",\n \"row_condition\",\n \"condition_parser\",\n \"ignore_row_if\",\n )\n function_domain_keys = (\n \"batch_id\",\n \"table\",\n \"column_list\",\n \"row_condition\",\n \"condition_parser\",\n \"ignore_row_if\",\n )\n condition_value_keys = tuple()\n function_value_keys = tuple()\n\n @classmethod\n def _get_evaluation_dependencies(\n cls,\n metric: MetricConfiguration,\n configuration: Optional[ExpectationConfiguration] = None,\n execution_engine: Optional[ExecutionEngine] = None,\n runtime_configuration: Optional[dict] = None,\n ):\n dependencies: dict = super()._get_evaluation_dependencies(\n metric=metric,\n configuration=configuration,\n execution_engine=execution_engine,\n runtime_configuration=runtime_configuration,\n )\n table_domain_kwargs: dict = {\n k: v\n for k, v in metric.metric_domain_kwargs.items()\n if k not in [\"column_list\", \"ignore_row_if\"]\n }\n dependencies[\"table.columns\"] = MetricConfiguration(\n metric_name=\"table.columns\",\n metric_domain_kwargs=table_domain_kwargs,\n metric_value_kwargs=None,\n metric_dependencies=None,\n )\n return dependencies\n" ]
[ [ "numpy.count_nonzero" ] ]
DarseZ/DL_hw5
[ "6229ef6493e92b93e67e71058f90bc4a6b537796" ]
[ "q_learning/utils/schedule.py" ]
[ "import numpy as np\nfrom utils.test_env import EnvTest\n\n\nclass LinearSchedule(object):\n def __init__(self, eps_begin, eps_end, nsteps):\n \"\"\"\n Args:\n eps_begin: initial exploration\n eps_end: end exploration\n nsteps: number of steps between the two values of eps\n \"\"\"\n self.epsilon = eps_begin\n self.eps_begin = eps_begin\n self.eps_end = eps_end\n self.nsteps = nsteps\n\n\n def update(self, t):\n \"\"\"\n Updates epsilon\n\n Args:\n t: int\n frame number\n \"\"\"\n if t > self.nsteps:\n self.epsilon = self.eps_end\n else:\n alpha = (1.0 * t) / self.nsteps\n self.epsilon = (alpha * self.eps_end) \\\n + ((1-alpha) * self.eps_begin)\n\n\nclass LinearExploration(LinearSchedule):\n def __init__(self, env, eps_begin, eps_end, nsteps):\n \"\"\"\n Args:\n env: gym environment\n eps_begin: float\n initial exploration rate\n eps_end: float\n final exploration rate\n nsteps: int\n number of steps taken to linearly decay eps_begin to eps_end\n \"\"\"\n self.env = env\n super(LinearExploration, self).__init__(eps_begin, eps_end, nsteps)\n\n\n def get_action(self, best_action):\n \"\"\"\n Returns a random action with prob epsilon, otherwise returns the best_action\n\n Args:\n best_action: int\n best action according some policy\n Returns:\n an action\n \"\"\"\n ##############################################################\n if np.random.uniform(0, 1) < self.epsilon:\n return self.env.action_space.sample()\n else:\n return best_action\n" ]
[ [ "numpy.random.uniform" ] ]
dennislwm/dtale-desktop
[ "1a034d505f6b45c1ece4c18b83af6ae367d16824" ]
[ "dtale_desktop/default_sources/dft_csv/get_data.py" ]
[ "import pandas as pd\n\n\ndef main(path: str) -> pd.DataFrame:\n return pd.read_csv(path)\n" ]
[ [ "pandas.read_csv" ] ]
rjplevin/BEST-AIR
[ "40f4bb74f4a8a98b66a452f58596f4c425c9a51b" ]
[ "best_air/bin/extract_EPA_monitor_data_88101_2000_2017.py" ]
[ "import csv\nimport pandas as pd\n\nCALIFORNIA = 6 # State Code to keep\n\ndata_dir = '/Volumes/T7/Box Sync/BEST-AIR/Data/AQ Monitoring/EPA Criteria Pollutants/PM Daily Data/'\n\npathname = data_dir + '2017/daily_88101_2017.csv'\n\n# Create 'Monitor ID' = State Code + County Code + Site Num + Parameter Code\n# Drop rows with 'Sample Duration' of '24-HR BLK AVG' (redundant)\n# Calculate quarterly average of daily means.\n# Calculate annual average of four quarterly averages.\n# Parameter code is always 88101; name is always 'PM2.5 - Local Conditions'\ncols_to_keep = [\n 'State Code',\n 'County Code',\n 'Site Num',\n 'Parameter Code',\n 'POC',\n 'Latitude',\n 'Longitude',\n 'Sample Duration',\n 'Date Local',\n 'Event Type', # ['None', 'Included', 'Excluded']\n 'Method Code', # decide which to keep\n # 'Method Name',\n 'Observation Count',\n 'Observation Percent',\n 'Arithmetic Mean',\n\n # 'Datum', # all are in ['WGS84', 'NAD83']\n # 'Units of Measure', # all are 'Micrograms/cubic meter (LC)'\n]\n\ndef verify_excludes_have_matching_includes(df):\n df = df.copy()\n df.columns = [name.replace(' ', '') for name in df.columns]\n excl = df.query(\"EventType == 'Excluded'\")\n\n count = 0\n for idx, row in excl.iterrows():\n id = row.monitor_id\n date = row.DateLocal\n poc = row.POC\n found = df.query(\"EventType == 'Included' and SampleDuration == '1 HOUR' and monitor_id == @id and POC == @poc and DateLocal == @date\")\n count += len(found)\n\n if len(found) > 1:\n print(\"Multiple matches: \\n\", found)\n\n if count != len(excl):\n raise Exception(f\"Found {count} Included matches for {len(excl)} Excluded\")\n\ndef extract(input_path, output_path):\n print(f\"Reading '{input_path}'\")\n df = pd.read_csv(input_path, index_col=None, usecols=cols_to_keep)\n\n mask = (df['State Code'] == CALIFORNIA) & (df['Sample Duration'] != '24-HR BLK AVG')\n df = df[mask].copy()\n\n # Create fixed width monitor ID from these four numeric columns\n df['monitor_id'] = (df['State Code'].astype(str).str.zfill(2) + '-' +\n df['County Code'].astype(str).str.zfill(3) + '-' +\n df['Site Num'].astype(str).str.zfill(4) + '-' +\n df['Parameter Code'].astype(str).str.zfill(5))\n\n cols_to_drop = ['Parameter Code', 'State Code']\n df.drop(cols_to_drop, axis='columns', inplace=True)\n\n verify_excludes_have_matching_includes(df)\n\n rows_to_keep = (df['Event Type'] != 'Excluded')\n df = df[rows_to_keep]\n\n print(f\"Saving extracted data {df.shape} to '{output_path}'\")\n df.to_csv(output_path, index=None, quoting=csv.QUOTE_NONNUMERIC)\n\nfor year in (2000, 2017):\n input_path = data_dir + f\"{year}/daily_88101_{year}.csv.gz\"\n output_path = data_dir + f\"extracted_monitor_data_88101_{year}.csv\"\n extract(input_path, output_path)\n" ]
[ [ "pandas.read_csv" ] ]
pierrepo/buildH
[ "4870ffc4fb41deec2c8af5ba5b589795bbb99563" ]
[ "buildh/core.py" ]
[ "\"\"\"Module holding the core functions.\"\"\"\n\nimport pandas as pd\nimport MDAnalysis as mda\nimport MDAnalysis.coordinates.XTC as XTC\n\nfrom . import hydrogens\nfrom . import geometry as geo\nfrom . import writers\n\n\n# For debugging.\n# TODO: Remove it after implement logging feature\nDEBUG=False\n\n\ndef buildHs_on_1C(atom, H_type, helper1, helper2, helper3=None):\n \"\"\"Build 1, 2 or 3 H on a given carbon.\n\n This function is a wrapper which takes the coordinates of the helpers\n and call the function that builds 1, 2 or 3 H.\n\n Parameters\n ----------\n atom : numpy 1D-array\n Central atom on which we want to reconstruct the hydrogen.\n H_type: str\n The type of H to build. It could be 'CH2', 'CH', 'CHdoublebond' or 'CH3'\n see dic_lipds.py\n helper1 : numpy 1D-array\n First neighbor of central atom.\n helper2 : numpy 1D-array\n Second neighbor of central atom.\n helper3 : numpy 1D-array\n Third neighbor of central atom.\n\n Returns\n -------\n tuple of numpy 1D-arrays\n Each element of the tuple is a numpy 1D-array containing 1, 2 or 3\n reconstructed hydrogen(s).\n !!! IMPORTANT !!! This function *should* return a tuple even if\n there's only one H that has been rebuilt.\n \"\"\"\n if H_type == \"CH2\":\n H1_coor, H2_coor = hydrogens.get_CH2(atom, helper1, helper2)\n return (H1_coor, H2_coor)\n elif H_type == \"CH\":\n # If we reconstruct a single H, we have a 3rd helper.\n #helper3_coor = sel(\"name {0}\".format(helper3_name))[0].position\n H1_coor = hydrogens.get_CH(atom, helper1, helper2,\n helper3)\n return (H1_coor,)\n elif H_type == \"CHdoublebond\":\n H1_coor = hydrogens.get_CH_double_bond(atom, helper1,\n helper2)\n return (H1_coor,)\n elif H_type == \"CH3\":\n H1_coor, H2_coor, H3_coor = hydrogens.get_CH3(atom,\n helper1, helper2)\n return (H1_coor, H2_coor, H3_coor)\n else:\n raise UserWarning(\"Wrong code for typeofH2build, expected 'CH2', 'CH'\"\n \", 'CHdoublebond' or 'CH3', got {}.\"\n .format(H_type))\n\n\ndef build_system_hydrogens(universe_woH, dic_lipid, dic_Cname2Hnames, dic_lipid_indexes):\n \"\"\"Build a new system *with* hydrogens.\n\n The function take the MDAnalysis universe *without* hydrogens, reconstruct all hydrogens\n and return a pandas dataframe. This latter will be used later to build a new\n MDAnalysis universe with H.\n\n Notes\n -----\n There is no simple way to create a new MDAnalysis universe directly.\n\n Parameters\n ----------\n universe_woH : MDAnalysis universe instance\n This is the universe *without* hydrogen.\n dic_lipid : dictionary\n Comes from dic_lipids.py. Contains carbon names and helper names needed\n for reconstructing hydrogens.\n dic_Cname2Hnames : dictionary\n This dict gives the correspondance Cname -> Hname. It is a dict of\n tuples. If there is more than 1 H for a given C, they need to be\n *ordered* like in the PDB. e.g. for CHARMM POPC :\n {'C13': ('H13A', 'H13B', 'H13C'), ..., 'C33': ('H3X', 'H3Y'),\n ..., 'C216': ('H16R', 'H16S'), ...}\n dic_lipids_with_indexes : dictionary\n The dictionary made in function make_dic_lipids_with_indexes().\n\n Returns\n -------\n pandas dataframe\n contains the system *with* hydrogens.\n \"\"\"\n # The list newrows will be used to store the new molecule *with* H.\n newrows = []\n # Counter for numbering the new mlcs with H.\n new_atom_num = 1\n # Loop over all atoms in the universe without H.\n for atom in universe_woH.atoms:\n resnum = atom.resnum\n resname = atom.resname\n name = atom.name\n # Append atom to the new list.\n # 0 1 2 3 4 5 6\n # atnum, atname, resname, resnum, x, y, z\n newrows.append([new_atom_num, name, resname, resnum]\n + list(atom.position))\n new_atom_num += 1\n # Build new H(s)?\n if (atom.name in dic_lipid and atom.residue.resname == dic_lipid[\"resname\"]):\n # Retrieve helpers coordinates\n # helperX_ix is the index of the helper inside one residue.\n if len(dic_lipid_indexes[atom.name]) == 6:\n typeofH2build, _, _, _, helper1_ix, helper2_ix = dic_lipid_indexes[atom.name]\n helper3_coor = None\n else:\n typeofH2build, _, _, _, _, helper1_ix, helper2_ix, helper3_ix = dic_lipid_indexes[atom.name]\n helper3_coor = atom.residue.atoms[helper3_ix].position\n\n helper1_coor = atom.residue.atoms[helper1_ix].position\n helper2_coor = atom.residue.atoms[helper2_ix].position\n\n # Build Hs and store them in a list of numpy 1D-arrays Hs_coor.\n # The \"s\" in Hs_coor means there can be more than 1 H:\n # For CH2, Hs_coor will contain: [H1_coor, H2_coor].\n # For CH3, Hs_coor will contain: [H1_coor, H2_coor, H3_coor].\n # For CH, Hs_coor will contain: [H1_coor].\n # For CHdoublebond, Hs_coor will contain: [H1_coor].\n Hs_coor = buildHs_on_1C(atom.position, typeofH2build,\n helper1_coor, helper2_coor, helper3_coor)\n\n # Loop over Hs_coor (H_coor is a 1D-array with the 3 coors of 1 H).\n for i, H_coor in enumerate(Hs_coor):\n # Retrieve name of newly built H.\n Hname = dic_Cname2Hnames[atom.name][i]\n # Add them to newrows.\n newrows.append([new_atom_num, Hname, resname, resnum]\n + list(H_coor))\n new_atom_num += 1\n\n # Create a dataframe to store the mlc with added hydrogens.\n new_df_atoms = pd.DataFrame(newrows, columns=[\"atnum\", \"atname\",\n \"resname\", \"resnum\",\n \"x\", \"y\", \"z\"])\n return new_df_atoms\n\n\n###\n### The next function build_all_Hs_calc_OP())\n### build new H, calculate the order parameter and write the new traj with Hs\n### to an output file (e.g. .xtc, etc).\n### Note: it is slow, it shouldn't be used if the user doesn't want to\n### write the trajectory. Instead, fast_build_all_Hs() should be used.\n###\ndef build_all_Hs_calc_OP(universe_woH, ts, dic_lipid, dic_Cname2Hnames, universe_wH, dic_OP,\n dic_corresp_numres_index_dic_OP, dic_lipid_indexes):\n \"\"\"Build all hydrogens and calculates order parameters for one frame.\n\n This function loop overs *all* atoms of the universe_woH in order to update\n the atom coordinates and the new H built into the universe_wH.\n\n The function also calculates the order parameter.\n The coordinates of the universe *with* H are updated in place.\n The order parameter is also added in place (within dic_OP dictionary).\n\n Notes\n -----\n This function is slow, thus it shall be used when one wants\n to create a trajectory with H (such as .xtc or whatever format).\n\n This function assumes all possible C-H pairs are present in the .def\n file (with -d option). They are needed since we want to build an xtc with\n the whole system. If one is interested in calculating only a subset of OPs,\n please use the function fast_build_all_Hs_calc_OP() instead.\n\n Parameters\n ----------\n universe_woH : MDAnalysis universe instance\n This is the universe *without* hydrogen.\n ts : Timestep instance\n the current timestep with the coordinates\n dic_lipid : dictionary\n Comes from dic_lipids.py. Contains carbon names and helper names needed\n for reconstructing hydrogens.\n dic_Cname2Hnames : dictionary\n This dict gives the correspondance Cname -> Hname. It is a dict of\n tuples. If there is more than 1 H for a given C, they need to be\n *ordered* like in the PDB. e.g. for CHARMM POPC :\n {'C13': ('H13A', 'H13B', 'H13C'), ..., 'C33': ('H3X', 'H3Y'),\n ..., 'C216': ('H16R', 'H16S'), ...}\n universe_wH : MDAnalysis universe instance (optional)\n This is the universe *with* hydrogens.\n dic_OP : ordered dictionary\n Each key of this dict is a couple carbon/H, and at the beginning it\n contains an empty list, e.g.\n OrderedDict([ ('C1', 'H11): [], ('C1', 'H12'): [], ... ])\n See function init_dic_OP() below to see how it is organized.\n dic_corresp_numres_index_dic_OP : dictionary\n This dict should contain the correspondance between the numres and\n the corresponding index in dic_OP. For example {..., 15: 14, ...} means\n the residue numbered 15 in the PDB has an index of 14 in dic_OP.\n \"\"\"\n # We will need the index in the numpy array for updating coordinates\n # in the universe with H.\n row_index_coor_array = 0\n resid = -9999\n\n # Loop over all atoms in the universe without H.\n for atom in universe_woH.atoms:\n # Update the position of the current atom in the universe with H.\n universe_wH.coord.positions[row_index_coor_array, :] = atom.position\n row_index_coor_array += 1\n\n # Build new H(s)?\n if (atom.name in dic_lipid and atom.residue.resname == dic_lipid[\"resname\"]):\n\n # Retrieve the index of the first atom in the current residue\n # Test to avoid refreshing it at every step of the loop\n if resid != atom.residue.resid:\n resid = atom.residue.resid\n ix_first_atom_res = atom.residue.atoms[0].ix\n\n # Retrieve helpers coordinates\n if len(dic_lipid_indexes[atom.name]) == 6:\n typeofH2build, _, _, _, helper1_ix, helper2_ix = dic_lipid_indexes[atom.name]\n helper3_coor = None\n else:\n typeofH2build, _, _, _, _, helper1_ix, helper2_ix, helper3_ix = dic_lipid_indexes[atom.name]\n helper3_coor = ts[helper3_ix + ix_first_atom_res]\n\n # Faster to retrieve the coordinates from ts than from universe_woH.atoms.positions\n helper1_coor = ts[helper1_ix + ix_first_atom_res]\n helper2_coor = ts[helper2_ix + ix_first_atom_res]\n\n # Build Hs and store them in a list of numpy 1D-arrays Hs_coor.\n # The \"s\" in Hs_coor means there can be more than 1 H:\n # For CH2, Hs_coor will contain: [H1_coor, H2_coor].\n # For CH3, Hs_coor will contain: [H1_coor, H2_coor, H3_coor].\n # For CH, Hs_coor will contain: [H1_coor].\n # For CHdoublebond, Hs_coor will contain: [H1_coor].\n Hs_coor = buildHs_on_1C(atom.position, typeofH2build,\n helper1_coor, helper2_coor, helper3_coor)\n\n # Loop over Hs_coor (H_coor is a 1D-array with the 3 coors of 1 H).\n for i, H_coor in enumerate(Hs_coor):\n # Retrieve name of newly built H.\n Hname = dic_Cname2Hnames[atom.name][i]\n ####\n #### We calculate here the order param on the fly :-D !\n ####\n if (atom.name, Hname) in dic_OP:\n op = geo.calc_OP(atom.position, H_coor)\n # We should get here the index of the residue in dic_OP.\n # For that we can use dic_corresp_numres_index_dic_OP\n # (key: resnum in pdb, value: index residue in dic_OP).\n lipid_ix = dic_corresp_numres_index_dic_OP[atom.resid]\n # OLD way: dic_OP[(atom.name, Hname)].append(op)\n if (atom.name, Hname) in dic_OP:\n dic_OP[(atom.name, Hname)][lipid_ix].append(op)\n if DEBUG:\n print(atom.name, H_coor, \"OP:\", op)\n\n # Update the position of the current H in the universe with H.\n universe_wH.coord.positions[row_index_coor_array, :] = H_coor\n row_index_coor_array += 1\n\n if dic_OP and DEBUG:\n print()\n print()\n if dic_OP and DEBUG:\n print(\"Final dic_OP:\", dic_OP)\n print()\n\n\n###\n### The next 3 functions (get_indexes(), make_dic_lipids_with_indexes()\n### and fast_build_all_Hs_calc_OP()) should be used when the\n### user doesn't want an output trajectory.\n### By using fast indexing to individual Catoms and helpers, they\n### are much faster.\n###\ndef get_indexes(atom, dic_lipid):\n \"\"\"Return the index of helpers for a given carbon.\n\n Parameters\n ----------\n atom : MDAnalysis Atom instance\n This is an Atom instance of a carbon on which we want to build Hs.\n dic_lipid : dictionary\n Comes from dic_lipids.py. Contains carbon names and helper names needed\n for reconstructing hydrogens.\n\n Returns\n -------\n tuple of 2 or 3 int\n The tuple contains the index of the 2 (or 3) helpers for the atom that\n was passed as argument. (e.g. for atom C37 with index 99, the function\n returns a tuple containing 98 (index of C36 = helper 1) and 100 (index\n of C38=helper2).\n \"\"\"\n # Get nb of H to build and helper names (we can have 2 or 3 helpers).\n if len(dic_lipid[atom.name]) == 3:\n typeofH2build, helper1_name, helper2_name = dic_lipid[atom.name]\n else:\n typeofH2build, helper1_name, helper2_name, helper3_name = dic_lipid[atom.name]\n # Get helper coordinates using atom, which an instance from Atom class.\n # atom.residue.atoms is a list of atoms we can select with\n # method .select_atoms().\n # To avoid too long line, we shorten its name to `sel`.\n sel = atom.residue.atoms.select_atoms\n helper1_ix = sel(\"name {}\".format(helper1_name))[0].ix\n helper2_ix = sel(\"name {}\".format(helper2_name))[0].ix\n if typeofH2build == \"CH\":\n # If we reconstruct a single H, we have a 3rd helper.\n helper3_ix = sel(\"name {0}\".format(helper3_name))[0].ix\n return (helper1_ix, helper2_ix, helper3_ix)\n else:\n return (helper1_ix, helper2_ix)\n\n\ndef make_dic_lipids_with_indexes(universe_woH, dic_lipid, dic_OP):\n \"\"\"Expand dic_lipid and adds the index of each atom and helper.\n\n IMPORTANT: the index of each atom/helper is given with respect to the\n first atom in that residue.\n For example, if we have a POPC where C1 is the first atom, and C50 the\n last one, we want in the end:\n {'C1': ('CH3', 'N4', 'C5', 0, 3, 4), ...,\n 'C50': ('CH3', 'C49', 'C48', 49, 48, 47)}\n Where the 3 last int are the index (ix) of the atom, helper1, helper2\n (possibly helper3) with respect to the first atom.\n Thus for C1 : 0 is index of C1, N4 is 3 atoms away from C1 and C5 is 4\n atoms away from C1.\n For C50: C50 is 49 atoms away from C1, C49 is 48 atoms away from C1,\n C48 is 47 atoms away from C1.\n\n Parameters\n ----------\n universe_woH : MDAnalysis Universe instance\n The universe without hydrogens.\n dic_lipid : dictionary\n Comes from dic_lipids.py. Contains carbon names and helper names needed\n for reconstructing hydrogens.\n dic_OP : ordered dictionary\n Each key of this dict is a couple carbon/H, and at the beginning it\n contains an empty list, e.g.\n OrderedDict([ ('C1', 'H11): [], ('C1', 'H12'): [], ... ])\n See function init_dic_OP() below to see how it is organized.\n\n Returns\n -------\n dictionary\n The returned dictionary as described above in this docstring.\n \"\"\"\n # Get lipid name.\n resname = dic_lipid[\"resname\"]\n # Get resnum of the 1st lipid encountered in the system whose name\n # is `resname`.\n selection = \"resname {}\".format(resname)\n first_lipid_residue = universe_woH.select_atoms(selection).residues[0]\n resnum_1st_lipid = first_lipid_residue.resnum\n # Get name of 1st atom of that lipid.\n first_atom_name = first_lipid_residue.atoms[0].name\n # Get index of this atom.\n first_atom_ix = first_lipid_residue.atoms[0].ix\n if DEBUG:\n print(\"resname: {}, first encountered residue: {},\\n\"\n \"resnum_1st_lipid: {}, first_atom_name: {}, first_atom_ix: {}\"\n .format(resname, first_lipid_residue, resnum_1st_lipid,\n first_atom_name, first_atom_ix))\n print()\n # Keep only carbons on which we want to build Hs.\n carbons2keep = []\n for Cname, _ in dic_OP:\n if Cname not in carbons2keep:\n carbons2keep.append(Cname)\n dic_lipids_with_indexes = {}\n for Cname in dic_lipid.keys():\n if Cname in carbons2keep:\n dic_lipids_with_indexes[Cname] = dic_lipid[Cname].copy()\n # Now add the helper indexes.\n # The reasonning is over one residue (e.g. POPC). We want to add (to the\n # dict) the index (ix) of each helper of a given carbon with respect to\n # the index of the first atom in that lipid residue.\n # Loop over each carbon on which we want to reconstruct Hs.\n for Cname in dic_lipids_with_indexes:\n # Loop over residues for a given Cname atom.\n selection = \"resid {} and name {}\".format(resnum_1st_lipid, Cname)\n for Catom in universe_woH.select_atoms(selection):\n # Get the (absolute) index of helpers.\n if dic_lipid[Cname][0] == \"CH\":\n helper1_ix, helper2_ix, helper3_ix = get_indexes(Catom, dic_lipid)\n else:\n helper1_ix, helper2_ix = get_indexes(Catom, dic_lipid)\n # If the first lipid doesn't start at residue 1 we must\n # substract the index of the first atom of that lipid.\n Catom_ix_inres = Catom.ix - first_atom_ix\n helper1_ix_inres = helper1_ix - first_atom_ix\n helper2_ix_inres = helper2_ix - first_atom_ix\n # Then add these indexes to dic_lipids_with_indexes.\n if dic_lipid[Cname][0] == \"CH\":\n helper3_ix_inres = helper3_ix - first_atom_ix\n tmp_tuple = (Catom_ix_inres, helper1_ix_inres,\n helper2_ix_inres, helper3_ix_inres)\n dic_lipids_with_indexes[Cname] += tmp_tuple\n else:\n tmp_tuple = (Catom_ix_inres, helper1_ix_inres,\n helper2_ix_inres)\n dic_lipids_with_indexes[Cname] += tmp_tuple\n if DEBUG:\n print(\"Everything is based on the following dic_lipids_with_indexes\\n{}\"\n .format(dic_lipids_with_indexes))\n print()\n return dic_lipids_with_indexes\n\n\ndef fast_build_all_Hs_calc_OP(universe_woH, begin, end,\n dic_OP, dic_lipid, dic_Cname2Hnames):\n \"\"\"Build Hs and calc OP using fast indexing.\n\n This function uses fast indexing to carbon atoms and helper atoms. It\n should be used when the user doesn't want any output traj with hydrogens.\n\n Parameters\n ----------\n universe_woH : MDAnalysis universe instance\n This is the universe *without* hydrogen.\n begin: int\n index of the first frame of trajectory\n end: int\n index of the last frame of trajectory\n dic_OP : ordered dictionary\n Each key of this dict is a couple carbon/H, and at the beginning it\n contains an empty list, e.g.\n OrderedDict([ ('C1', 'H11): [], ('C1', 'H12'): [], ... ])\n See function init_dic_OP() below to see how it is organized.\n dic_lipid : dictionary\n Comes from dic_lipids.py. Contains carbon names and helper names needed\n for reconstructing hydrogens.\n dic_Cname2Hnames : dictionary\n This dict gives the correspondance Cname -> Hname. It is a dict of\n tuples. If there is more than 1 H for a given C, they need to be\n *ordered* like in the PDB. e.g. for CHARMM POPC :\n {'C13': ('H13A', 'H13B', 'H13C'), ..., 'C33': ('H3X', 'H3Y'),\n ..., 'C216': ('H16R', 'H16S'), ...}\n\n Returns\n -------\n None\n This function returns nothing, dic_OP is changed *in place*.\n \"\"\"\n ###\n ### 1) Expand dic_lipids and store there helpers' index.\n ###\n ### We want {'C1': ('CH3', 'N4', 'C5', 0, 3, 4), ...,\n ### 'C50': ('CH3', 'C49', 'C48', 49, 48, 47)}\n ### Where the 3 last int are the index (ix) of the atom, helper1, helper2\n ### (possibly helper3) with respect to the first atom\n ### (e.g. 0 is index of C1, N4 is 3 atoms away from C1, etc).\n ###\n dic_lipids_with_indexes = make_dic_lipids_with_indexes(universe_woH,\n dic_lipid, dic_OP)\n # Get lipid name.\n resname = dic_lipid[\"resname\"]\n # Select first residue of that lipid.\n selection = \"resname {}\".format(resname)\n first_lipid_residue = universe_woH.select_atoms(selection).residues[0]\n # Get name of 1st atom of that lipid.\n first_atom_name = first_lipid_residue.atoms[0].name\n ###\n ### 2) Now loop over the traj, residues and Catoms.\n ### At each iteration build Hs and calc OP.\n ###\n # Loop over frames (ts is a Timestep instance).\n for ts in universe_woH.trajectory[begin:end]:\n print(\"Dealing with frame {} at {} ps.\"\n .format(ts.frame, universe_woH.trajectory.time))\n if DEBUG:\n print(\"Looping now over residues...\")\n print()\n # Loop over the 1st atom of each lipid, which is equiv to loop *over\n # residues* (first_lipid_atom is an Atom instance, lipid_ix is an int\n # that will be used for storing OPs in dic_OP).\n selection = \"resname {} and name {}\".format(resname, first_atom_name)\n for lipid_ix, first_lipid_atom in enumerate(universe_woH.select_atoms(selection)):\n if DEBUG:\n print(\"Dealing with Cname\", first_lipid_atom)\n print(\"which is part of residue\", first_lipid_atom.residue)\n print(\"Now looping over atoms of this residue\")\n print()\n # Get the index of this first atom.\n ix_first_atom_res = first_lipid_atom.ix\n # Now loop over each carbon on which we want to build Hs\n # (Cname is a string).\n for Cname in dic_lipids_with_indexes:\n # Get Cname and helpers coords.\n if len(dic_lipids_with_indexes[Cname]) == 6:\n typeofH2build, _, _, Cname_ix, helper1_ix, helper2_ix = dic_lipids_with_indexes[Cname]\n helper3_coor = None\n else:\n typeofH2build, _, _, _, Cname_ix, helper1_ix, helper2_ix, helper3_ix = dic_lipids_with_indexes[Cname]\n helper3_coor = ts[helper3_ix+ix_first_atom_res]\n helper1_coor = ts[helper1_ix+ix_first_atom_res]\n helper2_coor = ts[helper2_ix+ix_first_atom_res]\n Cname_position = ts[Cname_ix+ix_first_atom_res]\n if DEBUG:\n print(\"Dealing with Cname\", Cname)\n sel = first_lipid_atom.residue.atoms.select_atoms\n Cname_atom = sel(\"name {}\".format(Cname))[0]\n print(Cname_atom, Cname_atom.position)\n if len(dic_lipid[Cname]) == 3:\n _, helper1_name, helper2_name = dic_lipid[Cname]\n else:\n _, helper1_name, helper2_name, helper3_name = dic_lipid[Cname]\n helper1_atom = sel(\"name {}\".format(helper1_name))[0]\n print(\"helper1\", helper1_atom, helper1_atom.position)\n helper2_atom = sel(\"name {}\".format(helper2_name))[0]\n print(\"helper2\", helper2_atom, helper2_atom.position)\n if len(dic_lipid[Cname]) == 4:\n helper3_atom = sel(\"name {}\".format(helper3_name))[0]\n print(\"helper3\", helper3_atom, helper3_atom.position)\n # Get newly built H(s) on that atom.\n Hs_coor = buildHs_on_1C(Cname_position, typeofH2build,\n helper1_coor, helper2_coor, helper3_coor)\n if DEBUG:\n print(\"Cname_position with fast indexing:\", Cname_position)\n print(\"helper1_position with fast indexing:\",\n ts[helper1_ix+ix_first_atom_res])\n print(\"helper2_position with fast indexing:\",\n ts[helper2_ix+ix_first_atom_res])\n if len(dic_lipid[Cname]) == 4:\n print(\"helper3_position with fast indexing:\",\n ts[helper3_ix+ix_first_atom_res])\n # To retrieve Hname, we need a counter.\n counter4Hname = 0\n # Loop over all Hs.\n for H_coor in Hs_coor:\n # Retrieve name of newly built H.\n Hname = dic_Cname2Hnames[Cname][counter4Hname]\n # Calc and store OP for that couple C-H.\n Cname_position = ts[Cname_ix+ix_first_atom_res]\n op = geo.calc_OP(Cname_position, H_coor)\n # Old way: dic_OP[(Cname, Hname)].append(op)\n if (Cname, Hname) in dic_OP:\n dic_OP[(Cname, Hname)][lipid_ix].append(op)\n if DEBUG:\n print(Hname, H_coor, \"OP:\", op)\n # Increment counter4Hname for retrieving next H.\n counter4Hname += 1\n if DEBUG:\n print()\n print()\n if DEBUG:\n print(\"Final dic_OP:\", dic_OP)\n print()\n\n\ndef gen_coordinates_calcOP(basename, universe_woH, dic_OP, dic_lipid,\n dic_Cname2Hnames, dic_corresp_numres_index_dic_OP,\n begin, end, traj_file):\n \"\"\"Generate coordinates files (pdb and/or xtc) with computed hydrogens\n and compute the order parameter.\n\n If `traj_file` is set to False, only a pdb file will be written.\n This depends whether or not the user supplied a trajectory file\n in the first place.\n\n Parameters\n ----------\n basename : str\n basename for the output coordinate file(s).\n universe_woH : MDAnalysis universe instance\n This is the universe *without* hydrogen.\n dic_OP : ordered dictionary\n Each key of this dict is a couple carbon/H, and at the beginning it\n contains an empty list, e.g.\n OrderedDict([ ('C1', 'H11): [], ('C1', 'H12'): [], ... ])\n See function init_dic_OP() below to see how it is organized.\n dic_lipid : dictionary\n Comes from dic_lipids.py. Contains carbon names and helper names needed\n for reconstructing hydrogens.\n dic_Cname2Hnames : dictionary\n This dict gives the correspondance Cname -> Hname. It is a dict of\n tuples. If there is more than 1 H for a given C, they need to be\n *ordered* like in the PDB. e.g. for CHARMM POPC :\n {'C13': ('H13A', 'H13B', 'H13C'), ..., 'C33': ('H3X', 'H3Y'),\n ..., 'C216': ('H16R', 'H16S'), ...}\n dic_corresp_numres_index_dic_OP : dictionary\n This dict should contain the correspondance between the numres and\n the corresponding index in dic_OP.\n begin: int\n index of the first frame of trajectory\n end: int\n index of the last frame of trajectory\n traj_file : bool\n a trajectory output file has to be generated?\n \"\"\"\n dic_lipids_with_indexes = make_dic_lipids_with_indexes(universe_woH, dic_lipid,\n dic_OP)\n\n # Create filenames.\n pdbout_filename = basename + \".pdb\"\n # Build a new universe with H.\n # Build a pandas df with H.\n new_df_atoms = build_system_hydrogens(universe_woH, dic_lipid, dic_Cname2Hnames,\n dic_lipids_with_indexes)\n # Create a new universe with H using that df.\n print(\"Writing new pdb with hydrogens.\")\n # Write pdb with H to disk.\n with open(pdbout_filename, \"w\") as f:\n f.write(writers.pandasdf2pdb(new_df_atoms))\n # Then create the universe with H from that pdb.\n universe_wH = mda.Universe(pdbout_filename)\n\n #Do we need to generate a trajectory file ?\n if traj_file:\n xtcout_filename = basename + \".xtc\"\n # Create an xtc writer.\n print(\"Writing trajectory with hydrogens in xtc file.\")\n newxtc = XTC.XTCWriter(xtcout_filename, len(universe_wH.atoms))\n # Write 1st frame.\n newxtc.write(universe_wH)\n\n # 4) Loop over all frames of the traj *without* H, build Hs and\n # calc OP (ts is a Timestep instance).\n for ts in universe_woH.trajectory[begin:end]:\n print(\"Dealing with frame {} at {} ps.\"\n .format(ts.frame, universe_woH.trajectory.time))\n # Build H and update their positions in the universe *with* H (in place).\n # Calculate OPs on the fly while building Hs (dic_OP changed in place).\n build_all_Hs_calc_OP(universe_woH, ts, dic_lipid, dic_Cname2Hnames,\n universe_wH, dic_OP, dic_corresp_numres_index_dic_OP,\n dic_lipids_with_indexes)\n # Write new frame to xtc.\n newxtc.write(universe_wH)\n # Close xtc.\n newxtc.close()\n # if not, just compute OP in the fast way.\n else:\n fast_build_all_Hs_calc_OP(universe_woH, begin, end, dic_OP, dic_lipid, dic_Cname2Hnames)\n" ]
[ [ "pandas.DataFrame" ] ]
samuelstanton/lambo
[ "7b67684b884f75f7007501978c5299514d0efb75" ]
[ "lambo/models/mlm.py" ]
[ "import math\n\nimport numpy as np\nimport torch\nimport torchvision\nimport wandb\n\nfrom torch.nn import functional as F\nfrom torch import LongTensor\n\nfrom lambo import transforms as gfp_transforms, dataset as gfp_dataset\nfrom lambo.models.shared_elements import check_early_stopping\nfrom lambo.utils import str_to_tokens\n\n\ndef sample_tokens(base_tokens, logit_batch, enc_tokenizer, replacement=False, temp=1.):\n\tlogit_batch /= temp\n\t# don't sample special tokens\n\tnon_viable_idxs = np.array(enc_tokenizer.special_idxs)[None, None, :]\n\tnp.put_along_axis(logit_batch, non_viable_idxs, -1e10, axis=-1)\n\n\tif not replacement and base_tokens is not None:\n\t\t# don't sample the original tokens\n\t\tbase_tokens = base_tokens.numpy().astype(int)[..., None]\n\t\tnp.put_along_axis(logit_batch, base_tokens, -1e10, axis=-1)\n\n\t# sample tokens\n\ttoken_samples = torch.distributions.Categorical(logits=logit_batch).sample()\n\n\t# calculate entropy\n\tentropy = -(\n\t\t\tF.softmax(logit_batch, dim=-1) * F.log_softmax(logit_batch, dim=-1)\n\t).sum(-1)\n\n\treturn token_samples, entropy\n\n\ndef sample_mask(\n\t\ttoken_batch: LongTensor,\n\t\ttokenizer,\n\t\tmask_ratio: float = 0.125,\n\t\tmask_size=None\n):\n\t\"\"\"\n\tArgs:\n\t\ttoken_batch: (batch_size, num_tokens)\n\t\ttokenizer: only necessary to avoid masking special tokens\n\t\tmask_ratio: proportion of tokens to mask\n\t\tmask_size: (optional) override mask_ratio with a specific mask size\n\tReturns:\n\t\tmask_idxs: (batch_size, mask_size) np.ndarray of position indexes to mask\n\t\"\"\"\n\tif mask_size is None:\n\t\tmask_size = math.ceil(token_batch.shape[-1] * mask_ratio)\n\n\tspecial_idxs = torch.tensor(tokenizer.special_idxs).view(-1, 1, 1)\n\tis_non_special = token_batch.ne(special_idxs).prod(dim=0).float()\n\tmask_weights = is_non_special / is_non_special.sum(dim=-1, keepdims=True)\n\tmask_idxs = torch.multinomial(mask_weights, mask_size, replacement=False)\n\treturn mask_idxs.numpy()\n\n\ndef evaluate_windows(base_seqs, encoder, mask_size, replacement=True, encoder_obj='mlm'):\n\twindow_mask_idxs = {}\n\twindow_entropy = {}\n\twindow_features = {}\n\n\tfor idx, seq in enumerate(base_seqs):\n\t\twindow_mask_idxs[idx] = []\n\t\twindow_entropy[idx] = []\n\t\twindow_features[idx] = []\n\t\t# avoids evaluating windows corresponding to padding tokens\n\t\ttokens = str_to_tokens(np.array([seq]), encoder.tokenizer)\n\t\t# assert torch.all(tokens.ne(encoder.tokenizer.padding_idx)) # SELFIES no-op token may trigger\n\t\tmask_size = min(mask_size, tokens.shape[-1] - 2)\n\t\toffset = np.random.randint(1, mask_size + 1)\n\t\tfor mask_start in range(offset, tokens.shape[-1] - 1, mask_size):\n\t\t\tif mask_start + mask_size < tokens.shape[-1] - 1:\n\t\t\t\tmask_idxs = np.arange(mask_start, mask_start + mask_size).reshape(1, -1)\n\t\t\telse:\n\t\t\t\tmask_stop = tokens.shape[-1] - 1\n\t\t\t\tmask_idxs = np.arange(mask_stop - mask_size, mask_stop).reshape(1, -1)\n\n\t\t\twith torch.no_grad():\n\t\t\t\tmasked_inputs = tokens.clone().to(encoder.device)\n\t\t\t\tnp.put_along_axis(masked_inputs, mask_idxs, encoder.tokenizer.masking_idx, axis=1)\n\t\t\t\ttgt_tok_logits, tgt_mask = encoder.logits_from_tokens(masked_inputs)\n\t\t\t\tif encoder_obj == 'mlm':\n\t\t\t\t\t_, logit_entropy = sample_tokens(\n\t\t\t\t\t\ttokens, tgt_tok_logits, encoder.tokenizer, replacement\n\t\t\t\t\t)\n\t\t\t\t\tlogit_entropy = np.take_along_axis(logit_entropy, mask_idxs, axis=1)\n\t\t\t\telif encoder_obj == 'lanmt':\n\t\t\t\t\ttgt_tok_idxs, logit_entropy = encoder.sample_tgt_tok_idxs(\n\t\t\t\t\t\ttgt_tok_logits, tgt_mask, temp=1.\n\t\t\t\t\t)\n\t\t\t\telse:\n\t\t\t\t\traise ValueError\n\n\t\t\twindow_mask_idxs[idx].append(mask_idxs.copy())\n\t\t\twindow_entropy[idx].append(logit_entropy.mean().item())\n\n\treturn window_mask_idxs, window_entropy\n\n\ndef mlm_train_step(model, optimizer, token_batch, mask_ratio, loss_scale=1.):\n\toptimizer.zero_grad(set_to_none=True)\n\n\t# replace random tokens with mask token\n\tmask_idxs = sample_mask(token_batch, model.tokenizer, mask_ratio)\n\tmasked_token_batch = token_batch.clone().to(model.device)\n\tnp.put_along_axis(masked_token_batch, mask_idxs, model.tokenizer.masking_idx, axis=1)\n\n\t# get predicted logits for masked tokens\n\tlogits, _ = model.logits_from_tokens(masked_token_batch)\n\tvocab_size = logits.shape[-1]\n\tmasked_logits = np.take_along_axis(logits, mask_idxs[..., None], axis=1).view(-1, vocab_size)\n\n\t# use the ground-truth tokens as labels\n\tmasked_tokens = np.take_along_axis(token_batch, mask_idxs, axis=1)\n\tmasked_tokens = masked_tokens.view(-1).to(model.device)\n\n\tloss = loss_scale * F.cross_entropy(masked_logits, masked_tokens)\n\tloss.backward()\n\toptimizer.step()\n\n\treturn loss, masked_logits, masked_tokens\n\n\ndef mlm_train_epoch(model, optimizer, train_loader, mask_ratio):\n\tmetrics = dict(\n\t\ttrain_loss=0.,\n\t\ttrain_perplexity=0.,\n\t)\n\tmodel.train()\n\tfor minibatch in train_loader:\n\t\tif isinstance(minibatch, tuple):\n\t\t\ttoken_batch = minibatch[0]\n\t\telse:\n\t\t\tassert torch.is_tensor(minibatch)\n\t\t\ttoken_batch = minibatch\n\n\t\tloss, masked_logits, masked_tokens = mlm_train_step(model, optimizer, token_batch, mask_ratio)\n\n\t\t# logging\n\t\tlog_prob = F.log_softmax(masked_logits, dim=-1)\n\t\tlog_prob = np.take_along_axis(log_prob, masked_tokens.cpu().numpy()[..., None], axis=1)\n\t\tmetrics['train_perplexity'] += 2 ** (\n\t\t\t-(log_prob / math.log(2)).mean().detach()\n\t\t) / len(train_loader)\n\t\tmetrics['train_loss'] += loss.detach() / len(train_loader)\n\tmetrics = {key: val.item() for key, val in metrics.items()}\n\treturn metrics\n\n\ndef mlm_eval_epoch(model, eval_loader, mask_ratio, split):\n\tmetrics = dict(\n\t\tperplexity=0.,\n\t)\n\tmodel.eval()\n\tfor minibatch in eval_loader:\n\t\tif isinstance(minibatch, tuple):\n\t\t\ttoken_batch = minibatch[0]\n\t\telse:\n\t\t\tassert torch.is_tensor(minibatch)\n\t\t\ttoken_batch = minibatch\n\n\t\t# replace random tokens with mask token\n\t\tmask_idxs = sample_mask(token_batch, model.tokenizer, mask_ratio)\n\t\tmasked_token_batch = token_batch.clone().to(model.device)\n\t\tnp.put_along_axis(masked_token_batch, mask_idxs, model.tokenizer.masking_idx, axis=1)\n\n\t\t# get predicted logits for masked tokens\n\t\tlogits, _ = model.logits_from_tokens(masked_token_batch)\n\t\tvocab_size = logits.shape[-1]\n\t\tmasked_logits = np.take_along_axis(logits, mask_idxs[..., None], axis=1).view(-1, vocab_size)\n\n\t\t# use the ground-truth tokens as labels\n\t\tmasked_tokens = np.take_along_axis(token_batch, mask_idxs, axis=1)\n\t\tmasked_tokens = masked_tokens.view(-1).to(model.device)\n\n\t\t# logging\n\t\tlog_prob = F.log_softmax(masked_logits, dim=-1)\n\t\tlog_prob = np.take_along_axis(log_prob, masked_tokens.cpu().numpy()[..., None], axis=1)\n\t\tmetrics['perplexity'] += 2 ** (\n\t\t\t-(log_prob / math.log(2)).mean().detach()\n\t\t) / len(eval_loader)\n\n\tmetrics = {key: val.item() for key, val in metrics.items()}\n\tmetrics = {f'{split}_{key}': val for key, val in metrics.items()}\n\n\treturn metrics\n\n\ndef fit_masked_language_model(model, train_seqs, num_epochs, batch_size, lr, patience, mask_ratio, max_shift,\n\t\t\t\t\t\t\t weights=None, log_prefix=''):\n\n\t# random translation data augmentation, apply tokenizer\n\ttrain_transform = []\n\tif max_shift > 0:\n\t\ttrain_transform.append(gfp_transforms.SequenceTranslation(max_shift))\n\ttrain_transform.append(gfp_transforms.StringToLongTensor(model.tokenizer))\n\ttrain_transform = torchvision.transforms.Compose(train_transform)\n\n\t# make dataset, dataloader\n\ttrain_dataset = gfp_dataset.TransformTensorDataset([train_seqs], train_transform)\n\n\tif weights is None:\n\t\tloader_kwargs = dict(batch_size=batch_size, shuffle=True)\n\telse:\n\t\tsampler = torch.utils.data.WeightedRandomSampler(weights, batch_size, replacement=True)\n\t\tbatch_sampler = torch.utils.data.BatchSampler(sampler, batch_size=batch_size, drop_last=False)\n\t\tloader_kwargs = dict(batch_sampler=batch_sampler)\n\n\ttrain_loader = torch.utils.data.DataLoader(\n\t\ttrain_dataset, collate_fn=gfp_transforms.padding_collate_fn, **loader_kwargs\n\t)\n\n\toptimizer = torch.optim.Adam(model.param_groups(lr))\n\tlr_sched = torch.optim.lr_scheduler.ReduceLROnPlateau(\n\t\toptimizer, patience=math.ceil(patience / 2)\n\t)\n\n\trecords = []\n\tbest_score, best_epoch, best_weights = None, 0, None\n\tmodel.requires_grad_(True)\n\tfor epoch in range(num_epochs):\n\t\tmetrics = {}\n\t\tmetrics.update(\n\t\t\tmlm_train_epoch(model, optimizer, train_loader, mask_ratio)\n\t\t)\n\t\t# use avg. train loss as convergence crit.\n\t\tlr_sched.step(metrics['train_loss'])\n\t\tbest_score, best_epoch, best_weights, stop = check_early_stopping(\n\t\t\tmodel,\n\t\t\tbest_score,\n\t\t\tbest_epoch,\n\t\t\tbest_weights,\n\t\t\tmetrics['train_loss'],\n\t\t\tepoch + 1,\n\t\t\tpatience,\n\t\t\tsave_weights=True,\n\t\t\t)\n\n\t\t# logging\n\t\tmetrics.update(dict(best_score=best_score, best_epoch=best_epoch))\n\t\tif len(log_prefix) > 0:\n\t\t\tmetrics = {'/'.join((log_prefix, key)): val for key, val in metrics.items()}\n\t\ttry:\n\t\t\twandb.log(metrics)\n\t\texcept:\n\t\t\tpass\n\t\trecords.append(metrics)\n\n\t\tif stop:\n\t\t\tbreak\n\n\tmodel.load_state_dict(best_weights)\n\tmodel.requires_grad_(False)\n\n\treturn records\n" ]
[ [ "torch.utils.data.DataLoader", "torch.nn.functional.log_softmax", "torch.utils.data.BatchSampler", "torch.distributions.Categorical", "torch.nn.functional.softmax", "torch.multinomial", "torch.tensor", "torch.no_grad", "numpy.take_along_axis", "numpy.arange", "torch.is_tensor", "torch.nn.functional.cross_entropy", "numpy.array", "torch.utils.data.WeightedRandomSampler", "numpy.random.randint", "numpy.put_along_axis" ] ]
mmr12/DeepLearning18
[ "3e683c570ea8f5e224767a41a0e152267cfd08e7" ]
[ "data_loader/baseline_generator.py" ]
[ "import numpy as np\nimport os\nimport sys\n# To import from sibling directory ../utils\nsys.path.append(os.path.dirname(os.path.abspath(__file__)) + \"/..\")\nfrom data_loader.load_utils import load_obj\nfrom data_loader.load_utils import try_to_load_as_pickled_object\nfrom sklearn.model_selection import train_test_split\nfrom data_loader.process_files import process_all_files\n\nclass DataGenerator:\n def __init__(self, config):\n self.config = config\n\n # load data here\n #input = try_to_load_as_pickled_object('./data/patches.pkl')\n #y = try_to_load_as_pickled_object('./data/labels_patches.pkl')\n print(\"\\nloading the data\")\n input, y = process_all_files([0,1000,2000,3000,4000,5000,6000,7000,8000,9000])\n print(\"\\ndata loaded\")\n\n self.input, self.input_dev, self.y, self.y_dev = train_test_split(input,\n y,\n test_size=self.config.val_split)\n\n def next_batch(self, batch_size):\n idx = np.random.choice(len(self.input), batch_size)\n yield self.input[idx], self.y[idx]\n\n def next_batch_dev(self, batch_size):\n idx = np.random.choice(len(self.input_dev), batch_size)\n yield self.input_dev[idx], self.y_dev[idx]\n" ]
[ [ "sklearn.model_selection.train_test_split" ] ]
Data-drone/scaling_deep_learning
[ "476346179c4575ad6aeecc8c6a1b427d00abde5a" ]
[ "tensorflow/SAM Model - Petastorm.py" ]
[ "# Databricks notebook source\n# MAGIC %md\n# MAGIC \n# MAGIC ## Training and packaging a Tensorflow 2.x model with Model Hub\n# MAGIC \n# MAGIC - based on: https://www.tensorflow.org/text/tutorials/classify_text_with_bert\n# MAGIC - Sentiment Analysis Model\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC #### Extra libraries not in DB ML Image\n# MAGIC - tensorflow-text\n# MAGIC - tf-models-official\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ### Load Libs\n\n# COMMAND ----------\n\nimport os\n\nimport tensorflow as tf\nimport tensorflow_hub as hub\nimport tensorflow_text as text\nfrom official.nlp import optimization # to create AdamW optimizer\n\nimport matplotlib.pyplot as plt\n\ntf.get_logger().setLevel('DEBUG')\n\n# COMMAND ----------\n\n# Extra Dirs setup for DB\nlog_dir = '/dbfs/Users/[email protected]/tf_log_dirs'\ndataset_dir = '/dbfs/user/brian.law/data/'\n\n## Extra Cache Path for Petastorm\ncache_pathing = 'user/brian.law/pt_cache_1/'\nlocal_cache_path = os.path.join('/dbfs', cache_pathing)\ncache_dir = 'file://' + local_cache_path\n\n# COMMAND ----------\n\n## Clean up and create cache\ndbutils.fs.rm(local_cache_path, True)\ndbutils.fs.mkdirs(local_cache_path)\n\n# COMMAND ----------\n\n# MAGIC %run ./utils/aclimdb_utils\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ### Tensorboard Setup\n\n# COMMAND ----------\n\n# MAGIC %load_ext tensorboard\n# MAGIC experiment_log_dir = log_dir\n\n# COMMAND ----------\n\n# MAGIC %tensorboard --logdir $experiment_log_dir\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ## Sentiment Analysis\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ### Dataset Loading\n\n# COMMAND ----------\n\n# MAGIC %run ./dataloaders/aclimdb_dataloaders\n\n# COMMAND ----------\n\ntrain_ds, val_ds, test_ds, size_train, size_val, size_test = get_petastorm_dataset(cache_dir=cache_dir, partitions=4)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ### Loading Pretrained Model\n# MAGIC \n# MAGIC - Can choose any of the models in map_name_to_handle as long as it first in mem (this is single GPU example)\n# MAGIC - Each model has an associated preprocess\n\n# COMMAND ----------\n\n# MAGIC %run ./models/aclimdb_models\n\n# COMMAND ----------\n\nclassifier_model = build_tf_raw_model()\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ### Validating Model Works\n\n# COMMAND ----------\n\ntext_test = ['this is such an amazing movie!']\n\nbert_raw_result = classifier_model(tf.constant(text_test))\nprint(tf.sigmoid(bert_raw_result))\n\n# COMMAND ----------\n\n# requires pydot and graphviz - installed on cluster level\ntf.keras.utils.plot_model(classifier_model)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ### Model Training\n\n# COMMAND ----------\n\n## Adding extra MLflow steps\n# due to extra tf requirements we will manually call autolog and turn off the artifact logging\nimport mlflow\n\n# COMMAND ----------\n\n# Defining Optimizer\n\nepochs = 3\nbatch_size = 128\n\nsteps_per_epoch = size_train // batch_size \nnum_train_steps = steps_per_epoch * epochs\nnum_warmup_steps = int(0.1*num_train_steps)\n\ninit_lr = 3e-5\n\n# COMMAND ----------\n\n# Compile model\nloss = tf.keras.losses.BinaryCrossentropy(from_logits=True)\nmetrics = tf.metrics.BinaryAccuracy()\n\noptimizer = optimization.create_optimizer(init_lr=init_lr,\n num_train_steps=num_train_steps,\n num_warmup_steps=num_warmup_steps,\n optimizer_type='adamw')\n\nclassifier_model.compile(optimizer=optimizer,\n loss=loss,\n metrics=metrics)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ### Advanced MLFlow Logging\n# MAGIC \n# MAGIC We need to set these up to include with the main training loop\n\n# COMMAND ----------\n\n# unless we specify extra then mlflow will just log these\nfrom mlflow.models.signature import ModelSignature\nfrom mlflow.types.schema import Schema, ColSpec\n\nmlflow.tensorflow.get_default_pip_requirements()\n\n# COMMAND ----------\n\n# extra pip requirements for our specific example\nextra_reqs = [\n f\"tensorflow-text==2.8.*\",\n f\"tf-models-official==2.7.0\"\n] \n\n# for the input signature field\ninput_examples = [\n 'this is such an amazing movie!', # this is the same sentence tried earlier\n 'The movie was great!',\n 'The movie was meh.',\n 'The movie was okish.',\n 'The movie was terrible...'\n]\n\n# lets manually spec input and output schema\n\ninput_schema = Schema([\n ColSpec(\"string\", \"An Input Sentence to Evaluate\")\n])\n\noutput_schema = Schema([ColSpec(\"float\", \"The Sentiment Score\")])\n\nsignature = ModelSignature(inputs=input_schema, outputs=output_schema)\n\n# COMMAND ----------\n\nimport datetime\n# Main training Loop\nfrom petastorm.spark import make_spark_converter\n\nwith mlflow.start_run(experiment_id='224704298431727') as run:\n \n mlflow.tensorflow.autolog(log_models=False)\n \n ## Adding Extra logging\n run_log_dir = os.path.join(log_dir, datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\"))\n #debug_dir = os.path.join(run_log_dir, 'debug')\n\n tf.debugging.experimental.enable_dump_debug_info(\n run_log_dir,\n tensor_debug_mode=\"FULL_HEALTH\",\n circular_buffer_size=-1)\n \n # didn't seem to work?\n tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=run_log_dir, histogram_freq=1, update_freq=1)\n \n ### Extra code for Petastorm\n converter_train = make_spark_converter(train_ds)\n converter_val = make_spark_converter(val_ds)\n \n with converter_train.make_tf_dataset(batch_size=batch_size, workers_count=10) as train_pt_ds, \\\n converter_val.make_tf_dataset(batch_size=batch_size, workers_count=10) as val_pt_ds:\n \n # The dataset that comes out might not be:\n # -- the right format\n # -- the right ordering\n train_iter = train_pt_ds.map(lambda x: (x[0], x[1]))\n val_iter = val_pt_ds.map(lambda x: (x[0], x[1]))\n \n ### End Extra Code for Petastorm\n \n history = classifier_model.fit(x=train_iter,\n validation_data=val_iter,\n validation_steps=size_val // batch_size,\n epochs=epochs,\n steps_per_epoch=steps_per_epoch,\n batch_size=batch_size,\n callbacks=[tensorboard_callback])\n \n # we need to first save out the model to a temp folder then we can log it\n dataset_name = 'imdb'\n saved_model_path = './{}_bert'.format(dataset_name.replace('/', '_'))\n\n #classifier_model.save(saved_model_path, include_optimizer=False)\n \n # try manually speccing some things in log model\n # tf_signature_def_key was from trial and error seems like\n # meta_graph_tags is none by design \n # classifier_model automatically sets this\n \n #mlflow.tensorflow.log_model(tf_saved_model_dir=saved_model_path,\n # tf_meta_graph_tags=None,\n # tf_signature_def_key='serving_default', # default from tf official model\n # artifact_path='model', # model is default for mlflow in order to link to UI\n # signature=signature,\n # input_example=input_examples,\n # extra_pip_requirements=extra_reqs)\n\n fig = accuracy_and_loss_plots(history)\n mlflow.log_figure(fig, 'training_perf.png')\n \n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ### Model Evaluation\n# MAGIC \n# MAGIC -- option in training steps\n\n# COMMAND ----------\n\nconverter_test = make_spark_converter(test_ds)\n\nwith converter_test.make_tf_dataset(batch_size=batch_size, workers_count=10) as test_pt_ds:\n \n test_iter = test_pt_ds.map(lambda x: (x[0], x[1]))\n \n # Note if the steps isn't defined then it will loop infinitely\n loss, accuracy = classifier_model.evaluate(test_iter,\n steps=size_test // batch_size)\n\n print(f'Loss: {loss}')\n print(f'Accuracy: {accuracy}')\n\n# COMMAND ----------\n\nmlflow.end_run()\n\n# COMMAND ----------\n\n### clean up\nclean_up = False\n\nif clean_up:\n from numba import cuda\n \n cuda.select_device(0)\n cuda.close()\n \n\n# COMMAND ----------\n\n\n" ]
[ [ "tensorflow.keras.utils.plot_model", "tensorflow.get_logger", "tensorflow.keras.callbacks.TensorBoard", "tensorflow.sigmoid", "tensorflow.metrics.BinaryAccuracy", "tensorflow.keras.losses.BinaryCrossentropy", "tensorflow.constant", "tensorflow.debugging.experimental.enable_dump_debug_info" ] ]
herrlich10/mripy
[ "df9a8e57a21163579af49c59a9dcd2da279cb9fa" ]
[ "mripy/afni.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division, absolute_import, unicode_literals\nimport sys, os, re, shlex, shutil, glob, subprocess, collections\nfrom os import path\nfrom datetime import datetime\nimport numpy as np\nfrom scipy import interpolate\nimport matplotlib as mpl\nfrom . import six\n\n\n# Test afni installation\n# has_afni = bool(re.search('version', subprocess.check_output(['afni', '-ver']).decode('utf-8'), re.IGNORECASE))\nhas_afni = True\n\n# # Find afni path\n# config_dir = path.expanduser('~/.mripy')\n# if not path.exists(config_dir):\n# os.makedirs(config_dir)\n# if has_afni:\n# config_file = path.join(config_dir, 'afni_path')\n# if path.exists(config_file):\n# with open(config_file, 'r') as f:\n# afni_path = f.readline()\n# else:\n# afni_path = subprocess.check_output('find ~ -iregex \".*/abin\"', shell=True).decode('utf-8').split('\\n')[0]\n# with open(config_file, 'w') as f:\n# f.write(afni_path)\n# else:\n# afni_path = ''\n\n\ndef filter_output(lines, tags=None, pattern=None, ex_tags=None, ex_pattern=None):\n '''\n Filter output lines according to their initial tags (++, *+, **, etc.) and/or\n a regex search pattern.\n\n Parameters\n ----------\n tags : list of tags\n Default is [], which means all lines will pass the filter.\n pattern : str\n ex_tags : list of tags to exclude\n ex_pattern : str\n '''\n if tags is None:\n tags = []\n if ex_tags is None:\n ex_tags = []\n if len(tags) > 0:\n lines = [line for line in lines if line[:2] in tags]\n if len(ex_tags) > 0:\n lines = [line for line in lines if line[:2] not in ex_tags]\n if pattern is not None:\n lines = [line for line in lines if re.search(pattern, line)]\n if ex_pattern is not None:\n lines = [line for line in lines if not re.search(ex_pattern, line)]\n return lines\n\n\ndef check_output(cmd, tags=None, pattern=None, verbose=0, **kwargs):\n '''\n The syntax of subprocess.check_output(shell=False) is tedious for long cmd.\n But for security reason, we don't want to use shell=True for external cmd.\n This helper function allows you to execute a single cmd without shell=True.\n\n Parameters\n ----------\n cmd : str\n A single command string packed with all options (but no wildcard)\n **kwargs :\n Go to `subprocess.check_output(**kwargs)`\n\n Returns\n -------\n lines : list of lines\n Much easier to deal with compared with subprocess.check_output()\n '''\n if isinstance(cmd, six.string_types):\n cmd = shlex.split(cmd) # Split by space, preserving quoted substrings\n lines = subprocess.check_output(cmd, stderr=subprocess.STDOUT, **kwargs).decode('utf-8').split('\\n')\n lines = filter_output(lines, tags, pattern)\n if verbose:\n for line in lines:\n print(line, file=sys.stderr if line.startswith('*') else sys.stdout)\n return lines\n\n\ndef call(cmd):\n if isinstance(cmd, six.string_types):\n cmd = shlex.split(cmd) # Split by space, preserving quoted substrings\n cmd_str = ' '.join(cmd)\n print('>>', cmd_str)\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False)\n for line in iter(p.stdout.readline, b''): # The 2nd argument is sentinel character\n print(line.decode('utf-8'), end='')\n p.stdout.close() # Notify the child process that the PIPE has been broken\n if p.wait():\n raise RuntimeError(f'Error occurs when executing the following command (returncode={p.returncode}):\\n{cmd_str}') \n\n\ndef split_out_file(out_file, split_path=False, trailing_slash=False):\n '''\n Ensure that path.join(out_dir, prefix, ext) can be checked by path.exists().\n\n >>> split_out_file('dset.nii')\n ('dset', '.nii')\n >>> split_out_file('dset.1D')\n ('dset', '.1D')\n >>> split_out_file('folder/dset')\n ('folder/dset', '+orig.HEAD')\n >>> split_out_file('folder/dset+orig', split_path=True)\n ('folder', 'dset', '+orig.HEAD')\n >>> split_out_file('dset+orig.', split_path=True)\n ('', 'dset', '+orig.HEAD')\n >>> split_out_file('folder/dset+orig.HEAD', split_path=True, trailing_slash=True)\n ('folder/', 'dset', '+orig.HEAD')\n >>> split_out_file('dset+tlrc.BRIK', split_path=True, trailing_slash=True)\n ('', 'dset', '+tlrc.HEAD')\n '''\n out_dir, out_name = path.split(out_file)\n if trailing_slash and out_dir:\n out_dir += '/'\n match = re.match(r'(.+)(.nii|.nii.gz|.1D|.1D.dset|.1D.roi|.niml.dset|.niml.roi|.gii.dset|.csv)$', out_name)\n if match:\n prefix, ext = match.groups()\n else:\n match = re.match(r'(.+)(\\+(?:orig|tlrc))(?:.|.HEAD|.BRIK)?$', out_name)\n if match:\n prefix, ext = match.groups()\n ext += '.HEAD'\n else:\n prefix = out_name\n ext = '+orig.HEAD'\n if split_path:\n return out_dir, prefix, ext\n else:\n return path.join(out_dir, prefix), ext\n\n\ndef insert_suffix(fname, suffix):\n prefix, ext = split_out_file(fname)\n return f\"{prefix}{suffix}{ext}\"\n\n\ndef get_prefix(fname, with_path=False):\n '''\n Return \"dset\" given \"path/to/dset+orig.HEAD\", \"dset+orig.\", \"dset+tlrc\", \"dsets\"\n '''\n if path.splitext(fname)[1] in ['.niml', '.1D', '.dset']: # For surface dset\n match = re.match(r'(.+)\\.(?:niml|1D)(?:\\.dset)?', fname)\n prefix = match.group(1)\n else: # For 3d dset\n # fstem = path.splitext(path.basename(fname))[0]\n if fname[-5:].upper() in ['.HEAD', '.BRIK']:\n fstem = fname[:-5]\n elif fname.endswith('.'):\n fstem = fname[:-1]\n else:\n fstem = fname\n prefix = fstem[:-5] if len(fstem) > 5 and fstem[-5:] in ['+orig', '+tlrc'] else fstem\n if not with_path:\n prefix = path.basename(prefix)\n return prefix\n\n\ndef get_surf_vol(suma_dir):\n '''\n Infer SUMA SurfVol filename with full path (agnostic about file type: .nii vs +orig.HEAD/BRIK).\n '''\n # TODO: SurfVol.depth.nii\n candidates = glob.glob(path.join(suma_dir, '*_SurfVol*'))\n candidates = [f for f in candidates if re.search(r'_SurfVol(?:\\.nii|\\+orig\\.HEAD)', f)]\n if len(candidates) == 0:\n raise ValueError(f'>> Cannot identify SurfVol in \"{suma_dir}\"')\n else:\n return candidates[0]\n\n\ndef get_suma_subj(suma_dir):\n '''Infer SUMA subject given path to SUMA folder.'''\n match = re.match('(.+)_SurfVol.+', path.basename(get_surf_vol(suma_dir)))\n if match:\n return match.group(1)\n else:\n raise RuntimeError(f'>> Cannot infer SUMA subject from \"{suma_dir}\"')\n\n\ndef get_surf_type(suma_dir):\n '''Infer SUMA surface mesh file type (.gii vs .asc).'''\n surf_files = [f for f in os.listdir(suma_dir) if re.match('(?:lh|rh).(?:pial|smoothwm|inflated).*', f)]\n return path.splitext(surf_files[0])[1]\n\n\nSPEC_HEMIS = ['lh', 'rh', 'both', 'mh', 'bh']\nHEMI_PATTERN = r'(?:(?<=[^a-zA-Z0-9])|^)(?:lh|rh|both|mh|bh)(?=[^a-zA-Z0-9])'\n\ndef substitute_hemi(fname, hemi='{0}'):\n return re.sub(HEMI_PATTERN, hemi, fname)\n\n\ndef get_suma_spec(suma_spec):\n '''\n Infer other spec files from one spec file (either lh.spec, rh.spec, or both.spec).\n \n Parameters\n ----------\n suma_spec : str\n Either a .spec file or the suma_dir.\n '''\n if path.isdir(suma_spec): # It is actually the `suma_dir`\n subj = get_suma_subj(suma_spec)\n return {hemi: path.join(suma_spec, f\"{subj}_{hemi}.spec\") for hemi in SPEC_HEMIS}\n else: # It is a .spec file\n spec_fmt = re.sub(f\"({'|'.join(SPEC_HEMIS)}).spec\", '{0}.spec', suma_spec)\n return {hemi: spec_fmt.format(hemi) for hemi in SPEC_HEMIS}\n\n\ndef get_suma_info(suma_dir, suma_spec=None):\n info = {}\n info['subject'] = get_suma_subj(suma_dir)\n if suma_spec is None: # Infer spec files from suma_dir\n info['spec'] = get_suma_spec(suma_dir)\n else: # Infer other spec files from one spec file\n info['spec'] = get_suma_spec(suma_spec)\n return info\n\n\ndef get_hemi(fname):\n basename = path.basename(fname)\n match = re.search(HEMI_PATTERN, basename)\n if match:\n hemi = match.group(0)\n else:\n raise ValueError(f'** ERROR: Cannot infer \"hemi\" from \"{basename}\"')\n return hemi\n\n\ndef infer_surf_dset_variants(fname, hemis=SPEC_HEMIS):\n '''\n >>> infer_surf_dset_variants('data.niml.dset')\n {'lh': 'lh.data.niml.dset', 'rh': 'rh.data.niml.dset', 'both': 'both.data.niml.dset', mh': 'mh.data.niml.dset'}\n >>> infer_surf_dset_variants('lh.data.niml.dset')\n {'lh': 'lh.data.niml.dset'}\n\n Parameters\n ----------\n fname : str, list, or dict\n '''\n if isinstance(fname, six.string_types):\n match = re.search(HEMI_PATTERN, path.basename(fname))\n if match:\n fname = {match.group(0): fname}\n else:\n out_dir, prefix, ext = split_out_file(fname, split_path=True, trailing_slash=True)\n fname = {hemi: f\"{out_dir}{hemi}.{prefix}{ext}\" for hemi in hemis}\n if not isinstance(fname, dict):\n fdict = {}\n for f in fname:\n match = re.search(HEMI_PATTERN, path.basename(f))\n if match:\n fdict[match.group(0)] = f\n else:\n raise ValueError(f'** ERROR: Cannot infer \"hemi\" from \"{path.basename(f)}\"')\n fname = fdict\n return fname\n\n\ndef get_ORIENT(fname, format='str'):\n '''\n Parameters\n ----------\n format : str, {'code', 'str', 'mat', 'sorter'}\n\n References\n ----------\n [1] https://afni.nimh.nih.gov/pub/dist/doc/program_help/README.attributes.html\n #define ORI_R2L_TYPE 0 // Right to Left\n #define ORI_L2R_TYPE 1 // Left to Right\n #define ORI_P2A_TYPE 2 // Posterior to Anterior\n #define ORI_A2P_TYPE 3 // Anterior to Posterior\n #define ORI_I2S_TYPE 4 // Inferior to Superior\n #define ORI_S2I_TYPE 5 // Superior to Inferior\n\n Thus \"0 3 4\" is standard DICOM Reference Coordinates System, i.e., RAI.\n The AFNI convention is also that R-L, A-P, and I-S are negative-to-positive, i.e., RAI.\n\n [2] https://nipy.org/nibabel/nifti_images.html\n On the other hand, NIFTI images have an affine relating the voxel coordinates \n to world coordinates in RAS+ space, or LPI in AFNI's term.\n '''\n res = check_output(['3dAttribute', 'ORIENT_SPECIFIC', fname])[-2]\n ORIENT = np.fromiter(map(int, res.split()), int)\n code2str = np.array(['R', 'L', 'P', 'A', 'I', 'S'])\n code2mat = np.array([[ 1, 0, 0],\n [-1, 0, 0],\n [ 0,-1, 0],\n [ 0, 1, 0],\n [ 0, 0, 1],\n [ 0, 0,-1]])\n code2axis = np.array([0, 0, 1, 1, 2, 2])\n if format == 'code':\n return ORIENT\n elif format == 'str':\n return ''.join(code2str[ORIENT])\n elif format == 'mat':\n return code2mat[ORIENT]\n elif format == 'sorter':\n return np.argsort(code2axis[ORIENT])\n\n\ndef get_DIMENSION(fname):\n '''\n [x, y, z, t, 0]\n '''\n res = check_output(['3dAttribute', 'DATASET_DIMENSIONS', fname])[-2]\n DIMENSION = np.fromiter(map(int, res.split()), int)\n return DIMENSION\n\n\ndef get_ORIGIN(fname):\n res = check_output(['3dAttribute', 'ORIGIN', fname])[-2]\n ORIGIN = np.fromiter(map(float, res.split()), float)\n return ORIGIN\n\n\ndef get_DELTA(fname):\n res = check_output(['3dAttribute', 'DELTA', fname])[-2]\n DELTA = np.fromiter(map(float, res.split()), float)\n return DELTA\n\n\ndef get_affine(fname):\n ORIENT = get_ORIENT(fname, format='sorter')\n ORIGIN = get_ORIGIN(fname)\n DELTA = get_DELTA(fname)\n MAT = np.c_[np.diag(DELTA), ORIGIN][ORIENT,:]\n return MAT\n\n\ndef get_affine_nifti(fname):\n MAT = np.diag([-1,-1, 1]) @ get_affine(fname)\n return MAT\n\n\ndef get_dims(fname):\n '''\n Dimensions (number of voxels) of the data matrix.\n See also: get_head_dims\n '''\n # res = check_output(['@GetAfniDims', fname])[-2] # There can be leading warnings for oblique datasets\n res = check_output(['3dinfo', '-n4', fname])[-2] # `@GetAfniDims` may not work for things like `dset.nii'[0..10]'`\n return np.int_(res.split()) # np.fromiter(map(int, res.split()), int)\n\n\ndef get_head_dims(fname):\n '''\n Dimensions (number of voxels) along R-L, A-P, I-S axes.\n See also: get_dims\n '''\n res = check_output(['3dinfo', '-orient', '-n4', fname])[-2]\n res = res.split()\n orient = res[0]\n dims = np.int_(res[1:])\n ori2ax = {'R': 0, 'L': 0, 'A': 1, 'P': 1, 'I': 2, 'S': 2}\n axes = [ori2ax[ori] for ori in orient]\n return np.r_[dims[np.argsort(axes)], dims[3]]\n\n\ndef get_head_delta(fname):\n '''\n Resolution (voxel size) along R-L, A-P, I-S axes.\n '''\n res = check_output(['3dinfo', '-orient', '-d3', fname])[-2]\n res = res.split()\n orient = res[0]\n delta = np.abs(np.float_(res[1:]))\n ori2ax = {'R': 0, 'L': 0, 'A': 1, 'P': 1, 'I': 2, 'S': 2}\n axes = [ori2ax[ori] for ori in orient]\n return delta[np.argsort(axes)]\n\n\ndef get_head_extents(fname):\n '''\n Spatial extent along R, L, A, P, I and S.\n '''\n res = check_output(['3dinfo', '-extent', fname])[-2]\n return np.float_(res.split())\n\n\ndef get_brick_labels(fname, label2index=False):\n res = check_output(['3dAttribute', 'BRICK_LABS', fname])[-2]\n labels = res.split('~')[:-1] # Each label ends with \"~\"\n if label2index:\n return {label: k for k, label in enumerate(labels)}\n else:\n return np.array(labels)\n\n\ndef set_brick_labels(fname, labels):\n check_output(['3drefit', '-relabel_all_str', ' '.join(labels), fname])\n\n\ndef get_TR(fname):\n return float(check_output(['3dinfo', '-TR', fname])[-2])\n\n\ndef get_slice_timing(fname):\n res = check_output(['3dinfo', '-slice_timing', fname])[-2]\n times = np.float_(res.split('|'))\n return times\n\n\ndef set_slice_timing(fname, times, TR):\n '''\n We have to provide a TR because we don't know whether the default value TR=1.0 is valid.\n '''\n n_slices = get_dims(fname)[2]\n assert(len(times)==n_slices)\n times_cmd = [str(t) for t in times] # This has to be provided as separate arguments\n check_output(['3drefit', '-Tslices'] + times_cmd + ['-TR', str(TR), fname])\n\n\ndef get_attribute(fname, name, type=None):\n res = check_output(['3dAttribute', name, fname])[-2]\n if type == 'int':\n return np.int_(res[:-1].split())\n elif type == 'float':\n return np.float_(res[:-1].split())\n else:\n return res[:-1]\n\n\ndef set_attribute(fname, name, value, type=None):\n values = np.atleast_1d(value)\n if type == 'str' or isinstance(value, str):\n check_output(['3drefit', '-atrstring', name, f\"{value}\", fname])\n elif type == 'int' or np.issubdtype(values.dtype, np.integer):\n check_output(['3drefit', '-atrint', name, f\"{' '.join([str(v) for v in values])}\", fname])\n elif type == 'float' or np.issubdtype(values.dtype, np.floating):\n check_output(['3drefit', '-atrfloat', name, f\"{' '.join([str(v) for v in values])}\", fname])\n\n\ndef get_nifti_field(fname, name, type=None):\n res = check_output(['nifti_tool', '-disp_hdr', '-field', name, '-infiles', fname])[-2]\n if type == 'int':\n return np.int_(res.split()[3:])\n elif type == 'float':\n return np.float_(res.split()[3:])\n else:\n return res[37:]\n\n\ndef set_nifti_field(fname, name, value, out_file=None):\n values = np.atleast_1d(value)\n check_output(['nifti_tool', '-mod_hdr', '-mod_field', name, f\"{' '.join([str(v) for v in values])}\", '-infiles', fname] \n + (['-overwrite'] if out_file is None else ['-prefix', out_file]))\n\n\ndef get_S2E_mat(fname, mat='S2E'):\n mat = {'S2E': 'S2B', 'S2B': 'S2B', 'E2S': 'B2S', 'B2S': 'B2S'}[mat]\n res = check_output(\"cat_matvec -ONELINE '{0}::ALLINEATE_MATVEC_{1}_000000'\".format(fname, mat))[-2]\n return np.float_(res.split()).reshape(3,4)\n\n\ndef generate_spec(fname, surfs, ext=None, **kwargs):\n if ext is None:\n ext = '.gii'\n defaults = dict(dict(type={'.asc': 'FS', '.gii': 'GII'}[ext], state=None, anat=None, parent=None), **kwargs)\n surfs = [dict(defaults, **({'name': surf} if isinstance(surf, six.string_types) else surf)) for surf in surfs]\n has_smoothwm = np.any([('smoothwm' in surf['name']) for surf in surfs])\n is_both = np.any([('lh' in surf['name']) for surf in surfs]) and np.any([('rh' in surf['name']) for surf in surfs])\n for surf in surfs:\n match = re.search(rf'([l|r]h)\\.(.+)\\.{ext[1:]}', surf['name'])\n surf['hemi'] = match.group(1)\n surf['surf'] = match.group(2)\n is_anat = surf['surf'] in ['pial', 'smoothwm', 'white']\n if surf['state'] is None:\n if not is_anat and is_both:\n surf['state'] = '_'.join([surf['surf'], surf['hemi']])\n else:\n surf['state'] = surf['surf']\n if surf['anat'] is None:\n surf['anat'] = 'Y' if is_anat else 'N'\n if surf['parent'] is None:\n if surf['name'] == 'smoothwm' or not has_smoothwm:\n surf['parent'] = 'SAME'\n else:\n surf['parent'] = '.'.join([surf['hemi'], 'smoothwm', ext[1:]])\n cmds = []\n for surf in surfs:\n cmds.extend(['-tsnad', surf['type'], surf['state'], surf['name'], surf['anat'], surf['parent']])\n subprocess.check_call(['quickspec', '-spec', fname, '-overwrite'] + cmds)\n\n\ndef update_afnirc(**kwargs):\n rc_file = path.expanduser('~/.afnirc')\n bak_file = path.expanduser('~/.afnirc.{0}.bak'.format(datetime.now().strftime('%Y%m%d')))\n if not path.exists(bak_file):\n shutil.copy(rc_file, bak_file)\n with open(rc_file, 'r') as fin:\n lines = fin.read().splitlines()\n updated = []\n is_managed = False\n managed_begin = '// Managed by mripy: begin'\n managed_end = '// Managed by mripy: end'\n managed = collections.OrderedDict()\n for line in lines:\n if not is_managed:\n if line == managed_begin:\n is_managed = True\n else:\n updated.append(line)\n else:\n if line == managed_end:\n is_managed = False\n else:\n match = re.search('(\\S+)\\s+=\\s+((?:.(?!//))+)(?:\\s+//\\s+(.+))?', line)\n managed[match.group(1)] = (match.group(2).strip(), match.group(3)) # key, value, comment (can be None)\n for k, v in kwargs.items():\n if not isinstance(v, tuple):\n kwargs[k] = (v, None)\n managed.update(kwargs)\n n_managed = len([v for v in managed.values() if v[0] is not None])\n if n_managed > 0:\n if updated[-1] != '':\n updated.append('')\n updated.append(managed_begin)\n for key, (value, comment) in managed.items():\n if value is not None:\n updated.append(' {0: <24} = {1}'.format(key, value) +\n ('\\t// {0}'.format(comment) if comment is not None else ''))\n if n_managed > 0:\n updated.append(managed_end)\n with open(rc_file, 'w') as fout:\n fout.write('\\n'.join(updated))\n\n\ndef add_colormap(cmap, name=None, cyclic=False, index=None, categorical=False):\n '''\n cmap : list of RGB colors | matplotlib.colors.LinearSegmentedColormap\n '''\n if name is None:\n if isinstance(cmap, mpl.colors.LinearSegmentedColormap):\n name = cmap.name\n else:\n name = 'User{0:02d}'.format(index)\n if isinstance(cmap, mpl.colors.LinearSegmentedColormap):\n cmap = plots.get_color_list(cmap)\n if index is None:\n index = 1\n # Make colormap dir\n cmap_dir = path.expanduser('~/abin/colormaps')\n if not path.exists(cmap_dir):\n os.makedirs(cmap_dir)\n # Generate palette file\n temp_file = 'colors.tmp'\n with open(temp_file, 'w') as fout:\n fout.writelines(['\\t'.join(map(str, color))+'\\n' for color in cmap])\n cmap_file = path.join(cmap_dir, '{0}.pal'.format(name))\n with open(cmap_file, 'w') as fout:\n if categorical:\n subprocess.check_call(['MakeColorMap', '-f', temp_file, '-ah', name, '-nc', str(len(cmap))], stdout=fout)\n else:\n subprocess.check_call(['MakeColorMap', '-f', temp_file, '-ah', name] +\n (['-nc', str(128), '-sl'] if cyclic else ['-nc', str(129)]), stdout=fout)\n os.remove(temp_file)\n # Update .afnirc\n update_afnirc(**{'AFNI_COLORSCALE_{0:02d}'.format(index): path.relpath(cmap_file, path.expanduser('~'))})\n\n\ndef write_colorscale_file(fname, pal_name, colors, locations=None, interp=None):\n '''\n Parameters\n ----------\n fname : `*.pal` file name\n pal_name : palette name (or title)\n colors : a list of RGB colors within [0,1]\n first color (bottom) -> last color (top)\n locations : locations of the breakpoints where colors are defined\n 0 (bottom) -> 1 (top)\n interp : 'linear'|'nearest'\n\n AFNI document says \"There are exactly 128 color locations on an AFNI colorscale.\"\n For details, see https://afni.nimh.nih.gov/pub/dist/doc/OLD/afni_colorscale.html\n But in fact, if you fill the colorscale file with a lot of colors, only the first 256 colors will be used.\n '''\n if locations is None:\n locations = np.linspace(0, 1, len(colors))\n if interp is None:\n interp = 'linear'\n cmap = interpolate.interp1d(locations, colors, kind=interp, axis=0, bounds_error=False, fill_value='extrapolate')\n clist = [mpl.colors.to_hex(color) for color in cmap(np.linspace(0, 1, 256))]\n with open(fname, 'w') as fout:\n fout.write(f\"{pal_name}\\n\")\n fout.writelines([f\"{color}\\n\" for color in reversed(clist)])\n\n\ndef parse_patch(patch):\n '''\n Notes\n -----\n 1. Each replacement is started with one or more comment lines. The last\n comment line is treated as replacement target, which may contain an\n optional replacement directive at the end:\n # This is an example <replace command=\"1\"/>\n \n Possible directives for replacing the original scripts includes:\n\n 1) command=\"n\": replace n commands\n 2) line=\"n\": replace n lines\n 3) until=\"regexp\": replace until a specific line (the regexp is the\n last line to be replaced)\n\n 2. Each replacement must end with two consecutive newlines.\n '''\n with open(patch, 'r') as fin:\n lines = fin.read().splitlines()\n replacements = []\n is_content = False\n n_newlines = 0\n for k, line in enumerate(lines):\n if is_content:\n contents.append(line)\n if line.strip() == '':\n n_newlines += 1\n if n_newlines >= 2:\n is_content = False\n else:\n n_newlines = 0\n if not is_content or k+1 == len(lines):\n for kk in range(min(2, len(contents))):\n if contents[-1] == '':\n contents.pop(-1)\n else:\n break\n contents.append('# </patch>')\n replacements.append({'target': target, 'directives': directives, 'contents': contents})\n elif line[0] == '#':\n if k+1 < len(lines) and lines[k+1][0] != '#':\n match = re.match('((?:(?!<replace).)*)(?:<replace(.*)/>)?', line)\n target = match.group(1).rstrip()\n if match.group(2) is not None:\n attributes = shlex.split(match.group(2).strip())\n directives = dict([attr.split('=') for attr in attributes])\n else:\n directives = {'command': 1}\n is_content = True\n contents = ['# <patch>']\n return replacements\n\n\ndef patch_afni_proc(original, patch, inplace=True):\n replacements = parse_patch(patch)\n n = 0\n with open(original, 'r') as fin:\n lines = fin.read().splitlines()\n patched = []\n n_to_replace = 0\n for k, line in enumerate(lines):\n if n == len(replacements):\n patched.append(line)\n else:\n replacement = replacements[n]\n if not n_to_replace:\n patched.append(line)\n match = re.search(replacement['target'], line)\n if match:\n replacement['indent'] = match.start()\n replacement['n_lines'] = six.MAXSIZE\n directives = replacement['directives']\n if 'command' in directives:\n nc = 0\n n_lines = 0\n while nc < int(directives['command']):\n n_lines += 1\n x = lines[k+n_lines].strip()\n if x != '' and x[0] != '#' and x[-1] != '\\\\':\n nc += 1\n replacement['n_lines'] = min(replacement['n_lines'], n_lines)\n if 'until' in directives:\n n_lines = 0\n while not re.match(directives['until'], lines[k+n_lines]):\n n_lines += 1\n replacement['n_lines'] = min(replacement['n_lines'], n_lines)\n if 'line' in directives:\n replacement['n_lines'] = min(replacement['n_lines'], int(directives['line']))\n n_to_replace = replacement['n_lines']\n else:\n patched.append('# ' + line)\n n_to_replace -= 1\n if n_to_replace == 0:\n for content in replacement['contents']:\n patched.append(' '*replacement['indent'] + content)\n if not inplace:\n p, f = path.split(original)\n fname = path.join(p, 'patched.'+f)\n else:\n shutil.copy(original, original+'.bak')\n fname = original\n with open(fname, 'w') as fout:\n fout.write('\\n'.join(patched))\n\n\nif __name__ == '__main__':\n pass" ]
[ [ "scipy.interpolate.interp1d", "numpy.float_", "numpy.diag", "numpy.any", "numpy.argsort", "numpy.issubdtype", "numpy.int_", "numpy.atleast_1d", "matplotlib.colors.to_hex", "numpy.array", "numpy.linspace" ] ]
animesh-007/digit-identify
[ "236befc520af08ff838dfdf2ae0392d8afb7598a" ]
[ "app.py" ]
[ "import os\r\n#Define backend as tensorflow\r\nos.environ['KERAS_BACKEND']='tensorflow'\r\n#It is important to import keras after changing backend\r\nimport keras\r\nfrom flask import Flask, render_template,request\r\nfrom scipy.misc import imsave, imread, imresize\r\nimport numpy as np\r\n#import keras.models\r\nimport re\r\n\r\nimport sys \r\nimport os\r\nsys.path.append(os.path.abspath(\"./model\"))\r\nfrom load import * \r\n\r\napp = Flask(__name__)\r\n\r\nglobal model, graph\r\n\r\nmodel, graph = init()\r\n\r\ndef convertImage(imgData1):\r\n\timgstr = re.search(r'base64,(.*)',imgData1).group(1)\r\n\t#print(imgstr)\r\n\twith open('output.png','wb') as output:\r\n\t\toutput.write(imgstr.decode('base64'))\r\n\t\r\n\r\[email protected]('/')\r\ndef index():\r\n\treturn render_template(\"index.html\")\r\n\r\[email protected]('/predict/',methods=['GET','POST'])\r\ndef predict():\r\n\timgData = request.get_data()\r\n\r\n\tconvertImage(imgData)\r\n\tprint(\"debug\")\r\n\r\n\tx = imread('output.png',mode='L')\r\n\tx = np.invert(x)\r\n\tx = imresize(x,(28,28))\r\n\tx = x.reshape(1,28,28,1)\r\n\r\n\tprint(\"debug2\")\r\n\twith graph.as_default():\r\n\t\tout = model.predict(x)\r\n\t\tprint(out)\r\n\t\tprint(np.argmax(out,axis=1))\r\n\t\tprint(\"debug3\")\r\n\t\tresponse = np.array_str(np.argmax(out,axis=1))\r\n\t\treturn response\t\r\n\t\r\n\r\nif __name__ == \"__main__\":\r\n\t#decide what port to run the app in\r\n\t#port = int(os.environ.get('PORT', 5000))\r\n\r\n\t#run the app locally on the givn port\r\n\tapp.run(host='127.0.0.1', port=1245)\r\n\r\n" ]
[ [ "numpy.invert", "scipy.misc.imresize", "scipy.misc.imread", "numpy.argmax" ] ]
rozlana-g/FEDOT
[ "a909d6c0ef481cc1cf7a5f10f7b1292d8d2def5c" ]
[ "test/unit/data/test_data.py" ]
[ "import os\nfrom copy import deepcopy\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom sklearn.datasets import load_iris\n\nfrom fedot.core.data.data import InputData, OutputData\nfrom fedot.core.data.multi_modal import MultiModalData\nfrom fedot.core.repository.dataset_types import DataTypesEnum\nfrom fedot.core.repository.tasks import Task, TaskTypesEnum\nfrom fedot.core.utils import fedot_project_root\nfrom test.unit.tasks.test_classification import get_image_classification_data\n\n\[email protected]()\ndef data_setup() -> InputData:\n predictors, response = load_iris(return_X_y=True)\n np.random.seed(1)\n np.random.shuffle(predictors)\n np.random.shuffle(response)\n predictors = predictors[:100]\n response = response[:100]\n data = InputData(features=predictors, target=response, idx=np.arange(0, 100),\n task=Task(TaskTypesEnum.classification),\n data_type=DataTypesEnum.table)\n return data\n\n\[email protected]()\ndef output_dataset():\n task = Task(TaskTypesEnum.classification)\n\n samples = 1000\n x = 10.0 * np.random.rand(samples, ) - 5.0\n x = np.expand_dims(x, axis=1)\n threshold = 0.5\n y = 1.0 / (1.0 + np.exp(np.power(x, -1.0)))\n classes = np.array([0.0 if val <= threshold else 1.0 for val in y])\n classes = np.expand_dims(classes, axis=1)\n data = OutputData(idx=np.arange(0, 100), features=x, predict=classes,\n task=task, data_type=DataTypesEnum.table)\n\n return data\n\n\ndef test_data_subset_correct(data_setup):\n subset_size = 50\n subset = data_setup.subset(0, subset_size - 1)\n\n assert len(subset.idx) == subset_size\n assert len(subset.features) == subset_size\n assert len(subset.target) == subset_size\n\n\ndef test_data_subset_incorrect(data_setup):\n subset_size = 105\n with pytest.raises(ValueError):\n assert data_setup.subset(0, subset_size)\n\n with pytest.raises(ValueError):\n assert data_setup.subset(-1, subset_size)\n with pytest.raises(ValueError):\n assert data_setup.subset(-1, -1)\n\n\ndef test_data_from_csv():\n test_file_path = str(os.path.dirname(__file__))\n file = '../../data/simple_classification.csv'\n task = Task(TaskTypesEnum.classification)\n df = pd.read_csv(os.path.join(test_file_path, file))\n data_array = np.array(df).T\n features = data_array[1:-1].T\n target = data_array[-1]\n idx = data_array[0]\n expected_features = InputData(features=features, target=target,\n idx=idx,\n task=task,\n data_type=DataTypesEnum.table).features\n actual_features = InputData.from_csv(\n os.path.join(test_file_path, file)).features\n assert np.array_equal(expected_features, actual_features)\n\n\ndef test_with_custom_target():\n test_file_path = str(os.path.dirname(__file__))\n file = '../../data/simple_classification.csv'\n file_custom = '../../data/simple_classification_with_custom_target.csv'\n\n file_data = InputData.from_csv(\n os.path.join(test_file_path, file))\n\n expected_features = file_data.features\n expected_target = file_data.target\n\n custom_file_data = InputData.from_csv(\n os.path.join(test_file_path, file_custom), delimiter=';')\n actual_features = custom_file_data.features\n actual_target = custom_file_data.target\n\n assert not np.array_equal(expected_features, actual_features)\n assert not np.array_equal(expected_target, actual_target)\n\n custom_file_data = InputData.from_csv(\n os.path.join(test_file_path, file_custom), delimiter=';',\n columns_to_drop=['redundant'], target_columns='custom_target')\n\n actual_features = custom_file_data.features\n actual_target = custom_file_data.target\n\n assert np.array_equal(expected_features, actual_features)\n assert np.array_equal(expected_target, actual_target)\n\n\ndef test_data_from_predictions(output_dataset):\n data_1 = output_dataset\n data_2 = output_dataset\n data_3 = output_dataset\n new_input_data = InputData.from_predictions(outputs=[data_1, data_2, data_3])\n assert new_input_data.features.all() == np.array(\n [data_1.predict, data_2.predict, data_3.predict]).all()\n\n\ndef test_data_from_image():\n _, _, dataset_to_validate = get_image_classification_data()\n\n assert dataset_to_validate.data_type == DataTypesEnum.image\n assert type(dataset_to_validate.features) == np.ndarray\n assert type(dataset_to_validate.target) == np.ndarray\n\n\ndef test_data_from_json():\n # several features\n files_path = os.path.join('test', 'data', 'multi_modal')\n path = os.path.join(str(fedot_project_root()), files_path)\n data = InputData.from_json_files(path, fields_to_use=['votes', 'year'],\n label='rating', task=Task(TaskTypesEnum.regression))\n assert data.features.shape[1] == 2 # check there is two features\n assert len(data.target) == data.features.shape[0] == len(data.idx)\n\n # single feature\n data = InputData.from_json_files(path, fields_to_use=['votes'],\n label='rating', task=Task(TaskTypesEnum.regression))\n assert len(data.features.shape) == 1 # check there is one feature\n assert len(data.target) == len(data.features) == len(data.idx)\n\n\ndef test_multi_modal_data():\n num_samples = 5\n target = np.asarray([0, 0, 1, 0, 1])\n img_data = InputData(idx=range(num_samples),\n features=None, # in test the real data is not passed\n target=target,\n data_type=DataTypesEnum.text,\n task=Task(TaskTypesEnum.classification))\n tbl_data = InputData(idx=range(num_samples),\n features=None, # in test the real data is not passed\n target=target,\n data_type=DataTypesEnum.table,\n task=Task(TaskTypesEnum.classification))\n\n multi_modal = MultiModalData({\n 'data_source_img': img_data,\n 'data_source_table': tbl_data,\n })\n\n assert multi_modal.task.task_type == TaskTypesEnum.classification\n assert len(multi_modal.idx) == 5\n assert multi_modal.num_classes == 2\n assert np.array_equal(multi_modal.target, target)\n\n\ndef test_target_data_from_csv_correct():\n \"\"\" Function tests two ways of processing target columns in \"from_csv\"\n method\n \"\"\"\n test_file_path = str(os.path.dirname(__file__))\n file = '../../data/multi_target_sample.csv'\n path = os.path.join(test_file_path, file)\n task = Task(TaskTypesEnum.regression)\n\n # Process one column\n target_column = '1_day'\n one_column_data = InputData.from_csv(path, target_columns=target_column,\n columns_to_drop=['date'], task=task)\n\n # Process multiple target columns\n target_columns = ['1_day', '2_day', '3_day', '4_day', '5_day', '6_day', '7_day']\n seven_columns_data = InputData.from_csv(path, target_columns=target_columns,\n columns_to_drop=['date'], task=task)\n\n assert one_column_data.target.shape == (499, 1)\n assert seven_columns_data.target.shape == (499, 7)\n\n\ndef test_table_data_shuffle():\n test_file_path = str(os.path.dirname(__file__))\n file = '../../data/simple_classification.csv'\n\n data = InputData.from_csv(os.path.join(test_file_path, file))\n shuffled_data = deepcopy(data)\n shuffled_data.shuffle()\n\n assert not np.array_equal(data.idx, shuffled_data.idx)\n assert not np.array_equal(data.features, shuffled_data.features)\n assert not np.array_equal(data.target, shuffled_data.target)\n\n assert np.array_equal(data.idx, sorted(shuffled_data.idx))\n" ]
[ [ "numpy.random.shuffle", "numpy.random.seed", "numpy.asarray", "numpy.arange", "numpy.expand_dims", "numpy.power", "numpy.random.rand", "numpy.array_equal", "numpy.array", "sklearn.datasets.load_iris" ] ]
evelkey/vahun
[ "a7967ffd9d8e27911888057b4906fc4221c2a6fe" ]
[ "vahun_cmd.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nimport tensorflow as tf\nimport sys\nimport numpy as np\nfrom vahun.corpus import Corpus\nfrom vahun.genetic import evolution\nfrom vahun.genetic import experiment\nfrom vahun.tools import Timer\nfrom vahun.tools import explog\nfrom vahun.autoencoder import Autoencoder_ffnn\nfrom vahun.variational_autoencoder import Variational_autoencoder\nfrom vahun.tools import show_performance\nfrom vahun.tools import show_reconstruction\nimport argparse\n\n\n\ndef main(args=None):\n encode=args.encoding_dim\n dictsize=args.corp_len\n popsize=args.pop_size\n corp_path=args.corp_path\n\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n corp=Corpus(corpus_path=args.corp_path,language=\"Hun\",size=dictsize,encoding_len=args.feature_len,corpus_stream=None,printer=False)\n all_features=corp.featurize_data_charlevel_onehot(corp.hun_lower_unique)\n train=all_features[0:int(len(all_features)*0.8)]\n test=all_features[int(len(all_features)*0.8):len(all_features)]\n x_train = train.reshape((len(train), np.prod(train.shape[1:])))\n x_test = test.reshape((len(test), np.prod(test.shape[1:])))\n \n \n testcorp=Corpus(corpus_path=args.corp_path,language=\"Hun\",size=1000000,encoding_len=args.feature_len,corpus_stream=args.infile,printer=False)\n testdata=corp.featurize_data_charlevel_onehot(corp.hun_lower_unique)\n testdata= testdata.reshape((len(testdata), np.prod(testdata.shape[1:])))\n \n logger=explog(encoder_type=\"Demo_\"+str(encode),\n encoding_dim=encode,feature_len=10,\n lang=\"Hun\",unique_words=0,\n name=\"auto_demo_uni\"+str(encode),population_size=popsize,\n words=len(corp.hun_lower_unique))\n\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config)\n\n exp=experiment(encoded_width=10,layermax=10,layermin=2,maxw=10,minw=3,out_dim=380)\n #exp.weights=[348, 254, 10, 254, 348, 360]\n exp.weights=[args.encoding_dim, 380]\n exp.len=len(exp.weights)\n \n if args.encoder_type==0:\n encoder=Autoencoder_ffnn(experiment=exp,\n logger=logger,tf_session=sess,\n inputdim=380,\n layerlist=exp.weights,\n encode_index=int(exp.len/2),\n optimizer =tf.train.AdamOptimizer(learning_rate = 0.001),\n nonlinear=tf.sigmoid)\n else:\n encoder=Variational_autoencoder(logger=logger,tf_session=sess,\n inputdim=380,\n encoding_size=args.encoding_dim,\n optimizer =tf.train.AdamOptimizer(learning_rate = 0.001),\n nonlinear=tf.sigmoid)\n encoder.train(x_train,x_test,512,80)\n show_reconstruction(encoder,testdata,corp,length=0)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Autoencoder command line runner')\n parser.add_argument(\"--encoder_type\", dest=\"encoder_type\", default=0, type=int, help=\"0=fully connected ffnn autoencoder, 1=variational ffnn autoencoder\")\n parser.add_argument('--corp_path', dest='corp_path', type=str,default='/mnt/permanent/Language/Hungarian/Corp/Webkorpusz/webkorpusz.wpl',help='Path to the Corpus.')\n parser.add_argument(\"--encoding_dim\", dest=\"encoding_dim\", default=160, type=int, help='Encoding dimension')\n parser.add_argument(\"--corp_len\", dest=\"corp_len\", default=2000000, type=int, help=\"Words to read from corpus\")\n parser.add_argument(\"--feature_len\", dest=\"feature_len\", default=10, type=int, help=\"Feature size\")\n parser.add_argument('--infile', type=argparse.FileType('r'),default='-',help=\"Input stream\")\n \n args = parser.parse_args()\n\n main(args)" ]
[ [ "tensorflow.train.AdamOptimizer", "tensorflow.ConfigProto", "tensorflow.Session", "numpy.prod" ] ]
arc144/siim-pneumothorax
[ "98fdb1fe08e9c001e0191d5024ba6c56ec82a9c8" ]
[ "See/Model_001_f00/submit.py" ]
[ "import pandas as pd\nfrom zipfile import ZipFile\nimport torch as th\nimport cv2\nimport numpy as np\nimport os\nfrom glob import glob\nimport pydicom\nfrom matplotlib import pyplot as plt\nfrom segmentation_model import FPNSegmentation\n\n\ndef main():\n train_image_fns = sorted(glob(os.path.join(\n 'dicom-images-train', '*/*/*.dcm')))\n m = {os.path.basename(fn): fn for fn in train_image_fns}\n ref_file = 'Model_000_f00/f00-PREDS_VAL.zip'\n slug = 'r50d'\n weight = 'Model_000_f00/[email protected]'\n model = FPNSegmentation(slug)\n model.load_state_dict(th.load(weight))\n model = model.cuda()\n model.eval()\n\n with ZipFile(ref_file) as f:\n for fn in f.namelist()[::10]:\n path = m[fn.replace('.png', '.dcm')]\n img = pydicom.read_file(path).pixel_array\n # pimg = cv2.resize(img, (640, 640), interpolation=cv2.INTER_CUBIC)\n pimg = img.copy()\n X = th.from_numpy(pimg).unsqueeze(0).unsqueeze(0)\n with th.no_grad():\n X = X.cuda().float()\n y_pred = model(X).cpu().numpy().squeeze()\n y_pred_flip = th.flip(model(th.flip(X, (-1, ))),\n (-1, )).cpu().numpy().squeeze()\n y_pred = 0.5 * (y_pred_flip + y_pred)\n y_pred = (y_pred * 255).astype(np.uint8)\n with f.open(fn) as h:\n pred = cv2.imdecode(np.frombuffer(h.read(), 'uint8'), 0)\n\n diff = y_pred != pred\n print(\"DIFF: \", diff.sum())\n plt.subplot(2, 2, 1)\n plt.imshow(img)\n plt.subplot(2, 2, 2)\n plt.imshow(y_pred)\n plt.subplot(2, 2, 3)\n plt.imshow(pred)\n plt.subplot(2, 2, 4)\n plt.imshow(diff)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "torch.load", "torch.flip", "torch.no_grad", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "matplotlib.pyplot.imshow", "torch.from_numpy" ] ]
Gavin-Hoang/oneflow
[ "320038ff5efd948516f7259442190f9b31f75027" ]
[ "oneflow/python/test/ops/test_image_decode.py" ]
[ "\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport numpy as np\nimport oneflow as flow\nfrom PIL import Image\nimport oneflow.typing as oft\n\n\ndef _of_image_decode(images):\n image_files = [open(im, \"rb\") for im in images]\n images_bytes = [imf.read() for imf in image_files]\n static_shape = (len(images_bytes), max([len(bys) for bys in images_bytes]))\n for imf in image_files:\n imf.close()\n\n flow.clear_default_session()\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float)\n func_config.default_logical_view(flow.scope.mirrored_view())\n\n @flow.global_function(func_config)\n def image_decode_job(\n images_def: oft.ListListNumpy.Placeholder(shape=static_shape, dtype=flow.int8)\n ):\n images_buffer = flow.tensor_list_to_tensor_buffer(images_def)\n decoded_images_buffer = flow.image_decode(images_buffer)\n return flow.tensor_buffer_to_tensor_list(\n decoded_images_buffer, shape=(640, 640, 3), dtype=flow.uint8\n )\n\n images_np_arr = [\n np.frombuffer(bys, dtype=np.byte).reshape(1, -1) for bys in images_bytes\n ]\n decoded_images = image_decode_job([images_np_arr]).get().numpy_lists()\n return decoded_images[0]\n\n\ndef _compare_jpg_decode_with_pil(test_case, images, print_debug_info=False):\n r\"\"\"\n The jpg image's decoded results with opencv and pil image are slightly different,\n their green channels have difference of 1.\n \"\"\"\n of_decoded_images = _of_image_decode(images)\n pil_images = [Image.open(image) for image in images]\n # convert image to BGR\n pil_decoded_images = [np.array(image)[:, :, ::-1] for image in pil_images]\n\n for of_decoded_image, pil_decoded_image in zip(\n of_decoded_images, pil_decoded_images\n ):\n of_decoded_image = of_decoded_image.squeeze()\n test_case.assertTrue(len(of_decoded_image.shape) == 3)\n test_case.assertTrue(len(pil_decoded_image.shape) == 3)\n\n diff = of_decoded_image - pil_decoded_image\n diff_index = np.where(diff != 0)\n diff_abs_values = diff[diff_index]\n\n if print_debug_info:\n print(\"of_decoded_image:\\n\", of_decoded_image, of_decoded_image.shape)\n print(\"pil_decoded_image:\\n\", pil_decoded_image, pil_decoded_image.shape)\n print(\"diff_index:\\n\", diff_index)\n print(\"diff_abs_values:\\n\", diff_abs_values)\n print(\n \"of_decoded_image diff:\\n\",\n of_decoded_image[diff_index[0], diff_index[1]],\n )\n print(\n \"pil_decoded_image diff:\\n\",\n pil_decoded_image[diff_index[0], diff_index[1]],\n )\n\n # only green channel has difference of 1\n test_case.assertTrue(np.all(diff_index[-1] == 1))\n test_case.assertTrue(np.all(diff_abs_values == 1))\n\n\ndef test_image_decode(test_case):\n _compare_jpg_decode_with_pil(\n test_case,\n [\n \"/dataset/mscoco_2017/val2017/000000000139.jpg\",\n \"/dataset/mscoco_2017/val2017/000000000632.jpg\",\n ],\n # True,\n )\n" ]
[ [ "numpy.array", "numpy.where", "numpy.all", "numpy.frombuffer" ] ]
dutxubo/mmdetection
[ "607d2fc0bdff5a8f07e6a92da899505bd083dfc5" ]
[ "mmdet/models/bbox_heads/bbox_head.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.modules.utils import _pair\n\nfrom mmdet.core import (auto_fp16, bbox_target, delta2bbox, force_fp32,\n multiclass_nms)\nfrom ..builder import build_loss\nfrom ..losses import accuracy\nfrom ..registry import HEADS\nimport numpy as np\n\[email protected]_module\nclass BBoxHead(nn.Module):\n \"\"\"Simplest RoI head, with only two fc layers for classification and\n regression respectively\"\"\"\n\n def __init__(self,\n with_avg_pool=False,\n with_cls=True,\n with_reg=True,\n roi_feat_size=7,\n in_channels=256,\n num_classes=81,\n target_means=[0., 0., 0., 0.],\n target_stds=[0.1, 0.1, 0.2, 0.2],\n reg_class_agnostic=False,\n loss_cls=dict(\n type='CrossEntropyLoss',\n use_sigmoid=False,\n loss_weight=1.0),\n loss_bbox=dict(\n type='SmoothL1Loss', beta=1.0, loss_weight=1.0)):\n super(BBoxHead, self).__init__()\n assert with_cls or with_reg\n self.with_avg_pool = with_avg_pool\n self.with_cls = with_cls\n self.with_reg = with_reg\n self.roi_feat_size = _pair(roi_feat_size)\n self.roi_feat_area = self.roi_feat_size[0] * self.roi_feat_size[1]\n self.in_channels = in_channels\n self.num_classes = num_classes\n self.target_means = target_means\n self.target_stds = target_stds\n self.reg_class_agnostic = reg_class_agnostic\n self.fp16_enabled = False\n\n self.loss_cls = build_loss(loss_cls)\n self.loss_bbox = build_loss(loss_bbox)\n\n in_channels = self.in_channels\n if self.with_avg_pool:\n self.avg_pool = nn.AvgPool2d(self.roi_feat_size)\n else:\n in_channels *= self.roi_feat_area\n if self.with_cls:\n self.fc_cls = nn.Linear(in_channels, num_classes)\n if self.with_reg:\n out_dim_reg = 4 if reg_class_agnostic else 4 * num_classes\n self.fc_reg = nn.Linear(in_channels, out_dim_reg)\n self.debug_imgs = None\n\n def init_weights(self):\n # conv layers are already initialized by ConvModule\n if self.with_cls:\n nn.init.normal_(self.fc_cls.weight, 0, 0.01)\n nn.init.constant_(self.fc_cls.bias, 0)\n if self.with_reg:\n nn.init.normal_(self.fc_reg.weight, 0, 0.001)\n nn.init.constant_(self.fc_reg.bias, 0)\n\n @auto_fp16()\n def forward(self, x):\n if self.with_avg_pool:\n x = self.avg_pool(x)\n x = x.view(x.size(0), -1)\n cls_score = self.fc_cls(x) if self.with_cls else None\n bbox_pred = self.fc_reg(x) if self.with_reg else None\n return cls_score, bbox_pred\n\n def get_target(self, sampling_results, gt_bboxes, gt_labels,\n rcnn_train_cfg):\n pos_proposals = [res.pos_bboxes for res in sampling_results]\n neg_proposals = [res.neg_bboxes for res in sampling_results]\n pos_gt_bboxes = [res.pos_gt_bboxes for res in sampling_results]\n pos_gt_labels = [res.pos_gt_labels for res in sampling_results]\n reg_classes = 1 if self.reg_class_agnostic else self.num_classes\n cls_reg_targets = bbox_target(\n pos_proposals,\n neg_proposals,\n pos_gt_bboxes,\n pos_gt_labels,\n rcnn_train_cfg,\n reg_classes,\n target_means=self.target_means,\n target_stds=self.target_stds)\n return cls_reg_targets\n\n @force_fp32(apply_to=('cls_score', 'bbox_pred'))\n def loss(self,\n cls_score,\n bbox_pred,\n labels,\n label_weights,\n bbox_targets,\n bbox_weights,\n reduction_override=None):\n losses = dict()\n if cls_score is not None:\n avg_factor = max(torch.sum(label_weights > 0).float().item(), 1.)\n\n if cls_score.numel() > 0:\n losses['loss_cls'] = self.loss_cls(\n cls_score,\n labels,\n label_weights,\n avg_factor=avg_factor,\n reduction_override=reduction_override)\n losses['acc'] = accuracy(cls_score, labels)\n if bbox_pred is not None:\n pos_inds = labels > 0\n if pos_inds.any():\n if self.reg_class_agnostic:\n pos_bbox_pred = bbox_pred.view(\n bbox_pred.size(0), 4)[pos_inds.type(torch.bool)]\n else:\n pos_bbox_pred = bbox_pred.view(\n bbox_pred.size(0), -1,\n 4)[pos_inds.type(torch.bool),\n labels[pos_inds.type(torch.bool)]]\n losses['loss_bbox'] = self.loss_bbox(\n pos_bbox_pred,\n bbox_targets[pos_inds.type(torch.bool)],\n bbox_weights[pos_inds.type(torch.bool)],\n avg_factor=bbox_targets.size(0),\n reduction_override=reduction_override)\n return losses\n\n @force_fp32(apply_to=('cls_score', 'bbox_pred'))\n def get_det_bboxes(self,\n rois,\n cls_score,\n bbox_pred,\n img_shape,\n scale_factor,\n rescale=False,\n cfg=None):\n if isinstance(cls_score, list):\n cls_score = sum(cls_score) / float(len(cls_score))\n scores = F.softmax(cls_score, dim=1) if cls_score is not None else None\n\n if bbox_pred is not None:\n bboxes = delta2bbox(rois[:, 1:], bbox_pred, self.target_means,\n self.target_stds, img_shape)\n else:\n bboxes = rois[:, 1:].clone()\n if img_shape is not None:\n bboxes[:, [0, 2]].clamp_(min=0, max=img_shape[1] - 1)\n bboxes[:, [1, 3]].clamp_(min=0, max=img_shape[0] - 1)\n\n if rescale:\n if isinstance(scale_factor, float):\n bboxes /= scale_factor\n elif isinstance(scale_factor, torch.Tensor):\n scale_factor = scale_factor.to(bboxes.device)\n bboxes = (bboxes.view(bboxes.size(0), -1, 4) /\n scale_factor).view(bboxes.size()[0], -1)\n else:\n scale_factor = torch.from_numpy(scale_factor).to(bboxes.device)\n bboxes = (bboxes.view(bboxes.size(0), -1, 4) /\n scale_factor).view(bboxes.size()[0], -1)\n\n if cfg is None:\n return bboxes, scores\n else:\n det_bboxes, det_labels = multiclass_nms(bboxes, scores,\n cfg.score_thr, cfg.nms,\n cfg.max_per_img)\n\n return det_bboxes, det_labels\n\n @force_fp32(apply_to=('bbox_preds', ))\n def refine_bboxes(self, rois, labels, bbox_preds, pos_is_gts, img_metas):\n \"\"\"Refine bboxes during training.\n\n Args:\n rois (Tensor): Shape (n*bs, 5), where n is image number per GPU,\n and bs is the sampled RoIs per image. The first column is\n the image id and the next 4 columns are x1, y1, x2, y2.\n labels (Tensor): Shape (n*bs, ).\n bbox_preds (Tensor): Shape (n*bs, 4) or (n*bs, 4*#class).\n pos_is_gts (list[Tensor]): Flags indicating if each positive bbox\n is a gt bbox.\n img_metas (list[dict]): Meta info of each image.\n\n Returns:\n list[Tensor]: Refined bboxes of each image in a mini-batch.\n\n Example:\n >>> # xdoctest: +REQUIRES(module:kwarray)\n >>> import kwarray\n >>> import numpy as np\n >>> from mmdet.core.bbox.demodata import random_boxes\n >>> self = BBoxHead(reg_class_agnostic=True)\n >>> n_roi = 2\n >>> n_img = 4\n >>> scale = 512\n >>> rng = np.random.RandomState(0)\n >>> img_metas = [{'img_shape': (scale, scale)}\n ... for _ in range(n_img)]\n >>> # Create rois in the expected format\n >>> roi_boxes = random_boxes(n_roi, scale=scale, rng=rng)\n >>> img_ids = torch.randint(0, n_img, (n_roi,))\n >>> img_ids = img_ids.float()\n >>> rois = torch.cat([img_ids[:, None], roi_boxes], dim=1)\n >>> # Create other args\n >>> labels = torch.randint(0, 2, (n_roi,)).long()\n >>> bbox_preds = random_boxes(n_roi, scale=scale, rng=rng)\n >>> # For each image, pretend random positive boxes are gts\n >>> is_label_pos = (labels.numpy() > 0).astype(np.int)\n >>> lbl_per_img = kwarray.group_items(is_label_pos,\n ... img_ids.numpy())\n >>> pos_per_img = [sum(lbl_per_img.get(gid, []))\n ... for gid in range(n_img)]\n >>> pos_is_gts = [\n >>> torch.randint(0, 2, (npos,)).byte().sort(\n >>> descending=True)[0]\n >>> for npos in pos_per_img\n >>> ]\n >>> bboxes_list = self.refine_bboxes(rois, labels, bbox_preds,\n >>> pos_is_gts, img_metas)\n >>> print(bboxes_list)\n \"\"\"\n img_ids = rois[:, 0].long().unique(sorted=True)\n assert img_ids.numel() <= len(img_metas)\n\n bboxes_list = []\n for i in range(len(img_metas)):\n inds = torch.nonzero(rois[:, 0] == i).squeeze(dim=1)\n num_rois = inds.numel()\n\n bboxes_ = rois[inds, 1:]\n label_ = labels[inds]\n bbox_pred_ = bbox_preds[inds]\n img_meta_ = img_metas[i]\n pos_is_gts_ = pos_is_gts[i]\n\n bboxes = self.regress_by_class(bboxes_, label_, bbox_pred_,\n img_meta_)\n\n # filter gt bboxes\n pos_keep = 1 - pos_is_gts_\n keep_inds = pos_is_gts_.new_ones(num_rois)\n keep_inds[:len(pos_is_gts_)] = pos_keep\n\n bboxes_list.append(bboxes[keep_inds.type(torch.bool)])\n\n return bboxes_list\n\n @force_fp32(apply_to=('bbox_pred', ))\n def regress_by_class(self, rois, label, bbox_pred, img_meta):\n \"\"\"Regress the bbox for the predicted class. Used in Cascade R-CNN.\n\n Args:\n rois (Tensor): shape (n, 4) or (n, 5)\n label (Tensor): shape (n, )\n bbox_pred (Tensor): shape (n, 4*(#class+1)) or (n, 4)\n img_meta (dict): Image meta info.\n\n Returns:\n Tensor: Regressed bboxes, the same shape as input rois.\n \"\"\"\n assert rois.size(1) == 4 or rois.size(1) == 5, repr(rois.shape)\n\n if not self.reg_class_agnostic:\n label = label * 4\n inds = torch.stack((label, label + 1, label + 2, label + 3), 1)\n bbox_pred = torch.gather(bbox_pred, 1, inds)\n assert bbox_pred.size(1) == 4\n\n if rois.size(1) == 4:\n new_rois = delta2bbox(rois, bbox_pred, self.target_means,\n self.target_stds, img_meta['img_shape'])\n else:\n bboxes = delta2bbox(rois[:, 1:], bbox_pred, self.target_means,\n self.target_stds, img_meta['img_shape'])\n new_rois = torch.cat((rois[:, [0]], bboxes), dim=1)\n\n return new_rois\n" ]
[ [ "torch.sum", "torch.stack", "torch.nn.Linear", "torch.nonzero", "torch.nn.init.constant_", "torch.nn.functional.softmax", "torch.nn.init.normal_", "torch.gather", "torch.from_numpy", "torch.nn.AvgPool2d", "torch.cat", "torch.nn.modules.utils._pair" ] ]
ITWSDataScience/EducationFundingAnalysisInCaliforniaGroup3Fall2021
[ "1c7fb5265fb0a354c2a8a438fbe00f073667c397" ]
[ "data_manipulation.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"Data Manipulation\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n https://colab.research.google.com/drive/1dnbNHRyDzukEq2IVv2Bx2tdzVEbLZJc0\n\"\"\"\n\nimport pandas as pd\n\ndf1 = pd.read_csv(\"district_school_data.csv\")\ndf2 = pd.read_csv(\"district_expense_data.csv\")\nd = {'District': [], 'County': [], 'Students':[], 'Graduation Rate':[], 'Cost':[]}\ndf3 = pd.DataFrame(data=d)\n\nfor i1, row1 in df1.iterrows():\n for i2, row2 in df2.iterrows():\n if row1['District'] == row2['DISTRICT']:\n dprime = {'District': [row1['District']], 'County': [row1['County']], 'Students':[row1['Students']], 'Graduation Rate':[row1['Grad Rate']], 'Cost':[row2[' EDP 365 ']]}\n df4 = pd.DataFrame(data=dprime)\n df3 = df3.append(df4)\ndf3.to_csv(\"district_data.csv\")\n\nprint(len(df3))\n\nprint(df3)" ]
[ [ "pandas.read_csv", "pandas.DataFrame" ] ]
JarnoRFB/statsmodels
[ "9913b6a4f0243f94a6331c90a3951849f06720f7" ]
[ "statsmodels/tsa/statespace/tests/test_options.py" ]
[ "\"\"\"\nTests for setting options in KalmanFilter, KalmanSmoother, SimulationSmoother\n\n(does not test the filtering, smoothing, or simulation smoothing for each\noption)\n\nAuthor: Chad Fulton\nLicense: Simplified-BSD\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\n\nimport numpy as np\nfrom statsmodels.tsa.statespace.kalman_filter import (\n FILTER_CONVENTIONAL,\n FILTER_EXACT_INITIAL,\n FILTER_AUGMENTED,\n FILTER_SQUARE_ROOT,\n FILTER_UNIVARIATE,\n FILTER_COLLAPSED,\n FILTER_EXTENDED,\n FILTER_UNSCENTED,\n\n INVERT_UNIVARIATE,\n SOLVE_LU,\n INVERT_LU,\n SOLVE_CHOLESKY,\n INVERT_CHOLESKY,\n\n STABILITY_FORCE_SYMMETRY,\n\n MEMORY_STORE_ALL,\n MEMORY_NO_FORECAST,\n MEMORY_NO_PREDICTED,\n MEMORY_NO_FILTERED,\n MEMORY_NO_LIKELIHOOD,\n MEMORY_NO_GAIN,\n MEMORY_NO_SMOOTHING,\n MEMORY_NO_STD_FORECAST,\n MEMORY_CONSERVE\n)\nfrom statsmodels.tsa.statespace.kalman_smoother import (\n SMOOTHER_STATE,\n SMOOTHER_STATE_COV,\n SMOOTHER_STATE_AUTOCOV,\n SMOOTHER_DISTURBANCE,\n SMOOTHER_DISTURBANCE_COV,\n SMOOTHER_ALL\n)\nfrom statsmodels.tsa.statespace.simulation_smoother import (\n SimulationSmoother,\n SIMULATION_STATE,\n SIMULATION_DISTURBANCE,\n SIMULATION_ALL\n)\nfrom numpy.testing import assert_equal\n\n\nclass Options(object):\n @classmethod\n def setup_class(cls, *args, **kwargs):\n\n # Dummy data\n endog = np.arange(10)\n k_states = 1\n\n cls.model = SimulationSmoother(k_endog=1, k_states=k_states, *args,\n **kwargs)\n cls.model.bind(endog)\n\n\nclass TestOptions(Options):\n def test_filter_methods(self):\n model = self.model\n\n # TODO test FilterResults for accurante boolean versions of options\n # Clear the filter method\n model.filter_method = 0\n\n # Try setting via boolean\n model.filter_conventional = True\n assert_equal(model.filter_method, FILTER_CONVENTIONAL)\n\n model.filter_collapsed = True\n assert_equal(model.filter_method, FILTER_CONVENTIONAL | FILTER_COLLAPSED)\n model.filter_conventional = False\n assert_equal(model.filter_method, FILTER_COLLAPSED)\n\n # Try setting directly via method\n model.set_filter_method(FILTER_AUGMENTED)\n assert_equal(model.filter_method, FILTER_AUGMENTED)\n\n # Try setting via boolean via method\n model.set_filter_method(filter_conventional=True, filter_augmented=False)\n assert_equal(model.filter_method, FILTER_CONVENTIONAL)\n\n # Try setting and unsetting all\n model.filter_method = 0\n for name in model.filter_methods:\n setattr(model, name, True)\n assert_equal(\n model.filter_method,\n FILTER_CONVENTIONAL | FILTER_EXACT_INITIAL | FILTER_AUGMENTED |\n FILTER_SQUARE_ROOT | FILTER_UNIVARIATE | FILTER_COLLAPSED |\n FILTER_EXTENDED | FILTER_UNSCENTED\n )\n for name in model.filter_methods:\n setattr(model, name, False)\n assert_equal(model.filter_method, 0)\n\n def test_inversion_methods(self):\n model = self.model\n\n # Clear the inversion method\n model.inversion_method = 0\n\n # Try setting via boolean\n model.invert_univariate = True\n assert_equal(model.inversion_method, INVERT_UNIVARIATE)\n model.invert_cholesky = True\n assert_equal(model.inversion_method, INVERT_UNIVARIATE | INVERT_CHOLESKY)\n model.invert_univariate = False\n assert_equal(model.inversion_method, INVERT_CHOLESKY)\n\n # Try setting directly via method\n model.set_inversion_method(INVERT_LU)\n assert_equal(model.inversion_method, INVERT_LU)\n\n # Try setting via boolean via method\n model.set_inversion_method(invert_cholesky=True, invert_univariate=True, invert_lu=False)\n assert_equal(model.inversion_method, INVERT_UNIVARIATE | INVERT_CHOLESKY)\n\n # Try setting and unsetting all\n model.inversion_method = 0\n for name in model.inversion_methods:\n setattr(model, name, True)\n assert_equal(\n model.inversion_method,\n INVERT_UNIVARIATE | SOLVE_LU | INVERT_LU | SOLVE_CHOLESKY |\n INVERT_CHOLESKY\n )\n for name in model.inversion_methods:\n setattr(model, name, False)\n assert_equal(model.inversion_method, 0)\n\n def test_stability_methods(self):\n model = self.model\n\n # Clear the stability method\n model.stability_method = 0\n\n # Try setting via boolean\n model.stability_force_symmetry = True\n assert_equal(model.stability_method, STABILITY_FORCE_SYMMETRY)\n model.stability_force_symmetry = False\n assert_equal(model.stability_method, 0)\n\n # Try setting directly via method\n model.stability_method = 0\n model.set_stability_method(STABILITY_FORCE_SYMMETRY)\n assert_equal(model.stability_method, STABILITY_FORCE_SYMMETRY)\n\n # Try setting via boolean via method\n model.stability_method = 0\n model.set_stability_method(stability_method=True)\n assert_equal(model.stability_method, STABILITY_FORCE_SYMMETRY)\n\n # Try setting via keyword via method\n model.stability_method = 0\n model.set_stability_method(stability_force_symmetry=True)\n assert_equal(model.stability_method, STABILITY_FORCE_SYMMETRY)\n\n def test_conserve_memory(self):\n model = self.model\n\n # Clear the filter method\n model.conserve_memory = MEMORY_STORE_ALL\n\n # Try setting via boolean\n model.memory_no_forecast = True\n assert_equal(model.conserve_memory, MEMORY_NO_FORECAST)\n model.memory_no_filtered = True\n assert_equal(model.conserve_memory, MEMORY_NO_FORECAST | MEMORY_NO_FILTERED)\n model.memory_no_forecast = False\n assert_equal(model.conserve_memory, MEMORY_NO_FILTERED)\n\n # Try setting directly via method\n model.set_conserve_memory(MEMORY_NO_PREDICTED)\n assert_equal(model.conserve_memory, MEMORY_NO_PREDICTED)\n\n # Try setting via boolean via method\n model.set_conserve_memory(memory_no_filtered=True, memory_no_predicted=False)\n assert_equal(model.conserve_memory, MEMORY_NO_FILTERED)\n\n # Try setting and unsetting all\n model.conserve_memory = 0\n for name in model.memory_options:\n if name == 'memory_conserve':\n continue\n setattr(model, name, True)\n assert_equal(\n model.conserve_memory,\n MEMORY_NO_FORECAST | MEMORY_NO_PREDICTED | MEMORY_NO_FILTERED |\n MEMORY_NO_LIKELIHOOD | MEMORY_NO_GAIN | MEMORY_NO_SMOOTHING |\n MEMORY_NO_STD_FORECAST\n )\n assert_equal(model.conserve_memory, MEMORY_CONSERVE)\n for name in model.memory_options:\n if name == 'memory_conserve':\n continue\n setattr(model, name, False)\n assert_equal(model.conserve_memory, 0)\n\n def test_smoother_outputs(self):\n model = self.model\n\n # TODO test SmootherResults for accurante boolean versions of options\n\n # Clear the smoother output\n model.smoother_output = 0\n\n # Try setting via boolean\n model.smoother_state = True\n assert_equal(model.smoother_output, SMOOTHER_STATE)\n model.smoother_disturbance = True\n assert_equal(model.smoother_output, SMOOTHER_STATE | SMOOTHER_DISTURBANCE)\n model.smoother_state = False\n assert_equal(model.smoother_output, SMOOTHER_DISTURBANCE)\n\n # Try setting directly via method\n model.set_smoother_output(SMOOTHER_DISTURBANCE_COV)\n assert_equal(model.smoother_output, SMOOTHER_DISTURBANCE_COV)\n\n # Try setting via boolean via method\n model.set_smoother_output(smoother_disturbance=True, smoother_disturbance_cov=False)\n assert_equal(model.smoother_output, SMOOTHER_DISTURBANCE)\n\n # Try setting and unsetting all\n model.smoother_output = 0\n for name in model.smoother_outputs:\n if name == 'smoother_all':\n continue\n setattr(model, name, True)\n assert_equal(\n model.smoother_output,\n SMOOTHER_STATE | SMOOTHER_STATE_COV | SMOOTHER_STATE_AUTOCOV |\n SMOOTHER_DISTURBANCE | SMOOTHER_DISTURBANCE_COV\n )\n assert_equal(model.smoother_output, SMOOTHER_ALL)\n for name in model.smoother_outputs:\n if name == 'smoother_all':\n continue\n setattr(model, name, False)\n assert_equal(model.smoother_output, 0)\n\n def test_simulation_outputs(self):\n # TODO test changing simulation options in SimulationSmoothResults\n # instance\n\n assert_equal(self.model.get_simulation_output(SIMULATION_STATE), SIMULATION_STATE)\n assert_equal(self.model.get_simulation_output(simulate_state=True, simulate_disturbance=True), SIMULATION_ALL)\n" ]
[ [ "numpy.arange", "numpy.testing.assert_equal" ] ]
salesforce/burn-after-reading
[ "939d969d67a9ba325eba9e1cb9c696908f9d88db" ]
[ "data_loader.py" ]
[ "'''\n * Copyright (c) 2021, salesforce.com, inc.\n * All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause\n'''\n\nfrom torchvision import datasets, transforms\nimport torch\nimport numpy as np\nimport random\nfrom PIL import Image\nfrom torch.utils.data import Dataset\nimport os\nimport os.path\nimport cv2\nimport torchvision\nfrom randaugment import RandAugmentMC\nfrom wilds.common.data_loaders import get_eval_loader\nfrom wilds.datasets.camelyon17_dataset import Camelyon17Dataset\n\ntorch.manual_seed(999)\nnp.random.seed(999)\ntorch.backends.cudnn.benchmark = True\n\n\ndef load_training_from_list(root, list_path, batch_size, kwargs, shuffle=True, return_idx=False):\n transform = transforms.Compose(\n [transforms.Resize([256, 256]),\n transforms.RandomHorizontalFlip(),\n transforms.RandomCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])\n txt = open(list_path).readlines()\n data = ImageList_idx(root, txt, transform=transform, return_idx=return_idx)\n train_loader = torch.utils.data.DataLoader(data, batch_size=batch_size, shuffle=shuffle, drop_last=True, **kwargs)\n return train_loader\n\n\ndef load_training_strong_weak(root, list_path, batch_size, kwargs, shuffle=True, return_idx=False,\n return_test_img=False):\n txt = open(list_path).readlines()\n data = Imagelist_strong_weak(root, txt, return_idx=return_idx, return_test_img=return_test_img)\n train_loader = torch.utils.data.DataLoader(data, batch_size=batch_size, shuffle=shuffle, drop_last=True, **kwargs)\n return train_loader\n\n\ndef load_testing_from_list(root, list_path, batch_size, kwargs, shuffle=False, return_idx=False):\n transform = transforms.Compose(\n [transforms.Resize([256, 256]),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])\n txt = open(list_path).readlines()\n data = ImageList_idx(root, txt, transform=transform, return_idx=return_idx)\n train_loader = torch.utils.data.DataLoader(data, batch_size=batch_size, shuffle=shuffle, drop_last=False, **kwargs)\n return train_loader\n\n\ndef make_dataset(image_list, labels):\n if labels:\n len_ = len(image_list)\n images = [(image_list[i].strip(), labels[i, :]) for i in range(len_)]\n else:\n if len(image_list[0].split()) > 2:\n images = [(val.split()[0], np.array([int(la) for la in val.split()[1:]])) for val in image_list]\n else:\n images = [(val.split()[0], int(val.split()[1])) for val in image_list]\n return images\n\n\ndef rgb_loader(path):\n with open(path, 'rb') as f:\n with Image.open(f) as img:\n return img.convert('RGB')\n\n\ndef l_loader(path):\n with open(path, 'rb') as f:\n with Image.open(f) as img:\n return img.convert('L')\n\n\nclass ResizeImage():\n def __init__(self, size):\n if isinstance(size, int):\n self.size = (int(size), int(size))\n else:\n self.size = size\n\n def __call__(self, img):\n th, tw = self.size\n return img.resize((th, tw))\n\n\nclass ImageList_idx(Dataset):\n def __init__(self, root, image_list, labels=None, transform=None, target_transform=None, mode='RGB',\n return_idx=True,\n idx_mask=None):\n imgs = make_dataset(image_list, labels)\n self.root = root\n self.imgs = imgs\n if idx_mask is not None:\n self.imgs = [imgs[i] for i in idx_mask]\n\n self.transform = transform\n self.target_transform = target_transform\n self.return_idx = return_idx\n\n if mode == 'RGB':\n self.loader = rgb_loader\n elif mode == 'L':\n self.loader = l_loader\n\n def __getitem__(self, index):\n path, target = self.imgs[index]\n path = os.path.join(self.root, path)\n img = self.loader(path)\n if self.transform is not None:\n img = self.transform(img)\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n if self.return_idx:\n return img, target, index\n else:\n return img, target\n\n def __len__(self):\n return len(self.imgs)\n\n\ndef get_index_label(txt):\n image_list = open(txt).readlines()\n data = [(i, int(val.split()[1])) for i, val in enumerate(image_list)]\n return np.array(data)\n\n\nclass Imagelist_strong_weak(object):\n def __init__(self, root, image_list, return_idx=False, return_test_img=False):\n imgs = make_dataset(image_list, labels=None)\n self.root = root\n\n self.imgs = imgs\n self.loader = rgb_loader\n self.return_idx = return_idx\n self.return_test_img = return_test_img\n self.test = transforms.Compose([\n ResizeImage(256),\n transforms.CenterCrop(size=224)])\n self.weak = transforms.Compose([\n ResizeImage(256),\n transforms.RandomHorizontalFlip(),\n transforms.RandomCrop(size=224)])\n self.strong = transforms.Compose([\n ResizeImage(256),\n transforms.RandomHorizontalFlip(),\n transforms.RandomCrop(size=224),\n RandAugmentMC(n=2, m=10)])\n self.normalize = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n Returns:\n tuple: (image, target) where target is\n class_index of the target class.\n \"\"\"\n path, target = self.imgs[index]\n path = os.path.join(self.root, path)\n img = self.loader(path)\n\n img_strong = self.normalize(self.strong(img))\n img_weak = self.normalize(self.weak(img))\n img_test = self.normalize(self.test(img))\n\n if not self.return_idx:\n if not self.return_test_img:\n return (img_weak, img_strong), target\n else:\n return (img_weak, img_strong, img_test), target\n else:\n if not self.return_test_img:\n return (img_weak, img_strong), target, index\n else:\n return (img_weak, img_strong, img_test), target, index\n\n def __len__(self):\n return len(self.imgs)\n" ]
[ [ "numpy.array", "torch.utils.data.DataLoader", "torch.manual_seed", "numpy.random.seed" ] ]
bjajoh/lidar_transfer
[ "9a6366264b1fd95d7a84e05bd41659524fd9fd32" ]
[ "auxiliary/np_ioueval.py" ]
[ "#!/usr/bin/env python3\n# This file is covered by the LICENSE file in the root of this project.\n\nimport sys\nimport numpy as np\n\n\nclass iouEval:\n def __init__(self, n_classes, ignore=None):\n # classes\n self.n_classes = n_classes\n\n # What to include and ignore from the means\n self.ignore = np.array(ignore, dtype=np.int64)\n self.include = np.array(\n [n for n in range(self.n_classes) if n not in self.ignore], dtype=np.int64)\n print(\"[IOU EVAL] IGNORE: \", self.ignore)\n print(\"[IOU EVAL] INCLUDE: \", self.include)\n\n # reset the class counters\n self.reset()\n\n def num_classes(self):\n return self.n_classes\n\n def reset(self):\n self.conf_matrix = np.zeros((self.n_classes,\n self.n_classes),\n dtype=np.int64)\n\n def addBatch(self, x, y): # x=preds, y=targets\n # sizes should be matching\n x_row = x.reshape(-1) # de-batchify\n y_row = y.reshape(-1) # de-batchify\n\n # check\n assert(x_row.shape == x_row.shape)\n\n # create indexes\n idxs = tuple(np.stack((x_row, y_row), axis=0))\n\n # make confusion matrix (cols = gt, rows = pred)\n np.add.at(self.conf_matrix, idxs, 1)\n\n def getStats(self):\n # remove fp and fn from confusion on the ignore classes cols and rows\n conf = self.conf_matrix.copy()\n conf[self.ignore] = 0\n conf[:, self.ignore] = 0\n\n # get the clean stats\n tp = np.diag(conf)\n fp = conf.sum(axis=1) - tp\n fn = conf.sum(axis=0) - tp\n return tp, fp, fn\n\n def getIoU(self):\n tp, fp, fn = self.getStats()\n intersection = tp\n union = tp + fp + fn + 1e-15\n iou = intersection / union\n iou_mean = (intersection[self.include] / union[self.include]).mean()\n return iou_mean, iou # returns \"iou mean\", \"iou per class\" ALL CLASSES\n\n def getacc(self):\n tp, fp, fn = self.getStats()\n total_tp = tp.sum()\n total = tp[self.include].sum() + fp[self.include].sum() + 1e-15\n acc_mean = total_tp / total\n return acc_mean # returns \"acc mean\"\n\n\nif __name__ == \"__main__\":\n # mock problem\n nclasses = 2\n ignore = []\n\n # test with 2 squares and a known IOU\n lbl = np.zeros((7, 7), dtype=np.int64)\n argmax = np.zeros((7, 7), dtype=np.int64)\n\n # put squares\n lbl[2:4, 2:4] = 1\n argmax[3:5, 3:5] = 1\n\n # make evaluator\n eval = iouEval(nclasses, ignore)\n\n # run\n eval.addBatch(argmax, lbl)\n m_iou, iou = eval.getIoU()\n print(\"IoU: \", m_iou)\n print(\"IoU class: \", iou)\n m_acc = eval.getacc()\n print(\"Acc: \", m_acc)\n" ]
[ [ "numpy.zeros", "numpy.diag", "numpy.stack", "numpy.add.at", "numpy.array" ] ]
ssalopek/DFT_FFT_ImageDenoise
[ "9ced6175b39c0c8f205b84fcd7d3fbb16bdca8d8" ]
[ "FFT.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import fftpack\nfrom matplotlib.colors import LogNorm \nimport cv2\nimport time\n\nstart = time.time()\n#Load input image\nimage_source = cv2.imread('C:/FaksGit/FourierFilter/TestImages/man.png')\ngray_image = cv2.cvtColor(image_source, cv2.COLOR_BGR2GRAY)\n\n#Plot input image\nplt.figure()\nplt.imshow(gray_image, plt.cm.gray)\nplt.xticks([]), plt.yticks([])\nplt.title(\"Original image\")\n\n#Return the two-dimensional discrete Fourier transform of the 2-D argument x.\nimage_fft = fftpack.fft2(gray_image) \n\n#Logaritmic map\ndef show_spectrum(image_fft):\n plt.imshow(np.abs(image_fft), norm=LogNorm(vmin=5))\n plt.colorbar() #Add colorbar \n\n#Plot FT input image\nplt.figure()\nshow_spectrum(image_fft)\nplt.title(\"Fourier transform\")\n\nkeep_fraction = 0.3 #keep fraction (u oba smijera)\nimage_fft2 = image_fft.copy()\nrow, col = image_fft2.shape #get the current shape of an array\n\n#Set on zero all rows with index between row*keep_fraction and row*(1-keep_fraction)\nimage_fft2[int(row*keep_fraction):int(row*(1-keep_fraction))] = 0 \n#Similar for columns\nimage_fft2[:, int(col*keep_fraction):int(col*(1-keep_fraction))] = 0\n\n#Plot spectrum\nplt.figure()\nshow_spectrum(image_fft2)\nplt.title('Filtered Spectrum')\n\n#Return inverse two-dimensional discrete Fourier transform of arbitrary type sequence x\nimage_new = fftpack.ifft2(image_fft2).real\n\nend = time.time()\nprint(\"Time:\" ,end - start)\n\nfig = plt.figure(figsize=(20,10))\nplt.imshow(image_new, plt.cm.gray)\nplt.xticks([]), plt.yticks([])\nplt.title('Reconstructed Image FFT')\nfig.savefig('baboon_gauss60.3FFT.png')\n\n\n\n\n\n\n\n\n\n\n\n\n" ]
[ [ "matplotlib.pyplot.xticks", "scipy.fftpack.fft2", "matplotlib.pyplot.figure", "numpy.abs", "scipy.fftpack.ifft2", "matplotlib.pyplot.title", "matplotlib.colors.LogNorm", "matplotlib.pyplot.imshow", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.yticks" ] ]
histolab/histolab
[ "e5e28846fada56d04b90cf32a2772fbdb2e0786a" ]
[ "histolab/filters/image_filters_functional.py" ]
[ "# encoding: utf-8\n\n# ------------------------------------------------------------------------\n# Copyright 2020 All Histolab Contributors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ------------------------------------------------------------------------\n\nimport math\nimport operator\nfrom functools import reduce\nfrom typing import Any, Callable\n\nimport numpy as np\nimport PIL\nimport PIL.ImageOps\nimport skimage.color as sk_color\nimport skimage.exposure as sk_exposure\nimport skimage.feature as sk_feature\nimport skimage.filters as sk_filters\nimport skimage.future as sk_future\nimport skimage.morphology as sk_morphology\nimport skimage.segmentation as sk_segmentation\n\nfrom ..util import apply_mask_image, np_to_pil, threshold_to_mask, warn\nfrom .util import mask_percent\n\n\ndef adaptive_equalization(\n img: PIL.Image.Image, nbins: int = 256, clip_limit: float = 0.01\n) -> PIL.Image.Image:\n \"\"\"Increase image contrast using adaptive equalization.\n\n Contrast in local region of input image (gray or RGB) is increased using\n adaptive equalization\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input image (gray or RGB)\n nbins : int\n Number of histogram bins. Default is 256.\n clip_limit : float, optional\n Clipping limit where higher value increases contrast. Default is 0.01\n\n Returns\n -------\n PIL.Image.Image\n image with contrast enhanced by adaptive equalization.\n \"\"\"\n if not (isinstance(nbins, int) and nbins > 0):\n raise ValueError(\"Number of histogram bins must be a positive integer\")\n img_arr = np.array(img)\n adapt_equ = sk_exposure.equalize_adapthist(img_arr, nbins, clip_limit)\n adapt_equ = np_to_pil(adapt_equ)\n return adapt_equ\n\n\ndef blue_pen_filter(img: PIL.Image.Image) -> PIL.Image.Image:\n \"\"\"Filter out blue pen marks from a diagnostic slide.\n\n The resulting mask is a composition of green filters with different thresholds\n for the RGB channels.\n\n Parameters\n ---------\n img : PIL.Image.Image\n Input RGB image\n\n Returns\n -------\n PIL.Image.Image\n Input image with the blue pen marks filtered out.\n \"\"\"\n parameters = [\n {\"red_thresh\": 60, \"green_thresh\": 120, \"blue_thresh\": 190},\n {\"red_thresh\": 120, \"green_thresh\": 170, \"blue_thresh\": 200},\n {\"red_thresh\": 175, \"green_thresh\": 210, \"blue_thresh\": 230},\n {\"red_thresh\": 145, \"green_thresh\": 180, \"blue_thresh\": 210},\n {\"red_thresh\": 37, \"green_thresh\": 95, \"blue_thresh\": 160},\n {\"red_thresh\": 30, \"green_thresh\": 65, \"blue_thresh\": 130},\n {\"red_thresh\": 130, \"green_thresh\": 155, \"blue_thresh\": 180},\n {\"red_thresh\": 40, \"green_thresh\": 35, \"blue_thresh\": 85},\n {\"red_thresh\": 30, \"green_thresh\": 20, \"blue_thresh\": 65},\n {\"red_thresh\": 90, \"green_thresh\": 90, \"blue_thresh\": 140},\n {\"red_thresh\": 60, \"green_thresh\": 60, \"blue_thresh\": 120},\n {\"red_thresh\": 110, \"green_thresh\": 110, \"blue_thresh\": 175},\n ]\n\n blue_pen_filter_img = reduce(\n (lambda x, y: x & y), [blue_filter(img, **param) for param in parameters]\n )\n return apply_mask_image(img, blue_pen_filter_img)\n\n\ndef dab_channel(img: PIL.Image.Image) -> PIL.Image.Image:\n \"\"\"Obtain DAB channel from RGB image.\n\n Input image is first converted into HED space and the DAB channel is\n rescaled for increased contrast.\n\n Parameters\n ----------\n img : Image.Image\n Input RGB image\n\n Returns\n -------\n Image.Image\n Grayscale image corresponding to input image with DAB channel enhanced.\n \"\"\"\n if img.mode not in [\"RGB\", \"RGBA\"]:\n raise ValueError(\"Input image must be RGB/RGBA.\")\n dab = np.array(rgb_to_hed(img))[:, :, 2]\n dab = sk_exposure.rescale_intensity(dab)\n return np_to_pil(dab)\n\n\ndef eosin_channel(img: PIL.Image.Image) -> PIL.Image.Image:\n \"\"\"Obtain Eosin channel from RGB image.\n\n Input image is first converted into HED space and the Eosin channel is\n rescaled for increased contrast.\n\n Parameters\n ----------\n img : Image.Image\n Input RGB image\n\n Returns\n -------\n Image.Image\n Grayscale image corresponding to input image with Eosin channel enhanced.\n \"\"\"\n if img.mode not in [\"RGB\", \"RGBA\"]:\n raise ValueError(\"Input image must be RGB/RGBA.\")\n eosin = np.array(rgb_to_hed(img))[:, :, 1]\n eosin = sk_exposure.rescale_intensity(eosin)\n return np_to_pil(eosin)\n\n\ndef green_pen_filter(img: PIL.Image.Image) -> PIL.Image.Image:\n \"\"\"Filter out green pen marks from a diagnostic slide.\n\n The resulting mask is a composition of green filters with different thresholds\n for the RGB channels.\n\n Parameters\n ---------\n img : PIL.Image.Image\n Input RGB image\n\n Returns\n -------\n PIL.Image.Image\n Input image with the green pen marks filtered out.\n \"\"\"\n parameters = [\n {\"red_thresh\": 150, \"green_thresh\": 160, \"blue_thresh\": 140},\n {\"red_thresh\": 70, \"green_thresh\": 110, \"blue_thresh\": 110},\n {\"red_thresh\": 45, \"green_thresh\": 115, \"blue_thresh\": 100},\n {\"red_thresh\": 30, \"green_thresh\": 75, \"blue_thresh\": 60},\n {\"red_thresh\": 195, \"green_thresh\": 220, \"blue_thresh\": 210},\n {\"red_thresh\": 225, \"green_thresh\": 230, \"blue_thresh\": 225},\n {\"red_thresh\": 170, \"green_thresh\": 210, \"blue_thresh\": 200},\n {\"red_thresh\": 20, \"green_thresh\": 30, \"blue_thresh\": 20},\n {\"red_thresh\": 50, \"green_thresh\": 60, \"blue_thresh\": 40},\n {\"red_thresh\": 30, \"green_thresh\": 50, \"blue_thresh\": 35},\n {\"red_thresh\": 65, \"green_thresh\": 70, \"blue_thresh\": 60},\n {\"red_thresh\": 100, \"green_thresh\": 110, \"blue_thresh\": 105},\n {\"red_thresh\": 165, \"green_thresh\": 180, \"blue_thresh\": 180},\n {\"red_thresh\": 140, \"green_thresh\": 140, \"blue_thresh\": 150},\n {\"red_thresh\": 185, \"green_thresh\": 195, \"blue_thresh\": 195},\n ]\n\n green_pen_filter_img = reduce(\n (lambda x, y: x & y), [green_filter(img, **param) for param in parameters]\n )\n return apply_mask_image(img, green_pen_filter_img)\n\n\ndef hematoxylin_channel(img: PIL.Image.Image) -> PIL.Image.Image:\n \"\"\"Obtain Hematoxylin channel from RGB image.\n\n Input image is first converted into HED space and the hematoxylin channel is\n rescaled for increased contrast.\n\n Parameters\n ----------\n img : Image.Image\n Input RGB image\n\n Returns\n -------\n Image.Image\n Grayscale image corresponding to input image with Hematoxylin channel enhanced.\n \"\"\"\n if img.mode not in [\"RGB\", \"RGBA\"]:\n raise ValueError(\"Input image must be RGB/RGBA.\")\n hematoxylin = np.array(rgb_to_hed(img))[:, :, 0]\n hematoxylin = sk_exposure.rescale_intensity(hematoxylin)\n return np_to_pil(hematoxylin)\n\n\ndef histogram_equalization(img: PIL.Image.Image, nbins: int = 256) -> PIL.Image.Image:\n \"\"\"Increase image contrast using histogram equalization.\n\n The input image (gray or RGB) is filterd using histogram equalization to increase\n contrast.\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input image.\n nbins : int. optional\n Number of histogram bins. Default is 256.\n\n Returns\n -------\n PIL.Image.Image\n Image with contrast enhanced by histogram equalization.\n \"\"\"\n img_arr = np.array(img)\n hist_equ = sk_exposure.equalize_hist(img_arr.flatten(), nbins=nbins)\n hist_equ = hist_equ.reshape(img_arr.shape)\n return np_to_pil(hist_equ)\n\n\ndef hysteresis_threshold(\n img: PIL.Image.Image, low: int = 50, high: int = 100\n) -> PIL.Image.Image:\n \"\"\"Apply two-level (hysteresis) threshold to an image.\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input image\n low : int, optional\n low threshold. Default is 50.\n high : int, optional\n high threshold. Default is 100.\n\n Returns\n -------\n PIL.Image.Image\n Image with the hysteresis threshold applied\n \"\"\"\n if low is None or high is None:\n raise ValueError(\"thresholds cannot be None\")\n hyst = sk_filters.apply_hysteresis_threshold(np.array(img), low, high)\n img_out = apply_mask_image(img, hyst)\n return img_out\n\n\ndef invert(img: PIL.Image.Image) -> PIL.Image.Image:\n \"\"\"Invert an image, i.e. take the complement of the correspondent array.\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input image\n\n Returns\n -------\n PIL.Image.Image\n Inverted image\n \"\"\"\n if img.mode == \"RGBA\":\n red, green, blue, alpha = img.split()\n rgb_img = PIL.Image.merge(\"RGB\", (red, green, blue))\n inverted_img_rgb = PIL.ImageOps.invert(rgb_img)\n red, green, blue = inverted_img_rgb.split()\n inverted_img = PIL.Image.merge(\"RGBA\", (red, green, blue, alpha))\n else:\n inverted_img = PIL.ImageOps.invert(img)\n\n return inverted_img\n\n\ndef kmeans_segmentation(\n img: PIL.Image.Image, n_segments: int = 800, compactness: float = 10.0\n) -> PIL.Image.Image:\n \"\"\"Segment an image with K-means segmentation\n\n By using K-means segmentation (color/space proximity) each segment is\n colored based on the average color for that segment.\n\n Parameters\n ---------\n img : PIL.Image.Image\n Input image\n n_segments : int, optional\n The number of segments. Default is 800.\n compactness : float, optional\n Color proximity versus space proximity factor. Default is 10.0.\n\n Returns\n -------\n PIL.Image.Image\n RGB image where each segment has been colored based on the average\n color for that segment.\n\n Raises\n ------\n ValueError\n If ``img`` mode is RGBA.\n \"\"\"\n if img.mode == \"RGBA\":\n raise ValueError(\"Input image cannot be RGBA\")\n img_arr = np.array(img)\n labels = sk_segmentation.slic(img_arr, n_segments, compactness, start_label=0)\n return np_to_pil(sk_color.label2rgb(labels, img_arr, kind=\"avg\", bg_label=-1))\n\n\ndef local_equalization(img: PIL.Image.Image, disk_size: int = 50) -> PIL.Image.Image:\n \"\"\"Filter gray image using local equalization.\n\n Local equalization method uses local histograms based on a disk structuring element.\n\n Parameters\n ---------\n img: PIL.Image.Image\n Input image. Notice that it must be 2D\n disk_size: int, optional\n Radius of the disk structuring element used for the local histograms. Default is\n 50.\n\n Returns\n -------\n PIL.Image.Image\n 2D image with contrast enhanced using local equalization.\n \"\"\"\n\n if len(np.array(img).shape) != 2:\n raise ValueError(\"Input must be 2D.\")\n local_equ = sk_filters.rank.equalize(\n np.array(img), selem=sk_morphology.disk(disk_size)\n )\n return np_to_pil(local_equ)\n\n\ndef local_otsu_threshold(\n img: PIL.Image.Image, disk_size: float = 3.0\n) -> PIL.Image.Image:\n \"\"\"Mask image based on local Otsu threshold.\n\n Compute local Otsu threshold for each pixel and return boolean mask\n based on pixels being less than the local Otsu threshold.\n\n Note that the input image must be 2D.\n\n Parameters\n ----------\n img: PIL.Image.Image\n Input 2-dimensional image\n disk_size : float, optional\n Radius of the disk structuring element used to compute\n the Otsu threshold for each pixel. Default is 3.0.\n\n Returns\n -------\n PIL.Image.Image\n Resulting image where local Otsu threshold values have been\n applied to original image.\n \"\"\"\n if np.array(img).ndim != 2:\n raise ValueError(\"Input must be 2D.\")\n if disk_size is None or disk_size < 0 or disk_size == np.inf:\n raise ValueError(\"Disk size must be a positive number.\")\n img_arr = np.array(img)\n local_otsu = sk_filters.rank.otsu(img_arr, sk_morphology.disk(disk_size))\n return np_to_pil(local_otsu)\n\n\ndef rag_threshold(\n img: PIL.Image.Image,\n n_segments: int = 800,\n compactness: float = 10.0,\n threshold: int = 9,\n) -> PIL.Image.Image:\n \"\"\"Combine similar K-means segmented regions based on threshold value.\n\n Segment an image with K-means, build region adjacency graph based on\n the segments, combine similar regions based on threshold value,\n and then output these resulting region segments.\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input image\n n_segments : int, optional\n The number of segments. Default is 800.\n compactness : float, optional\n Color proximity versus space proximity factor. Default is 10.0.\n threshold : int, optional\n Threshold value for combining regions. Default is 9.\n\n Returns\n -------\n PIL.Image.Image\n Each segment has been colored based on the average\n color for that segment (and similar segments have been combined).\n\n Raises\n ------\n ValueError\n If ``img`` mode is RGBA.\n \"\"\"\n if img.mode == \"RGBA\":\n raise ValueError(\"Input image cannot be RGBA\")\n img_arr = np.array(img)\n labels = sk_segmentation.slic(img_arr, n_segments, compactness, start_label=0)\n green = sk_future.graph.rag_mean_color(img_arr, labels)\n labels2 = sk_future.graph.cut_threshold(labels, green, threshold)\n rag = sk_color.label2rgb(labels2, img_arr, kind=\"avg\", bg_label=-1)\n return np_to_pil(rag)\n\n\ndef red_pen_filter(img: PIL.Image.Image) -> PIL.Image.Image:\n \"\"\"Filter out red pen marks on diagnostic slides.\n\n The resulting mask is a composition of red filters with different thresholds\n for the RGB channels.\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input RGB image.\n\n Returns\n -------\n PIL.Image.Image\n Input image with the pen marks filtered out.\n \"\"\"\n parameters = [\n {\"red_thresh\": 150, \"green_thresh\": 80, \"blue_thresh\": 90},\n {\"red_thresh\": 110, \"green_thresh\": 20, \"blue_thresh\": 30},\n {\"red_thresh\": 185, \"green_thresh\": 65, \"blue_thresh\": 105},\n {\"red_thresh\": 195, \"green_thresh\": 85, \"blue_thresh\": 125},\n {\"red_thresh\": 220, \"green_thresh\": 115, \"blue_thresh\": 145},\n {\"red_thresh\": 125, \"green_thresh\": 40, \"blue_thresh\": 70},\n {\"red_thresh\": 100, \"green_thresh\": 50, \"blue_thresh\": 65},\n {\"red_thresh\": 85, \"green_thresh\": 25, \"blue_thresh\": 45},\n ]\n red_pen_filter_img = reduce(\n (lambda x, y: x & y), [red_filter(img, **param) for param in parameters]\n )\n return apply_mask_image(img, red_pen_filter_img)\n\n\ndef rgb_to_hed(img: PIL.Image.Image) -> PIL.Image.Image:\n \"\"\"Convert RGB channels to HED channels.\n\n image color space (RGB) is converted to Hematoxylin-Eosin-Diaminobenzidine space.\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input image\n\n Returns\n -------\n PIL.Image.Image\n Image in HED space\n \"\"\"\n if img.mode not in [\"RGB\", \"RGBA\"]:\n raise Exception(\"Input image must be RGB.\")\n if img.mode == \"RGBA\":\n red, green, blue, _ = img.split()\n img = PIL.Image.merge(\"RGB\", (red, green, blue))\n warn(\n \"Input image must be RGB. \"\n \"NOTE: the image will be converted to RGB before HED conversion.\"\n )\n\n img_arr = np.array(img)\n hed_arr = sk_color.rgb2hed(img_arr)\n hed = np_to_pil(hed_arr)\n\n return hed\n\n\ndef rgb_to_hsv(img: PIL.Image.Image) -> PIL.Image.Image:\n \"\"\"Convert RGB channels to HSV channels.\n\n image color space (RGB) is converted to Hue - Saturation - Value (HSV) space.\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input image\n\n Returns\n -------\n PIL.Image.Image\n Image in HED space\n\n Raises\n ------\n Exception\n If the image mode is not RGB\n \"\"\"\n if img.mode != \"RGB\":\n raise Exception(\"Input image must be RGB\")\n img_arr = np.array(img)\n hsv_arr = sk_color.rgb2hsv(img_arr)\n hsv = np_to_pil(hsv_arr)\n return hsv\n\n\ndef rgb_to_lab(\n img: PIL.Image.Image, illuminant: str = \"D65\", observer: int = \"2\"\n) -> PIL.Image.Image:\n \"\"\"Convert from the sRGB color space to the CIE Lab colorspace.\n\n sRGB color space reference: IEC 61966-2-1:1999\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input image\n illuminant : {“A”, “D50”, “D55”, “D65”, “D75”, “E”}, optional\n The name of the illuminant (the function is NOT case sensitive).\n observer : {“2”, “10”}, optional\n The aperture angle of the observer.\n\n Returns\n -------\n PIL.Image.Image\n Image in LAB space\n\n Raises\n ------\n Exception\n If the image mode is not RGB\n \"\"\"\n if img.mode != \"RGB\":\n raise Exception(\"Input image must be RGB\")\n img_arr = np.array(img)\n lab_arr = sk_color.rgb2lab(img_arr, illuminant=illuminant, observer=observer)\n lab = np_to_pil(lab_arr)\n return lab\n\n\ndef rgb_to_od(img: PIL.Image.Image) -> np.ndarray:\n \"\"\"Convert from RGB to optical density (OD_RGB) space.\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input image\n\n Returns\n -------\n np.ndarray\n Array representation of the image in OD space\n \"\"\"\n if img.mode == \"RGBA\":\n red, green, blue, _ = img.split()\n img = PIL.Image.merge(\"RGB\", (red, green, blue))\n\n warn(\n \"Input image must be RGB. \"\n \"NOTE: the image will be converted to RGB before OD conversion.\"\n )\n\n img_arr = np.array(img)\n\n od_arr = -np.log((img_arr.astype(float) + 1) / 240)\n return od_arr\n\n\ndef stretch_contrast(\n img: PIL.Image.Image, low: int = 40, high: int = 60\n) -> PIL.Image.Image:\n \"\"\"Increase image contrast.\n\n Th contrast in image is increased based on intensities in a specified range\n\n Parameters\n ----------\n img: PIL.Image.Image\n Input image\n low: int\n Range low value (0 to 255). Default is 40.\n high: int\n Range high value (0 to 255). Default is 60.\n\n Returns\n -------\n PIL.Image.Image\n Image with contrast enhanced.\n \"\"\"\n if low not in range(256) or high not in range(256):\n raise Exception(\"low and high values must be in range [0, 255]\")\n img_arr = np.array(img)\n low_p, high_p = np.percentile(img_arr, (low * 100 / 255, high * 100 / 255))\n return np_to_pil(sk_exposure.rescale_intensity(img_arr, in_range=(low_p, high_p)))\n\n\n# -------- Branching function --------\n\n\ndef blue_filter(\n img: PIL.Image.Image, red_thresh: int, green_thresh: int, blue_thresh: int\n) -> np.ndarray:\n \"\"\"Filter out blueish colors in an RGB image.\n\n Create a mask to filter out blueish colors, where the mask is based on a pixel\n being above a red channel threshold value, above a green channel threshold value,\n and below a blue channel threshold value.\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input RGB image\n red_thresh : int\n Red channel lower threshold value.\n green_thresh : int\n Green channel lower threshold value.\n blue_thresh : int\n Blue channel upper threshold value.\n\n Returns\n -------\n np.ndarray\n Boolean NumPy array representing the mask.\n \"\"\"\n if np.array(img).ndim != 3:\n raise ValueError(\"Input must be 3D.\")\n if not (\n 0 <= red_thresh <= 255 and 0 <= green_thresh <= 255 and 0 <= blue_thresh <= 255\n ):\n raise ValueError(\"RGB Thresholds must be in range [0, 255]\")\n img_arr = np.array(img)\n red = img_arr[:, :, 0] > red_thresh\n green = img_arr[:, :, 1] > green_thresh\n blue = img_arr[:, :, 2] < blue_thresh\n return red | green | blue\n\n\ndef canny_edges(\n img: PIL.Image.Image,\n sigma: float = 1.0,\n low_threshold: float = 0.0,\n high_threshold: float = 25.0,\n) -> np.ndarray:\n \"\"\"Filter image based on Canny edge algorithm.\n\n Note that input image must be 2D grayscale image\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input 2-dimensional image\n sigma : float, optional\n Width (std dev) of Gaussian. Default is 1.0.\n low_threshold : float, optional\n Low hysteresis threshold value. Default is 0.0.\n high_threshold : float, optional\n High hysteresis threshold value. Default is 25.0.\n\n Returns\n -------\n np.ndarray\n Boolean NumPy array representing Canny edge map.\n \"\"\"\n if np.array(img).ndim != 2:\n raise ValueError(\"Input must be 2D.\")\n img_arr = np.array(img)\n return sk_feature.canny(img_arr, sigma, low_threshold, high_threshold)\n\n\ndef filter_entropy(\n img: PIL.Image.Image,\n neighborhood: int = 9,\n threshold: float = 5.0,\n relate: Callable[..., Any] = operator.gt,\n) -> np.ndarray:\n \"\"\"Filter image based on entropy (complexity).\n\n The area of the image included in the local neighborhood is defined by a square\n neighborhood x neighborhood\n\n Note that input must be 2D.\n\n Parameters\n ----------\n img : PIL.Image.Image\n input 2-dimensional image\n neighborhood : int, optional\n Neighborhood size (defines height and width of 2D array of 1's). Default is 9.\n threshold : float, optional\n Threshold value. Default is 5.0\n relate : callable operator, optional\n Operator to be used to compute the mask from the threshold. Default is\n operator.lt\n\n Returns\n -------\n np.ndarray\n NumPy boolean array where True represent a measure of complexity.\n \"\"\"\n if np.array(img).ndim != 2:\n raise ValueError(\"Input must be 2D.\")\n img_arr = np.array(img)\n entropy = sk_filters.rank.entropy(img_arr, np.ones((neighborhood, neighborhood)))\n return threshold_to_mask(entropy, threshold, relate)\n\n\ndef grays(img: PIL.Image.Image, tolerance: int = 15) -> np.ndarray:\n \"\"\"Filter out gray pixels in RGB image.\n\n Gray pixels are those pixels where the red, green, and blue channel values\n are similar, i.e. under a specified tolerance.\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input image\n tolerance : int, optional\n if difference between values is below this threshold,\n values are considered similar and thus filtered out. Default is 15.\n\n Returns\n -------\n PIL.Image.Image\n Mask image where the grays values are masked out\n \"\"\"\n\n if np.array(img).ndim != 3:\n raise ValueError(\"Input must be 3D.\")\n # TODO: class image mode exception: raise exception if not RGB(A)\n img_arr = np.array(img).astype(np.int64)\n rg_diff = abs(img_arr[:, :, 0] - img_arr[:, :, 1]) > tolerance\n rb_diff = abs(img_arr[:, :, 0] - img_arr[:, :, 2]) > tolerance\n gb_diff = abs(img_arr[:, :, 1] - img_arr[:, :, 2]) > tolerance\n filter_grays = rg_diff | rb_diff | gb_diff\n return filter_grays\n\n\ndef green_channel_filter(\n img: PIL.Image.Image,\n green_thresh: int = 200,\n avoid_overmask: bool = True,\n overmask_thresh: float = 90.0,\n) -> np.ndarray:\n \"\"\"Mask pixels in an RGB image with G-channel greater than a specified threshold.\n\n Create a mask to filter out pixels with a green channel value greater than\n a particular threshold, since hematoxylin and eosin are purplish and pinkish,\n which do not have much green to them.\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input RGB image\n green_thresh : int, optional\n Green channel threshold value (0 to 255). Default is 200.\n If value is greater than green_thresh, mask out pixel.\n avoid_overmask : bool, optional\n If True, avoid masking above the overmask_thresh percentage. Default is True.\n overmask_thresh : float, optional\n If avoid_overmask is True, avoid masking above this percentage value. Default is\n 90.0\n\n Returns\n -------\n np.ndarray\n Boolean mask where pixels above a particular green channel\n threshold have been masked out.\n \"\"\"\n if green_thresh > 255.0 or green_thresh < 0.0:\n raise ValueError(\"threshold must be in range [0, 255]\")\n green = np.array(img)[:, :, 1]\n g_mask = green <= green_thresh\n mask_percentage = mask_percent(g_mask)\n if avoid_overmask and (mask_percentage >= overmask_thresh) and (green_thresh < 255):\n new_green_thresh = math.ceil((255 + green_thresh) / 2)\n g_mask = green_channel_filter(\n np.array(img), new_green_thresh, avoid_overmask, overmask_thresh\n )\n return g_mask\n\n\ndef green_filter(\n img: PIL.Image.Image, red_thresh: int, green_thresh: int, blue_thresh: int\n) -> np.ndarray:\n \"\"\"Filter out greenish colors in an RGB image.\n The mask is based on a pixel being above a red channel threshold value, below a\n green channel threshold value, and below a blue channel threshold value.\n\n Note that for the green ink, the green and blue channels tend to track together, so\n for blue channel we use a lower threshold rather than an upper threshold value.\n\n Parameters\n ----------\n img : PIL.Image.Image\n RGB input image.\n red_thresh : int\n Red channel upper threshold value.\n green_thresh : int\n Green channel lower threshold value.\n blue_thresh : int\n Blue channel lower threshold value.\n\n Returns\n -------\n np.ndarray\n Boolean NumPy array representing the mask.\n \"\"\"\n if np.array(img).ndim != 3:\n raise ValueError(\"Input must be 3D.\")\n if not (\n 0 <= red_thresh <= 255 and 0 <= green_thresh <= 255 and 0 <= blue_thresh <= 255\n ):\n raise ValueError(\"RGB Thresholds must be in range [0, 255]\")\n\n img_arr = np.array(img)\n red = img_arr[:, :, 0] > red_thresh\n green = img_arr[:, :, 1] < green_thresh\n blue = img_arr[:, :, 2] < blue_thresh\n return red | green | blue\n\n\ndef hysteresis_threshold_mask(\n img: PIL.Image.Image, low: int = 50, high: int = 100\n) -> np.ndarray:\n \"\"\"Mask an image using hysteresis threshold\n\n Compute the Hysteresis threshold on the complement of a grayscale image,\n and return boolean mask based on pixels above this threshold.\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input image.\n low : int, optional\n low threshold. Default is 50.\n high : int, optional\n high threshold. Default is 100.\n\n Returns\n -------\n np.ndarray\n Boolean NumPy array where True represents a pixel above Otsu threshold.\n \"\"\"\n if low is None or high is None:\n raise ValueError(\"thresholds cannot be None\")\n grey_scale = PIL.ImageOps.grayscale(img)\n comp = invert(grey_scale)\n hyst_mask = sk_filters.apply_hysteresis_threshold(np.array(comp), low, high)\n return hyst_mask\n\n\ndef otsu_threshold(\n img: PIL.Image.Image, relate: Callable[..., Any] = operator.lt\n) -> np.ndarray:\n \"\"\"Mask image based on pixel above Otsu threshold.\n\n Compute Otsu threshold on image and return boolean mask based on pixels above this\n threshold.\n\n Note that Otsu threshold is expected to work correctly only for grayscale images.\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input image.\n relate : operator, optional\n Operator to be used to compute the mask from the threshold. Default is\n operator.lt\n\n Returns\n -------\n np.ndarray\n Boolean NumPy array where True represents a pixel above Otsu threshold.\n \"\"\"\n if img.mode in [\"RGB\", \"RGBA\"]:\n image = PIL.ImageOps.grayscale(img)\n warn(\n \"otsu_threshold is expected to work correctly only for grayscale images.\"\n \"NOTE: the image will be converted to grayscale before applying Otsu\"\n \"threshold\"\n )\n else:\n image = img\n\n otsu_thresh = sk_filters.threshold_otsu(np.array(image))\n return threshold_to_mask(image, otsu_thresh, relate)\n\n\ndef red_filter(\n img: PIL.Image.Image, red_thresh: int, green_thresh: int, blue_thresh: int\n) -> np.ndarray:\n \"\"\"Mask reddish colors in an RGB image.\n\n Create a mask to filter out reddish colors, where the mask is based on a pixel\n being above a red channel threshold value, below a green channel threshold value,\n and below a blue channel threshold value.\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input RGB image\n red_thresh : int\n Red channel lower threshold value.\n green_thresh : int\n Green channel upper threshold value.\n blue_thresh : int\n Blue channel upper threshold value.\n\n Returns\n -------\n np.ndarray\n Boolean NumPy array representing the mask.\n \"\"\"\n if np.array(img).ndim != 3:\n raise ValueError(\"Input must be 3D.\")\n if not (\n 0 <= red_thresh <= 255 and 0 <= green_thresh <= 255 and 0 <= blue_thresh <= 255\n ):\n raise ValueError(\"RGB Thresholds must be in range [0, 255]\")\n\n img_arr = np.array(img)\n red = img_arr[:, :, 0] < red_thresh\n green = img_arr[:, :, 1] > green_thresh\n blue = img_arr[:, :, 2] > blue_thresh\n return red | green | blue\n\n\ndef yen_threshold(\n img: PIL.Image.Image, relate: Callable[..., Any] = operator.lt\n) -> np.ndarray:\n \"\"\"Mask image based on pixel below Yen's threshold.\n\n Compute Yen threshold on image and return boolean mask based on pixels below this\n threshold.\n\n Parameters\n ----------\n img : PIL.Image.Image\n Input image.\n relate : operator, optional\n Operator to be used to compute the mask from the threshold. Default is\n operator.lt\n\n Returns\n -------\n np.ndarray\n Boolean NumPy array where True represents a pixel below Yen's threshold.\n \"\"\"\n\n yen_thresh = sk_filters.threshold_yen(np.array(img))\n return threshold_to_mask(img, yen_thresh, relate)\n" ]
[ [ "numpy.array", "numpy.ones", "numpy.percentile" ] ]
paulchou0309/obj
[ "d7ae404fa73db60a6fe539d613e48f478b81dbef" ]
[ "object_detection/exporter.py" ]
[ "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Functions to export object detection inference graph.\"\"\"\nimport logging\nimport os\nimport tempfile\nimport tensorflow as tf\nfrom tensorflow.core.protobuf import rewriter_config_pb2\nfrom tensorflow.python import pywrap_tensorflow\nfrom tensorflow.python.client import session\nfrom tensorflow.python.framework import graph_util\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.saved_model import signature_constants\nfrom tensorflow.python.training import saver as saver_lib\nfrom object_detection.builders import model_builder\nfrom object_detection.core import standard_fields as fields\nfrom object_detection.data_decoders import tf_example_decoder\n\nslim = tf.contrib.slim\n\n\n# TODO: Replace with freeze_graph.freeze_graph_with_def_protos when\n# newer version of Tensorflow becomes more common.\ndef freeze_graph_with_def_protos(\n input_graph_def,\n input_saver_def,\n input_checkpoint,\n output_node_names,\n restore_op_name,\n filename_tensor_name,\n clear_devices,\n initializer_nodes,\n optimize_graph=True,\n variable_names_blacklist=''):\n \"\"\"Converts all variables in a graph and checkpoint into constants.\"\"\"\n del restore_op_name, filename_tensor_name # Unused by updated loading code.\n\n # 'input_checkpoint' may be a prefix if we're using Saver V2 format\n if not saver_lib.checkpoint_exists(input_checkpoint):\n raise ValueError(\n 'Input checkpoint \"' + input_checkpoint + '\" does not exist!')\n\n if not output_node_names:\n raise ValueError(\n 'You must supply the name of a node to --output_node_names.')\n\n # Remove all the explicit device specifications for this node. This helps to\n # make the graph more portable.\n if clear_devices:\n for node in input_graph_def.node:\n node.device = ''\n\n with tf.Graph().as_default():\n tf.import_graph_def(input_graph_def, name='')\n\n if optimize_graph:\n logging.info('Graph Rewriter optimizations enabled')\n rewrite_options = rewriter_config_pb2.RewriterConfig(\n optimize_tensor_layout=True)\n rewrite_options.optimizers.append('pruning')\n rewrite_options.optimizers.append('constfold')\n rewrite_options.optimizers.append('layout')\n graph_options = tf.GraphOptions(\n rewrite_options=rewrite_options, infer_shapes=True)\n else:\n logging.info('Graph Rewriter optimizations disabled')\n graph_options = tf.GraphOptions()\n config = tf.ConfigProto(graph_options=graph_options)\n with session.Session(config=config) as sess:\n if input_saver_def:\n saver = saver_lib.Saver(saver_def=input_saver_def)\n saver.restore(sess, input_checkpoint)\n else:\n var_list = {}\n reader = pywrap_tensorflow.NewCheckpointReader(input_checkpoint)\n var_to_shape_map = reader.get_variable_to_shape_map()\n for key in var_to_shape_map:\n try:\n tensor = sess.graph.get_tensor_by_name(key + ':0')\n except KeyError:\n # This tensor doesn't exist in the graph (for example it's\n # 'global_step' or a similar housekeeping element) so skip it.\n continue\n var_list[key] = tensor\n saver = saver_lib.Saver(var_list=var_list)\n saver.restore(sess, input_checkpoint)\n if initializer_nodes:\n sess.run(initializer_nodes)\n\n variable_names_blacklist = (variable_names_blacklist.split(',') if\n variable_names_blacklist else None)\n output_graph_def = graph_util.convert_variables_to_constants(\n sess,\n input_graph_def,\n output_node_names.split(','),\n variable_names_blacklist=variable_names_blacklist)\n\n return output_graph_def\n\n\ndef replace_variable_values_with_moving_averages(graph,\n current_checkpoint_file,\n new_checkpoint_file):\n \"\"\"Replaces variable values in the checkpoint with their moving averages.\n\n If the current checkpoint has shadow variables maintaining moving averages of\n the variables defined in the graph, this function generates a new checkpoint\n where the variables contain the values of their moving averages.\n\n Args:\n graph: a tf.Graph object.\n current_checkpoint_file: a checkpoint containing both original variables and\n their moving averages.\n new_checkpoint_file: file path to write a new checkpoint.\n \"\"\"\n with graph.as_default():\n variable_averages = tf.train.ExponentialMovingAverage(0.0)\n ema_variables_to_restore = variable_averages.variables_to_restore()\n with tf.Session() as sess:\n read_saver = tf.train.Saver(ema_variables_to_restore)\n read_saver.restore(sess, current_checkpoint_file)\n write_saver = tf.train.Saver()\n write_saver.save(sess, new_checkpoint_file)\n\n\ndef _image_tensor_input_placeholder(input_shape=None):\n \"\"\"Returns input placeholder and a 4-D uint8 image tensor.\"\"\"\n if input_shape is None:\n input_shape = (None, None, None, 3)\n input_tensor = tf.placeholder(\n dtype=tf.uint8, shape=input_shape, name='image_tensor')\n return input_tensor, input_tensor\n\n\ndef _tf_example_input_placeholder():\n \"\"\"Returns input that accepts a batch of strings with tf examples.\n\n Returns:\n a tuple of input placeholder and the output decoded images.\n \"\"\"\n batch_tf_example_placeholder = tf.placeholder(\n tf.string, shape=[None], name='tf_example')\n def decode(tf_example_string_tensor):\n tensor_dict = tf_example_decoder.TfExampleDecoder().decode(\n tf_example_string_tensor)\n image_tensor = tensor_dict[fields.InputDataFields.image]\n return image_tensor\n return (batch_tf_example_placeholder,\n tf.map_fn(decode,\n elems=batch_tf_example_placeholder,\n dtype=tf.uint8,\n parallel_iterations=32,\n back_prop=False))\n\n\ndef _encoded_image_string_tensor_input_placeholder():\n \"\"\"Returns input that accepts a batch of PNG or JPEG strings.\n\n Returns:\n a tuple of input placeholder and the output decoded images.\n \"\"\"\n batch_image_str_placeholder = tf.placeholder(\n dtype=tf.string,\n shape=[None],\n name='encoded_image_string_tensor')\n def decode(encoded_image_string_tensor):\n image_tensor = tf.image.decode_image(encoded_image_string_tensor,\n channels=3)\n image_tensor.set_shape((None, None, 3))\n return image_tensor\n return (batch_image_str_placeholder,\n tf.map_fn(\n decode,\n elems=batch_image_str_placeholder,\n dtype=tf.uint8,\n parallel_iterations=32,\n back_prop=False))\n\n\ninput_placeholder_fn_map = {\n 'image_tensor': _image_tensor_input_placeholder,\n 'encoded_image_string_tensor':\n _encoded_image_string_tensor_input_placeholder,\n 'tf_example': _tf_example_input_placeholder,\n}\n\n\ndef _add_output_tensor_nodes(postprocessed_tensors,\n output_collection_name='inference_op'):\n \"\"\"Adds output nodes for detection boxes and scores.\n\n Adds the following nodes for output tensors -\n * num_detections: float32 tensor of shape [batch_size].\n * detection_boxes: float32 tensor of shape [batch_size, num_boxes, 4]\n containing detected boxes.\n * detection_scores: float32 tensor of shape [batch_size, num_boxes]\n containing scores for the detected boxes.\n * detection_classes: float32 tensor of shape [batch_size, num_boxes]\n containing class predictions for the detected boxes.\n * detection_masks: (Optional) float32 tensor of shape\n [batch_size, num_boxes, mask_height, mask_width] containing masks for each\n detection box.\n\n Args:\n postprocessed_tensors: a dictionary containing the following fields\n 'detection_boxes': [batch, max_detections, 4]\n 'detection_scores': [batch, max_detections]\n 'detection_classes': [batch, max_detections]\n 'detection_masks': [batch, max_detections, mask_height, mask_width]\n (optional).\n 'num_detections': [batch]\n output_collection_name: Name of collection to add output tensors to.\n\n Returns:\n A tensor dict containing the added output tensor nodes.\n \"\"\"\n label_id_offset = 1\n boxes = postprocessed_tensors.get('detection_boxes')\n scores = postprocessed_tensors.get('detection_scores')\n classes = postprocessed_tensors.get('detection_classes') + label_id_offset\n masks = postprocessed_tensors.get('detection_masks')\n num_detections = postprocessed_tensors.get('num_detections')\n outputs = {}\n outputs['detection_boxes'] = tf.identity(boxes, name='detection_boxes')\n outputs['detection_scores'] = tf.identity(scores, name='detection_scores')\n outputs['detection_classes'] = tf.identity(classes, name='detection_classes')\n outputs['num_detections'] = tf.identity(num_detections, name='num_detections')\n if masks is not None:\n outputs['detection_masks'] = tf.identity(masks, name='detection_masks')\n for output_key in outputs:\n tf.add_to_collection(output_collection_name, outputs[output_key])\n if masks is not None:\n tf.add_to_collection(output_collection_name, outputs['detection_masks'])\n return outputs\n\ndef _add_predict_tensor_nodes(predict_tensors,\n output_collection_name='predict_op'):\n \"\"\"Adds predict nodes for region proposal boxes and feature.\n\n Adds the following nodes for output tensors -\n * proposal_boxes_normalized: float32 tensor of shape [batch_size, num_boxes, 4]\n containing region proposal boxes(after non maximum surpression).\n\n Args:\n predict_tensors: a dictionary containing the following fields\n 'proposal_boxes_normalized': [batch, max_detections, 4]\n output_collection_name: Name of collection to add output tensors to.\n\n Returns:\n A tensor dict containing the added output tensor nodes.\n \"\"\"\n label_id_offset = 1\n boxes = predict_tensors.get('proposal_boxes_normalized')\n outputs = {}\n outputs['proposal_boxes'] = tf.identity(boxes, name='proposal_boxes')\n for output_key in outputs:\n tf.add_to_collection(output_collection_name, outputs[output_key])\n return outputs\n\ndef _write_frozen_graph(frozen_graph_path, frozen_graph_def):\n \"\"\"Writes frozen graph to disk.\n\n Args:\n frozen_graph_path: Path to write inference graph.\n frozen_graph_def: tf.GraphDef holding frozen graph.\n \"\"\"\n with gfile.GFile(frozen_graph_path, 'wb') as f:\n f.write(frozen_graph_def.SerializeToString())\n logging.info('%d ops in the final graph.', len(frozen_graph_def.node))\n\n\ndef _write_saved_model(saved_model_path,\n frozen_graph_def,\n inputs,\n outputs):\n \"\"\"Writes SavedModel to disk.\n\n If checkpoint_path is not None bakes the weights into the graph thereby\n eliminating the need of checkpoint files during inference. If the model\n was trained with moving averages, setting use_moving_averages to true\n restores the moving averages, otherwise the original set of variables\n is restored.\n\n Args:\n saved_model_path: Path to write SavedModel.\n frozen_graph_def: tf.GraphDef holding frozen graph.\n inputs: The input image tensor to use for detection.\n outputs: A tensor dictionary containing the outputs of a DetectionModel.\n \"\"\"\n with tf.Graph().as_default():\n with session.Session() as sess:\n\n tf.import_graph_def(frozen_graph_def, name='')\n\n builder = tf.saved_model.builder.SavedModelBuilder(saved_model_path)\n\n tensor_info_inputs = {\n 'inputs': tf.saved_model.utils.build_tensor_info(inputs)}\n tensor_info_outputs = {}\n for k, v in outputs.items():\n tensor_info_outputs[k] = tf.saved_model.utils.build_tensor_info(v)\n\n detection_signature = (\n tf.saved_model.signature_def_utils.build_signature_def(\n inputs=tensor_info_inputs,\n outputs=tensor_info_outputs,\n method_name=signature_constants.PREDICT_METHOD_NAME))\n\n builder.add_meta_graph_and_variables(\n sess, [tf.saved_model.tag_constants.SERVING],\n signature_def_map={\n signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:\n detection_signature,\n },\n )\n builder.save()\n\n\ndef _write_graph_and_checkpoint(inference_graph_def,\n model_path,\n input_saver_def,\n trained_checkpoint_prefix):\n for node in inference_graph_def.node:\n node.device = ''\n with tf.Graph().as_default():\n tf.import_graph_def(inference_graph_def, name='')\n with session.Session() as sess:\n saver = saver_lib.Saver(saver_def=input_saver_def,\n save_relative_paths=True)\n saver.restore(sess, trained_checkpoint_prefix)\n saver.save(sess, model_path)\n\n\ndef _export_inference_graph(input_type,\n detection_model,\n use_moving_averages,\n trained_checkpoint_prefix,\n output_directory,\n additional_output_tensor_names=None,\n input_shape=None,\n optimize_graph=True,\n output_collection_name='inference_op'):\n \"\"\"Export helper.\"\"\"\n tf.gfile.MakeDirs(output_directory)\n frozen_graph_path = os.path.join(output_directory,\n 'frozen_inference_graph.pb')\n saved_model_path = os.path.join(output_directory, 'saved_model')\n model_path = os.path.join(output_directory, 'model.ckpt')\n\n if input_type not in input_placeholder_fn_map:\n raise ValueError('Unknown input type: {}'.format(input_type))\n placeholder_args = {}\n if input_shape is not None:\n if input_type != 'image_tensor':\n raise ValueError('Can only specify input shape for `image_tensor` '\n 'inputs.')\n placeholder_args['input_shape'] = input_shape\n placeholder_tensor, input_tensors = input_placeholder_fn_map[input_type](\n **placeholder_args)\n inputs = tf.to_float(input_tensors)\n preprocessed_inputs = detection_model.preprocess(inputs)\n output_tensors = detection_model.predict(preprocessed_inputs)\n outputs = _add_predict_tensor_nodes(output_tensors,\n output_collection_name)\n \n # postprocessed_tensors = detection_model.postprocess(output_tensors)\n # outputs = _add_output_tensor_nodes(postprocessed_tensors,\n # output_collection_name)\n # Add global step to the graph.\n slim.get_or_create_global_step()\n\n if use_moving_averages:\n temp_checkpoint_file = tempfile.NamedTemporaryFile()\n replace_variable_values_with_moving_averages(\n tf.get_default_graph(), trained_checkpoint_prefix,\n temp_checkpoint_file.name)\n checkpoint_to_use = temp_checkpoint_file.name\n else:\n checkpoint_to_use = trained_checkpoint_prefix\n\n saver = tf.train.Saver()\n input_saver_def = saver.as_saver_def()\n\n _write_graph_and_checkpoint(\n inference_graph_def=tf.get_default_graph().as_graph_def(),\n model_path=model_path,\n input_saver_def=input_saver_def,\n trained_checkpoint_prefix=checkpoint_to_use)\n\n if additional_output_tensor_names is not None:\n output_node_names = ','.join(list(outputs.keys())+additional_output_tensor_names)\n else:\n output_node_names = ','.join(outputs.keys())\n\n frozen_graph_def = freeze_graph_with_def_protos(\n input_graph_def=tf.get_default_graph().as_graph_def(),\n input_saver_def=input_saver_def,\n input_checkpoint=checkpoint_to_use,\n output_node_names=output_node_names,\n restore_op_name='save/restore_all',\n filename_tensor_name='save/Const:0',\n clear_devices=True,\n optimize_graph=optimize_graph,\n initializer_nodes='')\n _write_frozen_graph(frozen_graph_path, frozen_graph_def)\n _write_saved_model(saved_model_path, frozen_graph_def,\n placeholder_tensor, outputs)\n\n\ndef export_inference_graph(input_type,\n pipeline_config,\n trained_checkpoint_prefix,\n output_directory,\n input_shape=None,\n optimize_graph=True,\n output_collection_name='inference_op',\n additional_output_tensor_names=['SecondStageBoxPredictor/AvgPool']):\n \"\"\"Exports inference graph for the model specified in the pipeline config.\n\n Args:\n input_type: Type of input for the graph. Can be one of [`image_tensor`,\n `tf_example`].\n pipeline_config: pipeline_pb2.TrainAndEvalPipelineConfig proto.\n trained_checkpoint_prefix: Path to the trained checkpoint file.\n output_directory: Path to write outputs.\n input_shape: Sets a fixed shape for an `image_tensor` input. If not\n specified, will default to [None, None, None, 3].\n optimize_graph: Whether to optimize graph using Grappler.\n output_collection_name: Name of collection to add output tensors to.\n If None, does not add output tensors to a collection.\n additional_output_tensor_names: list of additional output\n tensors to include in the frozen graph.\n \"\"\"\n detection_model = model_builder.build(pipeline_config.model,\n is_training=False)\n _export_inference_graph(input_type, detection_model,\n pipeline_config.eval_config.use_moving_averages,\n trained_checkpoint_prefix,\n output_directory, additional_output_tensor_names,\n input_shape, optimize_graph, output_collection_name)\n" ]
[ [ "tensorflow.python.training.saver.Saver", "tensorflow.python.platform.gfile.GFile", "tensorflow.identity", "tensorflow.train.ExponentialMovingAverage", "tensorflow.Graph", "tensorflow.python.pywrap_tensorflow.NewCheckpointReader", "tensorflow.python.client.session.Session", "tensorflow.import_graph_def", "tensorflow.gfile.MakeDirs", "tensorflow.saved_model.builder.SavedModelBuilder", "tensorflow.GraphOptions", "tensorflow.add_to_collection", "tensorflow.core.protobuf.rewriter_config_pb2.RewriterConfig", "tensorflow.to_float", "tensorflow.python.training.saver.checkpoint_exists", "tensorflow.saved_model.utils.build_tensor_info", "tensorflow.train.Saver", "tensorflow.Session", "tensorflow.ConfigProto", "tensorflow.image.decode_image", "tensorflow.placeholder", "tensorflow.map_fn", "tensorflow.saved_model.signature_def_utils.build_signature_def", "tensorflow.get_default_graph" ] ]
lydia07/mdsearch
[ "a328e822d6d66869aeefef687887b0a39d4f4512" ]
[ "mdsearch/Similarity/sentence_similarity.py" ]
[ "import torch\nfrom scipy.spatial.distance import cosine\nfrom transformers import BertModel, BertTokenizer\nimport os\n\n\nclass SentenceSimilarity:\n\n def __init__(self, model_path='bert-base-uncased'):\n self.tokenizer = BertTokenizer.from_pretrained(model_path)\n self.model = BertModel.from_pretrained(model_path)\n self.model.eval()\n self.device = torch.device('cuda:0')\n self.model = self.model.to(self.device)\n\n def text_to_tensor(self, text):\n text = text.strip().lower()\n tokens = self.tokenizer.tokenize(text)\n tokens_ids = self.tokenizer.convert_tokens_to_ids(tokens)\n tokens_ids = self.tokenizer.build_inputs_with_special_tokens(tokens_ids)\n tokens_tensor = torch.tensor([tokens_ids])\n return tokens_tensor\n\n def get_embedding(self, sent):\n tokens_tensor = self.text_to_tensor(sent)\n tokens_tensor = tokens_tensor.to(self.device)\n with torch.no_grad():\n output = self.model(tokens_tensor)[0]\n embedding = output[0].mean(dim=0).cpu().numpy()\n return embedding\n\n def similarity(self, emb1, emb2):\n return cosine(emb1, emb2)\n\n\nif __name__ == '__main__':\n\n ss = SentenceSimilarity()\n s1 = 'I am a girl'\n s2 = 'I am a boy'\n s3 = 'Thank you'\n print(\"1\")\n e1 = ss.get_embedding(s1)\n print(type(e1))\n e2 = ss.get_embedding(s2)\n e3 = ss.get_embedding(s3)\n print(\"2\")\n print(1 - ss.similarity(e1, e2))\n print(1 - ss.similarity(e1, e3))\n print(\"3\")\n" ]
[ [ "torch.no_grad", "torch.tensor", "torch.device", "scipy.spatial.distance.cosine" ] ]
ParadoxZW/CIFAR100-PRACTICE
[ "175d9a72fc8e7d79ec3ef8670028d1efe830e5b9" ]
[ "Chanet.py" ]
[ "# just for fun, give channel some meanings about relations\n# between positions.\nfrom modules import *\nfrom torch import tensor\nimport torch\nimport numpy as np\nimport torch.nn.functional as F\nfrom torch import nn\n\n\n\nclass Group(nn.Module):\n \"\"\"\n resblocks with same input and output size.\n \"\"\"\n\n def __init__(self, n, in_channels, in_width):\n super(Group, self).__init__()\n branch1 = [SeResBlock(channels=in_channels) for _ in range(n)]\n self.branch1 = nn.Sequential(*group)\n branch2 = [Channel_Attn(id_dim=in_channels, N=in_width**2) for _ in range(n)]\n self.branch2 = nn.Sequential(*group)\n\n def forward(self, x):\n return torch.cat((self.branch1(x), self.branch2(x)), 1)\n\n\nclass Chanet(nn.Module):\n \"\"\"\n wideresnet for cifar10.\n \"\"\"\n\n def __init__(self, n=6, k=10):\n super(Chanet, self).__init__()\n self.cin = Conv2d(3, 16 * k,\n kernel_size=3, stride=1, padding=1)\n self.fc = nn.Linear(128 * k, 10)\n self.resnet = nn.Sequential(Group(n=n, in_channels=16 * k, in_width=32),\n nn.MaxPool2d(2, stride=2, padding=0),\n Group(n=n, in_channels=32 * k, in_width=16),\n nn.MaxPool2d(2, stride=2, padding=0),\n Group(n=n, in_channels=64 * k, in_width=8))\n self.GlobalAvgPooling = nn.AdaptiveAvgPool2d(1)\n\n def forward(self, x):\n x = self.cin(x)\n x = self.resnet(x)\n x = self.GlobalAvgPooling(x)\n x = self.fc(x.view(x.shape[0], -1))\n # return F.softmax(x, dim=1)\n return x\n" ]
[ [ "torch.nn.MaxPool2d", "torch.nn.AdaptiveAvgPool2d", "torch.nn.Linear", "torch.nn.Sequential" ] ]
JingweiToo/Machine-Learning-Regression-Toolbox
[ "77f2b1ee49cf5e5116102197064ce2dc13a23ed0" ]
[ "MLR/nn.py" ]
[ "import numpy as np\r\nfrom sklearn.neural_network import MLPRegressor\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.model_selection import KFold\r\nfrom sklearn.model_selection import LeaveOneOut\r\nfrom sklearn.metrics import r2_score\r\n\r\n\r\ndef jho(feat, label, opts):\r\n ho = 0.3 # ratio of testing set\r\n hls = 100 # hidden layer size \r\n fun = 'relu' # activation function\r\n max_iter = 100 # maximum iterations\r\n \r\n if 'ho' in opts:\r\n ho = opts['ho']\r\n if 'hls' in opts:\r\n hls = opts['hls']\r\n if 'fun' in opts:\r\n fun = opts['fun']\r\n if 'T' in opts:\r\n max_iter = opts['T']\r\n \r\n # number of instances\r\n num_data = np.size(feat, 0)\r\n label = label.reshape(num_data) # Solve bug\r\n \r\n # prepare data\r\n xtrain, xtest, ytrain, ytest = train_test_split(feat, label, test_size=ho) \r\n # train model\r\n mdl = MLPRegressor(hidden_layer_sizes=(hls,), activation=fun, max_iter=max_iter) \r\n mdl.fit(xtrain, ytrain)\r\n \r\n # prediction\r\n ypred = mdl.predict(xtest)\r\n \r\n # mean square error\r\n mse = np.mean((ytest - ypred) ** 2)\r\n # r2 score\r\n r2 = r2_score(ytest, ypred)\r\n \r\n print(\"Mean Square Error (NN_HO):\", mse)\r\n print(\"R Square Score (NN_HO):\", r2)\r\n \r\n nn = {'mse': mse, 'r2': r2, 'xtest': xtest, 'ytest': ytest, 'ypred': ypred}\r\n \r\n return nn\r\n \r\n\r\ndef jkfold(feat, label, opts):\r\n kfold = 10 # number of k in kfold\r\n hls = 100 # hidden layer size \r\n fun = 'relu' # activation function\r\n max_iter = 100 # maximum iterations\r\n \r\n if 'kfold' in opts:\r\n kfold = opts['kfold']\r\n if 'hls' in opts:\r\n hls = opts['hls']\r\n if 'fun' in opts:\r\n fun = opts['fun']\r\n if 'T' in opts:\r\n max_iter = opts['T']\r\n \r\n # number of instances\r\n num_data = np.size(feat, 0)\r\n # define selected features\r\n x_data = feat\r\n y_data = label.reshape(num_data) # Solve bug\r\n \r\n fold = KFold(n_splits=kfold)\r\n fold.get_n_splits(x_data, y_data)\r\n \r\n ytest2 = []\r\n ypred2 = []\r\n t = 0\r\n for train_idx, test_idx in fold.split(x_data, y_data):\r\n xtrain = x_data[train_idx,:] \r\n ytrain = y_data[train_idx]\r\n xtest = x_data[test_idx,:]\r\n ytest = y_data[test_idx]\r\n # train model\r\n mdl = MLPRegressor(hidden_layer_sizes=(hls,), activation=fun, max_iter=max_iter) \r\n mdl.fit(xtrain, ytrain)\r\n # prediction\r\n ypred = mdl.predict(xtest)\r\n \r\n ytest2 = np.concatenate((ytest2, ytest), axis=0)\r\n ypred2 = np.concatenate((ypred2, ypred), axis=0)\r\n \r\n if t == 0:\r\n xtest2 = xtest\r\n else:\r\n xtest2 = np.concatenate((xtest2, xtest), axis=0)\r\n \r\n t += 1\r\n\r\n # mean square error\r\n mse = np.mean((ytest2 - ypred2) ** 2)\r\n # r2 score\r\n r2 = r2_score(ytest2, ypred2)\r\n \r\n print(\"Mean Square Error (NN_K-fold):\", mse)\r\n print(\"R Square Score (NN_K-fold):\", r2)\r\n \r\n nn = {'mse': mse, 'r2': r2, 'xtest': xtest2, 'ytest': ytest2, 'ypred': ypred2}\r\n \r\n return nn\r\n\r\n\r\ndef jloo(feat, label, opts):\r\n hls = 100 # hidden layer size \r\n fun = 'relu' # activation function\r\n max_iter = 100 # maximum iterations\r\n\r\n if 'hls' in opts:\r\n hls = opts['hls']\r\n if 'fun' in opts:\r\n fun = opts['fun']\r\n if 'T' in opts:\r\n max_iter = opts['T']\r\n \r\n # number of instances\r\n num_data = np.size(feat, 0)\r\n # define selected features\r\n x_data = feat\r\n y_data = label.reshape(num_data) # Solve bug\r\n \r\n loo = LeaveOneOut()\r\n loo.get_n_splits(x_data)\r\n \r\n ytest2 = []\r\n ypred2 = []\r\n t = 0\r\n for train_idx, test_idx in loo.split(x_data):\r\n xtrain = x_data[train_idx,:] \r\n ytrain = y_data[train_idx]\r\n xtest = x_data[test_idx,:]\r\n ytest = y_data[test_idx]\r\n # train model\r\n mdl = MLPRegressor(hidden_layer_sizes=(hls,), activation=fun, max_iter=max_iter) \r\n mdl.fit(xtrain, ytrain)\r\n # prediction\r\n ypred = mdl.predict(xtest)\r\n \r\n ytest2 = np.concatenate((ytest2, ytest), axis=0)\r\n ypred2 = np.concatenate((ypred2, ypred), axis=0)\r\n \r\n if t == 0:\r\n xtest2 = xtest\r\n else:\r\n xtest2 = np.concatenate((xtest2, xtest), axis=0)\r\n \r\n t += 1\r\n \r\n # mean square error\r\n mse = np.mean((ytest2 - ypred2) ** 2)\r\n # r2 score\r\n r2 = r2_score(ytest2, ypred2)\r\n \r\n print(\"Mean Square Error (NN_LOO):\", mse)\r\n print(\"R Square Score (NN_LOO):\", r2)\r\n \r\n nn = {'mse': mse, 'r2': r2, 'xtest': xtest2, 'ytest': ytest2, 'ypred': ypred2}\r\n \r\n return nn\r\n\r\n" ]
[ [ "sklearn.model_selection.LeaveOneOut", "numpy.concatenate", "numpy.size", "sklearn.model_selection.KFold", "sklearn.neural_network.MLPRegressor", "sklearn.metrics.r2_score", "sklearn.model_selection.train_test_split", "numpy.mean" ] ]
xxelloss/Markov-Learning
[ "56b47f046fcc130b33aeaff7792fd73ee40f0501" ]
[ "Markov_comp.py" ]
[ "# Markov chain comparison class\n# create multiple Markov_learning classes, and conduct comparison\n\nimport numpy as np\nimport Markov_learning as ml\nimport copy\n\nclass Markov_comp(object):\n # attributes\n # it may have multiple Markov_learning objects\n # maximum, 10\n ML=[]\n # how many MLs? for comparison between different evolution schedules.\n num_ML = 0\n # testmode?\n test_mode = 0\n # how many conditions?\n conditions = 0\n # status matrix size\n size = 0\n # current status matrix\n status_t0 = 0\n # total time length\n length = 0\n # matrix for comparison-regression.\n comp_matrix = []\n\n\n \n def __init__(self, conditions, size, length, schedules):\n #initialize\n # test mode, if all -1s\n if conditions == -1 & size == -1 & length == -1 & schedules == -1:\n # test mode, as published\n self.conditions = 3\n self.size = 2\n self.num_ML = 2\n # x = ml.Markov_learning(-1,-1,-1)\n# self.ML.append(x)\n# y = ml.Markov_learning(-2,-2,-2)\n# self.ML.append(y)\n self.ML_test1=copy.copy(ml.Markov_learning(-1,-1,-1))\n self.ML_test2=copy.copy(ml.Markov_learning(-2,-2,-2))\n# self.ML = [ml.Markov_learning(-1,-1,-1),ml.Markov_learning(-2,-2,-2)]\n# self.ML = [ml.Markov_learning() for i in range(2)]\n# self.ML[0] = ml.Markov_learning(-1,-1,-1)\n# self.ML[1] = ml.Markov_learning(-2,-2,-2)\n \n self.test_mode = 1\n self.length = 100\n self.status_t0 = np.zeros((self.size))\n\n\n # testmode\n def test1(self):\n if self.test_mode < 1:\n return -1\n self.ML[0].test1()\n \n" ]
[ [ "numpy.zeros" ] ]
Shank2358/NPMMR-Det
[ "869f3f537af9bc656f2bfdfa97ebb95bf70847a7" ]
[ "model/layers/multiscale_fusion_blocks.py" ]
[ "import torch\nimport torch.nn as nn\nfrom ..layers.convolutions import Convolutional, Separable_Conv_dila, Separable_Conv, Deformable_Convolutional\nimport torch.nn.functional as F\nfrom ..layers.attention_blocks import SELayer\n\nclass SPP(nn.Module):\n def __init__(self, depth=512):\n super(SPP,self).__init__()\n self.__maxpool5 = nn.MaxPool2d(kernel_size=5, stride=1, padding=2)\n self.__maxpool9 = nn.MaxPool2d(kernel_size=9, stride=1, padding=4)\n self.__maxpool13 = nn.MaxPool2d(kernel_size=13, stride=1, padding=6)\n self.__outconv = nn.Conv2d(depth * 4, depth, 1, 1)\n\n def forward(self, x):\n maxpool5 = self.__maxpool5(x)\n maxpool9 = self.__maxpool9(x)\n maxpool13 = self.__maxpool13(x)\n cat_maxpool = torch.cat([x, maxpool5, maxpool9, maxpool13], dim=1)\n SPP = self.__outconv(cat_maxpool)\n return SPP\n\nclass SPP_rec(nn.Module):\n def __init__(self, depth=512):\n super(SPP_rec,self).__init__()\n self.__maxpool5 = nn.MaxPool2d(kernel_size=5, stride=1, padding=2)\n self.__maxpool9 = nn.MaxPool2d(kernel_size=9, stride=1, padding=4)\n self.__maxpool13 = nn.MaxPool2d(kernel_size=13, stride=1, padding=6)\n\n self.__maxpool5w = nn.MaxPool2d(kernel_size=(5,1), stride=1, padding=(2,0))\n self.__maxpool5h = nn.MaxPool2d(kernel_size=(1,5), stride=1, padding=(0,2))\n self.__maxpool9w = nn.MaxPool2d(kernel_size=(9,3), stride=1, padding=(4,1))\n self.__maxpool9h = nn.MaxPool2d(kernel_size=(3,9), stride=1, padding=(1,4))\n self.__maxpool13w = nn.MaxPool2d(kernel_size=(13,5), stride=1, padding=(6,2))\n self.__maxpool13h = nn.MaxPool2d(kernel_size=(5,13), stride=1, padding=(2,6))\n\n self.__outconv = nn.Conv2d(depth * 4, depth, 1, 1)\n\n def forward(self, x):\n maxpool5 = self.__maxpool5(x) + self.__maxpool5h(x) + self.__maxpool5w(x)\n maxpool9 = self.__maxpool9(x) + self.__maxpool9h(x) + self.__maxpool9w(x)\n maxpool13 = self.__maxpool13(x) + self.__maxpool13h(x) + self.__maxpool13w(x)\n cat_maxpool = torch.cat([x, maxpool5, maxpool9, maxpool13], dim=1)\n SPP_rec = self.__outconv(cat_maxpool)\n return SPP_rec\n\nclass ASPP_se(nn.Module):\n def __init__(self, in_channel=1280, depth=512):\n super(ASPP_se,self).__init__()\n self.__dilaconv1 = nn.Conv2d(in_channel, depth, 1, 1)\n self.__dilaconv5 = nn.Conv2d(in_channel, depth, 3, 1, padding=2, dilation=2)\n self.__dilaconv9 = nn.Conv2d(in_channel, depth, 3, 1, padding=4, dilation=4)\n self.__dilaconv13 = nn.Conv2d(in_channel, depth, 3, 1, padding=6, dilation=6)\n self.__outconv = nn.Conv2d(depth * 4, depth, 1, 1)\n self.__se = SELayer(depth)\n\n\n def forward(self, x):\n dilaconv1 = self.__dilaconv1(x)\n dilaconv5 = self.__dilaconv5(x)\n dilaconv9 = self.__dilaconv9(x)\n dilaconv13 = self.__dilaconv13(x)\n cat_dilaconv = torch.cat([dilaconv1, dilaconv5, dilaconv9, dilaconv13], dim=1)\n ASPP_se = self.__se(self.__outconv(cat_dilaconv))\n return ASPP_se\n\nclass ASPP(nn.Module):\n def __init__(self, in_channel=1280, depth=512):\n super(ASPP,self).__init__()\n self.__dilaconv1 = nn.Conv2d(in_channel, depth, 1, 1)\n self.__dilaconv5 = nn.Conv2d(in_channel, depth, 3, 1, padding=2, dilation=2)\n self.__dilaconv9 = nn.Conv2d(in_channel, depth, 3, 1, padding=4, dilation=4)\n self.__dilaconv13 = nn.Conv2d(in_channel, depth, 3, 1, padding=6, dilation=6)\n self.__outconv = nn.Conv2d(depth * 4, depth, 1, 1)\n\n def forward(self, x):\n dilaconv1 = self.__dilaconv1(x)\n dilaconv5 = self.__dilaconv5(x)\n dilaconv9 = self.__dilaconv9(x)\n dilaconv13 = self.__dilaconv13(x)\n cat_dilaconv = torch.cat([dilaconv1, dilaconv5, dilaconv9, dilaconv13], dim=1)\n ASPP = self.__outconv(cat_dilaconv)\n return ASPP\n\nclass Sparable_ASPP(nn.Module):\n def __init__(self, in_channel=1280, depth=512):\n super(Sparable_ASPP,self).__init__()\n self.__dilaconv1 = nn.Conv2d(in_channel, depth, 1, 1)\n self.__dilaconv5 = Separable_Conv_dila(in_channel, depth, 1, pad=2, dila=2)\n self.__dilaconv9 = Separable_Conv_dila(in_channel, depth, 1, pad=4, dila=4)\n self.__dilaconv13 = Separable_Conv_dila(in_channel, depth, 1, pad=6, dila=6)\n self.__outconv = nn.Conv2d(depth * 4, depth, 1, 1)\n\n def forward(self, x):\n dilaconv1 = self.__dilaconv1(x)\n dilaconv5 = self.__dilaconv5(x)\n dilaconv9 = self.__dilaconv9(x)\n dilaconv13 = self.__dilaconv13(x)\n cat_dilaconv = torch.cat([dilaconv1, dilaconv5, dilaconv9, dilaconv13], dim=1)\n ASPP = self.__outconv(cat_dilaconv)\n return ASPP\n\nclass Sparable_ASPP_se(nn.Module):\n def __init__(self, in_channel=1024, depth=512):\n super(Sparable_ASPP_se,self).__init__()\n self.__dilaconv1 = Separable_Conv(in_channel, depth, 1)\n self.__dilaconv5 = Separable_Conv_dila(depth, depth, 1, pad=2, dila=2)\n self.__dilaconv9 = Separable_Conv_dila(depth, depth//2, 1, pad=4, dila=4)\n self.__dilaconv13 = Separable_Conv_dila(depth, depth//2, 1, pad=6, dila=6)\n self.__outconv = nn.Conv2d(depth * 3, depth, 1, 1)\n #self.__outconv = Convolutional(filters_in=depth * 3, filters_out=depth, kernel_size=1, stride=1, pad=0, norm='bn', activate='leaky')\n self.__se = SELayer(depth)\n\n def forward(self, x):\n dilaconv1 = self.__dilaconv1(x)\n dilaconv5 = self.__dilaconv5(dilaconv1)\n dilaconv9 = self.__dilaconv9(dilaconv1)\n dilaconv13 = self.__dilaconv13(dilaconv1)\n cat_dilaconv = torch.cat([dilaconv1, dilaconv5, dilaconv9, dilaconv13], dim=1)\n ASPP_se = self.__se(self.__outconv(cat_dilaconv))\n #ASPP_se = self.__outconv(cat_dilaconv)\n return ASPP_se\n\nclass ASFF(nn.Module):\n def __init__(self, level, vis=False):\n super(ASFF, self).__init__()\n self.level = level\n self.dim = [512,256,128]\n self.inter_dim = self.dim[self.level]\n if level == 0:\n self.stride_level_1 = Convolutional(256, self.inter_dim, 3, 2, pad=1, norm='bn', activate='relu6')\n self.stride_level_2 = Convolutional(128, self.inter_dim, 3, 2, pad=1, norm='bn', activate='relu6')\n self.expand = Convolutional(self.inter_dim, 1024, 3, 1, pad=1, norm='bn', activate='relu6')\n elif level == 1:\n self.compress_level_0 = Convolutional(512, self.inter_dim, 1, 1, pad=0, norm='bn', activate='relu6')\n self.stride_level_2 = Convolutional(128, self.inter_dim, 3, 2, pad=1, norm='bn', activate='relu6')\n self.expand = Convolutional(self.inter_dim, 512, 3, 1, pad=1, norm='bn', activate='relu6')\n elif level == 2:\n self.compress_level_0 = Convolutional(512, self.inter_dim, 1, 1, pad=0, norm='bn', activate='relu6')\n self.compress_level_1 = Convolutional(256, self.inter_dim, 1, 1, pad=0, norm='bn', activate='relu6')\n self.expand = Convolutional(self.inter_dim, 256, 3, 1, pad=1, norm='bn', activate='relu6')\n compress_c = 16\n self.weight_level_0 = Convolutional(self.inter_dim, compress_c, 1, 1, pad=0, norm='bn', activate='relu6')\n self.weight_level_1 = Convolutional(self.inter_dim, compress_c, 1, 1, pad=0, norm='bn', activate='relu6')\n self.weight_level_2 = Convolutional(self.inter_dim, compress_c, 1, 1, pad=0, norm='bn', activate='relu6')\n self.weight_levels = nn.Conv2d(compress_c * 3, 3, kernel_size=1, stride=1, padding=0)\n self.vis = vis\n\n def forward(self, x_level_0, x_level_1, x_level_2):\n if self.level == 0:\n level_0_resized = x_level_0\n level_1_resized = self.stride_level_1(x_level_1)\n level_2_downsampled_inter = F.max_pool2d(x_level_2, 3, stride=2, padding=1)\n level_2_resized = self.stride_level_2(level_2_downsampled_inter)\n elif self.level == 1:\n level_0_compressed = self.compress_level_0(x_level_0)\n level_0_resized = F.interpolate(level_0_compressed, scale_factor=2, mode='nearest')\n level_1_resized = x_level_1\n level_2_resized = self.stride_level_2(x_level_2)\n elif self.level == 2:\n level_0_compressed = self.compress_level_0(x_level_0)\n level_0_resized = F.interpolate(level_0_compressed, scale_factor=4, mode='nearest')\n level_1_compressed = self.compress_level_1(x_level_1)\n level_1_resized = F.interpolate(level_1_compressed, scale_factor=2, mode='nearest')\n level_2_resized = x_level_2\n\n level_0_weight_v = self.weight_level_0(level_0_resized)\n level_1_weight_v = self.weight_level_1(level_1_resized)\n level_2_weight_v = self.weight_level_2(level_2_resized)\n levels_weight_v = torch.cat((level_0_weight_v, level_1_weight_v, level_2_weight_v), 1)\n levels_weight = self.weight_levels(levels_weight_v)\n levels_weight = F.softmax(levels_weight, dim=1)\n\n fused_out_reduced = level_0_resized * levels_weight[:, 0:1, :, :] + \\\n level_1_resized * levels_weight[:, 1:2, :, :] + \\\n level_2_resized * levels_weight[:, 2:, :, :]\n\n out = self.expand(fused_out_reduced)\n\n if self.vis:\n return out, levels_weight, fused_out_reduced.sum(dim=1)\n else:\n return out\n\nclass ASFF_Mobile(nn.Module):\n def __init__(self, level, vis=False):\n super(ASFF_Mobile, self).__init__()\n self.level = level\n self.dim = [512,256,128]\n self.inter_dim = self.dim[self.level]\n if level == 0:\n self.stride_level_1 = Separable_Conv(256, self.inter_dim, 2)\n self.stride_level_2 = Separable_Conv(128, self.inter_dim, 2)\n self.expand = Separable_Conv(self.inter_dim, 1024, 1)\n elif level == 1:\n self.compress_level_0 = Convolutional(512, self.inter_dim, 1, 1, pad=0, norm='bn', activate='relu6')\n self.stride_level_2 = Separable_Conv(128, self.inter_dim, 2)\n self.expand = Separable_Conv(self.inter_dim, 512, 1)\n elif level == 2:\n self.compress_level_0 = Convolutional(512, self.inter_dim, 1, 1, pad=0, norm='bn', activate='relu6')\n self.compress_level_1 = Convolutional(256, self.inter_dim, 1, 1, pad=0, norm='bn', activate='relu6')\n self.expand = Separable_Conv(self.inter_dim, 256, 1)\n compress_c = 16\n self.weight_level_0 = Convolutional(self.inter_dim, compress_c, 1, 1, pad=0, norm='bn', activate='relu6')\n self.weight_level_1 = Convolutional(self.inter_dim, compress_c, 1, 1, pad=0, norm='bn', activate='relu6')\n self.weight_level_2 = Convolutional(self.inter_dim, compress_c, 1, 1, pad=0, norm='bn', activate='relu6')\n self.weight_levels = nn.Conv2d(compress_c * 3, 3, kernel_size=1, stride=1, padding=0)\n self.vis = vis\n\n def forward(self, x_level_0, x_level_1, x_level_2):\n if self.level == 0:\n level_0_resized = x_level_0\n level_1_resized = self.stride_level_1(x_level_1)\n level_2_downsampled_inter = F.max_pool2d(x_level_2, 3, stride=2, padding=1)\n level_2_resized = self.stride_level_2(level_2_downsampled_inter)\n elif self.level == 1:\n level_0_compressed = self.compress_level_0(x_level_0)\n level_0_resized = F.interpolate(level_0_compressed, scale_factor=2, mode='nearest')\n level_1_resized = x_level_1\n level_2_resized = self.stride_level_2(x_level_2)\n elif self.level == 2:\n level_0_compressed = self.compress_level_0(x_level_0)\n level_0_resized = F.interpolate(level_0_compressed, scale_factor=4, mode='nearest')\n level_1_compressed = self.compress_level_1(x_level_1)\n level_1_resized = F.interpolate(level_1_compressed, scale_factor=2, mode='nearest')\n level_2_resized = x_level_2\n\n level_0_weight_v = self.weight_level_0(level_0_resized)\n level_1_weight_v = self.weight_level_1(level_1_resized)\n level_2_weight_v = self.weight_level_2(level_2_resized)\n levels_weight_v = torch.cat((level_0_weight_v, level_1_weight_v, level_2_weight_v), 1)\n levels_weight = self.weight_levels(levels_weight_v)\n levels_weight = F.softmax(levels_weight, dim=1)\n\n fused_out_reduced = level_0_resized * levels_weight[:, 0:1, :, :] + \\\n level_1_resized * levels_weight[:, 1:2, :, :] + \\\n level_2_resized * levels_weight[:, 2:, :, :]\n\n out = self.expand(fused_out_reduced)\n\n if self.vis:\n return out, levels_weight, fused_out_reduced.sum(dim=1)\n else:\n return out\n\nclass FeatureAdaption(nn.Module):\n def __init__(self, in_ch, out_ch, n_anchors):\n super(FeatureAdaption, self).__init__()\n self.sep=False\n self.conv_offset = nn.Conv2d(in_channels=2*n_anchors, out_channels=2*9*n_anchors, groups = n_anchors, kernel_size=1,stride=1,padding=0)\n self.dconv = Deformable_Convolutional(filters_in=in_ch, filters_out=out_ch, kernel_size=3, stride=1, pad=1, groups=n_anchors)\n\n def forward(self, input, wh_pred):\n wh_pred_new = wh_pred.detach()\n offset = self.conv_offset(wh_pred_new)\n out = self.dconv(input, offset)\n return out\n\nclass Features_Fusion(nn.Module):\n def __init__(self, in_channels, out_channels, r=16):\n super(Features_Fusion,self).__init__()\n self.out_channels = out_channels\n self.avg_pool = nn.AdaptiveAvgPool2d(1)\n self.conv_fc1 = Convolutional(in_channels, in_channels // r, kernel_size=1, stride=1, pad=0, norm='bn', activate='leaky')\n self.conv_fc2 = nn.Conv2d(in_channels // r, out_channels * 2, kernel_size=1, padding=0, bias=False)\n self.softmax = nn.Softmax(dim=2)\n\n\n def forward(self, x1, x2):\n batch_size = x1.size(0)\n x_mix = torch.add(x1,x2) # 逐元素相加生成 混合特征U\n x_avg = self.avg_pool(x_mix)\n x_fcout = self.conv_fc2(self.conv_fc1(x_avg)) # 先降维,后升维,结果中前一半通道值为a,后一半为b\n x_reshape = x_fcout.reshape(batch_size, self.out_channels, 2, -1) # 调整形状,变为两个全连接层的值\n x_softmax = self.softmax(x_reshape) # 使得两个全连接层对应位置进行softmax\n w1 = x_softmax[:, :, 0:1,:] #将tensor按照指定维度切分成2个tensor块\n w2 = x_softmax[:, :, 1:2,:]\n out = x1*w1 + x2*w2 # 两个加权后的特征 逐元素相加\n return out" ]
[ [ "torch.nn.MaxPool2d", "torch.add", "torch.nn.functional.max_pool2d", "torch.nn.AdaptiveAvgPool2d", "torch.nn.functional.softmax", "torch.nn.Softmax", "torch.nn.Conv2d", "torch.cat", "torch.nn.functional.interpolate" ] ]
babak2520/ml-io
[ "d79a895c3fe5e10f0f832cfdcee5a73058abb7c7" ]
[ "src/mlio-py/mlio/integ/scipy.py" ]
[ "# Copyright 2019-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nimport numpy as np\n\nfrom mlio._core import CooTensor\nfrom scipy.sparse import coo_matrix\n\n\ndef to_coo_matrix(tensor):\n \"\"\"\n Converts the specified Tensor to a ``coo_matrix``.\n \"\"\"\n\n if not isinstance(tensor, CooTensor):\n raise ValueError(\"The Tensor must be an Instance of CooTensor.\")\n\n s = tensor.shape\n\n if len(s) > 2:\n raise ValueError(\"Only one- and two-dimensional COO tensors are \"\n \"supported.\")\n\n if len(s) == 1:\n s = (1,) + s\n\n data = np.array(tensor.data, copy=False)\n rows = np.array(tensor.indices(0), copy=False)\n cols = np.array(tensor.indices(1), copy=False)\n\n return coo_matrix((data, (rows, cols)), s, copy=True)\n\n\ndef to_tensor(mtx):\n \"\"\"\n Converts the specified ``coo_matrix`` to a Tensor.\n \"\"\"\n\n if not isinstance(mtx, coo_matrix):\n raise ValueError(\"Only coo_matrix is supported.\")\n\n rows = mtx.row\n cols = mtx.col\n\n rows = rows.astype(np.int64, copy=True)\n cols = cols.astype(np.int64, copy=True)\n\n return CooTensor(mtx.shape, mtx.data, [rows, cols], copy=False)\n" ]
[ [ "numpy.array", "scipy.sparse.coo_matrix" ] ]
MothVine/DESC
[ "8f18ca63b34dad07ec67a4d43945d39287b303b8" ]
[ "tests/test_configuration.py" ]
[ "import numpy as np\nimport pytest\nimport unittest\nfrom desc.equilibrium import Equilibrium, EquilibriaFamily\nfrom desc.grid import ConcentricGrid\nfrom desc.profiles import PowerSeriesProfile, SplineProfile\nfrom desc.geometry import (\n FourierRZCurve,\n FourierRZToroidalSurface,\n ZernikeRZToroidalSection,\n)\n\n\nclass TestConstructor(unittest.TestCase):\n def test_defaults(self):\n\n eq = Equilibrium()\n\n self.assertEqual(eq.spectral_indexing, \"ansi\")\n self.assertEqual(eq.NFP, 1)\n self.assertEqual(eq.L, 1)\n self.assertEqual(eq.M, 1)\n self.assertEqual(eq.N, 0)\n self.assertEqual(eq.sym, False)\n self.assertTrue(eq.surface.eq(FourierRZToroidalSurface()))\n self.assertIsInstance(eq.pressure, PowerSeriesProfile)\n np.testing.assert_allclose(eq.p_l, [0])\n self.assertIsInstance(eq.iota, PowerSeriesProfile)\n np.testing.assert_allclose(eq.i_l, [0])\n\n def test_supplied_objects(self):\n\n pressure = SplineProfile([1, 2, 3])\n iota = SplineProfile([2, 3, 4])\n surface = ZernikeRZToroidalSection(spectral_indexing=\"ansi\")\n axis = FourierRZCurve([-1, 10, 1], [1, 0, -1], NFP=2)\n\n eq = Equilibrium(pressure=pressure, iota=iota, surface=surface, axis=axis)\n\n self.assertTrue(eq.pressure.eq(pressure))\n self.assertTrue(eq.iota.eq(iota))\n self.assertTrue(eq.surface.eq(surface))\n self.assertTrue(eq.axis.eq(axis))\n self.assertEqual(eq.spectral_indexing, \"ansi\")\n self.assertEqual(eq.NFP, 2)\n\n surface2 = FourierRZToroidalSurface(NFP=3)\n eq2 = Equilibrium(surface=surface2)\n self.assertEqual(eq2.NFP, 3)\n self.assertEqual(eq2.axis.NFP, 3)\n\n eq3 = Equilibrium(surface=surface, axis=None)\n np.testing.assert_allclose(eq3.axis.R_n, [10])\n\n def test_dict(self):\n\n inputs = {\n \"L\": 4,\n \"M\": 2,\n \"N\": 2,\n \"NFP\": 3,\n \"sym\": False,\n \"spectral_indexing\": \"ansi\",\n \"surface\": np.array(\n [[0, 0, 0, 10, 0], [0, 1, 0, 1, 1], [0, -1, 1, 0.1, 0.1]]\n ),\n \"axis\": np.array([[0, 10, 0]]),\n \"pressure\": np.array([[0, 10], [2, 5]]),\n \"iota\": np.array([[0, 1], [2, 3]]),\n }\n eq = Equilibrium(**inputs)\n\n self.assertEqual(eq.L, 4)\n self.assertEqual(eq.M, 2)\n self.assertEqual(eq.N, 2)\n self.assertEqual(eq.NFP, 3)\n self.assertEqual(eq.spectral_indexing, \"ansi\")\n np.testing.assert_allclose(eq.p_l, [10, 0, 5])\n np.testing.assert_allclose(eq.i_l, [1, 0, 3])\n self.assertIsInstance(eq.surface, FourierRZToroidalSurface)\n np.testing.assert_allclose(\n eq.Rb_lmn,\n [\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 10.0,\n 1.0,\n 0.0,\n 0.0,\n 0.1,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ],\n )\n np.testing.assert_allclose(\n eq.Zb_lmn,\n [\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 1.0,\n 0.0,\n 0.0,\n 0.1,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ],\n )\n\n inputs[\"surface\"] = np.array([[0, 0, 0, 10, 0], [1, 1, 0, 1, 1]])\n eq = Equilibrium(**inputs)\n self.assertEqual(eq.bdry_mode, \"poincare\")\n np.testing.assert_allclose(\n eq.Rb_lmn, [10.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n )\n\n def test_asserts(self):\n\n with pytest.raises(AssertionError):\n eq = Equilibrium(L=3.4)\n with pytest.raises(AssertionError):\n eq = Equilibrium(M=3.4)\n with pytest.raises(AssertionError):\n eq = Equilibrium(N=3.4)\n with pytest.raises(AssertionError):\n eq = Equilibrium(NFP=3.4j)\n with pytest.raises(ValueError):\n eq = Equilibrium(surface=np.array([[1, 1, 1, 10, 2]]))\n with pytest.raises(TypeError):\n eq = Equilibrium(surface=FourierRZCurve())\n with pytest.raises(TypeError):\n eq = Equilibrium(axis=2)\n with pytest.raises(ValueError):\n eq = Equilibrium(surface=FourierRZToroidalSurface(NFP=1), NFP=2)\n with pytest.raises(TypeError):\n eq = Equilibrium(pressure=\"abc\")\n with pytest.raises(TypeError):\n eq = Equilibrium(iota=\"def\")\n\n def test_supplied_coeffs(self):\n\n R_lmn = np.random.random(3)\n Z_lmn = np.random.random(3)\n L_lmn = np.random.random(3)\n eq = Equilibrium(R_lmn=R_lmn, Z_lmn=Z_lmn, L_lmn=L_lmn)\n np.testing.assert_allclose(R_lmn, eq.R_lmn)\n np.testing.assert_allclose(Z_lmn, eq.Z_lmn)\n np.testing.assert_allclose(L_lmn, eq.L_lmn)\n\n with pytest.raises(ValueError):\n eq = Equilibrium(L=4, R_lmn=R_lmn)\n\n\nclass TestInitialGuess(unittest.TestCase):\n def test_default_set(self):\n eq = Equilibrium()\n eq.set_initial_guess()\n np.testing.assert_allclose(eq.compute(\"V\")[\"V\"], 2 * 10 * np.pi * np.pi * 1 * 1)\n del eq._axis\n eq.set_initial_guess()\n np.testing.assert_allclose(eq.compute(\"V\")[\"V\"], 2 * 10 * np.pi * np.pi * 1 * 1)\n\n def test_errors(self):\n\n eq = Equilibrium()\n with pytest.raises(ValueError):\n eq.set_initial_guess(1, \"a\", 4, 5, 6)\n with pytest.raises(ValueError):\n eq.set_initial_guess(1, 2)\n with pytest.raises(ValueError):\n eq.set_initial_guess(eq, eq.surface)\n with pytest.raises(TypeError):\n eq.set_initial_guess(eq.surface, [1, 2, 3])\n del eq._surface\n with pytest.raises(ValueError):\n eq.set_initial_guess()\n\n with pytest.raises(ValueError):\n eq.set_initial_guess(\"path\", 3)\n with pytest.raises(ValueError):\n eq.set_initial_guess(\"path\", \"hdf5\")\n with pytest.raises(ValueError):\n eq.surface = eq.get_surface_at(rho=1)\n eq.change_resolution(2, 2, 2)\n eq._initial_guess_surface(eq.R_basis, eq.R_lmn, eq.R_basis)\n with pytest.raises(ValueError):\n eq._initial_guess_surface(\n eq.R_basis, eq.surface.R_lmn, eq.surface.R_basis, mode=\"foo\"\n )\n\n def test_guess_from_other(self):\n\n eq1 = Equilibrium(L=4, M=2)\n eq2 = Equilibrium(L=2, M=1)\n eq2.set_initial_guess(eq1)\n\n eq2.change_resolution(L=4, M=2)\n np.testing.assert_allclose(eq1.R_lmn, eq2.R_lmn)\n np.testing.assert_allclose(eq1.Z_lmn, eq2.Z_lmn)\n\n def test_guess_from_file(self):\n\n eq1 = Equilibrium(L=24, M=12, sym=True, spectral_indexing=\"fringe\")\n path = \"./tests/inputs/SOLOVEV_output.h5\"\n eq1.set_initial_guess(path)\n eq2 = EquilibriaFamily.load(path)\n\n np.testing.assert_allclose(eq1.R_lmn, eq2[-1].R_lmn)\n np.testing.assert_allclose(eq1.Z_lmn, eq2[-1].Z_lmn)\n\n def test_guess_from_surface(self):\n\n eq = Equilibrium()\n surface = FourierRZToroidalSurface()\n # turn the circular cross section into an elipse w AR=2\n surface.set_coeffs(m=-1, n=0, R=None, Z=2)\n # move z axis up to 0.5 for no good reason\n axis = FourierRZCurve([0, 10, 0], [0, 0.5, 0])\n eq.set_initial_guess(surface, axis)\n np.testing.assert_allclose(eq.compute(\"V\")[\"V\"], 2 * 10 * np.pi * np.pi * 2 * 1)\n\n def test_guess_from_surface2(self):\n\n eq = Equilibrium()\n # specify an interior flux surface\n surface = FourierRZToroidalSurface(rho=0.5)\n eq.set_initial_guess(surface)\n np.testing.assert_allclose(\n eq.compute(\"V\")[\"V\"], 2 * 10 * np.pi * np.pi * 2 ** 2\n )\n\n def test_guess_from_points(self):\n eq = Equilibrium(L=3, M=3, N=1)\n # these are just the default circular tokamak with a random normal\n # perturbation with std=0.03, fixed for repeatability\n eq.R_lmn = np.array(\n [\n 3.94803875e-02,\n 7.27321367e-03,\n -8.88095373e-03,\n 1.47523628e-02,\n 1.18518478e-02,\n -2.61657165e-02,\n -1.27473081e-02,\n 3.26441003e-02,\n 4.47427817e-03,\n 1.24734770e-02,\n 9.99231496e00,\n -2.74400311e-03,\n 1.00447777e00,\n 3.22285107e-02,\n 1.16571026e-02,\n -3.15868165e-03,\n -6.77657739e-04,\n -1.97894171e-02,\n 2.13535622e-02,\n -2.19703593e-02,\n 5.15586341e-02,\n 3.39651128e-02,\n -1.66077603e-02,\n -2.20514583e-02,\n -3.13335598e-02,\n 7.16090760e-02,\n -1.30064709e-03,\n -4.00687024e-02,\n 5.25583677e-02,\n 4.04325991e-03,\n ]\n )\n eq.Z_lmn = np.array(\n [\n 2.58179465e-02,\n -6.58108612e-03,\n 3.67459870e-02,\n 9.32236734e-04,\n -2.07982449e-03,\n -1.67700140e-02,\n 2.56951390e-02,\n -4.49230035e-04,\n 9.93325894e-02,\n 4.28162330e-03,\n 9.39812383e-03,\n 9.95829268e-01,\n 4.14468984e-02,\n -3.10725101e-02,\n -1.42026152e-02,\n -2.20423483e-02,\n -1.37389716e-02,\n -1.31592276e-02,\n -3.13922472e-02,\n 1.88145630e-03,\n 2.72255620e-02,\n -9.42746650e-03,\n 2.15264372e-02,\n 2.43549268e-02,\n 5.33383228e-02,\n 1.65948808e-02,\n 1.45908076e-03,\n 1.85101895e-02,\n 1.25967662e-02,\n -2.07374046e-02,\n ]\n )\n grid = ConcentricGrid(L=6, M=6, N=2, node_pattern=\"ocs\")\n coords = eq.compute(\"R\", grid)\n coords = eq.compute(\"lambda\", grid, coords)\n eq2 = Equilibrium(L=3, M=3, N=1)\n eq2.set_initial_guess(grid.nodes, coords[\"R\"], coords[\"Z\"], coords[\"lambda\"])\n np.testing.assert_allclose(eq.R_lmn, eq2.R_lmn, atol=1e-8)\n np.testing.assert_allclose(eq.Z_lmn, eq2.Z_lmn, atol=1e-8)\n np.testing.assert_allclose(eq.L_lmn, eq2.L_lmn, atol=1e-8)\n\n\nclass TestSurfaces(unittest.TestCase):\n def test_get_rho_surface(self):\n eq = Equilibrium()\n surf = eq.get_surface_at(rho=0.5)\n print(\"eq\", eq)\n\n print(\"surf\", surf)\n\n np.testing.assert_allclose(\n surf.compute_surface_area(), 4 * np.pi ** 2 * 10 * 0.5\n )\n assert surf.rho == 0.5\n\n def test_get_zeta_surface(self):\n eq = Equilibrium()\n surf = eq.get_surface_at(zeta=np.pi)\n np.testing.assert_allclose(surf.compute_surface_area(), np.pi * (1.0) ** 2)\n assert surf.zeta == np.pi\n\n def test_get_theta_surface(self):\n eq = Equilibrium()\n with pytest.raises(NotImplementedError):\n surf = eq.get_surface_at(theta=np.pi)\n\n def test_asserts(self):\n eq = Equilibrium()\n with pytest.raises(ValueError):\n surf = eq.get_surface_at(rho=1, zeta=2)\n with pytest.raises(AssertionError):\n surf = eq.get_surface_at(rho=1.2)\n" ]
[ [ "numpy.array", "numpy.random.random", "numpy.testing.assert_allclose" ] ]
Sage-Bionetworks/Genie
[ "ce70861b0d3717cd5b57a393a16b4d6fea9500f3" ]
[ "genie/dashboard_table_updater.py" ]
[ "\"\"\"Updates dashboard tables\"\"\"\nimport argparse\nimport datetime\nimport logging\nimport os\n\nimport pandas as pd\nimport synapseclient\nfrom synapseclient.core.utils import to_unix_epoch_time\n\nfrom genie import process_functions\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_center_data_completion(center, df):\n \"\"\"\n Gets center data completion. Calulates the percentile of\n how complete a clinical data element is:\n Number of not blank/Unknown/NA divded by\n total number of patients or samples\n\n Args:\n center: GENIE center\n df: sample or patient dataframe\n\n Returns:\n Dataframe: Center data\n \"\"\"\n centerdf = df[df['CENTER'] == center]\n total = len(centerdf)\n center_data = pd.DataFrame()\n skip_cols = ['CENTER', 'PATIENT_ID', 'SAMPLE_ID', 'SAMPLE_TYPE_DETAILED',\n 'SECONDARY_RACE', 'TERTIARY_RACE']\n for col in centerdf:\n if col not in skip_cols:\n not_missing = [not pd.isnull(value) and value != 'Not Collected'\n for value in centerdf[col]]\n completeness = float(sum(not_missing)) / int(total)\n returned = pd.DataFrame([[col, center, total, completeness]])\n center_data = center_data.append(returned)\n return center_data\n\n\ndef update_samples_in_release_table(syn, file_mapping, release,\n samples_in_release_synid):\n '''\n Updates the sample in release table\n This tracks the samples of each release. 1 means it exists, and 0\n means it doesn't\n\n Args:\n syn: synapse object\n file_mapping: file mapping generated from file mapping function\n release: GENIE release number (ie. 5.3-consortium)\n samples_in_release_synid: Synapse Id of 'samples in release' Table\n '''\n clinical_ent = syn.get(file_mapping['clinical'], followLink=True)\n clinicaldf = pd.read_csv(clinical_ent.path, sep=\"\\t\", comment=\"#\")\n cols = [i['name'] for i in\n list(syn.getTableColumns(samples_in_release_synid))]\n\n if release not in cols:\n schema = syn.get(samples_in_release_synid)\n syn_col = synapseclient.Column(name=release, columnType='INTEGER',\n defaultValue=0)\n new_column = syn.store(syn_col)\n schema.addColumn(new_column)\n schema = syn.store(schema)\n # Columns of samples in release\n samples_per_release = syn.tableQuery(\n 'SELECT SAMPLE_ID, \"{}\" FROM {}'.format(release,\n samples_in_release_synid))\n\n samples_per_releasedf = samples_per_release.asDataFrame()\n new_samples = clinicaldf[['SAMPLE_ID']][\n ~clinicaldf.SAMPLE_ID.isin(samples_per_releasedf.SAMPLE_ID)]\n\n new_samples[release] = 1\n old_samples = clinicaldf[['SAMPLE_ID']][\n clinicaldf.SAMPLE_ID.isin(samples_per_releasedf.SAMPLE_ID)]\n\n old_samples[release] = 1\n samples_in_releasedf = new_samples.append(old_samples)\n process_functions.updateDatabase(syn, samples_per_releasedf,\n samples_in_releasedf,\n samples_in_release_synid, [\"SAMPLE_ID\"])\n\n\ndef update_cumulative_sample_table(syn, file_mapping, release,\n cumulative_sample_count_synid):\n '''\n Consortium release sample count table update function\n This gets the cumulative sample count of each file type in each release\n\n Args:\n syn: synapse object\n file_mapping: file mapping generated from file mapping function\n release: GENIE release number (ie. 5.3-consortium)\n cumulative_sample_count_synid: Synapse Id of\n 'Cumulative sample count' Table\n '''\n\n sample_count_per_round = syn.tableQuery(\n \"SELECT * FROM {} where Release = '{}'\".format(cumulative_sample_count_synid,\n release))\n sample_count_per_rounddf = sample_count_per_round.asDataFrame()\n\n clinical_ent = syn.get(file_mapping['clinical'], followLink=True)\n clinicaldf = pd.read_csv(clinical_ent.path, sep=\"\\t\", comment=\"#\")\n clinicaldf.columns = [i.upper() for i in clinicaldf.columns]\n if clinicaldf.get(\"CENTER\") is None:\n clinicaldf['CENTER'] = \\\n [sample.split(\"-\")[1] for sample in clinicaldf.SAMPLE_ID]\n clinical_counts = clinicaldf['CENTER'].value_counts()\n clinical_counts['Total'] = sum(clinical_counts)\n clinical_counts.name = \"Clinical\"\n\n fusion_ent = syn.get(file_mapping['fusion'], followLink=True)\n fusiondf = pd.read_csv(fusion_ent.path, sep=\"\\t\", comment=\"#\")\n fusiondf.columns = [i.upper() for i in fusiondf.columns]\n fusion_counts = fusiondf['CENTER'][\n ~fusiondf['TUMOR_SAMPLE_BARCODE'].duplicated()].value_counts()\n fusion_counts['Total'] = sum(fusion_counts)\n\n cna_ent = syn.get(file_mapping['cna'], followLink=True)\n cnadf = pd.read_csv(cna_ent.path, sep=\"\\t\", comment=\"#\")\n cna_counts = pd.Series(\n [i.split(\"-\")[1] for i in cnadf.columns[1:]]).value_counts()\n cna_counts['Total'] = sum(cna_counts)\n\n seg_ent = syn.get(file_mapping['seg'], followLink=True)\n segdf = pd.read_csv(seg_ent.path, sep=\"\\t\", comment=\"#\")\n segdf.columns = [i.upper() for i in segdf.columns]\n\n segdf['CENTER'] = [i.split(\"-\")[1] for i in segdf['ID']]\n seg_counts = segdf['CENTER'][~segdf['ID'].duplicated()].value_counts()\n seg_counts['Total'] = sum(seg_counts)\n\n total_counts = pd.DataFrame(clinical_counts)\n total_counts['Fusions'] = fusion_counts\n total_counts['CNV'] = cna_counts\n total_counts['Mutation'] = clinical_counts\n total_counts['SEG'] = seg_counts\n total_counts = total_counts.fillna(0)\n total_counts = total_counts.applymap(int)\n total_counts['Center'] = total_counts.index\n total_counts['Release'] = release\n process_functions.updateDatabase(syn, sample_count_per_rounddf,\n total_counts,\n cumulative_sample_count_synid,\n [\"Center\", \"Release\"],\n to_delete=True)\n\n\ndef get_file_mapping(syn, release_folder_synid):\n \"\"\"\n Get file mapping between important files needed for dashboard and\n their synapse ids\n\n Args:\n syn: synapse object\n release_folder_synid: synapse id of release\n\n \"\"\"\n files = syn.getChildren(release_folder_synid)\n file_mapping = dict()\n for metadata in files:\n filename = metadata['name']\n synid = metadata['id']\n if not filename.startswith(\"meta\"):\n if filename.startswith(\"data_clinical_sample\"):\n file_mapping['clinical'] = synid\n elif filename.endswith(\"fusions.txt\"):\n file_mapping['fusion'] = synid\n elif filename.endswith(\"CNA.txt\"):\n file_mapping['cna'] = synid\n elif filename.endswith(\".seg\"):\n file_mapping['seg'] = synid\n return file_mapping\n\n\ndef update_release_numbers(syn, database_mappingdf, release=None):\n \"\"\"\n Updates all release dashboard numbers or specific release number\n\n Args:\n syn: synapse object\n database_mappingdf: mapping between synapse ids and database\n release: GENIE release (ie. 5.3-consortium). Defaults to None\n \"\"\"\n # Update release table with current release or all releases\n samples_in_release_synid = database_mappingdf['Id'][\n database_mappingdf['Database'] == 'samplesInRelease'].values[0]\n cumulative_sample_count_synid = database_mappingdf['Id'][\n database_mappingdf['Database'] == 'cumulativeSampleCount'].values[0]\n\n release_folder_fileview_synid = database_mappingdf['Id'][\n database_mappingdf['Database'] == 'releaseFolder'].values[0]\n release_folder = syn.tableQuery(\n \"select id,name from %s\" % release_folder_fileview_synid +\n \" where name not like 'Release%' and name <> 'case_lists' and \" +\n \"name not like '%.0.%'\")\n release_folderdf = release_folder.asDataFrame()\n\n for rel_synid, rel_name in zip(release_folderdf.id, release_folderdf.name):\n file_mapping = get_file_mapping(syn, rel_synid)\n # If release is specified, only process on that,\n # otherwise process for all\n if release is None or release == rel_name:\n update_samples_in_release_table(\n syn, file_mapping, rel_name, samples_in_release_synid)\n update_cumulative_sample_table(\n syn, file_mapping, rel_name, cumulative_sample_count_synid)\n else:\n pass\n\n\ndef update_database_numbers(syn, database_mappingdf):\n \"\"\"\n Updates database cumulative numbers (Only called when not staging)\n\n Args:\n syn: synapse object\n database_mappingdf: mapping between synapse ids and database\n \"\"\"\n cumulative_sample_count_synid = database_mappingdf['Id'][\n database_mappingdf['Database'] == 'cumulativeSampleCount'].values[0]\n # Database\n database_count = syn.tableQuery(\n \"SELECT * FROM %s where Release = 'Database'\" %\n cumulative_sample_count_synid)\n database_countdf = database_count.asDataFrame()\n clinical = syn.tableQuery('select CENTER from syn7517674')\n clinicaldf = clinical.asDataFrame()\n clinincal_counts = clinicaldf['CENTER'].value_counts()\n clinincal_counts['Total'] = sum(clinincal_counts)\n clinincal_counts.name = \"Clinical\"\n\n fusion = syn.tableQuery('select * from syn7893268')\n fusiondf = fusion.asDataFrame()\n fusion_counts = fusiondf['CENTER'][\n ~fusiondf['TUMOR_SAMPLE_BARCODE'].duplicated()].value_counts()\n fusion_counts['Total'] = sum(fusion_counts)\n\n center_flat_files = syn.getChildren(\"syn12278118\")\n cna_file_paths = [syn.get(file['id']).path for file in center_flat_files if\n file['name'].startswith(\"data_CNA\")]\n cna_numbers = {}\n for cna_file in cna_file_paths:\n center = os.path.basename(cna_file).replace(\".txt\", \"\").split(\"_\")[2]\n with open(cna_file, 'r') as cna:\n header = cna.readline()\n samples = header.split(\"\\t\")\n # Minus one because of Hugo_Symbol\n cna_numbers[center] = len(samples) - 1\n cna_counts = pd.Series(cna_numbers)\n cna_counts['Total'] = sum(cna_counts)\n\n seg = syn.tableQuery('select * from syn7893341')\n segdf = seg.asDataFrame()\n seg_counts = segdf['CENTER'][~segdf['ID'].duplicated()].value_counts()\n seg_counts['Total'] = sum(seg_counts)\n\n db_counts = pd.DataFrame(clinincal_counts)\n db_counts['Fusions'] = fusion_counts\n db_counts['CNV'] = cna_counts\n db_counts['Mutation'] = clinincal_counts\n db_counts['SEG'] = seg_counts\n db_counts = db_counts.fillna(0)\n db_counts = db_counts.applymap(int)\n db_counts['Center'] = db_counts.index\n db_counts['Release'] = \"Database\"\n process_functions.updateDatabase(syn, database_countdf, db_counts,\n cumulative_sample_count_synid,\n [\"Center\", \"Release\"])\n today = datetime.date.today()\n if today.month in [1, 4, 8, 12]:\n db_count_tracker = db_counts[['Clinical', 'Center', 'Release']]\n db_count_tracker.rename(\n columns={'Clinical': 'sample_count',\n 'Center': 'center',\n 'Release': 'date'},\n inplace=True)\n db_count_tracker['date'] = today.strftime(\"%b-%Y\")\n # Hard coded syn id\n syn.store(synapseclient.Table(\"syn18404852\", db_count_tracker))\n\n\ndef update_oncotree_code_tables(syn, database_mappingdf):\n \"\"\"\n Updates database statistics of oncotree codes\n and primary onocotree codes\n\n Args:\n syn: synapse object\n database_mappingdf: mapping between synapse ids and database\n \"\"\"\n oncotree_distribution_synid = database_mappingdf['Id'][\n database_mappingdf['Database'] == 'oncotree'].values[0]\n\n clinical = syn.tableQuery('select * from syn7517674')\n clinicaldf = clinical.asDataFrame()\n\n # DISTRIBUTION OF ONCOTREE CODE TABLE UPDATE\n oncotree_code_distributiondf = pd.DataFrame(\n columns=set(clinicaldf['CENTER']),\n index=set(clinicaldf['ONCOTREE_CODE']))\n for center in oncotree_code_distributiondf.columns:\n onc_counts = clinicaldf['ONCOTREE_CODE'][\n clinicaldf['CENTER'] == center].value_counts()\n oncotree_code_distributiondf[center] = onc_counts\n oncotree_code_distributiondf = oncotree_code_distributiondf.fillna(0)\n oncotree_code_distributiondf = oncotree_code_distributiondf.applymap(int)\n oncotree_code_distributiondf['Total'] = \\\n oncotree_code_distributiondf.apply(sum, axis=1)\n oncotree_code_distributiondf['Oncotree_Code'] = \\\n oncotree_code_distributiondf.index\n\n oncotree_distribution_db = syn.tableQuery(\n 'SELECT %s FROM %s' %\n (\"Oncotree_Code,\" + \",\".join(clinicaldf['CENTER'].unique()) +\n \",Total\", oncotree_distribution_synid))\n\n oncotree_distribution_dbdf = oncotree_distribution_db.asDataFrame()\n process_functions.updateDatabase(syn, oncotree_distribution_dbdf,\n oncotree_code_distributiondf,\n oncotree_distribution_synid,\n [\"Oncotree_Code\"], to_delete=True)\n\n # DISTRIBUTION OF PRIMARY CODE TABLE UPDATE\n oncotree_link_synid = database_mappingdf['Id'][\n database_mappingdf['Database'] == 'oncotreeLink'].values[0]\n primary_code_synId = database_mappingdf['Id'][\n database_mappingdf['Database'] == 'primaryCode'].values[0]\n\n # Can also use most up to date oncotree code,\n # because these tables are updated from the database\n oncotree_link_ent = syn.get(oncotree_link_synid)\n oncotree_link = oncotree_link_ent.externalURL\n oncotree_mapping = \\\n process_functions.get_oncotree_code_mappings(oncotree_link)\n\n clinicaldf['PRIMARY_CODES'] = \\\n [oncotree_mapping[i.upper()]['ONCOTREE_PRIMARY_NODE']\n if i.upper() in oncotree_mapping.keys() else 'DEPRECATED_CODE'\n for i in clinicaldf.ONCOTREE_CODE]\n\n # ### DISTRIBUTION OF PRIMARY ONCOTREE CODE TABLE UPDATE\n primary_code_distributiondf = pd.DataFrame(\n columns=set(clinicaldf['CENTER']),\n index=set(clinicaldf['PRIMARY_CODES']))\n\n for center in primary_code_distributiondf.columns:\n onc_counts = clinicaldf['PRIMARY_CODES'][\n clinicaldf['CENTER'] == center].value_counts()\n primary_code_distributiondf[center] = onc_counts\n primary_code_distributiondf = primary_code_distributiondf.fillna(0)\n primary_code_distributiondf = primary_code_distributiondf.applymap(int)\n primary_code_distributiondf['Total'] = \\\n primary_code_distributiondf.apply(sum, axis=1)\n primary_code_distributiondf['Oncotree_Code'] = \\\n primary_code_distributiondf.index\n\n primary_code_dist_db = syn.tableQuery(\n 'SELECT %s FROM %s' %\n (\"Oncotree_Code,\" + \",\".join(clinicaldf['CENTER'].unique()) +\n \",Total\", primary_code_synId))\n\n primary_code_dist_dbdf = primary_code_dist_db.asDataFrame()\n process_functions.updateDatabase(syn, primary_code_dist_dbdf,\n primary_code_distributiondf,\n primary_code_synId, [\"Oncotree_Code\"],\n to_delete=True)\n\n\ndef update_sample_difference_table(syn, database_mappingdf):\n \"\"\"\n Updates sample difference table between\n consortium releases\n\n Args:\n syn: synapse object\n database_mappingdf: mapping between synapse ids and database\n \"\"\"\n cumulative_sample_count_synid = database_mappingdf['Id'][\n database_mappingdf['Database'] == 'cumulativeSampleCount'].values[0]\n\n sample_diff_count_synid = database_mappingdf['Id'][\n database_mappingdf['Database'] == 'sampleDiffCount'].values[0]\n\n # UPDATE DIFF TABLE\n sample_count_per_round = syn.tableQuery(\n \"SELECT * FROM %s where Center <> 'Total' and Release <> 'Database'\"\n % cumulative_sample_count_synid)\n\n sample_count_per_rounddf = sample_count_per_round.asDataFrame()\n releases = list(sample_count_per_rounddf['Release'].unique())\n # sort the releases and remove public releases\n releases.sort()\n consortium_releases = [\n release for release in releases if \"public\" not in release\n and \".0.\" not in release]\n\n diff_between_releasesdf = sample_count_per_rounddf[\n sample_count_per_rounddf['Release'] == consortium_releases[0]]\n\n for index, release_name in enumerate(consortium_releases[1:]):\n prior_release = sample_count_per_rounddf[\n sample_count_per_rounddf['Release'] == consortium_releases[index]]\n\n current_release = sample_count_per_rounddf[\n sample_count_per_rounddf['Release'] == release_name]\n\n prior_release.index = prior_release['Center']\n current_release.index = current_release['Center']\n\n del prior_release['Center']\n del prior_release['Release']\n del current_release['Center']\n del current_release['Release']\n # Append new rows of centers that are new and\n # just added to the releases\n new_centers = current_release.index[\n ~current_release.index.isin(prior_release.index)]\n\n if not new_centers.empty:\n prior_release = prior_release.append(\n pd.DataFrame(index=new_centers))\n prior_release = prior_release.fillna(0)\n difference = current_release - prior_release\n difference['Center'] = difference.index\n difference['Release'] = release_name\n diff_between_releasesdf = diff_between_releasesdf.append(difference)\n\n difftable_db = syn.tableQuery('SELECT * FROM %s' % sample_diff_count_synid)\n difftable_dbdf = difftable_db.asDataFrame()\n difftable_dbdf = difftable_dbdf.fillna(0)\n new_values = diff_between_releasesdf[[\n 'Clinical', 'Mutation',\n 'CNV', 'SEG', 'Fusions']].fillna(0).applymap(int)\n\n diff_between_releasesdf[\n ['Clinical', 'Mutation', 'CNV', 'SEG', 'Fusions']] = new_values\n\n process_functions.updateDatabase(syn, difftable_dbdf,\n diff_between_releasesdf,\n sample_diff_count_synid,\n [\"Center\", \"Release\"],\n to_delete=True)\n\n\ndef update_data_completeness_table(syn, database_mappingdf):\n \"\"\"\n Updates the data completeness of the database\n\n Args:\n syn: synapse object\n database_mappingdf: mapping between synapse ids and database\n \"\"\"\n data_completion_synid = database_mappingdf['Id'][\n database_mappingdf['Database'] == 'dataCompletion'].values[0]\n\n sample = syn.tableQuery('select * from syn7517674')\n sampledf = sample.asDataFrame()\n patient = syn.tableQuery('select * from syn7517669')\n patientdf = patient.asDataFrame()\n\n data_completenessdf = pd.DataFrame()\n center_infos = sampledf.CENTER.drop_duplicates().apply(\n lambda center: get_center_data_completion(center, sampledf))\n for center_info in center_infos:\n data_completenessdf = data_completenessdf.append(center_info)\n\n center_infos = patientdf.CENTER.drop_duplicates().apply(\n lambda center: get_center_data_completion(center, patientdf))\n for center_info in center_infos:\n data_completenessdf = data_completenessdf.append(center_info)\n\n data_completeness_db = syn.tableQuery(\n 'select * from %s' % data_completion_synid)\n data_completeness_dbdf = data_completeness_db.asDataFrame()\n data_completenessdf.columns = data_completeness_dbdf.columns\n process_functions.updateDatabase(syn, data_completeness_dbdf,\n data_completenessdf,\n data_completion_synid,\n [\"FIELD\", \"CENTER\"],\n to_delete=True)\n\n\ndef update_wiki(syn, database_mappingdf):\n \"\"\"\n Updates the GENIE project dashboard wiki timestamp\n\n Args:\n syn: synapse object\n database_mappingdf: mapping between synapse ids and database\n\n \"\"\"\n # Updates to query and date dashboard was updated\n cumulative_sample_count_synid = database_mappingdf['Id'][\n database_mappingdf['Database'] == 'cumulativeSampleCount'].values[0]\n\n primary_code_synId = database_mappingdf['Id'][\n database_mappingdf['Database'] == 'primaryCode'].values[0]\n\n centers = syn.tableQuery(\n 'select distinct(CENTER) as CENTER from syn7517674')\n\n centersdf = centers.asDataFrame()\n now = datetime.datetime.now()\n markdown = \\\n [\"_Updated {month}/{day}/{year}_\\n\\n\".format(\n month=now.month,\n day=now.day,\n year=now.year),\n \"##Count of Clinical Samples\\n\",\n \"${synapsetable?query=SELECT Center%2C Clinical%2C Release FROM \" +\n cumulative_sample_count_synid + \"}\\n\\n\",\n \"\\n\\n##Primary Oncotree Codes\\n\\n\",\n \"${synapsetable?query=SELECT Oncotree%5FCode%2C \" +\n \"%2C \".join(centersdf['CENTER'].unique()) +\n \"%2C Total FROM \" + primary_code_synId +\n \" ORDER BY Total DESC&limit=15}\\n\\n\"]\n\n wikipage = syn.getWiki(\"syn3380222\", 235803)\n wikipage.markdown = \"\".join(markdown)\n syn.store(wikipage)\n\n\ndef string_to_unix_epoch_time_milliseconds(string_time):\n \"\"\"\n Takes dates in this format: 2018-10-25T20:16:07.959Z\n and turns it into unix epoch time in milliseconds\n\n Args:\n string_time: string in this format: 2018-10-25T20:16:07.959Z\n\n Returns:\n unix epoch time in milliseconds\n \"\"\"\n datetime_obj = datetime.datetime.strptime(\n string_time.split(\".\")[0], \"%Y-%m-%dT%H:%M:%S\")\n return to_unix_epoch_time(datetime_obj)\n\n\ndef update_data_release_file_table(syn, database_mappingdf):\n \"\"\"\n Updates data release file table\n\n Args:\n syn: synapse object\n database_mappingdf: mapping between synapse ids and database\n \"\"\"\n release_folder_fileview_synid = database_mappingdf['Id'][\n database_mappingdf['Database'] == 'releaseFolder'].values[0]\n release_folder = syn.tableQuery(\n \"select id,name from %s\" % release_folder_fileview_synid +\n \" where name not like 'Release%' and name <> 'case_lists' \" +\n \"and name not like '0.%'\")\n release_folderdf = release_folder.asDataFrame()\n\n data_release_table_synid = \"syn16804261\"\n data_release_table = syn.tableQuery(\n \"select * from %s\" % data_release_table_synid)\n data_release_tabledf = data_release_table.asDataFrame()\n\n not_in_release_tabledf = release_folderdf[\n ~release_folderdf.name.isin(data_release_tabledf.release)]\n\n for synid, name in zip(not_in_release_tabledf.id,\n not_in_release_tabledf.name):\n release_files = syn.getChildren(synid)\n\n append_rows = [\n [release_file['name'],\n release_file['id'],\n name,\n string_to_unix_epoch_time_milliseconds(\n release_file['modifiedOn']), synid]\n for release_file in release_files\n if release_file['name'] != \"case_lists\"]\n\n syn.store(synapseclient.Table(data_release_table_synid, append_rows))\n\n\ndef check_column_decreases(currentdf, olderdf):\n \"\"\"\n Checks entity decreases\n\n Args:\n current_ent: Current entity dataframe\n old_ent: Older entity dataframe\n\n Returns:\n Differences in values\n \"\"\"\n diff_map = dict()\n for col in currentdf:\n new_counts = currentdf[col].value_counts()\n if olderdf.get(col) is not None:\n old_counts = olderdf[col].value_counts()\n # Make sure any values that exist in the new get added\n # to the old to show the decrease\n new_keys = pd.Series(index=new_counts.keys()[\n ~new_counts.keys().isin(old_counts.keys())])\n old_counts = old_counts.add(new_keys, fill_value=0)\n old_counts.fillna(0, inplace=True)\n # Make sure any values that don't exist in the old get added\n # to show the decrease\n new_keys = pd.Series(index=old_counts.keys()[\n ~old_counts.keys().isin(new_counts.keys())])\n new_counts = new_counts.add(new_keys, fill_value=0)\n new_counts.fillna(0, inplace=True)\n if any(new_counts - old_counts < 0):\n logger.info(\"\\tDECREASE IN COLUMN: %s\" % col)\n # diff = new_counts[new_counts - old_counts < 0]\n diffs = new_counts-old_counts\n diffstext = diffs[diffs < 0].to_csv().replace(\"\\n\", \"; \")\n logger.info(\"\\t\" + diffstext)\n diff_map[col] = True\n else:\n diff_map[col] = False\n return diff_map\n\n\ndef print_clinical_values_difference_table(syn, database_mappingdf):\n \"\"\"\n Checks for a decrease in values in the clinical file\n from last consortium release to most recent consortium release\n\n Args:\n syn: synapse object\n database_mappingdf: mapping between synapse ids and database\n \"\"\"\n release_folder_fileview_synid = database_mappingdf['Id'][\n database_mappingdf['Database'] == 'releaseFolder'].values[0]\n\n clinical_key_decrease_synid = database_mappingdf['Id'][\n database_mappingdf['Database'] == 'clinicalKeyDecrease'].values[0]\n\n release_folder = syn.tableQuery(\n f\"select id,name from {release_folder_fileview_synid} \"\n \"where name not like 'Release%' and name <> 'case_lists' \"\n \"and name not like '%.0.%' and name not like '%-public' \"\n \"and name <> 'potential_artifacts'\"\n )\n\n release_folderdf = release_folder.asDataFrame()\n # Set release number as a numerical value since string \"10\" < \"9\"\n # Also can't set by created on date, because sometimes\n # there are patch releases\n release_folderdf['num_release'] = [\n float(name.replace(\".0\", \"\").replace(\"-consortium\", \"\"))\n for name in release_folderdf['name']\n ]\n release_folderdf.sort_values(\"num_release\", ascending=False, inplace=True)\n current_release = release_folderdf['id'][0]\n older_release = release_folderdf['id'][1]\n\n current_release_files = syn.getChildren(current_release)\n current_clinical_synids = {\n file['name']: file['id']\n for file in current_release_files if file['name'] in\n ['data_clinical_sample.txt', 'data_clinical_patient.txt']}\n\n older_release_files = syn.getChildren(older_release)\n\n older_clinical_synids = {\n file['name']: file['id']\n for file in older_release_files if file['name'] in\n ['data_clinical_sample.txt', 'data_clinical_patient.txt']}\n\n current_sample_ent = syn.get(\n current_clinical_synids['data_clinical_sample.txt'], followLink=True)\n\n older_sample_ent = syn.get(\n older_clinical_synids['data_clinical_sample.txt'], followLink=True)\n current_sampledf = pd.read_csv(\n current_sample_ent.path, sep=\"\\t\", comment=\"#\")\n\n current_sampledf['CENTER'] = [\n patient.split(\"-\")[1] for patient in current_sampledf['PATIENT_ID']]\n\n older_sampledf = pd.read_csv(older_sample_ent.path, sep=\"\\t\", comment=\"#\")\n older_sampledf['CENTER'] = [\n patient.split(\"-\")[1] for patient in older_sampledf['PATIENT_ID']]\n # Rather than take the CENTER, must take the SAMPLE_ID to compare\n current_sampledf = current_sampledf[current_sampledf['SAMPLE_ID'].isin(\n older_sampledf['SAMPLE_ID'].unique())]\n\n logger.info(\"SAMPLE CLINICAL VALUE DECREASES\")\n center_decrease_mapping = dict()\n for center in older_sampledf['CENTER'].unique():\n current_center_sampledf = current_sampledf[\n current_sampledf['CENTER'] == center]\n\n older_center_sampledf = older_sampledf[\n older_sampledf['CENTER'] == center]\n\n logger.info(center)\n\n decrease_map = check_column_decreases(\n current_center_sampledf, older_center_sampledf)\n center_decrease_mapping[center] = decrease_map\n\n current_patient_ent = syn.get(\n current_clinical_synids['data_clinical_patient.txt'], followLink=True)\n\n older_patient_ent = syn.get(\n older_clinical_synids['data_clinical_patient.txt'], followLink=True)\n\n current_patientdf = pd.read_csv(\n current_patient_ent.path, sep=\"\\t\", comment=\"#\")\n\n older_patientdf = pd.read_csv(\n older_patient_ent.path, sep=\"\\t\", comment=\"#\")\n # Rather than take the CENTER, must take the PATIENT_ID to compare\n current_patientdf = current_patientdf[current_patientdf['PATIENT_ID'].isin(\n older_patientdf['PATIENT_ID'].unique())]\n\n logger.info(\"PATIENT CLINICAL VALUE DECREASES\")\n for center in older_patientdf['CENTER'].unique():\n current_center_patientdf = current_patientdf[\n current_patientdf['CENTER'] == center]\n\n older_center_patientdf = older_patientdf[\n older_patientdf['CENTER'] == center]\n\n logger.info(center)\n patient_decrease_map = check_column_decreases(\n current_center_patientdf, older_center_patientdf)\n\n center_decrease_mapping[center].update(patient_decrease_map)\n\n center_decrease_mapping = pd.DataFrame(center_decrease_mapping)\n center_decrease_mapping = center_decrease_mapping.transpose()\n center_decrease_mapping['CENTER'] = center_decrease_mapping.index\n\n clinical_key_decrease = syn.tableQuery(\"select * from {0}\".format(\n clinical_key_decrease_synid))\n clinical_key_decreasedbdf = clinical_key_decrease.asDataFrame()\n process_functions.updateDatabase(syn, clinical_key_decreasedbdf,\n center_decrease_mapping,\n clinical_key_decrease_synid, [\"CENTER\"],\n to_delete=True)\n\n\ndef run_dashboard(syn, database_mappingdf, release, staging=False,\n public=False):\n \"\"\"\n Runs the dashboard scripts\n\n Args:\n syn: synapse object\n database_mappingdf: mapping between synapse ids and database\n release: GENIE release (ie. 5.3-consortium)\n\n \"\"\"\n update_release_numbers(syn, database_mappingdf, release=release)\n\n if not staging:\n update_data_release_file_table(syn, database_mappingdf)\n if not public:\n print_clinical_values_difference_table(syn, database_mappingdf)\n update_sample_difference_table(syn, database_mappingdf)\n update_data_completeness_table(syn, database_mappingdf)\n update_database_numbers(syn, database_mappingdf)\n update_oncotree_code_tables(syn, database_mappingdf)\n update_wiki(syn, database_mappingdf)\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Update dashboard tables')\n\n parser.add_argument(\n '--release',\n help=\"GENIE release number (ie. 5.3-consortium)\",\n default=None)\n\n parser.add_argument(\n \"--pem_file\",\n type=str,\n help=\"Path to PEM file (genie.pem)\")\n\n parser.add_argument(\n \"--staging\",\n action='store_true',\n help=\"Using staging directory files\")\n\n parser.add_argument(\n \"--debug\",\n action='store_true',\n help=\"Synapse debugging flag\")\n\n parser.add_argument(\n \"--public\",\n action='store_true',\n help=\"Set true if releasing public release\")\n\n args = parser.parse_args()\n syn = process_functions.synLogin(args)\n if args.staging:\n # Database to Synapse Id mapping Table\n database_mapping_synid = 'syn12094210'\n else:\n database_mapping_synid = 'syn10967259'\n\n database_mapping = syn.tableQuery(\n 'select * from %s' % database_mapping_synid)\n database_mappingdf = database_mapping.asDataFrame()\n\n run_dashboard(syn, database_mappingdf, args.release,\n staging=args.staging, public=args.public)\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "pandas.read_csv", "pandas.isnull", "pandas.Series", "pandas.DataFrame" ] ]
shihchengli/APE
[ "c2f529b9e20959824317dbc3c018ce41702d67f6" ]
[ "ape/OptimalVibrations.py" ]
[ "# -*- coding: utf-8 -*-\n\n\"\"\"\nA module to find the optimizing vibrational coordinates to reduce intermode coupling\n\"\"\"\n\nimport os\nimport time\nimport logging\nimport numpy as np\nfrom copy import deepcopy\nfrom scipy import optimize\nfrom numba import jit\n\nimport rmgpy.constants as constants\n\nfrom ape.job.job import Job\nfrom ape.qchem import QChemLog\nfrom ape.exceptions import InputError, ConvergeError\nfrom ape.common import diagonalize_projected_hessian\nfrom ape.intcoords.InternalCoordinates import getXYZ\nfrom ape.intcoords.constants import BOHR2ANG\n\nclass OptVib(object):\n def __init__(self, symbols, nmode, coordinate_system, cart_coords, internal_object, conformer, hessian, linearity, n_vib, rotors, label, path, ncpus, \n charge=None, multiplicity=None, rem_variables_dict=None, gen_basis=\"\", is_QM_MM_INTERFACE=None, QM_USER_CONNECT=None, QM_ATOMS=None,\n ISOTOPE=None, force_field_params=None, fixed_molecule_string=None, opt=None):\n self.symbols = symbols\n self.nmode = nmode\n self.coordinate_system = coordinate_system\n self.cart_coords = cart_coords\n self.internal_object = internal_object\n self.conformer = conformer\n self.hessian = hessian\n self.linearity = linearity\n self.n_vib = n_vib\n self.rotors = rotors\n self.label = label\n self.path = path\n self.ncpus = ncpus\n self.charge = charge\n self.multiplicity = multiplicity\n self.rem_variables_dict = rem_variables_dict\n self.gen_basis = gen_basis\n self.n_rotors = len(self.rotors)\n\n # QMMM parameters\n self.is_QM_MM_INTERFACE = is_QM_MM_INTERFACE\n self.QM_USER_CONNECT = QM_USER_CONNECT\n self.QM_ATOMS = QM_ATOMS\n self.ISOTOPE = ISOTOPE\n self.force_field_params = force_field_params\n self.fixed_molecule_string = fixed_molecule_string\n self.opt = opt\n \n def get_optvib(self):\n \"\"\"\n Algorithms for local and optimal vibrations.\n \"\"\"\n logging.info('{0} modes of {1} finding...'.format(self.coordinate_system, self.label))\n self.grid_of_hessians = self.get_grid_of_hessians()\n self.mwv = diagonalize_projected_hessian(self.conformer, self.hessian, self.linearity, self.n_vib, \n self.rotors, get_weighted_vectors=True, label=self.label)\n\n # random rotations by 1° over all pairs of normal modes to break symmetry\n num = int(self.n_vib * (self.n_vib - 1) / 2) # 2-combination of self.n_vib\n angles = np.zeros(num)\n ind = 0\n for i in range(self.n_vib):\n new_raw = True\n for j in range(self.n_vib):\n if i < j:\n if (i + 1) % 2 == 1 and new_raw:\n angles[ind] = 1 / 180 * np.pi\n new_raw = False\n else:\n angles[ind] = 0\n ind += 1\n Ui = self.U(angles)\n self.mwv = self.mwv.T.dot(Ui)\n\n # Do Jacobi sweeps over all pairs of modes\n logging.info('-------------------------------------------------------------------------------------------------------------------')\n logging.info(' Jacobi sweeps ')\n logging.info('-------------------------------------------------------------------------------------------------------------------')\n self.Jacobi_sweeps()\n\n # Calculate anharmonic frequencies\n mwv = self.mwv\n H = mwv.T.dot(self.grid_of_hessians[0]).dot(mwv)\n vib_freq = []\n for i in range(self.n_vib):\n freq = np.sqrt(H[i][i]) / (2 * np.pi * constants.c * 100)\n vib_freq.append(freq)\n \n # Calculate optimal coordinates in terms of not mass-weighted cartesian coordinate\n mass = self.conformer.mass.value_si\n mass_3N_array = np.array([i for i in mass for j in range(3)])\n mass_mat = np.diag(mass_3N_array)\n inv_sq_mass_mat = np.linalg.inv(mass_mat ** 0.5)\n unweighted_v = np.matmul(inv_sq_mass_mat, mwv).T\n\n # Sort anharmonic frequencies in ascending order\n unweighted_v = [v for _, v in sorted(zip(vib_freq, unweighted_v))]\n vib_freq = sorted(vib_freq)\n\n return vib_freq, unweighted_v\n\n def get_grid_of_hessians(self):\n \"\"\"\n Hessians are generated on a grid of one point per vibrational mode.\n \"\"\"\n logging.info('A grid of Hessians generating...\\n')\n vib_freq, unweighted_v = diagonalize_projected_hessian(self.conformer, self.hessian, self.linearity, self.n_vib, self.rotors, label=self.label)\n grid_of_hessians = {}\n fm = diagonalize_projected_hessian(self.conformer, self.hessian, self.linearity, self.n_vib, self.rotors, get_mass_weighted_hessian=True, label=self.label)\n grid_of_hessians[0] = deepcopy(fm)\n for i in range(self.nmode):\n if i in range(self.n_rotors): continue\n logging.info('Sampling Mode {mode}'.format(mode=i+1))\n mode = i + 1\n vector = unweighted_v[i - self.n_rotors]\n freq = vib_freq[i - self.n_rotors]\n magnitude = np.linalg.norm(vector)\n reduced_mass = magnitude ** -2 / constants.amu # in amu\n step_size = np.sqrt(constants.hbar / (reduced_mass * constants.amu) / (freq * 2 * np.pi * constants.c * 100)) * 10 ** 10 # in angstrom\n normalizes_vector = vector / magnitude\n qj = np.matmul(self.internal_object.B, normalizes_vector/BOHR2ANG)\n qj = qj.reshape(-1,)\n \n initial_geometry = self.cart_coords.copy()\n cart_coords = initial_geometry.copy()\n internal = deepcopy(self.internal_object)\n\n cart_coords += internal.transform_int_step((qj * step_size).reshape(-1,)) * BOHR2ANG\n xyz = getXYZ(self.symbols, cart_coords)\n file_name = mode\n if self.is_QM_MM_INTERFACE:\n QMMM_xyz_string = ''\n for i, xyz in enumerate(xyz.split('\\n')):\n QMMM_xyz_string += \" \".join([xyz, self.QM_USER_CONNECT[i]]) + '\\n'\n if i == len(self.QM_ATOMS)-1:\n break\n QMMM_xyz_string += self.fixed_molecule_string\n job = Job(QMMM_xyz_string, self.path, file_name, jobtype='freq', ncpus=self.ncpus, charge=self.charge, multiplicity=self.multiplicity,\n rem_variables_dict=self.rem_variables_dict, gen_basis=self.gen_basis, QM_atoms=self.QM_ATOMS, ISOTOPE=self.ISOTOPE,\n force_field_params=self.force_field_params, opt=self.opt)\n else:\n job = Job(xyz, self.path, file_name, jobtype='freq', ncpus=self.ncpus, charge=self.charge, multiplicity=self.multiplicity,\n rem_variables_dict=self.rem_variables_dict, gen_basis=self.gen_basis)\n\n # Write Q-Chem input file\n job.write_input_file()\n\n # Job submission\n job.submit()\n\n # Parse output file to get the hessian matrix\n output_file_path = os.path.join(self.path, '{}.q.out'.format(file_name))\n hessian = QChemLog(output_file_path).load_force_constant_matrix()\n fm = diagonalize_projected_hessian(self.conformer, hessian, self.linearity, self.n_vib, self.rotors, get_mass_weighted_hessian=True, label=self.label)\n grid_of_hessians[mode] = fm\n\n return grid_of_hessians\n\n def objectiveFunction(self, angle):\n \"\"\"\n To produce optimal coordinates, metrics which quantify off-diagonal couplings\n over a grid of Hessian matrices are minimized through unitary rotations of\n the vibrational basis.\n \n 1. coordinate_system == \"E-Optimized\"\n Return the sum of squared off-diagonal coupling\n 2. coordinate_system == \"E'-Optimized\"\n Return the sum squared change in off-diagonal coupling\n 3. coordinate_system == \"Pipek_Mezey\"\n Return the sum of squares of the atomic contribution to the modes\n \"\"\"\n angles = self.angles.copy()\n angles[self.n] = angle\n\n # Rotate the paires of eigenvectors\n U = self.U(angles)\n V = self.mwv.dot(U)\n E = 0\n if self.coordinate_system == \"E-Optimized\":\n for key in self.grid_of_hessians.keys():\n dim = self.n_vib\n hessian = self.grid_of_hessians[key]\n E += E_Optimized_batch_run(hessian, V ,dim)\n elif self.coordinate_system == \"E'-Optimized\":\n H0 = V.T.dot(self.grid_of_hessians[0]).dot(V) / ((2 * np.pi * constants.c * 100) ** 2)\n for key in self.grid_of_hessians.keys():\n if key == 0: continue\n dim = self.n_vib\n hessian = self.grid_of_hessians[key]\n E += dE_Optimized_batch_run(hessian, V ,dim, H0)\n elif self.coordinate_system == \"Pipek_Mezey\":\n modes = V.T\n squared_modes = modes ** 2\n c = squared_modes[:, 0::3] + squared_modes[:, 1::3] + squared_modes[:, 2::3]\n E = -np.linalg.norm(c) ** 2 \n else:\n raise InputError(\"The value of coordinate_system should be E-Optimized or E'-Optimized to produce optimal coordinates.\")\n\n return E\n\n def Jacobi_sweeps(self, thresh=1e-6, thresh2=1e-4, printing=True):\n \"\"\"\n Jacobi sweeps are performed over the angles until minimization was reached.\n \"\"\"\n start = time.time()\n num = int(self.n_vib * (self.n_vib - 1) / 2) # 2-combination of a set self.n_vib\n err = 1e10\n err2 = 1e10\n isweep = 0\n while (err > thresh) or (err2 > thresh2):\n isweep += 1\n self.angles = np.zeros(num)\n if isweep == 1:\n self.n = 0\n old_E = self.objectiveFunction(0)\n for n in range(num):\n self.n = n\n bounds = [[0, 2 * np.pi]]\n result = optimize.minimize_scalar(self.objectiveFunction, bounds=bounds)\n if not result.success:\n raise ConvergeError('Optimization to find optimal vibrational coordinates fails.')\n else:\n self.angles[n] = result.x\n \n # Update vectors\n U = self.U(self.angles)\n self.mwv = self.mwv.dot(U)\n\n # Check convergence\n E = result.fun\n err = abs(E - old_E)\n err2 = abs(self.angles.sum())\n old_E = E\n \n if printing:\n logging.info('Normal mode localization: Cycle {:3d} E: {:>25.7f} change: {:>25.7f} {:>10.5f}'\\\n .format(isweep, E, err, err2))\n end = time.time()\n logging.info('-------------------------------------------------------------------------------------------------------------------')\n logging.info('\\nThe Jacobi sweeps have converged in {:.2f} s(wall)'.format(end - start))\n \n def Ui(self, angle, i, j):\n \"\"\"\n Ui is a Jacobi rotation matrix of two by two rotation (among mode i and mode j).\n \"\"\"\n Ui = np.identity(self.n_vib)\n if i > j:\n tmp = i\n i = j\n j = tmp\n c = np.cos(angle)\n s = np.sin(angle) \n Ui[i][i] = c\n Ui[j][j] = c\n Ui[i][j] = -s\n Ui[j][i] = s\n return Ui\n\n def U(self, angles):\n \"\"\"\n Matrix U is expressed as consecutive Jacobi rotations.\n \"\"\"\n U = np.identity(self.n_vib)\n ind = 0\n for i in range(self.n_vib):\n for j in range(self.n_vib):\n if i < j:\n angle = angles[ind]\n Ui = self.Ui(angle, i, j)\n U = np.matmul(U, Ui)\n ind += 1\n return U\n\n#@jit(nopython=True)\ndef E_Optimized_batch_run(hessian, V, dim):\n E = 0\n H = V.T.dot(hessian).dot(V) / ((2 * np.pi * constants.c * 100) ** 2)\n for i in range(dim):\n for j in range(dim):\n if i < j:\n E += (H[i][j]) ** 2\n return E\n\n#@jit(nopython=True)\ndef dE_Optimized_batch_run(hessian, V, dim, H0):\n E = 0\n H = V.T.dot(hessian).dot(V) / ((2 * np.pi * constants.c * 100) ** 2)\n for i in range(dim):\n for j in range(dim):\n if i < j:\n E += (H[i][j] - H0[i][j]) ** 2\n return E" ]
[ [ "numpy.matmul", "numpy.linalg.norm", "scipy.optimize.minimize_scalar", "numpy.zeros", "numpy.diag", "numpy.linalg.inv", "numpy.cos", "numpy.sqrt", "numpy.sin", "numpy.identity" ] ]
njcuk9999/apero-utils
[ "f77de4c9123874e5bb6ed6bd03a7de3b27057402" ]
[ "general/paper_plots/general.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nPlots for the apero drs paper\n\nCreated on 2021-08-01\n\n@author: cook\n\"\"\"\nimport matplotlib\nmatplotlib.use('Qt5Agg')\nfrom astropy.io import fits\nfrom astropy.visualization import imshow_norm, ZScaleInterval, LinearStretch\nimport glob\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport numpy as np\nimport os\n\nfrom apero import lang\nfrom apero.core import constants\nfrom apero.core.core import drs_log\nfrom apero.core.core import drs_database\nfrom apero.science import preprocessing as prep\nfrom apero.io import drs_image\nfrom apero.core.instruments.spirou import file_definitions\n\n\n# =============================================================================\n# Define variables\n# =============================================================================\n# Get Logging function\nWLOG = drs_log.wlog\n# Get the text types\ntextentry = lang.textentry\n# Raw prefix\nRAW_PREFIX = file_definitions.raw_prefix\n# get the object database\nObjectDatabase = drs_database.ObjectDatabase\n# define the night of data we want to use\nNIGHT = '2020-08-31'\n# define where we want to save plots\n# PLOT_PATH = '/data/spirou/drs-data/misc/paper_plots'\nPLOT_PATH = '/scratch2/drs-data/misc/paper_plots'\n# define plots and append those we want\nPLOTS = []\n# PLOTS.append('SIZE_GRID')\nPLOTS.append('RAW_FEATURES')\n# PLOTS.append('BADMAP')\n\n\n# =============================================================================\n# PLOT functions\n# =============================================================================\n# SIZE_GRID\ndef plot_size_grid(params):\n\n odocode = '2510288a'\n hashcode = '3444961B5D'\n # get file paths\n raw_file = os.path.join(params['DRS_DATA_RAW'], NIGHT,\n '{0}.fits'.format(odocode))\n pp_file = os.path.join(params['DRS_DATA_REDUC'], NIGHT,\n '{0}_pp.fits'.format(hashcode))\n e2ds_file = os.path.join(params['DRS_DATA_REDUC'], NIGHT,\n '{0}_pp_e2dsff_AB.fits'.format(hashcode))\n # get\n print('Loading raw image')\n raw_image = fits.getdata(raw_file)\n print('Loading pp image')\n pp_image = fits.getdata(pp_file)\n print('Loading E2DS image')\n e2ds_image = fits.getdata(e2ds_file)\n\n # rotation to match HARPS orientation (expected by DRS)\n # image1 = drs_image.rotate_image(raw_image, params['RAW_TO_PP_ROTATION'])\n # flip image\n image2 = drs_image.flip_image(params, pp_image)\n # get resize size\n sargs = dict(xlow=params['IMAGE_X_LOW'], xhigh=params['IMAGE_X_HIGH'],\n ylow=params['IMAGE_Y_LOW'], yhigh=params['IMAGE_Y_HIGH'])\n # resize flat\n image3 = drs_image.resize(params, image2, **sargs)\n\n print('Plotting size_grid plot')\n fig = plt.figure(figsize=(12, 12))\n size = (2, 2)\n frame1 = plt.subplot2grid(size, (0, 0))\n frame2 = plt.subplot2grid(size, (0, 1))\n frame3 = plt.subplot2grid(size, (1, 0), colspan=2)\n\n cmap = matplotlib.cm.get_cmap('inferno').copy()\n cmap.set_bad(color='green')\n # -------------------------------------------------------------------------\n # top left raw image\n im, norm = _norm_image(raw_image, frame1, cmap)\n # add labels\n frame1.set(xlim=(0, 4096), ylim=(0, 4096))\n frame1.tick_params(axis='both', which='both', bottom=False, top=False,\n left=False, right=False, labelleft=False,\n labelbottom=False)\n frame1.set_title('raw (4096x4096)', loc='left',\n x=0.05, y=0.95, pad=-14,\n color='black', backgroundcolor='white')\n # -------------------------------------------------------------------------\n # middle right: flipped + resized image\n im, norm = _norm_image(image3, frame2, cmap)\n # add labels\n frame2.set(xlim=(-4, 4092), ylim=(0-250, 4096-250))\n frame2.tick_params(axis='both', which='both', bottom=False, top=False,\n left=False, right=False, labelleft=False,\n labelbottom=False)\n frame2.set_title('pre-processed, flipped, resized (3100x4088)', loc='left',\n x=0.05, y=0.95, pad=-14,\n color='black', backgroundcolor='white')\n # -------------------------------------------------------------------------\n # bottom: e2ds\n im, norm = _norm_image(e2ds_image, frame3, cmap)\n # add labels\n frame3.set(xlim=(0, 4088), ylim=(0, 49))\n frame3.tick_params(axis='both', which='both', bottom=False, top=False,\n left=False, right=False, labelleft=False,\n labelbottom=False)\n frame3.set_title('Extracted (E2DS) 49x4088', loc='left',\n x=0.025, y=0.95, pad=-14,\n color='black', backgroundcolor='white')\n\n plt.subplots_adjust(wspace=0.05, hspace=0.05,\n left=0.01, right=0.99, top=0.975, bottom=0.025)\n # -------------------------------------------------------------------------\n outfile = os.path.join(PLOT_PATH, 'size_grid.pdf')\n print('Saving to file: ' + outfile)\n plt.savefig(outfile, dpi=500)\n print('Showing graph')\n plt.show()\n plt.close()\n\n\n# RAW_FEATURES\ndef plot_raw_features(params):\n # set file to use\n odocode = '2510288a'\n # get file paths\n raw_file = os.path.join(params['DRS_DATA_RAW'], NIGHT,\n '{0}.fits'.format(odocode))\n # get raw image\n print('Loading raw image')\n raw_image = fits.getdata(raw_file)\n # plot feature grid\n plot_feature_grid(raw_image)\n\n\ndef plot_pp_features(params):\n # get pseudo constants\n pconst = constants.pload()\n # set file to use\n odocode = '2510288a'\n # get file paths\n raw_file = os.path.join(params['DRS_DATA_RAW'], NIGHT,\n '{0}.fits'.format(odocode))\n # get raw image\n print('Loading raw images')\n datalist = []\n for ext in [1, 2, 3, 4]:\n datalist.append(fits.getdata(raw_file, ext=ext))\n # get header\n header = fits.getheader(raw_file)\n # get flux image from the data list\n image = datalist[0]\n # get intercept from the data list\n intercept = datalist[1]\n # get error on slope from the data list\n errslope = datalist[2]\n # get frame time\n frame_time = pconst.FRAME_TIME(params, header)\n # get the pixel exposure time from the data list\n inttime = datalist[3] * frame_time\n # Get hot pixels for corruption check\n hotpixels = prep.get_hot_pixels(params)\n # ----------------------------------------------------------------------\n # Check for pixel shift and/or corrupted files\n # ----------------------------------------------------------------------\n # storage\n snr_hotpix, rms_list = [], []\n shiftdx, shiftdy = 0, 0\n # do this iteratively as if there is a shift need to re-workout QC\n for iteration in range(2):\n # get pass condition\n cout = prep.test_for_corrupt_files(params, image, hotpixels)\n snr_hotpix, rms_list = cout[0], cout[1]\n shiftdx, shiftdy = int(cout[2]), int(cout[3])\n # use dx/dy to shift the image back to where the engineering flat\n # is located\n if shiftdx != 0 and shiftdy != 0:\n # log process\n wmsg = textentry('40-010-00013', args=[shiftdx, shiftdy])\n WLOG(params, '', wmsg)\n # roll on the y axis\n image = np.roll(image, [shiftdy], axis=0)\n intercept = np.roll(intercept, [shiftdy], axis=0)\n errslope = np.roll(errslope, [shiftdy], axis=0)\n inttime = np.roll(inttime, [shiftdy], axis=0)\n # roll on the x axis\n image = np.roll(image, [shiftdx], axis=1)\n intercept = np.roll(intercept, [shiftdx], axis=1)\n errslope = np.roll(errslope, [shiftdx], axis=1)\n inttime = np.roll(inttime, [shiftdx], axis=1)\n elif shiftdx != 0:\n # log process\n wmsg = textentry('40-010-00013', args=[shiftdx, shiftdy])\n WLOG(params, '', wmsg)\n # roll on the x axis\n image = np.roll(image, [shiftdx], axis=1)\n intercept = np.roll(intercept, [shiftdx], axis=1)\n errslope = np.roll(errslope, [shiftdx], axis=1)\n inttime = np.roll(inttime, [shiftdx], axis=1)\n elif shiftdy != 0:\n # log process\n wmsg = textentry('40-010-00013', args=[shiftdx, shiftdy])\n WLOG(params, '', wmsg)\n # roll on the y axis\n image = np.roll(image, [shiftdy], axis=0)\n intercept = np.roll(intercept, [shiftdy], axis=0)\n errslope = np.roll(errslope, [shiftdy], axis=0)\n inttime = np.roll(inttime, [shiftdy], axis=0)\n # ------------------------------------------------------------------\n # correct image\n # ------------------------------------------------------------------\n # correct for the top and bottom reference pixels\n WLOG(params, '', textentry('40-010-00003'))\n image = prep.correct_top_bottom(params, image)\n # correct by a median filter from the dark amplifiers\n WLOG(params, '', textentry('40-010-00004'))\n image = prep.median_filter_dark_amps(params, image)\n # correct for the 1/f noise\n WLOG(params, '', textentry('40-010-00005'))\n image = prep.median_one_over_f_noise(params, image)\n # ---------------------------------------------------------------------\n # Correct for cosmic rays before the possible pixel shift\n # ---------------------------------------------------------------------\n # correct the intercept\n WLOG(params, '', textentry('40-010-00021'))\n intercept = prep.intercept_correct(intercept)\n # correct error slope\n WLOG(params, '', textentry('40-010-00022'))\n errslope1 = prep.errslope_correct(errslope)\n # correct cosmic rays\n WLOG(params, '', textentry('40-010-00018'))\n image, cprops = prep.correct_cosmics(params, image, intercept,\n errslope1, inttime)\n\n # ---------------------------------------------------------------------\n # plot\n # ---------------------------------------------------------------------\n # plot feature grid\n plot_feature_grid(image, 'pp_features.pdf')\n\n\n# plot for raw features and pp features\ndef plot_feature_grid(image, outname='raw_features.pdf'):\n # define cuts / zooms\n cut1area = [100, 700, 1200, 1800]\n cut2area = [2375, 2575, 525, 725]\n zoom0area = [800, 1200, 3396, 3796]\n zoom1area = [3596, 3996, 800, 1200]\n zoom2area = [1240, 1290, 1590, 1640]\n # text height above image [in raw image pixel units]\n textheight = 100\n rcolor = 'r'\n # -------------------------------------------------------------------------\n print('Plotting raw_features plot')\n # set up grid\n plt.close()\n fig = plt.figure(figsize=(12, 14))\n size = (3, 3)\n topright = plt.subplot2grid(size, (0, 0))\n topmid = plt.subplot2grid(size, (0, 1))\n topleft = plt.subplot2grid(size, (0, 2))\n rightmid = plt.subplot2grid(size, (1, 0))\n rightbot = plt.subplot2grid(size, (2, 0))\n panel = plt.subplot2grid(size, (1, 1), colspan=2, rowspan=2)\n\n # get colour map\n cmap = matplotlib.cm.get_cmap('inferno').copy()\n cmap.set_bad(color='green')\n\n cmap0 = matplotlib.cm.get_cmap('Greys_r').copy()\n cmap0.set_bad(color='green')\n # -------------------------------------------------------------------------\n # dark region\n cut1 = image[cut1area[2]:cut1area[3], cut1area[0]:cut1area[1]]\n c1im, _ = _norm_image(cut1, rightmid, cmap)\n _add_colorbar(fig, c1im, rightmid, side='bottom')\n rightmid.set_title('D. dark region', loc='left',\n x=0.05, y=0.95, pad=-14,\n color='black', backgroundcolor='white')\n rightmid.tick_params(axis='both', which='both', bottom=False, top=False,\n left=False, right=False, labelleft=False,\n labelbottom=False)\n # -------------------------------------------------------------------------\n # holes\n cut2 = image[cut2area[2]:cut2area[3], cut2area[0]:cut2area[1]]\n c2im, _ = _norm_image(cut2, rightbot, cmap)\n _add_colorbar(fig, c2im, rightbot, side='bottom')\n rightbot.set_title('E. detector holes', loc='left',\n x=0.05, y=0.95, pad=-14,\n color='black', backgroundcolor='white')\n rightbot.tick_params(axis='both', which='both', bottom=False, top=False,\n left=False, right=False, labelleft=False,\n labelbottom=False)\n # -------------------------------------------------------------------------\n # zoom 0\n zoom0 = image[zoom0area[2]:zoom0area[3], zoom0area[0]:zoom0area[1]]\n z0im, _ = _norm_image(zoom0, topright, cmap)\n _add_colorbar(fig, z0im, topright, side='bottom')\n topright.set_title('A. Zoom reddest orders', loc='left',\n x=0.05, y=0.95, pad=-14,\n color='black', backgroundcolor='white')\n topright.tick_params(axis='both', which='both', bottom=False, top=False,\n left=False, right=False, labelleft=False,\n labelbottom=False)\n # -------------------------------------------------------------------------\n # zoom 1\n zoom1 = image[zoom1area[2]:zoom1area[3], zoom1area[0]:zoom1area[1]]\n z1im, norm = _norm_image(zoom1, topmid, cmap)\n _add_colorbar(fig, z1im, topmid, side='bottom')\n topmid.set_title('B. Zoom bluest orders', loc='left',\n x=0.05, y=0.95, pad=-14,\n color='black', backgroundcolor='white')\n topmid.tick_params(axis='both', which='both', bottom=False, top=False,\n left=False, right=False, labelleft=False,\n labelbottom=False)\n # -------------------------------------------------------------------------\n # zoom 2\n zoom2 = image[zoom2area[2]:zoom2area[3], zoom2area[0]:zoom2area[1]]\n z2im, norm = _norm_image(zoom2, topleft, cmap)\n _add_colorbar(fig, z2im, topleft, side='bottom')\n topleft.set_title('C. Zoom on slices', loc='left',\n x=0.05, y=0.95, pad=-14,\n color='black', backgroundcolor='white')\n topleft.tick_params(axis='both', which='both', bottom=False, top=False,\n left=False, right=False, labelleft=False,\n labelbottom=False)\n # -------------------------------------------------------------------------\n # panel\n pim, norm = _norm_image(image, panel, cmap0)\n _add_colorbar(fig, pim, panel, side='bottom')\n panel.tick_params(axis='both', which='both', bottom=False, top=False,\n left=False, right=False, labelleft=False,\n labelbottom=False)\n panel.set_title('raw (4096x4096)', loc='left',\n x=0.5, y=0.95, pad=-14,\n color='black', backgroundcolor='white')\n # -------------------------------------------------------------------------\n # add rectangle dark cut\n rcut1 = patches.Rectangle((cut1area[0], cut1area[2]),\n cut1area[1] - cut1area[0],\n cut1area[3] - cut1area[2],\n linewidth=1, edgecolor=rcolor, facecolor='none')\n panel.add_patch(rcut1)\n # add text\n panel.text(0.5*(cut1area[1] + cut1area[0]), cut1area[3] + textheight,\n 'D', color=rcolor, backgroundcolor='white')\n # -------------------------------------------------------------------------\n # add rectangle holes\n rcut2 = patches.Rectangle((cut2area[0], cut2area[2]),\n cut2area[1] - cut2area[0],\n cut2area[3] - cut2area[2],\n linewidth=1, edgecolor=rcolor, facecolor='none')\n panel.add_patch(rcut2)\n # add text\n panel.text(0.5*(cut2area[1] + cut2area[0]), cut2area[3] + textheight,\n 'E', color=rcolor, backgroundcolor='white')\n # -------------------------------------------------------------------------\n # add rectangle zoom 1\n rzoom0 = patches.Rectangle((zoom0area[0], zoom0area[2]),\n zoom0area[1] - zoom0area[0],\n zoom0area[3] - zoom0area[2],\n linewidth=1, edgecolor=rcolor, facecolor='none')\n panel.add_patch(rzoom0)\n # add text\n panel.text(0.5*(zoom0area[1] + zoom0area[0]), zoom0area[3] + textheight,\n 'A', color=rcolor, backgroundcolor='white')\n # -------------------------------------------------------------------------\n # add rectangle zoom 1\n rzoom1 = patches.Rectangle((zoom1area[0], zoom1area[2]),\n zoom1area[1] - zoom1area[0],\n zoom1area[3] - zoom1area[2],\n linewidth=1, edgecolor=rcolor, facecolor='none')\n panel.add_patch(rzoom1)\n # add text\n panel.text(0.5*(zoom1area[1] + zoom1area[0]), zoom1area[3] + textheight,\n 'B', color=rcolor, backgroundcolor='white')\n # -------------------------------------------------------------------------\n # add rectangle zoom 2\n rzoom2 = patches.Rectangle((zoom2area[0], zoom2area[2]),\n zoom2area[1] - zoom2area[0],\n zoom2area[3] - zoom2area[2],\n linewidth=1, edgecolor=rcolor, facecolor='none')\n panel.add_patch(rzoom2)\n # add text\n panel.text(0.5*(zoom2area[1] + zoom2area[0]), zoom2area[3] + textheight,\n 'C', color=rcolor, backgroundcolor='white')\n # -------------------------------------------------------------------------\n plt.subplots_adjust(wspace=0.05, hspace=0.075,\n left=0.01, right=0.99, top=0.975, bottom=0.025)\n # -------------------------------------------------------------------------\n outfile = os.path.join(PLOT_PATH, outname)\n print('Saving to file: ' + outfile)\n plt.savefig(outfile, dpi=300)\n print('Showing graph')\n plt.show()\n plt.close()\n\n\n# BADMAP\ndef plot_badpix_plot(params):\n\n hashcode = 'DB67D5C4F5'\n xlow = params['IMAGE_X_LOW']\n xhigh = params['IMAGE_X_HIGH']\n ylow = params['IMAGE_Y_LOW']\n yhigh = params['IMAGE_Y_HIGH']\n\n dark_file = glob.glob(os.path.join(params['DRS_DATA_REDUC'], 'other',\n '*d_pp_dark_master.fits'))[0]\n bad_file = os.path.join(params['DRS_DATA_REDUC'], NIGHT,\n '{0}_pp_badpixel.fits'.format(hashcode))\n\n dark_image = fits.getdata(dark_file)\n bad_image = fits.getdata(bad_file).astype(float)\n\n # fill bad image\n bad_image_full = np.zeros_like(dark_image)\n bad_image_full[ylow:yhigh, xlow:xhigh] = bad_image\n dark_image = drs_image.flip_image(params, dark_image)\n\n cmap1 = matplotlib.cm.get_cmap('Greys_r').copy()\n cmap2 = matplotlib.cm.get_cmap('Greys').copy()\n\n plt.close()\n fig, frames = plt.subplots(figsize=(20, 10), ncols=2, nrows=1)\n frame0 = frames[0]\n frame1 = frames[1]\n\n im, norm = imshow_norm(dark_image, frame0, origin='lower', aspect='auto',\n interval=ZScaleInterval(), stretch=LinearStretch(),\n cmap=cmap1, interpolation='None', rasterized=True)\n im, norm = imshow_norm(bad_image_full, frame1, origin='lower', aspect='auto',\n cmap=cmap2, interpolation='None', rasterized=True)\n\n\n\n frame0.tick_params(axis='both', which='both', bottom=False, top=False,\n left=False, right=False, labelleft=False,\n labelbottom=False)\n frame1.tick_params(axis='both', which='both', bottom=False, top=False,\n left=False, right=False, labelleft=False,\n labelbottom=False)\n\n frame0.hlines(y=ylow, xmin=xlow, xmax=xhigh, color='r', lw=2)\n frame0.hlines(y=yhigh, xmin=xlow, xmax=xhigh, color='r', lw=2)\n frame0.vlines(x=xlow, ymin=ylow, ymax=yhigh, color='r', lw=2)\n frame0.vlines(x=xhigh, ymin=ylow, ymax=yhigh, color='r', lw=2)\n frame1.hlines(y=ylow, xmin=xlow, xmax=xhigh, color='r', lw=2)\n frame1.hlines(y=yhigh, xmin=xlow, xmax=xhigh, color='r', lw=2)\n frame1.vlines(x=xlow, ymin=ylow, ymax=yhigh, color='r', lw=2)\n frame1.vlines(x=xhigh, ymin=ylow, ymax=yhigh, color='r', lw=2)\n\n frame0.set(xlim=[0, 4096], ylim=[0, 4096])\n frame1.set(xlim=[0, 4096], ylim=[0, 4096])\n\n plt.subplots_adjust(wspace=0, hspace=0, left=0.01, right=0.99,\n bottom=0.01, top=0.99)\n\n outfile = os.path.join(PLOT_PATH, 'badmap.pdf')\n print('Saving to file: ' + outfile)\n plt.savefig(outfile)\n print('Showing graph')\n plt.show()\n plt.close()\n\n\n# =============================================================================\n# worker functions (private)\n# =============================================================================\ndef _norm_image(image, frame, cmap):\n im, norm = imshow_norm(image, frame, origin='lower', aspect='auto',\n interval=ZScaleInterval(), stretch=LinearStretch(),\n cmap=cmap, interpolation='None', rasterized=True)\n return im, norm\n\n\ndef _add_colorbar(fig, im, frame, side='bottom'):\n\n if side in ['right', 'left']:\n orientation = 'vertical'\n else:\n orientation = 'horizontal'\n\n divider = make_axes_locatable(frame)\n cax = divider.append_axes(side, '5%', pad=0)\n cbar = fig.colorbar(im, cax=cax, orientation=orientation)\n cbar.ax.tick_params(labelsize=8)\n\n\n# =============================================================================\n# Start of code\n# =============================================================================\nif __name__ == '__main__':\n\n params = constants.load()\n\n if 'SIZE_GRID' in PLOTS:\n plot_size_grid(params)\n if 'RAW_FEATURES' in PLOTS:\n plot_raw_features(params)\n if 'BADMAP' in PLOTS:\n plot_badpix_plot(params)\n\n# =============================================================================\n# End of code\n# =============================================================================\n" ]
[ [ "numpy.zeros_like", "numpy.roll", "matplotlib.pyplot.figure", "matplotlib.pyplot.savefig", "matplotlib.pyplot.subplots", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.show", "matplotlib.patches.Rectangle", "matplotlib.cm.get_cmap", "matplotlib.pyplot.close", "matplotlib.use", "matplotlib.pyplot.subplot2grid" ] ]
viantirreau/cupy
[ "cafe9af0e974ff88fc6aa43bf106e343a60fb983" ]
[ "tests/cupyx_tests/scipy_tests/sparse_tests/test_csr.py" ]
[ "import contextlib\nimport pickle\nimport unittest\nimport warnings\n\nimport numpy\nimport pytest\ntry:\n import scipy.sparse\n scipy_available = True\nexcept ImportError:\n scipy_available = False\n\nimport cupy\nfrom cupy.core import _accelerator\nfrom cupy import testing\nfrom cupyx.scipy import sparse\n\n\ndef _make(xp, sp, dtype):\n data = xp.array([0, 1, 2, 3], dtype)\n indices = xp.array([0, 1, 3, 2], 'i')\n indptr = xp.array([0, 2, 3, 4], 'i')\n # 0, 1, 0, 0\n # 0, 0, 0, 2\n # 0, 0, 3, 0\n return sp.csr_matrix((data, indices, indptr), shape=(3, 4))\n\n\ndef _make_complex(xp, sp, dtype):\n data = xp.array([0, 1, 2, 3], dtype)\n if dtype in [numpy.complex64, numpy.complex128]:\n data = data - 1j\n indices = xp.array([0, 1, 3, 2], 'i')\n indptr = xp.array([0, 2, 3, 4], 'i')\n # 0, 1 - 1j, 0, 0\n # 0, 0, 0, 2 - 1j\n # 0, 0, 3 - 1j, 0\n return sp.csr_matrix((data, indices, indptr), shape=(3, 4))\n\n\ndef _make2(xp, sp, dtype):\n data = xp.array([1, 2, 3, 4], dtype)\n indices = xp.array([2, 1, 2, 2], 'i')\n indptr = xp.array([0, 1, 3, 4], 'i')\n # 0, 0, 1, 0\n # 0, 2, 3, 0\n # 0, 0, 4, 0\n return sp.csr_matrix((data, indices, indptr), shape=(3, 4))\n\n\ndef _make3(xp, sp, dtype):\n data = xp.array([1, 2, 3, 4, 5], dtype)\n indices = xp.array([0, 2, 1, 0, 2], 'i')\n indptr = xp.array([0, 1, 3, 3, 5], 'i')\n # 1, 0, 0\n # 0, 3, 2\n # 0, 0, 0\n # 4, 0, 5\n return sp.csr_matrix((data, indices, indptr), shape=(4, 3))\n\n\ndef _make4(xp, sp, dtype):\n data = xp.array([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype)\n indices = xp.array([0, 2, 3, 0, 1, 3, 0, 1, 2], 'i')\n indptr = xp.array([0, 3, 6, 9], 'i')\n # 1, 0, 2, 3\n # 4, 5, 0, 6\n # 7, 8, 9, 0\n return sp.csr_matrix((data, indices, indptr), shape=(3, 4))\n\n\ndef _make_unordered(xp, sp, dtype):\n data = xp.array([1, 2, 3, 4], dtype)\n indices = xp.array([1, 0, 1, 2], 'i')\n indptr = xp.array([0, 2, 3, 4], 'i')\n # 2, 1, 0, 0\n # 0, 3, 0, 0\n # 0, 0, 4, 0\n return sp.csr_matrix((data, indices, indptr), shape=(3, 4))\n\n\ndef _make_duplicate(xp, sp, dtype):\n data = xp.array([0, 1, 3, 2, 4, 5], dtype)\n indices = xp.array([0, 0, 0, 2, 0, 2], 'i')\n indptr = xp.array([0, 3, 6, 6], 'i')\n # 4, 0, 0, 0\n # 4, 0, 7, 0\n # 0, 0, 0, 0\n return sp.csr_matrix((data, indices, indptr), shape=(3, 4))\n\n\ndef _make_empty(xp, sp, dtype):\n data = xp.array([], dtype)\n indices = xp.array([], 'i')\n indptr = xp.array([0, 0, 0, 0], 'i')\n return sp.csr_matrix((data, indices, indptr), shape=(3, 4))\n\n\ndef _make_square(xp, sp, dtype):\n data = xp.array([0, 1, 2, 3], dtype)\n indices = xp.array([0, 1, 0, 2], 'i')\n indptr = xp.array([0, 2, 3, 4], 'i')\n # 0, 1, 0\n # 2, 0, 0\n # 0, 0, 3\n return sp.csr_matrix((data, indices, indptr), shape=(3, 3))\n\n\ndef _make_row(xp, sp, dtype):\n data = xp.array([1, 2, 3], dtype)\n indices = xp.array([0, 2, 3], 'i')\n indptr = xp.array([0, 3], 'i')\n # 1, 0, 2, 3\n return sp.csr_matrix((data, indices, indptr), shape=(1, 4))\n\n\ndef _make_col(xp, sp, dtype):\n data = xp.array([1, 2], dtype)\n indices = xp.array([0, 0], 'i')\n indptr = xp.array([0, 1, 1, 2], 'i')\n # 1\n # 0\n # 2\n return sp.csr_matrix((data, indices, indptr), shape=(3, 1))\n\n\ndef _make_shape(xp, sp, dtype):\n return sp.csr_matrix((3, 4), dtype=dtype)\n\n\[email protected](*testing.product({\n 'dtype': [numpy.float32, numpy.float64, numpy.complex64, numpy.complex128],\n}))\nclass TestCsrMatrix(unittest.TestCase):\n\n def setUp(self):\n self.m = _make(cupy, sparse, self.dtype)\n\n def test_dtype(self):\n assert self.m.dtype == self.dtype\n\n def test_data(self):\n assert self.m.data.dtype == self.dtype\n testing.assert_array_equal(\n self.m.data, cupy.array([0, 1, 2, 3], self.dtype))\n\n def test_indices(self):\n assert self.m.indices.dtype == numpy.int32\n testing.assert_array_equal(\n self.m.indices, cupy.array([0, 1, 3, 2], self.dtype))\n\n def test_indptr(self):\n assert self.m.indptr.dtype == numpy.int32\n testing.assert_array_equal(\n self.m.indptr, cupy.array([0, 2, 3, 4], self.dtype))\n\n def test_init_copy(self):\n n = sparse.csr_matrix(self.m)\n assert n is not self.m\n cupy.testing.assert_array_equal(n.data, self.m.data)\n cupy.testing.assert_array_equal(n.indices, self.m.indices)\n cupy.testing.assert_array_equal(n.indptr, self.m.indptr)\n assert n.shape == self.m.shape\n\n def test_init_copy_other_sparse(self):\n n = sparse.csr_matrix(self.m.tocsc())\n cupy.testing.assert_array_equal(n.data, self.m.data)\n cupy.testing.assert_array_equal(n.indices, self.m.indices)\n cupy.testing.assert_array_equal(n.indptr, self.m.indptr)\n assert n.shape == self.m.shape\n\n @testing.with_requires('scipy')\n def test_init_copy_scipy_sparse(self):\n m = _make(numpy, scipy.sparse, self.dtype)\n n = sparse.csr_matrix(m)\n assert isinstance(n.data, cupy.ndarray)\n assert isinstance(n.indices, cupy.ndarray)\n assert isinstance(n.indptr, cupy.ndarray)\n cupy.testing.assert_array_equal(n.data, m.data)\n cupy.testing.assert_array_equal(n.indices, m.indices)\n cupy.testing.assert_array_equal(n.indptr, m.indptr)\n assert n.shape == m.shape\n\n @testing.with_requires('scipy')\n def test_init_copy_other_scipy_sparse(self):\n m = _make(numpy, scipy.sparse, self.dtype)\n n = sparse.csr_matrix(m.tocsc())\n assert isinstance(n.data, cupy.ndarray)\n assert isinstance(n.indices, cupy.ndarray)\n assert isinstance(n.indptr, cupy.ndarray)\n cupy.testing.assert_array_equal(n.data, m.data)\n cupy.testing.assert_array_equal(n.indices, m.indices)\n cupy.testing.assert_array_equal(n.indptr, m.indptr)\n assert n.shape == m.shape\n\n def test_init_dense(self):\n m = cupy.array([[0, 1, 0, 2],\n [0, 0, 0, 0],\n [0, 0, 3, 0]], dtype=self.dtype)\n n = sparse.csr_matrix(m)\n assert n.nnz == 3\n assert n.shape == (3, 4)\n cupy.testing.assert_array_equal(n.data, [1, 2, 3])\n cupy.testing.assert_array_equal(n.indices, [1, 3, 2])\n cupy.testing.assert_array_equal(n.indptr, [0, 2, 2, 3])\n\n def test_init_dense_empty(self):\n m = cupy.array([[0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]], dtype=self.dtype)\n n = sparse.csr_matrix(m)\n assert n.nnz == 0\n assert n.shape == (3, 4)\n cupy.testing.assert_array_equal(n.data, [])\n cupy.testing.assert_array_equal(n.indices, [])\n cupy.testing.assert_array_equal(n.indptr, [0, 0, 0, 0])\n\n def test_init_dense_one_dim(self):\n m = cupy.array([0, 1, 0, 2], dtype=self.dtype)\n n = sparse.csr_matrix(m)\n assert n.nnz == 2\n assert n.shape == (1, 4)\n cupy.testing.assert_array_equal(n.data, [1, 2])\n cupy.testing.assert_array_equal(n.indices, [1, 3])\n cupy.testing.assert_array_equal(n.indptr, [0, 2])\n\n def test_init_dense_zero_dim(self):\n m = cupy.array(1, dtype=self.dtype)\n n = sparse.csr_matrix(m)\n assert n.nnz == 1\n assert n.shape == (1, 1)\n cupy.testing.assert_array_equal(n.data, [1])\n cupy.testing.assert_array_equal(n.indices, [0])\n cupy.testing.assert_array_equal(n.indptr, [0, 1])\n\n def test_init_data_row_col(self):\n o = self.m.tocoo()\n n = sparse.csr_matrix((o.data, (o.row, o.col)))\n cupy.testing.assert_array_equal(n.data, self.m.data)\n cupy.testing.assert_array_equal(n.indices, self.m.indices)\n cupy.testing.assert_array_equal(n.indptr, self.m.indptr)\n assert n.shape == self.m.shape\n\n @testing.with_requires('scipy')\n def test_init_dense_invalid_ndim(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = xp.zeros((1, 1, 1), dtype=self.dtype)\n with pytest.raises(TypeError):\n sp.csr_matrix(m)\n\n def test_copy(self):\n n = self.m.copy()\n assert isinstance(n, sparse.csr_matrix)\n assert n is not self.m\n assert n.data is not self.m.data\n assert n.indices is not self.m.indices\n assert n.indptr is not self.m.indptr\n cupy.testing.assert_array_equal(n.data, self.m.data)\n cupy.testing.assert_array_equal(n.indices, self.m.indices)\n cupy.testing.assert_array_equal(n.indptr, self.m.indptr)\n assert n.shape == self.m.shape\n\n def test_shape(self):\n assert self.m.shape == (3, 4)\n\n def test_ndim(self):\n assert self.m.ndim == 2\n\n def test_nnz(self):\n assert self.m.nnz == 4\n\n def test_conj(self):\n n = _make_complex(cupy, sparse, self.dtype)\n cupy.testing.assert_array_equal(n.conj().data, n.data.conj())\n\n @testing.with_requires('scipy')\n def test_get(self):\n m = self.m.get()\n assert isinstance(m, scipy.sparse.csr_matrix)\n expect = [\n [0, 1, 0, 0],\n [0, 0, 0, 2],\n [0, 0, 3, 0]\n ]\n numpy.testing.assert_allclose(m.toarray(), expect)\n\n @testing.with_requires('scipy')\n def test_str(self):\n if numpy.dtype(self.dtype).kind == 'f':\n expect = ''' (0, 0)\\t0.0\n (0, 1)\\t1.0\n (1, 3)\\t2.0\n (2, 2)\\t3.0'''\n elif numpy.dtype(self.dtype).kind == 'c':\n expect = ''' (0, 0)\\t0j\n (0, 1)\\t(1+0j)\n (1, 3)\\t(2+0j)\n (2, 2)\\t(3+0j)'''\n\n assert str(self.m) == expect\n\n def test_toarray(self):\n m = self.m.toarray()\n expect = [\n [0, 1, 0, 0],\n [0, 0, 0, 2],\n [0, 0, 3, 0]\n ]\n assert m.flags.c_contiguous\n cupy.testing.assert_allclose(m, expect)\n\n def test_pickle_roundtrip(self):\n s = _make(cupy, sparse, self.dtype)\n\n s2 = pickle.loads(pickle.dumps(s))\n assert s._descr.descriptor != s2._descr.descriptor\n assert s.shape == s2.shape\n assert s.dtype == s2.dtype\n if scipy_available:\n assert (s.get() != s2.get()).count_nonzero() == 0\n\n\[email protected](*testing.product({\n 'dtype': [numpy.float32, numpy.float64, numpy.complex64, numpy.complex128],\n}))\[email protected]_requires('scipy')\nclass TestCsrMatrixInit(unittest.TestCase):\n\n def setUp(self):\n self.shape = (3, 4)\n\n def data(self, xp):\n return xp.array([1, 2, 3, 4], self.dtype)\n\n def indices(self, xp):\n return xp.array([0, 1, 3, 2], 'i')\n\n def indptr(self, xp):\n return xp.array([0, 2, 3, 4], 'i')\n\n @testing.numpy_cupy_equal(sp_name='sp')\n def test_shape_none(self, xp, sp):\n x = sp.csr_matrix(\n (self.data(xp), self.indices(xp), self.indptr(xp)), shape=None)\n assert x.shape == (3, 4)\n\n @testing.numpy_cupy_equal(sp_name='sp')\n def test_dtype(self, xp, sp):\n data = self.data(xp).real.astype('i')\n x = sp.csr_matrix(\n (data, self.indices(xp), self.indptr(xp)), dtype=self.dtype)\n assert x.dtype == self.dtype\n\n @testing.numpy_cupy_equal(sp_name='sp')\n def test_copy_true(self, xp, sp):\n data = self.data(xp)\n indices = self.indices(xp)\n indptr = self.indptr(xp)\n x = sp.csr_matrix((data, indices, indptr), copy=True)\n\n assert data is not x.data\n assert indices is not x.indices\n assert indptr is not x.indptr\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_init_with_shape(self, xp, sp):\n s = sp.csr_matrix(self.shape)\n assert s.shape == self.shape\n assert s.dtype == 'd'\n assert s.size == 0\n return s\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_init_with_shape_and_dtype(self, xp, sp):\n s = sp.csr_matrix(self.shape, dtype=self.dtype)\n assert s.shape == self.shape\n assert s.dtype == self.dtype\n assert s.size == 0\n return s\n\n @testing.numpy_cupy_allclose(sp_name='sp', atol=1e-5)\n def test_intlike_shape(self, xp, sp):\n s = sp.csr_matrix((self.data(xp), self.indices(xp), self.indptr(xp)),\n shape=(xp.array(self.shape[0]),\n xp.int32(self.shape[1])))\n assert isinstance(s.shape[0], int)\n assert isinstance(s.shape[1], int)\n return s\n\n def test_shape_invalid(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n with pytest.raises(ValueError):\n sp.csr_matrix(\n (self.data(xp), self.indices(xp), self.indptr(xp)),\n shape=(2,))\n\n def test_data_invalid(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n with pytest.raises(ValueError):\n sp.csr_matrix(\n ('invalid', self.indices(xp), self.indptr(xp)),\n shape=self.shape)\n\n def test_data_invalid_ndim(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n with pytest.raises(ValueError):\n sp.csr_matrix(\n (self.data(xp)[None], self.indices(xp), self.indptr(xp)),\n shape=self.shape)\n\n def test_indices_invalid(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n with pytest.raises(ValueError):\n sp.csr_matrix(\n (self.data(xp), 'invalid', self.indptr(xp)),\n shape=self.shape)\n\n def test_indices_invalid_ndim(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n with pytest.raises(ValueError):\n sp.csr_matrix(\n (self.data(xp), self.indices(xp)[None], self.indptr(xp)),\n shape=self.shape)\n\n def test_indptr_invalid(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n with pytest.raises(ValueError):\n sp.csr_matrix(\n (self.data(xp), self.indices(xp), 'invalid'),\n shape=self.shape)\n\n def test_indptr_invalid_ndim(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n with pytest.raises(ValueError):\n sp.csr_matrix(\n (self.data(xp), self.indices(xp), self.indptr(xp)[None]),\n shape=self.shape)\n\n def test_data_indices_different_length(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n data = xp.arange(5, dtype=self.dtype)\n with pytest.raises(ValueError):\n sp.csr_matrix(\n (data, self.indices(xp), self.indptr(xp)),\n shape=self.shape)\n\n def test_indptr_invalid_length(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n indptr = xp.array([0, 1], 'i')\n with pytest.raises(ValueError):\n sp.csr_matrix(\n (self.data(xp), self.indices(xp), indptr),\n shape=self.shape)\n\n def test_unsupported_dtype(self):\n with self.assertRaises(ValueError):\n sparse.csr_matrix(\n (self.data(cupy), self.indices(cupy), self.indptr(cupy)),\n shape=self.shape, dtype='i')\n\n @testing.numpy_cupy_equal(sp_name='sp')\n def test_conj(self, xp, sp):\n n = _make_complex(xp, sp, self.dtype)\n cupy.testing.assert_array_equal(n.conj().data, n.data.conj())\n\n\[email protected](*testing.product({\n 'make_method': [\n '_make', '_make_unordered', '_make_empty', '_make_duplicate',\n '_make_shape'],\n 'dtype': [numpy.float32, numpy.float64, numpy.complex64, numpy.complex128],\n}))\[email protected]_requires('scipy')\nclass TestCsrMatrixScipyComparison(unittest.TestCase):\n\n @property\n def make(self):\n return globals()[self.make_method]\n\n def test_len(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n with pytest.raises(TypeError):\n len(m)\n\n @testing.with_requires('scipy>=1.4.0')\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_iter(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n rows = []\n for r in m:\n rows.append(r)\n assert isinstance(r, sp.spmatrix)\n assert len(rows) == 3\n return xp.concatenate([r.toarray() for r in rows])\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_asfptype(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return m.asfptype().toarray()\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_toarray(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n a = m.toarray()\n assert a.flags.c_contiguous\n return a\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_toarray_c_order(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n a = m.toarray(order='C')\n assert a.flags.c_contiguous\n return a\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_toarray_f_order(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n a = m.toarray(order='F')\n assert a.flags.f_contiguous\n return a\n\n @testing.with_requires('numpy>=1.19')\n def test_toarray_unknown_order(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n with pytest.raises(ValueError):\n m.toarray(order='#')\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_A(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return m.A\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_tocoo(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return m.tocoo()\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_tocoo_copy(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n n = m.tocoo(copy=True)\n assert m.data is not n.data\n return n\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_tocsc(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return m.tocsc()\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_tocsc_copy(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n n = m.tocsc(copy=True)\n assert m.data is not n.data\n assert m.indices is not n.indices\n assert m.indptr is not n.indptr\n return n\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_tocsr(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return m.tocsr()\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_tocsr_copy(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n n = m.tocsr(copy=True)\n assert m.data is not n.data\n assert m.indices is not n.indices\n assert m.indptr is not n.indptr\n return n\n\n # dot\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_dot_scalar(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return m.dot(2.0)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_dot_numpy_scalar(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return m.dot(numpy.dtype(self.dtype).type(2.0)).toarray()\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_dot_csr(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = _make3(xp, sp, self.dtype)\n return m.dot(x)\n\n def test_dot_csr_invalid_shape(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n x = sp.csr_matrix((5, 3), dtype=self.dtype)\n with pytest.raises(ValueError):\n m.dot(x)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_dot_csc(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = _make3(xp, sp, self.dtype).tocsc()\n return m.dot(x)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_dot_sparse(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = _make3(xp, sp, self.dtype).tocoo()\n return m.dot(x)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_dot_zero_dim(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = xp.array(2, dtype=self.dtype)\n return m.dot(x)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_dot_dense_vector(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(4).astype(self.dtype)\n return m.dot(x)\n\n def test_dot_dense_vector_invalid_shape(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(5).astype(self.dtype)\n with pytest.raises(ValueError):\n m.dot(x)\n\n @testing.numpy_cupy_allclose(sp_name='sp', contiguous_check=False)\n def test_dot_dense_matrix(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(8).reshape(4, 2).astype(self.dtype)\n return m.dot(x)\n\n def test_dot_dense_matrix_invalid_shape(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(10).reshape(5, 2).astype(self.dtype)\n with pytest.raises(ValueError):\n m.dot(x)\n\n def test_dot_dense_ndim3(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(24).reshape(4, 2, 3).astype(self.dtype)\n with pytest.raises(ValueError):\n m.dot(x)\n\n def test_dot_unsupported(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n with pytest.raises(TypeError):\n m.dot(None)\n\n # __add__\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_add_zero(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return m + 0\n\n def test_add_scalar(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n with pytest.raises(NotImplementedError):\n m + 1\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_add_csr(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n n = _make2(xp, sp, self.dtype)\n return m + n\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_add_coo(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n n = _make2(xp, sp, self.dtype).tocoo()\n return m + n\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_add_dense(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n n = xp.arange(12).reshape(3, 4)\n return m + n\n\n # __radd__\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_radd_zero(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return (0 + m).toarray()\n\n def test_radd_scalar(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n with pytest.raises(NotImplementedError):\n 1 + m\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_radd_dense(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n n = xp.arange(12).reshape(3, 4)\n return n + m\n\n # __sub__\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_sub_zero(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return (m - 0).toarray()\n\n def test_sub_scalar(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n with pytest.raises(NotImplementedError):\n m - 1\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_sub_csr(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n n = _make2(xp, sp, self.dtype)\n return (m - n).toarray()\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_sub_coo(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n n = _make2(xp, sp, self.dtype).tocoo()\n return m - n\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_sub_dense(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n n = xp.arange(12).reshape(3, 4)\n return m - n\n\n # __rsub__\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_rsub_zero(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return 0 - m\n\n def test_rsub_scalar(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n with pytest.raises(NotImplementedError):\n 1 - m\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_rsub_dense(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n n = xp.arange(12).reshape(3, 4)\n return n - m\n\n # __mul__\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_mul_scalar(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return m * 2.0\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_mul_numpy_scalar(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return m * numpy.dtype(self.dtype).type(2.0)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_mul_csr(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = _make3(xp, sp, self.dtype)\n return m * x\n\n def test_mul_csr_invalid_shape(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n x = sp.csr_matrix((5, 3), dtype=self.dtype)\n with pytest.raises(ValueError):\n m * x\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_mul_csc(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = _make3(xp, sp, self.dtype).tocsc()\n return m * x\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_mul_sparse(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = _make3(xp, sp, self.dtype).tocoo()\n return m * x\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_mul_zero_dim(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = xp.array(2, dtype=self.dtype)\n return m * x\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_mul_dense_vector(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(4).astype(self.dtype)\n return m * x\n\n def test_mul_dense_vector_invalid_shape(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(5).astype(self.dtype)\n with pytest.raises(ValueError):\n m * x\n\n @testing.numpy_cupy_allclose(sp_name='sp', contiguous_check=False)\n def test_mul_dense_matrix(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(8).reshape(4, 2).astype(self.dtype)\n return m * x\n\n def test_mul_dense_matrix_invalid_shape(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(10).reshape(5, 2).astype(self.dtype)\n with pytest.raises(ValueError):\n m * x\n\n def test_mul_dense_ndim3(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(24).reshape(4, 2, 3).astype(self.dtype)\n with pytest.raises(ValueError):\n m * x\n\n def test_mul_unsupported(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n with pytest.raises(TypeError):\n m * None\n\n # __rmul__\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_rmul_scalar(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return 2.0 * m\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_rmul_numpy_scalar(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return numpy.dtype(self.dtype).type(2.0) * m\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_rmul_csr(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = _make3(xp, sp, self.dtype)\n return x * m\n\n @testing.numpy_cupy_allclose(sp_name='sp', _check_sparse_format=False)\n def test_rmul_csc(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = _make3(xp, sp, self.dtype).tocsc()\n return x * m\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_rmul_sparse(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = _make3(xp, sp, self.dtype).tocoo()\n return x * m\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_rmul_zero_dim(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = xp.array(2, dtype=self.dtype)\n return x * m\n\n @testing.numpy_cupy_allclose(sp_name='sp', contiguous_check=False)\n def test_rmul_dense_matrix(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(12).reshape(4, 3).astype(self.dtype)\n return x * m\n\n def test_rmul_dense_ndim3(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(24).reshape(4, 2, 3).astype(self.dtype)\n with pytest.raises(ValueError):\n x * m\n\n def test_rmul_unsupported(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n if m.nnz == 0:\n # When there is no element, a SciPy's sparse matrix does\n # not raise an error when it is multiplied with None.\n continue\n with pytest.raises(TypeError):\n None * m\n\n # Note: '@' operator is almost equivalent to '*' operator. Only test the\n # cases where '@' raises an exception and '*' does not.\n def test_matmul_scalar(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n x = 2.0\n with pytest.raises(ValueError):\n m @ x\n with pytest.raises(ValueError):\n x @ m\n\n def test_matmul_numpy_scalar(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n x = numpy.dtype(self.dtype).type(2.0)\n with pytest.raises(ValueError):\n m @ x\n with pytest.raises(ValueError):\n x @ m\n\n def test_matmul_scalar_like_array(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n x = xp.array(2.0, self.dtype)\n with pytest.raises(ValueError):\n m @ x\n with pytest.raises(ValueError):\n x @ m\n\n @testing.numpy_cupy_equal(sp_name='sp')\n def test_has_canonical_format(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return m.has_canonical_format\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_has_canonical_format2(self, xp, sp):\n # this test is adopted from SciPy's\n M = sp.csr_matrix((xp.array([2], dtype=self.dtype),\n xp.array([0]), xp.array([0, 1])))\n assert M.has_canonical_format is True\n return M\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_has_canonical_format3(self, xp, sp):\n # this test is adopted from SciPy's\n indices = xp.array([0, 0]) # contains duplicate\n data = xp.array([1, 1], dtype=self.dtype)\n indptr = xp.array([0, 2])\n\n M = sp.csr_matrix((data, indices, indptr))\n assert M.has_canonical_format is False\n\n # set by deduplicating\n M.sum_duplicates()\n assert M.has_canonical_format is True\n assert 1 == len(M.indices)\n return M\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_has_canonical_format4(self, xp, sp):\n # this test is adopted from SciPy's\n indices = xp.array([0, 0]) # contains duplicate\n data = xp.array([1, 1], dtype=self.dtype)\n indptr = xp.array([0, 2])\n\n M = sp.csr_matrix((data, indices, indptr))\n # set manually (although underlyingly duplicated)\n M.has_canonical_format = True\n assert M.has_canonical_format\n assert 2 == len(M.indices) # unaffected content\n\n # ensure deduplication bypassed when has_canonical_format == True\n M.sum_duplicates()\n assert 2 == len(M.indices) # unaffected content\n return M\n\n @testing.with_requires('scipy>1.6.0')\n @testing.numpy_cupy_equal(sp_name='sp')\n def test_has_sorted_indices(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return m.has_sorted_indices\n\n # TODO(asi1024): Remove test after the fixed version is released.\n # https://github.com/scipy/scipy/pull/13426\n @testing.with_requires('scipy<=1.6.0')\n @testing.numpy_cupy_equal(sp_name='sp')\n def test_has_sorted_indices_for_old_scipy(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return bool(m.has_sorted_indices)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_has_sorted_indices2(self, xp, sp):\n # this test is adopted from SciPy's\n sorted_inds = xp.array([0, 1])\n data = xp.array([1, 1], dtype=self.dtype)\n indptr = xp.array([0, 2])\n M = sp.csr_matrix((data, sorted_inds, indptr))\n assert M.has_sorted_indices\n return M\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_has_sorted_indices3(self, xp, sp):\n # this test is adopted from SciPy's\n sorted_inds = xp.array([0, 1])\n unsorted_inds = xp.array([1, 0])\n data = xp.array([1, 1], dtype=self.dtype)\n indptr = xp.array([0, 2])\n M = sp.csr_matrix((data, unsorted_inds, indptr))\n assert not M.has_sorted_indices\n\n # set by sorting\n M.sort_indices()\n assert M.has_sorted_indices\n assert (M.indices == sorted_inds).all()\n return M\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_has_sorted_indices4(self, xp, sp):\n # this test is adopted from SciPy's\n unsorted_inds = xp.array([1, 0])\n data = xp.array([1, 1], dtype=self.dtype)\n indptr = xp.array([0, 2])\n M = sp.csr_matrix((data, unsorted_inds, indptr))\n\n # set manually (although underlyingly unsorted)\n M.has_sorted_indices = True\n assert M.has_sorted_indices\n assert (M.indices == unsorted_inds).all()\n\n # ensure sort bypassed when has_sorted_indices == True\n M.sort_indices()\n assert (M.indices == unsorted_inds).all()\n return M\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_sort_indices(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n m.sort_indices()\n assert m.has_sorted_indices\n return m\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_sort_indices2(self, xp, sp):\n # this test is adopted from SciPy's\n data = xp.arange(5).astype(xp.float32)\n indices = xp.array([7, 2, 1, 5, 4])\n indptr = xp.array([0, 3, 5])\n asp = sp.csr_matrix((data, indices, indptr), shape=(2, 10))\n asp.sort_indices()\n assert (asp.indices == xp.array([1, 2, 7, 4, 5])).all()\n return asp.todense()\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_sorted_indices(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n m = m.sorted_indices()\n assert m.has_sorted_indices\n return m\n\n def test_sum_tuple_axis(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n with pytest.raises(TypeError):\n m.sum(axis=(0, 1))\n\n def test_sum_str_axis(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n with pytest.raises(TypeError):\n m.sum(axis='test')\n\n def test_sum_too_large_axis(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n with pytest.raises(ValueError):\n m.sum(axis=3)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_sum_duplicates(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n m.sum_duplicates()\n assert m.has_canonical_format\n return m\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_transpose(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return m.transpose()\n\n def test_transpose_axes_int(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = self.make(xp, sp, self.dtype)\n with pytest.raises(ValueError):\n m.transpose(axes=0)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_eliminate_zeros(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n m.eliminate_zeros()\n return m\n\n @testing.numpy_cupy_equal(sp_name='sp')\n @unittest.skipIf(\n cupy.cuda.runtime.runtimeGetVersion() < 8000,\n 'CUDA <8 cannot keep number of non-zero entries ')\n def test_eliminate_zeros_nnz(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n m.eliminate_zeros()\n return m.nnz\n\n # multiply\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_multiply_scalar(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n return m.multiply(2).toarray()\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_multiply_dense_row(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(4, dtype=self.dtype)\n return m.multiply(x).toarray()\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_multiply_dense_col(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(3, dtype=self.dtype).reshape(3, 1)\n return m.multiply(x).toarray()\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_multiply_dense_matrix(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(12, dtype=self.dtype).reshape(3, 4)\n return m.multiply(x).toarray()\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_multiply_csr_matrix(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = _make4(xp, sp, self.dtype)\n return m.multiply(x).toarray()\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_multiply_csr_row(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = _make_row(xp, sp, self.dtype)\n return m.multiply(x).toarray()\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_multiply_csr_col(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = _make_col(xp, sp, self.dtype)\n return m.multiply(x).toarray()\n\n def _make_scalar(self, dtype):\n if numpy.issubdtype(dtype, numpy.integer):\n return dtype(2)\n elif numpy.issubdtype(dtype, numpy.floating):\n return dtype(2.5)\n else:\n return dtype(2.5 - 1.5j)\n\n # divide\n @testing.for_dtypes('ifdFD')\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_divide_scalar(self, xp, sp, dtype):\n m = self.make(xp, sp, self.dtype)\n y = m / self._make_scalar(dtype)\n return y.toarray()\n\n @testing.for_dtypes('ifdFD')\n # type promotion rules are different for ()-shaped arrays\n @testing.numpy_cupy_allclose(sp_name='sp', type_check=False)\n def test_divide_scalarlike(self, xp, sp, dtype):\n m = self.make(xp, sp, self.dtype)\n y = m / xp.array(self._make_scalar(dtype))\n return y.toarray()\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_divide_dense_row(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(4, dtype=self.dtype)\n return m / x\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_divide_dense_col(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(3, dtype=self.dtype).reshape(3, 1)\n return m / x\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_divide_dense_matrix(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(12, dtype=self.dtype).reshape(3, 4)\n return m / x\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_divide_csr_matrix(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = _make4(xp, sp, self.dtype)\n return m / x\n\n\[email protected](*testing.product({\n 'dtype': [numpy.float32, numpy.float64, numpy.complex64, numpy.complex128],\n}))\[email protected]_requires('scipy')\nclass TestCsrMatrixPowScipyComparison(unittest.TestCase):\n\n @testing.numpy_cupy_allclose(sp_name='sp', _check_sparse_format=False)\n def test_pow_0(self, xp, sp):\n m = _make_square(xp, sp, self.dtype)\n return m ** 0\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_pow_1(self, xp, sp):\n m = _make_square(xp, sp, self.dtype)\n return m ** 1\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_pow_2(self, xp, sp):\n m = _make_square(xp, sp, self.dtype)\n return m ** 2\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_pow_3(self, xp, sp):\n m = _make_square(xp, sp, self.dtype)\n return m ** 3\n return m ** 3\n\n def test_pow_neg(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = _make_square(xp, sp, self.dtype)\n with pytest.raises(ValueError):\n m ** -1\n\n def test_pow_not_square(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = _make(xp, sp, self.dtype)\n with pytest.raises(TypeError):\n m ** 2\n\n def test_pow_float(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = _make_square(xp, sp, self.dtype)\n with pytest.raises(ValueError):\n m ** 1.5\n\n def test_pow_list(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n m = _make_square(xp, sp, self.dtype)\n with pytest.raises(TypeError):\n m ** []\n\n\[email protected](*testing.product({\n 'dtype': [numpy.float32, numpy.float64],\n 'ret_dtype': [None, numpy.float32, numpy.float64],\n 'axis': [None, 0, 1, -1, -2],\n}))\[email protected]_requires('scipy')\nclass TestCsrMatrixSum(unittest.TestCase):\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_sum(self, xp, sp):\n m = _make(xp, sp, self.dtype)\n return m.sum(axis=self.axis, dtype=self.ret_dtype)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_sum_with_out(self, xp, sp):\n m = _make(xp, sp, self.dtype)\n if self.axis is None:\n shape = ()\n else:\n shape = list(m.shape)\n shape[self.axis] = 1\n shape = tuple(shape)\n out = xp.empty(shape, dtype=self.ret_dtype)\n if xp is numpy:\n # TODO(unno): numpy.matrix is used for scipy.sparse though\n # cupy.ndarray is used for cupyx.scipy.sparse.\n out = xp.asmatrix(out)\n return m.sum(axis=self.axis, dtype=self.ret_dtype, out=out)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_mean(self, xp, sp):\n m = _make(xp, sp, self.dtype)\n return m.mean(axis=self.axis, dtype=self.ret_dtype)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_mean_with_out(self, xp, sp):\n m = _make(xp, sp, self.dtype)\n if self.axis is None:\n shape = ()\n else:\n shape = list(m.shape)\n shape[self.axis] = 1\n shape = tuple(shape)\n out = xp.empty(shape, dtype=self.ret_dtype)\n if xp is numpy:\n # TODO(unno): numpy.matrix is used for scipy.sparse though\n # cupy.ndarray is used for cupyx.scipy.sparse.\n out = xp.asmatrix(out)\n return m.mean(axis=self.axis, dtype=self.ret_dtype, out=out)\n\n\[email protected](*testing.product({\n 'dtype': [numpy.float32, numpy.float64, numpy.complex64, numpy.complex128],\n}))\[email protected]_requires('scipy')\nclass TestCsrMatrixScipyCompressed(unittest.TestCase):\n\n @testing.numpy_cupy_equal(sp_name='sp')\n def test_get_shape(self, xp, sp):\n return _make(xp, sp, self.dtype).get_shape()\n\n @testing.numpy_cupy_equal(sp_name='sp')\n def test_getnnz(self, xp, sp):\n return _make(xp, sp, self.dtype).getnnz()\n\n\[email protected](*testing.product({\n # TODO(takagi): Test dtypes\n 'axis': [None, -2, -1, 0, 1],\n 'dense': [False, True], # means a sparse matrix but all elements filled\n}))\[email protected]_requires('scipy>=0.19.0')\nclass TestCsrMatrixScipyCompressedMinMax(unittest.TestCase):\n def _make_data_min(self, xp, sp, dense=False):\n dm_data = testing.shaped_random((10, 20), xp=xp, scale=1.0)\n if not dense:\n dm_data[abs(dm_data) < 0.95] = 0\n return sp.csr_matrix(xp.array(dm_data))\n\n def _make_data_max(self, xp, sp, dense=False):\n return -self._make_data_min(xp, sp, dense=dense)\n\n def _make_data_min_explicit(self, xp, sp, axis):\n dm_data = testing.shaped_random((10, 20), xp=xp, scale=1.0)\n if xp is cupy:\n dm_data[dm_data < 0.95] = 0\n else:\n # As SciPy sparse matrix does not have `explicit` parameter, we\n # make SciPy inputs such that SciPy's spmatrix.min(axis=axis)\n # returns the same value as CuPy's spmatrix.min(axis=axis,\n # explicit=True).\n\n # Put infinity instead of zeros so spmatrix.min(axis=axis) returns\n # the smallest numbers except for zero.\n dm_data[dm_data < 0.95] = numpy.inf\n\n if axis is None:\n # If all elements in the array are set to infinity, we make it\n # have at least a zero so SciPy's spmatrix.min(axis=None)\n # returns zero.\n if numpy.isinf(dm_data).all():\n dm_data[0, 0] = 0\n else:\n if axis < 0:\n axis += 2\n\n # If all elements in a row/column are set to infinity, we make\n # it have at least a zero so spmatrix.min(axis=axis) returns\n # zero for the row/column.\n mask = numpy.zeros_like(dm_data, dtype=numpy.bool_)\n if axis == 0:\n rows = dm_data.argmin(axis=0)\n cols = numpy.arange(20)\n else:\n rows = numpy.arange(10)\n cols = dm_data.argmin(axis=1)\n mask[rows, cols] = numpy.isinf(dm_data[rows, cols])\n dm_data[mask] = 0\n\n return sp.csr_matrix(xp.array(dm_data))\n\n def _make_data_max_explicit(self, xp, sp, axis):\n return -self._make_data_min_explicit(xp, sp, axis=axis)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_min(self, xp, sp):\n data = self._make_data_min(xp, sp, dense=self.dense)\n return data.min(axis=self.axis)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_min_explicit(self, xp, sp):\n data = self._make_data_min_explicit(xp, sp, axis=self.axis)\n if xp is cupy:\n return data.min(axis=self.axis, explicit=True)\n else:\n return data.min(axis=self.axis)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_max(self, xp, sp):\n data = self._make_data_max(xp, sp, dense=self.dense)\n return data.max(axis=self.axis)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_max_explicit(self, xp, sp):\n data = self._make_data_max_explicit(xp, sp, axis=self.axis)\n if xp is cupy:\n return data.max(axis=self.axis, explicit=True)\n else:\n return data.max(axis=self.axis)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_argmin(self, xp, sp):\n # TODO(takagi) Fix axis=None\n if self.axis is None:\n pytest.skip()\n data = self._make_data_min(xp, sp, dense=self.dense)\n return data.argmin(axis=self.axis)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_argmax(self, xp, sp):\n # TODO(takagi) Fix axis=None\n if self.axis is None:\n pytest.skip()\n data = self._make_data_max(xp, sp, dense=self.dense)\n return data.argmax(axis=self.axis)\n\n\[email protected](*testing.product({\n 'dtype': [numpy.float32, numpy.float64, numpy.complex64, numpy.complex128],\n}))\[email protected]_requires('scipy')\nclass TestCsrMatrixData(unittest.TestCase):\n\n @testing.numpy_cupy_equal(sp_name='sp')\n def test_dtype(self, xp, sp):\n return _make(xp, sp, self.dtype).dtype\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_abs(self, xp, sp):\n m = _make(xp, sp, self.dtype)\n return abs(m)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_neg(self, xp, sp):\n m = _make(xp, sp, self.dtype)\n return -m\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_astype(self, xp, sp):\n m = _make(xp, sp, self.dtype)\n if numpy.dtype(self.dtype).kind == 'c':\n t = 'D'\n else:\n t = 'd'\n return m.astype(t)\n\n @testing.numpy_cupy_equal(sp_name='sp')\n def test_count_nonzero(self, xp, sp):\n m = _make(xp, sp, self.dtype)\n return m.count_nonzero()\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_power(self, xp, sp):\n m = _make(xp, sp, self.dtype)\n return m.power(2)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_power_with_dtype(self, xp, sp):\n m = _make(xp, sp, self.dtype)\n if numpy.dtype(self.dtype).kind == 'c':\n t = 'D'\n else:\n t = 'd'\n return m.power(2, t)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_mean_axis_None(self, xp, sp):\n m = _make(xp, sp, self.dtype)\n return m.mean(axis=None)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_mean_axis_0(self, xp, sp):\n m = _make(xp, sp, self.dtype)\n return m.mean(axis=0)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_mean_axis_1(self, xp, sp):\n m = _make(xp, sp, self.dtype)\n return m.mean(axis=1)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_mean_axis_negative_1(self, xp, sp):\n m = _make(xp, sp, self.dtype)\n return m.mean(axis=-1)\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_mean_axis_negative_2(self, xp, sp):\n m = _make(xp, sp, self.dtype)\n return m.mean(axis=-2)\n\n\[email protected](*testing.product({\n 'dtype': [numpy.float32, numpy.float64],\n 'ufunc': [\n 'arcsin', 'arcsinh', 'arctan', 'arctanh', 'ceil', 'deg2rad', 'expm1',\n 'floor', 'log1p', 'rad2deg', 'rint', 'sign', 'sin', 'sinh', 'sqrt',\n 'tan', 'tanh', 'trunc',\n ],\n}))\[email protected]_requires('scipy')\nclass TestUfunc(unittest.TestCase):\n\n @testing.numpy_cupy_allclose(sp_name='sp', atol=1e-5)\n def test_ufun(self, xp, sp):\n x = _make(xp, sp, self.dtype)\n x.data *= 0.1\n func = getattr(x, self.ufunc)\n complex_unsupported = {'ceil', 'deg2rad', 'floor', 'rad2deg', 'trunc'}\n if (numpy.dtype(self.dtype).kind == 'c' and\n self.ufunc in complex_unsupported):\n with self.assertRaises(TypeError):\n func()\n return numpy.array(0)\n else:\n return func()\n\n\nclass TestIsspmatrixCsr(unittest.TestCase):\n\n def test_csr(self):\n x = sparse.csr_matrix(\n (cupy.array([], 'f'),\n cupy.array([], 'i'),\n cupy.array([0], 'i')),\n shape=(0, 0), dtype='f')\n assert sparse.isspmatrix_csr(x) is True\n\n def test_csc(self):\n x = sparse.csr_matrix(\n (cupy.array([], 'f'),\n cupy.array([], 'i'),\n cupy.array([0], 'i')),\n shape=(0, 0), dtype='f')\n assert sparse.isspmatrix_csc(x) is False\n\n\[email protected](*testing.product({\n 'dtype': [numpy.float32, numpy.float64, cupy.complex64, cupy.complex128],\n}))\[email protected]_requires('scipy>=1.4.0')\nclass TestCsrMatrixGetitem(unittest.TestCase):\n\n @testing.numpy_cupy_equal(sp_name='sp')\n def test_getitem_int_int(self, xp, sp):\n assert _make(xp, sp, self.dtype)[0, 1] == 1\n\n @testing.numpy_cupy_equal(sp_name='sp')\n def test_getitem_int_int_not_found(self, xp, sp):\n assert _make(xp, sp, self.dtype)[1, 1] == 0\n\n @testing.numpy_cupy_equal(sp_name='sp')\n def test_getitem_int_int_negative(self, xp, sp):\n assert _make(xp, sp, self.dtype)[-1, -2] == 3\n\n def test_getitem_int_int_too_small_row(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n with pytest.raises(IndexError):\n _make(xp, sp, self.dtype)[-4, 0]\n\n def test_getitem_int_int_too_large_row(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n with pytest.raises(IndexError):\n _make(xp, sp, self.dtype)[3, 0]\n\n def test_getitem_int_int_too_small_col(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n with pytest.raises(IndexError):\n _make(xp, sp, self.dtype)[0, -5]\n\n def test_getitem_int_int_too_large_col(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n with pytest.raises(IndexError):\n _make(xp, sp, self.dtype)[0, 4]\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_getitem_int(self, xp, sp):\n return _make(xp, sp, self.dtype)[1]\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_getitem_int_negative(self, xp, sp):\n return _make(xp, sp, self.dtype)[-1]\n\n def test_getitem_int_to_small(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n with pytest.raises(IndexError):\n _make(xp, sp, self.dtype)[-4]\n\n def test_getitem_int_to_large(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n with pytest.raises(IndexError):\n _make(xp, sp, self.dtype)[3]\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_getitem_int_none_slice(self, xp, sp):\n return _make(xp, sp, self.dtype)[1, :]\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_getitem_negative_int_none_slice(self, xp, sp):\n return _make(xp, sp, self.dtype)[-1, :]\n\n def test_getitem_int_too_small_none_slice(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n with pytest.raises(IndexError):\n _make(xp, sp, self.dtype)[-4, :]\n\n def test_getitem_int_too_large_none_slice(self):\n for xp, sp in ((numpy, scipy.sparse), (cupy, sparse)):\n with pytest.raises(IndexError):\n _make(xp, sp, self.dtype)[3, :]\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_getitem_slice(self, xp, sp):\n return _make(xp, sp, self.dtype)[1:3]\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_getitem_slice_negative(self, xp, sp):\n return _make(xp, sp, self.dtype)[-2:-1]\n\n # SciPy prior to 1.4 has bugs where either an IndexError is raised or a\n # segfault occurs instead of returning an empty slice.\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_getitem_slice_start_larger_than_stop(self, xp, sp):\n return _make(xp, sp, self.dtype)[3:2]\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_getitem_ellipsis(self, xp, sp):\n return _make(xp, sp, self.dtype)[...]\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_getitem_int_ellipsis(self, xp, sp):\n return _make(xp, sp, self.dtype)[1, ...]\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_getitem_rowslice_all(self, xp, sp):\n # This test is adapted from Scipy\n return _make(xp, sp, self.dtype)[slice(None, None, None)]\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_getitem_rowslice_negative_stop(self, xp, sp):\n # This test is adapted from Scipy\n return _make(xp, sp, self.dtype)[slice(1, -2, 2)]\n\n def test_getrow(self):\n\n # This test is adapted from Scipy's CSR tests\n N = 10\n X = testing.shaped_random((N, N), cupy, seed=0)\n X[X > 0.7] = 0\n Xcsr = sparse.csr_matrix(X)\n\n for i in range(N):\n arr_row = X[i:i + 1, :]\n csr_row = Xcsr.getrow(i)\n assert sparse.isspmatrix_csr(csr_row)\n assert (arr_row == csr_row.toarray()).all()\n\n def test_getcol(self):\n # This test is adapted from Scipy's CSR tests\n N = 10\n X = testing.shaped_random((N, N), cupy, seed=0)\n X[X > 0.7] = 0\n Xcsr = sparse.csr_matrix(X)\n\n for i in range(N):\n arr_col = X[:, i:i + 1]\n csr_col = Xcsr.getcol(i)\n\n assert sparse.isspmatrix_csr(csr_col)\n assert (arr_col == csr_col.toarray()).all()\n\n\[email protected](*testing.product({\n 'dtype': [numpy.float32, numpy.float64, cupy.complex64, cupy.complex128],\n}))\[email protected]_requires('scipy>=1.4.0')\nclass TestCsrMatrixGetitem2(unittest.TestCase):\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_getitem_slice_start_too_small(self, xp, sp):\n return _make(xp, sp, self.dtype)[-4:None]\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_getitem_slice_start_too_large(self, xp, sp):\n return _make(xp, sp, self.dtype)[4:None]\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_getitem_slice_stop_too_small(self, xp, sp):\n return _make(xp, sp, self.dtype)[None:-4]\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_getitem_slice_stop_too_large(self, xp, sp):\n return _make(xp, sp, self.dtype)[None:4]\n\n\n# CUB SpMV works only when the matrix size is nonzero\[email protected](*testing.product({\n 'make_method': ['_make', '_make_unordered', '_make_duplicate'],\n 'dtype': [numpy.float32, numpy.float64, cupy.complex64, cupy.complex128],\n}))\[email protected]_requires('scipy')\[email protected]\[email protected](cupy.cuda.cub.available, 'The CUB routine is not enabled')\nclass TestCubSpmv(unittest.TestCase):\n\n def setUp(self):\n self.old_accelerators = _accelerator.get_routine_accelerators()\n _accelerator.set_routine_accelerators(['cub'])\n\n def tearDown(self):\n _accelerator.set_routine_accelerators(self.old_accelerators)\n\n @property\n def make(self):\n return globals()[self.make_method]\n\n @testing.numpy_cupy_allclose(sp_name='sp')\n def test_mul_dense_vector(self, xp, sp):\n m = self.make(xp, sp, self.dtype)\n x = xp.arange(4).astype(self.dtype)\n if xp is numpy:\n return m * x\n\n # xp is cupy, first ensure we really use CUB\n func = 'cupyx.scipy.sparse.csr.cub.device_csrmv'\n with testing.AssertFunctionIsCalled(func):\n m * x\n # ...then perform the actual computation\n return m * x\n\n\[email protected](*testing.product({\n 'a_dtype': ['float32', 'float64', 'complex64', 'complex128'],\n 'b_dtype': ['float32', 'float64', 'complex64', 'complex128'],\n 'shape': [(4, 25), (10, 10), (25, 4)],\n 'nz_rate': [0.1, 0.5],\n 'opt': ['maximum', 'minimum'],\n}))\[email protected]_requires('scipy')\[email protected]\nclass TestCsrMatrixMaximumMinimum(unittest.TestCase):\n\n def _make_array(self, shape, dtype, xp):\n dtype = numpy.dtype(dtype)\n if dtype.char in 'fF':\n real_dtype = 'float32'\n elif dtype.char in 'dD':\n real_dtype = 'float64'\n a = testing.shaped_random(shape, xp, dtype=real_dtype, scale=2)\n a = (a - 1) / self.nz_rate\n a[a > 1] = 0\n a[a < -1] = 0\n return a\n\n def _make_matrix(self, shape, dtype, xp):\n dtype = numpy.dtype(dtype)\n a = self._make_array(shape, dtype, xp)\n if dtype.char in 'FD':\n a = a + 1j * self._make_array(shape, dtype, xp)\n return a\n\n def _make_sp_matrix(self, dtype, xp, sp):\n return sp.csr_matrix(self._make_matrix(self.shape, dtype, xp))\n\n def _make_sp_matrix_row(self, dtype, xp, sp):\n shape = 1, self.shape[1]\n return sp.csr_matrix(self._make_matrix(shape, dtype, xp))\n\n def _make_sp_matrix_col(self, dtype, xp, sp):\n shape = self.shape[0], 1\n return sp.csr_matrix(self._make_matrix(shape, dtype, xp))\n\n def _make_sp_matrix_shape(self, shape, dtype, xp, sp):\n return sp.csr_matrix(self._make_matrix(shape, dtype, xp))\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_sparse(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n b = self._make_sp_matrix(self.b_dtype, xp, sp)\n return getattr(a, self.opt)(b)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_sparse_row(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n b = self._make_sp_matrix_row(self.b_dtype, xp, sp)\n if xp == numpy:\n # SciPy does not support sparse broadcasting\n return getattr(a, self.opt)(b.toarray())\n else:\n return getattr(a, self.opt)(b).toarray()\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_sparse_col(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n b = self._make_sp_matrix_col(self.b_dtype, xp, sp)\n if xp == numpy:\n # SciPy does not support sparse broadcasting\n return getattr(a, self.opt)(b.toarray())\n else:\n return getattr(a, self.opt)(b).toarray()\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_dense(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n b = self._make_sp_matrix(self.b_dtype, xp, sp).toarray()\n return getattr(a, self.opt)(b)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_dense_row(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n b = self._make_sp_matrix_row(self.b_dtype, xp, sp).toarray()\n return getattr(a, self.opt)(b)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_dense_col(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n b = self._make_sp_matrix_col(self.b_dtype, xp, sp).toarray()\n return getattr(a, self.opt)(b)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_scalar_plus(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n return getattr(a, self.opt)(0.5)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_scalar_minus(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n return getattr(a, self.opt)(-0.5)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_scalar_zero(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n return getattr(a, self.opt)(0)\n\n def test_ng_shape(self):\n xp, sp = cupy, sparse\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n for i, j in ((-1, 0), (1, 0), (0, -1), (0, 1)):\n shape = self.shape[0] + i, self.shape[1] + j\n b = self._make_sp_matrix_shape(shape, self.b_dtype, xp, sp)\n with self.assertRaises(ValueError):\n getattr(a, self.opt)(b)\n\n\[email protected](*testing.product({\n 'a_dtype': ['float32', 'float64', 'complex64', 'complex128'],\n 'b_dtype': ['float32', 'float64', 'complex64', 'complex128'],\n 'shape': [(6, 15), (15, 6)],\n 'opt': ['_eq_', '_ne_', '_lt_', '_gt_', '_le_', '_ge_'],\n}))\[email protected]_requires('scipy>=1.2')\[email protected]\nclass TestCsrMatrixComparison(unittest.TestCase):\n nz_rate = 0.3\n\n def _make_array(self, shape, dtype, xp):\n dtype = numpy.dtype(dtype)\n if dtype.char in 'fF':\n real_dtype = 'float32'\n elif dtype.char in 'dD':\n real_dtype = 'float64'\n a = testing.shaped_random(shape, xp, dtype=real_dtype, scale=2)\n a = (a - 1) / self.nz_rate\n a[a > 1] = 0\n a[a < -1] = 0\n return a\n\n def _make_matrix(self, shape, dtype, xp):\n dtype = numpy.dtype(dtype)\n a = self._make_array(shape, dtype, xp)\n if dtype.char in 'FD':\n a = a + 1j * self._make_array(shape, dtype, xp)\n return a\n\n def _make_sp_matrix(self, dtype, xp, sp):\n return sp.csr_matrix(self._make_matrix(self.shape, dtype, xp))\n\n def _make_sp_matrix_row(self, dtype, xp, sp):\n shape = 1, self.shape[1]\n return sp.csr_matrix(self._make_matrix(shape, dtype, xp))\n\n def _make_sp_matrix_col(self, dtype, xp, sp):\n shape = self.shape[0], 1\n return sp.csr_matrix(self._make_matrix(shape, dtype, xp))\n\n def _make_sp_matrix_shape(self, shape, dtype, xp, sp):\n return sp.csr_matrix(self._make_matrix(shape, dtype, xp))\n\n def _compare(self, a, b):\n if self.opt == '_eq_':\n return a == b\n elif self.opt == '_ne_':\n return a != b\n elif self.opt == '_lt_':\n return a < b\n elif self.opt == '_gt_':\n return a > b\n elif self.opt == '_le_':\n return a <= b\n elif self.opt == '_ge_':\n return a >= b\n\n @contextlib.contextmanager\n def _ignore_efficiency_warning(self):\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', sparse.SparseEfficiencyWarning)\n yield\n\n @contextlib.contextmanager\n def _assert_warns_efficiency(self, sp, scalar_rhs=None):\n if scalar_rhs is None and self._compare(0, 0):\n with testing.assert_warns(sp.SparseEfficiencyWarning):\n yield\n elif scalar_rhs is not None and self._compare(0, scalar_rhs):\n if sp is sparse: # cupy\n # TODO(kataoka): Test it, too. But, it seems the current\n # implementation does not depend on the scalar value.\n with self._ignore_efficiency_warning():\n yield\n else: # scipy\n with testing.assert_warns(sp.SparseEfficiencyWarning):\n yield\n else:\n yield\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_sparse(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n b = self._make_sp_matrix(self.b_dtype, xp, sp)\n with self._assert_warns_efficiency(sp):\n return self._compare(a, b)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_sparse_row(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n b = self._make_sp_matrix_row(self.b_dtype, xp, sp)\n if xp == numpy:\n # SciPy does not support sparse broadcasting\n return self._compare(a, b.toarray())\n else:\n with self._assert_warns_efficiency(sp):\n return self._compare(a, b).toarray()\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_sparse_col(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n b = self._make_sp_matrix_col(self.b_dtype, xp, sp)\n if xp == numpy:\n # SciPy does not support sparse broadcasting\n return self._compare(a, b.toarray())\n else:\n with self._assert_warns_efficiency(sp):\n return self._compare(a, b).toarray()\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_dense(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n b = self._make_sp_matrix(self.b_dtype, xp, sp).toarray()\n return self._compare(a, b)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_dense_row(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n b = self._make_sp_matrix_row(self.b_dtype, xp, sp).toarray()\n return self._compare(a, b)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_dense_col(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n b = self._make_sp_matrix_col(self.b_dtype, xp, sp).toarray()\n return self._compare(a, b)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_scalar_plus(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n with self._assert_warns_efficiency(sp, 0.5):\n return self._compare(a, 0.5)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_scalar_minus(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n with self._assert_warns_efficiency(sp, -0.5):\n return self._compare(a, -0.5)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_scalar_zero(self, xp, sp):\n if self.opt in ('_le_', '_ge_'):\n # <= and >= with 0 are not supported by SciPy\n pytest.skip()\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n with self._assert_warns_efficiency(sp, 0):\n return self._compare(a, 0)\n\n @testing.numpy_cupy_array_equal(sp_name='sp')\n def test_scalar_nan(self, xp, sp):\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n with self._assert_warns_efficiency(sp, numpy.nan):\n return self._compare(a, numpy.nan)\n\n def test_ng_shape(self):\n xp, sp = cupy, sparse\n a = self._make_sp_matrix(self.a_dtype, xp, sp)\n for i, j in ((-1, 0), (1, 0), (0, -1), (0, 1)):\n shape = self.shape[0] + i, self.shape[1] + j\n b = self._make_sp_matrix_shape(shape, self.b_dtype, xp, sp)\n with self.assertRaises(ValueError):\n with self._ignore_efficiency_warning():\n self._compare(a, b)\n\n\[email protected](*testing.product({\n 'shape': [(8, 5), (5, 5), (5, 8)],\n}))\[email protected]_requires('scipy>=1.5.0')\[email protected]\nclass TestCsrMatrixDiagonal(unittest.TestCase):\n density = 0.5\n\n def _make_matrix(self, dtype):\n a = testing.shaped_random(self.shape, numpy, dtype=dtype)\n mask = testing.shaped_random(self.shape, numpy, dtype='f', scale=1.0)\n a[mask > self.density] = 0\n scipy_a = scipy.sparse.csr_matrix(a)\n cupyx_a = sparse.csr_matrix(cupy.array(a))\n return scipy_a, cupyx_a\n\n @testing.for_dtypes('fdFD')\n def test_diagonal(self, dtype):\n scipy_a, cupyx_a = self._make_matrix(dtype)\n m, n = self.shape\n for k in range(-m, n+1):\n scipy_diag = scipy_a.diagonal(k=k)\n cupyx_diag = cupyx_a.diagonal(k=k)\n testing.assert_allclose(scipy_diag, cupyx_diag)\n\n def _test_setdiag(self, scipy_a, cupyx_a, x, k):\n scipy_a = scipy_a.copy()\n cupyx_a = cupyx_a.copy()\n scipy_a.setdiag(x, k=k)\n cupyx_a.setdiag(cupy.array(x), k=k)\n testing.assert_allclose(scipy_a.data, cupyx_a.data)\n testing.assert_array_equal(scipy_a.indices, cupyx_a.indices)\n testing.assert_array_equal(scipy_a.indptr, cupyx_a.indptr)\n\n @testing.for_dtypes('fdFD')\n def test_setdiag(self, dtype):\n scipy_a, cupyx_a = self._make_matrix(dtype)\n m, n = self.shape\n for k in range(-m+1, n):\n m_st, n_st = max(0, -k), max(0, k)\n for d in (-1, 0, 1):\n x_len = min(m - m_st, n - n_st) + d\n if x_len <= 0:\n continue\n x = numpy.ones((x_len,), dtype=dtype)\n self._test_setdiag(scipy_a, cupyx_a, x, k)\n\n @testing.for_dtypes('fdFD')\n def test_setdiag_scalar(self, dtype):\n scipy_a, cupyx_a = self._make_matrix(dtype)\n x = numpy.array(1.0, dtype=dtype)\n m, n = self.shape\n for k in range(-m+1, n):\n self._test_setdiag(scipy_a, cupyx_a, x, k)\n\n def test_setdiag_invalid(self):\n dtype = 'f'\n scipy_a, cupyx_a = self._make_matrix(dtype)\n x = numpy.array(1.0, dtype=dtype)\n m, n = self.shape\n for k in (-m, n):\n with self.assertRaises(ValueError):\n scipy_a.setdiag(x, k=k)\n with self.assertRaises(ValueError):\n cupyx_a.setdiag(x, k=k)\n" ]
[ [ "numpy.zeros_like", "numpy.ones", "numpy.dtype", "numpy.isinf", "numpy.issubdtype", "numpy.arange", "numpy.array" ] ]
FelixAbrahamsson/zounds
[ "197c358acf3bea4252cfc2561da70cbe799e2c75" ]
[ "zounds/spectral/frequencyscale.py" ]
[ "\nimport numpy as np\nimport bisect\n\n\nclass Hertz(float):\n def __init__(self, hz):\n try:\n self.hz = hz.hz\n except AttributeError:\n self.hz = hz\n\n def __neg__(self):\n return Hertz(-self.hz)\n\n def __add__(self, other):\n try:\n other = other.hz\n except AttributeError:\n pass\n return Hertz(self.hz + other)\n\n def __float__(self):\n return self.hz\n\n\nHz = Hertz\n\n\n# TODO: What commonalities can be factored out of this class and TimeSlice?\nclass FrequencyBand(object):\n \"\"\"\n Represents an interval, or band of frequencies in hertz (cycles per second)\n\n Args:\n start_hz (float): The lower bound of the frequency band in hertz\n stop_hz (float): The upper bound of the frequency band in hertz\n\n Examples::\n >>> import zounds\n >>> band = zounds.FrequencyBand(500, 1000)\n >>> band.center_frequency\n 750.0\n >>> band.bandwidth\n 500\n \"\"\"\n\n def __init__(self, start_hz, stop_hz):\n super(FrequencyBand, self).__init__()\n if stop_hz <= start_hz:\n raise ValueError('stop_hz must be greater than start_hz')\n self.stop_hz = stop_hz\n self.start_hz = start_hz\n\n def __eq__(self, other):\n try:\n return \\\n self.start_hz == other.start_hz \\\n and self.stop_hz == other.stop_hz\n except AttributeError:\n return super(FrequencyBand, self).__eq__(other)\n\n def __hash__(self):\n return (self.__class__.__name__, self.start_hz, self.stop_hz).__hash__()\n\n def intersect(self, other):\n \"\"\"\n Return the intersection between this frequency band and another.\n\n Args:\n other (FrequencyBand): the instance to intersect with\n\n Examples::\n >>> import zounds\n >>> b1 = zounds.FrequencyBand(500, 1000)\n >>> b2 = zounds.FrequencyBand(900, 2000)\n >>> intersection = b1.intersect(b2)\n >>> intersection.start_hz, intersection.stop_hz\n (900, 1000)\n \"\"\"\n lowest_stop = min(self.stop_hz, other.stop_hz)\n highest_start = max(self.start_hz, other.start_hz)\n return FrequencyBand(highest_start, lowest_stop)\n\n @classmethod\n def audible_range(cls, samplerate):\n return FrequencyBand(Hz(20), Hz(samplerate.nyquist))\n\n def bandwidth_ratio(self, other):\n return other.bandwidth / self.bandwidth\n\n def intersection_ratio(self, other):\n intersection = self.intersect(other)\n return self.bandwidth_ratio(intersection)\n\n @staticmethod\n def from_start(start_hz, bandwidth_hz):\n \"\"\"\n Produce a :class:`FrequencyBand` instance from a lower bound and\n bandwidth\n\n Args:\n start_hz (float): the lower bound of the desired FrequencyBand\n bandwidth_hz (float): the bandwidth of the desired FrequencyBand\n\n \"\"\"\n return FrequencyBand(start_hz, start_hz + bandwidth_hz)\n\n @staticmethod\n def from_center(center_hz, bandwidth_hz):\n half_bandwidth = bandwidth_hz / 2\n return FrequencyBand(\n center_hz - half_bandwidth, center_hz + half_bandwidth)\n\n @property\n def bandwidth(self):\n \"\"\"\n The span of this frequency band, in hertz\n \"\"\"\n return self.stop_hz - self.start_hz\n\n @property\n def center_frequency(self):\n return self.start_hz + (self.bandwidth / 2)\n\n def __repr__(self):\n return '''FrequencyBand(\nstart_hz={start_hz},\nstop_hz={stop_hz},\ncenter={center},\nbandwidth={bandwidth})'''.format(\n start_hz=self.start_hz,\n stop_hz=self.stop_hz,\n center=self.center_frequency,\n bandwidth=self.bandwidth)\n\n\nclass FrequencyScale(object):\n \"\"\"\n Represents a set of frequency bands with monotonically increasing start\n frequencies\n\n Args:\n frequency_band (FrequencyBand): A band representing the entire span of\n this scale. E.g., one might want to generate a scale spanning the\n entire range of human hearing by starting with\n :code:`FrequencyBand(20, 20000)`\n n_bands (int): The number of bands in this scale\n always_even (bool): when converting frequency slices to integer indices\n that numpy can understand, should the slice size always be even?\n\n See Also:\n :class:`~zounds.spectral.LinearScale`\n :class:`~zounds.spectral.GeometricScale`\n \"\"\"\n\n def __init__(self, frequency_band, n_bands, always_even=False):\n super(FrequencyScale, self).__init__()\n self.always_even = always_even\n self.n_bands = n_bands\n self.frequency_band = frequency_band\n self._bands = None\n self._starts = None\n self._stops = None\n\n @property\n def bands(self):\n \"\"\"\n An iterable of all bands in this scale\n \"\"\"\n if self._bands is None:\n self._bands = self._compute_bands()\n return self._bands\n\n @property\n def band_starts(self):\n if self._starts is None:\n self._starts = [b.start_hz for b in self.bands]\n return self._starts\n\n @property\n def band_stops(self):\n if self._stops is None:\n self._stops = [b.stop_hz for b in self.bands]\n return self._stops\n\n def _compute_bands(self):\n raise NotImplementedError()\n\n def __len__(self):\n return self.n_bands\n\n @property\n def center_frequencies(self):\n \"\"\"\n An iterable of the center frequencies of each band in this scale\n \"\"\"\n return (band.center_frequency for band in self)\n\n @property\n def bandwidths(self):\n \"\"\"\n An iterable of the bandwidths of each band in this scale\n \"\"\"\n return (band.bandwidth for band in self)\n\n def ensure_overlap_ratio(self, required_ratio=0.5):\n \"\"\"\n Ensure that every adjacent pair of frequency bands meets the overlap\n ratio criteria. This can be helpful in scenarios where a scale is\n being used in an invertible transform, and something like the `constant\n overlap add constraint\n <https://ccrma.stanford.edu/~jos/sasp/Constant_Overlap_Add_COLA_Cases.html>`_\n must be met in order to not introduce artifacts in the reconstruction.\n\n Args:\n required_ratio (float): The required overlap ratio between all\n adjacent frequency band pairs\n\n Raises:\n AssertionError: when the overlap ratio for one or more adjacent\n frequency band pairs is not met\n \"\"\"\n\n msg = \\\n 'band {i}: ratio must be at least {required_ratio} but was {ratio}'\n\n for i in range(0, len(self) - 1):\n b1 = self[i]\n b2 = self[i + 1]\n\n try:\n ratio = b1.intersection_ratio(b2)\n except ValueError:\n ratio = 0\n\n if ratio < required_ratio:\n raise AssertionError(msg.format(**locals()))\n\n @property\n def Q(self):\n \"\"\"\n The quality factor of the scale, or, the ratio of center frequencies\n to bandwidths\n \"\"\"\n return np.array(list(self.center_frequencies)) \\\n / np.array(list(self.bandwidths))\n\n @property\n def start_hz(self):\n \"\"\"\n The lower bound of this frequency scale\n \"\"\"\n return self.frequency_band.start_hz\n\n @property\n def stop_hz(self):\n \"\"\"\n The upper bound of this frequency scale\n \"\"\"\n return self.frequency_band.stop_hz\n\n def _basis(self, other_scale, window):\n weights = np.zeros((len(self), len(other_scale)))\n for i, band in enumerate(self):\n band_slice = other_scale.get_slice(band)\n slce = weights[i, band_slice]\n slce[:] = window * np.ones(len(slce))\n return weights\n\n def apply(self, time_frequency_repr, window):\n basis = self._basis(time_frequency_repr.dimensions[-1].scale, window)\n transformed = np.dot(basis, time_frequency_repr.T).T\n return transformed\n\n def __eq__(self, other):\n return \\\n self.__class__ == other.__class__ \\\n and self.frequency_band == other.frequency_band \\\n and self.n_bands == other.n_bands\n\n def __iter__(self):\n return iter(self.bands)\n\n def _construct_scale_from_slice(self, bands):\n freq_band = FrequencyBand(bands[0].start_hz, bands[-1].stop_hz)\n return self.__class__(freq_band, len(bands))\n\n def get_slice(self, frequency_band):\n \"\"\"\n Given a frequency band, and a frequency dimension comprised of\n n_samples, return a slice using integer indices that may be used to\n extract only the frequency samples that intersect with the frequency\n band\n \"\"\"\n index = frequency_band\n\n if isinstance(index, slice):\n types = {\n index.start.__class__,\n index.stop.__class__,\n index.step.__class__\n }\n\n if Hertz not in types:\n return index\n\n try:\n start = Hertz(0) if index.start is None else index.start\n if start < Hertz(0):\n start = self.stop_hz + start\n stop = self.stop_hz if index.stop is None else index.stop\n if stop < Hertz(0):\n stop = self.stop_hz + stop\n frequency_band = FrequencyBand(start, stop)\n except (ValueError, TypeError):\n pass\n\n start_index = bisect.bisect_left(\n self.band_stops, frequency_band.start_hz)\n stop_index = bisect.bisect_left(\n self.band_starts, frequency_band.stop_hz)\n\n if self.always_even and (stop_index - start_index) % 2:\n # KLUDGE: This is simple, but it may make sense to choose move the\n # upper *or* lower bound, based on which one introduces a lower\n # error\n stop_index += 1\n return slice(start_index, stop_index)\n\n def __getitem__(self, index):\n\n try:\n # index is an integer or slice\n bands = self.bands[index]\n except TypeError:\n # index is a frequency band\n bands = self.bands[self.get_slice(index)]\n\n if isinstance(bands, FrequencyBand):\n return bands\n\n return self._construct_scale_from_slice(bands)\n\n def __str__(self):\n cls = self.__class__.__name__\n return '{cls}(band={self.frequency_band}, n_bands={self.n_bands})' \\\n .format(**locals())\n\n def __repr__(self):\n return self.__str__()\n\n\nclass LinearScale(FrequencyScale):\n \"\"\"\n A linear frequency scale with constant bandwidth. Appropriate for use\n with transforms whose coefficients also lie on a linear frequency scale,\n e.g. the FFT or DCT transforms.\n\n Args:\n frequency_band (FrequencyBand): A band representing the entire span of\n this scale. E.g., one might want to generate a scale spanning the\n entire range of human hearing by starting with\n :code:`FrequencyBand(20, 20000)`\n n_bands (int): The number of bands in this scale\n always_even (bool): when converting frequency slices to integer indices\n that numpy can understand, should the slice size always be even?\n\n Examples:\n >>> from zounds import FrequencyBand, LinearScale\n >>> scale = LinearScale(FrequencyBand(20, 20000), 10)\n >>> scale\n LinearScale(band=FrequencyBand(\n start_hz=20,\n stop_hz=20000,\n center=10010.0,\n bandwidth=19980), n_bands=10)\n >>> scale.Q\n array([ 0.51001001, 1.51001001, 2.51001001, 3.51001001, 4.51001001,\n 5.51001001, 6.51001001, 7.51001001, 8.51001001, 9.51001001])\n \"\"\"\n\n def __init__(self, frequency_band, n_bands, always_even=False):\n super(LinearScale, self).__init__(frequency_band, n_bands, always_even)\n\n @staticmethod\n def from_sample_rate(sample_rate, n_bands, always_even=False):\n \"\"\"\n Return a :class:`~zounds.spectral.LinearScale` instance whose upper\n frequency bound is informed by the nyquist frequency of the sample rate.\n\n Args:\n sample_rate (SamplingRate): the sample rate whose nyquist frequency\n will serve as the upper frequency bound of this scale\n n_bands (int): the number of evenly-spaced frequency bands\n \"\"\"\n fb = FrequencyBand(0, sample_rate.nyquist)\n return LinearScale(fb, n_bands, always_even=always_even)\n\n def _compute_bands(self):\n freqs = np.linspace(\n self.start_hz, self.stop_hz, self.n_bands, endpoint=False)\n # constant, non-overlapping bandwidth\n bandwidth = freqs[1] - freqs[0]\n return tuple(FrequencyBand(f, f + bandwidth) for f in freqs)\n\n\n# class LogScale(FrequencyScale):\n# def __init__(self, frequency_band, n_bands, always_even=False):\n# super(LogScale, self).__init__(\n# frequency_band, n_bands, always_even=always_even)\n#\n# def _compute_bands(self):\n# center_freqs = np.logspace(\n# np.log10(self.start_hz),\n# np.log10(self.stop_hz),\n# self.n_bands + 1)\n# # variable bandwidth\n# bandwidths = np.diff(center_freqs)\n# return tuple(FrequencyBand.from_center(cf, bw)\n# for (cf, bw) in zip(center_freqs[:-1], bandwidths))\n\n\nclass GeometricScale(FrequencyScale):\n \"\"\"\n A constant-Q scale whose center frequencies progress geometrically rather\n than linearly\n\n Args:\n start_center_hz (int): the center frequency of the first band in the\n scale\n stop_center_hz (int): the center frequency of the last band in the scale\n bandwidth_ratio (float): the center frequency to bandwidth ratio\n n_bands (int): the total number of bands\n\n Examples:\n >>> from zounds import GeometricScale\n >>> scale = GeometricScale(20, 20000, 0.05, 10)\n >>> scale\n GeometricScale(band=FrequencyBand(\n start_hz=19.5,\n stop_hz=20500.0,\n center=10259.75,\n bandwidth=20480.5), n_bands=10)\n >>> scale.Q\n array([ 20., 20., 20., 20., 20., 20., 20., 20., 20., 20.])\n >>> list(scale.center_frequencies)\n [20.000000000000004, 43.088693800637671, 92.831776672255558,\n 200.00000000000003, 430.88693800637651, 928.31776672255558,\n 2000.0000000000005, 4308.8693800637648, 9283.1776672255564,\n 20000.000000000004]\n \"\"\"\n\n def __init__(\n self,\n start_center_hz,\n stop_center_hz,\n bandwidth_ratio,\n n_bands,\n always_even=False):\n self.__bands = [\n FrequencyBand.from_center(cf, cf * bandwidth_ratio)\n for cf in np.geomspace(start_center_hz, stop_center_hz, num=n_bands)\n ]\n band = FrequencyBand(self.__bands[0].start_hz, self.__bands[-1].stop_hz)\n super(GeometricScale, self).__init__(\n band, n_bands, always_even=always_even)\n self.start_center_hz = start_center_hz\n self.stop_center_hz = stop_center_hz\n self.bandwidth_ratio = bandwidth_ratio\n\n def _construct_scale_from_slice(self, bands):\n return ExplicitScale(bands)\n\n def __eq__(self, other):\n return \\\n super(GeometricScale, self).__eq__(other) \\\n and self.start_center_hz == other.start_center_hz \\\n and self.stop_center_hz == other.stop_center_hz \\\n and self.bandwidth_ratio == other.bandwidth_ratio\n\n def _compute_bands(self):\n return self.__bands\n\n\nclass ExplicitScale(FrequencyScale):\n \"\"\"\n A scale where the frequency bands are provided explicitly, rather than\n computed\n\n Args:\n bands (list of FrequencyBand): The explicit bands used by this scale\n\n See Also:\n :class:`~zounds.spectral.FrequencyAdaptive`\n \"\"\"\n\n def __init__(self, bands):\n bands = list(bands)\n frequency_band = FrequencyBand(bands[0].start_hz, bands[-1].stop_hz)\n super(ExplicitScale, self).__init__(\n frequency_band, len(bands), always_even=False)\n self._bands = bands\n\n def _construct_scale_from_slice(self, bands):\n return ExplicitScale(bands)\n\n def _compute_bands(self):\n return self._bands\n\n def __eq__(self, other):\n return all([a == b for (a, b) in zip(self, other)])\n\n\nclass Bark(Hertz):\n def __init__(self, bark):\n self.bark = bark\n super(Bark, self).__init__(Bark.to_hz(bark))\n\n @staticmethod\n def to_hz(bark):\n return 300. * ((np.e ** (bark / 6.0)) - (np.e ** (-bark / 6.)))\n\n @staticmethod\n def to_bark(hz):\n return 6. * np.log((hz / 600.) + np.sqrt((hz / 600.) ** 2 + 1))\n\n\ndef equivalent_rectangular_bandwidth(hz):\n return (0.108 * hz) + 24.7\n\n\nclass BarkScale(FrequencyScale):\n def __init__(self, frequency_band, n_bands):\n super(BarkScale, self).__init__(frequency_band, n_bands)\n\n def _compute_bands(self):\n start = Bark.to_bark(self.frequency_band.start_hz)\n stop = Bark.to_bark(self.frequency_band.stop_hz)\n barks = np.linspace(start, stop, self.n_bands)\n center_frequencies_hz = Bark.to_hz(barks)\n bandwidths = equivalent_rectangular_bandwidth(center_frequencies_hz)\n return [\n FrequencyBand.from_center(c, b)\n for c, b in zip(center_frequencies_hz, bandwidths)]\n\n\nclass Mel(Hertz):\n def __init__(self, mel):\n self.mel = mel\n super(Mel, self).__init__(Mel.to_hz(mel))\n\n @staticmethod\n def to_hz(mel):\n return 700 * ((np.e ** (mel / 1127)) - 1)\n\n @staticmethod\n def to_mel(hz):\n return 1127 * np.log(1 + (hz / 700))\n\n\nclass MelScale(FrequencyScale):\n def __init__(self, frequency_band, n_bands):\n super(MelScale, self).__init__(frequency_band, n_bands)\n\n def _compute_bands(self):\n start = Mel.to_mel(self.frequency_band.start_hz)\n stop = Mel.to_mel(self.frequency_band.stop_hz)\n mels = np.linspace(start, stop, self.n_bands)\n center_frequencies_hz = Mel.to_hz(mels)\n bandwidths = equivalent_rectangular_bandwidth(center_frequencies_hz)\n return [\n FrequencyBand.from_center(c, b)\n for c, b in zip(center_frequencies_hz, bandwidths)]\n\n\nclass ChromaScale(FrequencyScale):\n def __init__(self, frequency_band):\n self._a440 = 440.\n self._a = 2 ** (1 / 12.)\n super(ChromaScale, self).__init__(frequency_band, n_bands=12)\n\n def _compute_bands(self):\n raise NotImplementedError()\n\n def get_slice(self, frequency_band):\n raise NotImplementedError()\n\n def _semitones_to_hz(self, semitone):\n return self._a440 * (self._a ** semitone)\n\n def _hz_to_semitones(self, hz):\n \"\"\"\n Convert hertz into a number of semitones above or below some reference\n value, in this case, A440\n \"\"\"\n return np.log(hz / self._a440) / np.log(self._a)\n\n def _basis(self, other_scale, window):\n basis = np.zeros((self.n_bands, len(other_scale)))\n\n # for each tone in the twelve-tone scale, generate narrow frequency\n # bands for every octave of that note that falls within the frequency\n # band.\n start_semitones = \\\n int(np.round(self._hz_to_semitones(self.frequency_band.start_hz)))\n stop_semitones = \\\n int(np.round(self._hz_to_semitones(self.frequency_band.stop_hz)))\n\n semitones = np.arange(start_semitones - 1, stop_semitones)\n hz = self._semitones_to_hz(semitones)\n\n bands = []\n for i in range(0, len(semitones) - 2):\n fh, mh, lh = hz[i: i + 3]\n bands.append(FrequencyBand(fh, lh))\n\n for semitone, band in zip(semitones, bands):\n slce = other_scale.get_slice(band)\n chroma_index = semitone % self.n_bands\n slce = basis[chroma_index, slce]\n slce[:] += np.ones(len(slce)) * window\n\n return basis\n" ]
[ [ "numpy.geomspace", "numpy.arange", "numpy.log", "numpy.sqrt", "numpy.dot", "numpy.linspace" ] ]
Pugavkomm/NS-analyst
[ "698af0e94f57b431fd77c17c49d4a23f11d21d3f" ]
[ "temp/maintestgraph.py" ]
[ "import sys\nimport time\n\nimport numpy as np\n\nfrom matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5\nif is_pyqt5():\n from matplotlib.backends.backend_qt5agg import (\n FigureCanvas, NavigationToolbar2QT as NavigationToolbar)\nelse:\n from matplotlib.backends.backend_qt4agg import (\n FigureCanvas, NavigationToolbar2QT as NavigationToolbar)\nfrom matplotlib.figure import Figure\n\n\nclass ApplicationWindow(QtWidgets.QMainWindow):\n def __init__(self):\n super().__init__()\n self._main = QtWidgets.QWidget()\n self.setCentralWidget(self._main)\n layout = QtWidgets.QVBoxLayout(self._main)\n\n static_canvas = FigureCanvas(Figure(figsize=(5, 3)))\n layout.addWidget(static_canvas)\n self.addToolBar(NavigationToolbar(static_canvas, self))\n\n dynamic_canvas = FigureCanvas(Figure(figsize=(5, 3)))\n layout.addWidget(dynamic_canvas)\n self.addToolBar(QtCore.Qt.BottomToolBarArea,\n NavigationToolbar(dynamic_canvas, self))\n\n self._static_ax = static_canvas.figure.subplots()\n t = np.linspace(0, 10, 501)\n self._static_ax.plot(t, np.tan(t), \".\")\n\n self._dynamic_ax = dynamic_canvas.figure.subplots()\n self._timer = dynamic_canvas.new_timer(\n 100, [(self._update_canvas, (), {})])\n self._timer.start()\n\n def _update_canvas(self):\n self._dynamic_ax.clear()\n t = np.linspace(0, 10, 101)\n # Shift the sinusoid as a function of time.\n self._dynamic_ax.plot(t, np.sin(t + time.time()))\n self._dynamic_ax.figure.canvas.draw()\n\n\nif __name__ == \"__main__\":\n qapp = QtWidgets.QApplication(sys.argv)\n app = ApplicationWindow()\n app.show()\n qapp.exec_()" ]
[ [ "matplotlib.backends.backend_qt4agg.NavigationToolbar2QT", "matplotlib.backends.qt_compat.QtWidgets.QVBoxLayout", "matplotlib.backends.qt_compat.QtWidgets.QWidget", "matplotlib.figure.Figure", "numpy.tan", "matplotlib.backends.qt_compat.is_pyqt5", "matplotlib.backends.qt_compat.QtWidgets.QApplication", "numpy.linspace" ] ]
rjleveque/amrclaw
[ "d7acfe4a71b2515778b134540a015923ce77a3cd" ]
[ "examples/advection_2d_flagregions/setrun.py" ]
[ "\"\"\" \nModule to set up run time parameters for Clawpack.\n\nThe values set in the function setrun are then written out to data files\nthat will be read in by the Fortran code.\n \n\"\"\" \n\nfrom __future__ import absolute_import\nimport os\nimport numpy as np\n\n# used to create ruled rectangle:\nfrom clawpack.amrclaw import region_tools \n\n\n#------------------------------\ndef setrun(claw_pkg='amrclaw'):\n#------------------------------\n \n \"\"\" \n Define the parameters used for running Clawpack.\n\n INPUT:\n claw_pkg expected to be \"amrclaw\" for this setrun.\n\n OUTPUT:\n rundata - object of class ClawRunData \n \n \"\"\" \n \n from clawpack.clawutil import data \n \n \n assert claw_pkg.lower() == 'amrclaw', \"Expected claw_pkg = 'amrclaw'\"\n\n num_dim = 2\n rundata = data.ClawRunData(claw_pkg, num_dim)\n\n #------------------------------------------------------------------\n # Problem-specific parameters to be written to setprob.data:\n #------------------------------------------------------------------\n\n probdata = rundata.new_UserData(name='probdata',fname='setprob.data')\n probdata.add_param('u', 0.5, 'ubar advection velocity')\n probdata.add_param('v', 1.0, 'vbar advection velocity')\n \n #------------------------------------------------------------------\n # Standard Clawpack parameters to be written to claw.data:\n # (or to amr2ez.data for AMR)\n #------------------------------------------------------------------\n\n clawdata = rundata.clawdata # initialized when rundata instantiated\n\n\n # Set single grid parameters first.\n # See below for AMR parameters.\n\n\n # ---------------\n # Spatial domain:\n # ---------------\n\n # Number of space dimensions:\n clawdata.num_dim = num_dim\n \n # Lower and upper edge of computational domain:\n clawdata.lower[0] = 0. # xlower\n clawdata.upper[0] = 1. # xupper\n clawdata.lower[1] = 0. # ylower\n clawdata.upper[1] = 1. # yupper\n \n # Number of grid cells:\n clawdata.num_cells[0] = 50 # mx\n clawdata.num_cells[1] = 50 # my\n \n\n # ---------------\n # Size of system:\n # ---------------\n\n # Number of equations in the system:\n clawdata.num_eqn = 1\n\n # Number of auxiliary variables in the aux array (initialized in setaux)\n clawdata.num_aux = 0\n \n # Index of aux array corresponding to capacity function, if there is one:\n clawdata.capa_index = 0\n \n \n # -------------\n # Initial time:\n # -------------\n\n clawdata.t0 = 0.0 \n \n\n # Restart from checkpoint file of a previous run?\n # If restarting, t0 above should be from original run, and the\n # restart_file 'fort.chkNNNNN' specified below should be in \n # the OUTDIR indicated in Makefile.\n\n clawdata.restart = False # True to restart from prior results\n clawdata.restart_file = 'fort.chk00006' # File to use for restart data\n \n \n # -------------\n # Output times:\n #--------------\n\n # Specify at what times the results should be written to fort.q files.\n # Note that the time integration stops after the final output time.\n \n clawdata.output_style = 1\n \n if clawdata.output_style==1:\n # Output ntimes frames at equally spaced times up to tfinal:\n # Can specify num_output_times = 0 for no output\n clawdata.num_output_times = 10\n clawdata.tfinal = 1.0\n clawdata.output_t0 = True # output at initial (or restart) time?\n \n elif clawdata.output_style == 2:\n # Specify a list or numpy array of output times:\n # Include t0 if you want output at the initial time.\n clawdata.output_times = [0., 0.1]\n \n elif clawdata.output_style == 3:\n # Output every step_interval timesteps over total_steps timesteps:\n clawdata.output_step_interval = 2\n clawdata.total_steps = 4\n clawdata.output_t0 = True # output at initial (or restart) time?\n \n\n clawdata.output_format = 'ascii' # 'ascii', 'binary', 'netcdf'\n\n clawdata.output_q_components = 'all' # could be list such as [True,True]\n clawdata.output_aux_components = 'none' # could be list\n clawdata.output_aux_onlyonce = True # output aux arrays only at t0\n \n\n # ---------------------------------------------------\n # Verbosity of messages to screen during integration: \n # ---------------------------------------------------\n\n # The current t, dt, and cfl will be printed every time step\n # at AMR levels <= verbosity. Set verbosity = 0 for no printing.\n # (E.g. verbosity == 2 means print only on levels 1 and 2.)\n clawdata.verbosity = 0\n \n \n\n # --------------\n # Time stepping:\n # --------------\n\n # if dt_variable==True: variable time steps used based on cfl_desired,\n # if dt_variable==False: fixed time steps dt = dt_initial always used.\n clawdata.dt_variable = True\n \n # Initial time step for variable dt. \n # (If dt_variable==0 then dt=dt_initial for all steps)\n clawdata.dt_initial = 0.016\n \n # Max time step to be allowed if variable dt used:\n clawdata.dt_max = 1e+99\n \n # Desired Courant number if variable dt used \n clawdata.cfl_desired = 0.9\n # max Courant number to allow without retaking step with a smaller dt:\n clawdata.cfl_max = 1.0\n \n # Maximum number of time steps to allow between output times:\n clawdata.steps_max = 100000\n\n\n # ------------------\n # Method to be used:\n # ------------------\n\n # Order of accuracy: 1 => Godunov, 2 => Lax-Wendroff plus limiters\n clawdata.order = 2\n \n # Use dimensional splitting?\n clawdata.dimensional_split = 'unsplit'\n \n # For unsplit method, transverse_waves can be \n # 0 or 'none' ==> donor cell (only normal solver used)\n # 1 or 'increment' ==> corner transport of waves\n # 2 or 'all' ==> corner transport of 2nd order corrections too\n clawdata.transverse_waves = 'all'\n \n \n # Number of waves in the Riemann solution:\n clawdata.num_waves = 1\n \n # List of limiters to use for each wave family: \n # Required: len(limiter) == num_waves\n # Some options:\n # 0 or 'none' ==> no limiter (Lax-Wendroff)\n # 1 or 'minmod' ==> minmod\n # 2 or 'superbee' ==> superbee\n # 3 or 'vanleer' ==> van Leer\n # 4 or 'mc' ==> MC limiter\n clawdata.limiter = ['vanleer']\n \n clawdata.use_fwaves = False # True ==> use f-wave version of algorithms\n \n # Source terms splitting:\n # src_split == 0 or 'none' ==> no source term (src routine never called)\n # src_split == 1 or 'godunov' ==> Godunov (1st order) splitting used, \n # src_split == 2 or 'strang' ==> Strang (2nd order) splitting used, not recommended.\n clawdata.source_split = 'none'\n \n \n # --------------------\n # Boundary conditions:\n # --------------------\n\n # Number of ghost cells (usually 2)\n clawdata.num_ghost = 2\n \n # Choice of BCs at xlower and xupper:\n # 0 or 'user' => user specified (must modify bcNamr.f to use this option)\n # 1 or 'extrap' => extrapolation (non-reflecting outflow)\n # 2 or 'periodic' => periodic (must specify this at both boundaries)\n # 3 or 'wall' => solid wall for systems where q(2) is normal velocity\n \n clawdata.bc_lower[0] = 'periodic' # at xlower\n clawdata.bc_upper[0] = 'periodic' # at xupper\n\n clawdata.bc_lower[1] = 'periodic' # at ylower\n clawdata.bc_upper[1] = 'periodic' # at yupper\n \n\n # ---------------\n # Gauges:\n # ---------------\n rundata.gaugedata.gauges = []\n # for gauges append lines of the form [gaugeno, x, y, t1, t2]\n rundata.gaugedata.gauges.append([1, 0.6, 0.4, 0., 10.])\n \n \n # --------------\n # Checkpointing:\n # --------------\n\n # Specify when checkpoint files should be created that can be\n # used to restart a computation.\n\n clawdata.checkpt_style = 0\n\n if clawdata.checkpt_style == 0:\n # Do not checkpoint at all\n pass\n\n elif clawdata.checkpt_style == 1:\n # Checkpoint only at tfinal.\n pass\n\n elif clawdata.checkpt_style == 2:\n # Specify a list of checkpoint times. \n clawdata.checkpt_times = [0.1,0.15]\n\n elif clawdata.checkpt_style == 3:\n # Checkpoint every checkpt_interval timesteps (on Level 1)\n # and at the final time.\n clawdata.checkpt_interval = 5\n\n # ---------------\n # AMR parameters:\n # ---------------\n amrdata = rundata.amrdata\n\n\n # max number of refinement levels:\n amrdata.amr_levels_max = 3\n\n # List of refinement ratios at each level (length at least amr_level_max-1)\n amrdata.refinement_ratios_x = [2,2]\n amrdata.refinement_ratios_y = [2,2]\n amrdata.refinement_ratios_t = [2,2]\n\n\n # Specify type of each aux variable in amrdata.auxtype.\n # This must be a list of length num_aux, each element of which is one of:\n # 'center', 'capacity', 'xleft', or 'yleft' (see documentation).\n amrdata.aux_type = []\n\n\n # Flag for refinement based on Richardson error estimater:\n amrdata.flag_richardson = False # use Richardson?\n amrdata.flag_richardson_tol = 0.1 # Richardson tolerance\n \n # Flag for refinement using routine flag2refine:\n amrdata.flag2refine = True # use this?\n amrdata.flag2refine_tol = 0.05 # tolerance used in this routine\n # User can modify flag2refine to change the criterion for flagging.\n # Default: check max-norm of difference between q in a cell and \n # each of its neighbors.\n\n # steps to take on each level L between regriddings of level L+1:\n amrdata.regrid_interval = 2 \n\n # width of buffer zone around flagged points:\n # (typically the same as regrid_interval so waves don't escape):\n amrdata.regrid_buffer_width = 3 \n\n # clustering alg. cutoff for (# flagged pts) / (total # of cells refined)\n # (closer to 1.0 => more small grids may be needed to cover flagged cells)\n amrdata.clustering_cutoff = 0.9\n\n # print info about each regridding up to this level:\n amrdata.verbosity_regrid = 3 \n\n\n # ---------------\n # Regions: (old style rectangles)\n # ---------------\n rundata.regiondata.regions = []\n # to specify regions of refinement append lines of the form\n # [minlevel,maxlevel,t1,t2,x1,x2,y1,y2]\n\n # ---------------\n # NEW flagregions\n # ---------------\n\n flagregions = rundata.flagregiondata.flagregions # initialized to []\n\n # now append as many flagregions as desired to this list:\n from clawpack.amrclaw.data import FlagRegion\n\n # The entire domain restricted to level 1 for illustration:\n # Note that this is a rectangle specified in the new way:\n # (other regions below will force/allow more refinement)\n flagregion = FlagRegion(num_dim=2)\n flagregion.name = 'Region_domain'\n flagregion.minlevel = 1\n flagregion.maxlevel = 1\n flagregion.t1 = 0.\n flagregion.t2 = 1e9\n flagregion.spatial_region_type = 1 # Rectangle\n flagregion.spatial_region = [0.,1.,0.,1.] # = [x1,x2,y1,y2]\n flagregions.append(flagregion)\n\n # A more general ruled rectangle:\n flagregion = FlagRegion(num_dim=2)\n flagregion.name = 'Region_triangle'\n flagregion.minlevel = 1\n flagregion.maxlevel = 3\n flagregion.t1 = 0.\n flagregion.t2 = 1e9\n flagregion.spatial_region_type = 2 # Ruled Rectangle\n flagregion.spatial_region_file = \\\n os.path.abspath('RuledRectangle_Triangle.data')\n flagregions.append(flagregion)\n\n # code to make RuledRectangle_Triangle.data:\n rr = region_tools.RuledRectangle()\n rr.method = 1 # piecewiselinear edges between s values\n rr.ixy = 'x' # so s refers to x, lower & upper are limits in y\n rr.s = np.array([0.1, 0.8])\n rr.lower = np.array([0.2, 0.8])\n rr.upper = np.array([0.8, 0.8])\n rr.write('RuledRectangle_Triangle.data')\n \n # A trapezoid:\n flagregion = FlagRegion(num_dim=2)\n flagregion.name = 'Region_trapezoid'\n flagregion.minlevel = 3\n flagregion.maxlevel = 3\n flagregion.t1 = 0.\n flagregion.t2 = 1e9\n flagregion.spatial_region_type = 2 # Ruled Rectangle\n flagregion.spatial_region_file = \\\n os.path.abspath('RuledRectangle_Trapezoid.data')\n flagregions.append(flagregion)\n\n # code to make RuledRectangle_Trapezoid.data:\n rr = region_tools.RuledRectangle()\n rr.method = 1 # piecewiselinear edges between s values\n rr.ixy = 'x' # so s refers to x, lower & upper are limits in y\n rr.s = np.array([0.2, 0.9])\n rr.lower = np.array([0.05, 0.75])\n rr.upper = np.array([0.15, 0.85])\n rr.write('RuledRectangle_Trapezoid.data')\n\n\n # ----- For developers ----- \n # Toggle debugging print statements:\n amrdata.dprint = False # print domain flags\n amrdata.eprint = False # print err est flags\n amrdata.edebug = False # even more err est flags\n amrdata.gprint = False # grid bisection/clustering\n amrdata.nprint = False # proper nesting output\n amrdata.pprint = False # proj. of tagged points\n amrdata.rprint = False # print regridding summary\n amrdata.sprint = False # space/memory output\n amrdata.tprint = False # time step reporting each level\n amrdata.uprint = False # update/upbnd reporting\n \n return rundata\n\n # end of function setrun\n # ----------------------\n\n\nif __name__ == '__main__':\n # Set up run-time parameters and write all data files.\n import sys\n rundata = setrun(*sys.argv[1:])\n rundata.write()\n \n" ]
[ [ "numpy.array" ] ]
pragupta/Inverse-Reinforcement-Learning
[ "e7bbb7bb0ad24ebc36d9e0d4b4e6c6788229fd9c" ]
[ "irl/mdp/gridworld.py" ]
[ "\"\"\"\nImplements the gridworld MDP.\n\nMatthew Alger, 2015\[email protected]\n\"\"\"\n\nimport numpy as np\nimport numpy.random as rn\nimport matplotlib.pyplot as plt\n\nclass Gridworld(object):\n \"\"\"\n Gridworld MDP.\n \"\"\"\n\n def __init__(self, grid_size, wind, discount):\n \"\"\"\n grid_size: Grid size. int.\n wind: Chance of moving randomly. float.\n discount: MDP discount. float.\n -> Gridworld\n \"\"\"\n\n self.actions = ((1, 0), (0, 1), (-1, 0), (0, -1), (0, 0))\n self.n_actions = len(self.actions)\n self.n_states = grid_size**2\n self.grid_size = grid_size\n self.wind = wind\n self.discount = discount\n\n # Preconstruct the transition probability array.\n self.transition_probability = np.array(\n [[[self._transition_probability(i, j, k)\n for k in range(self.n_states)]\n for j in range(self.n_actions)]\n for i in range(self.n_states)])\n\n def __str__(self):\n return \"Gridworld({}, {}, {})\".format(self.grid_size, self.wind,\n self.discount)\n\n def plot_grid (self, filename=\"grid_world.png\", policy=[], value=[]):\n fig = plt.figure()\n ax = fig.add_subplot(111, xlim=(0, self.grid_size),\n ylim=(0, self.grid_size))\n\n\n font_size = 'x-large'\n ax.title.set_text(\"Gridworld\")\n\n cell_color = ['black', 'gray', 'white']\n\n for i in range(self.n_states):\n x, y = self.int_to_point(i)\n c_x = x\n c_y = y\n\n x = x - 0.5\n y = y - 0.5\n if self.reward(i) == 0:\n rect_color = 'gray'\n ec = 'white'\n else:\n rect_color = 'white'\n ec = 'black'\n\n p = plt.Rectangle([x, y], 1, 1, ec=ec)\n p.set_facecolor(rect_color)\n ax.add_patch(p)\n\n if len(policy) > 0:\n actions = [\">\", \"^\", \"<\", \"v\", \"-\"]\n if len(policy.shape) > 1:\n action = actions[np.argmax(policy[i])]\n else:\n action = actions[policy[i]]\n ax.text(c_x, c_y, action, color='k', #weight='bold',\n fontsize=10, ha='center', va='top')\n\n if len(value) > 0:\n ax.text(c_x, c_y, round(value[i], 2), color='k', #weight='bold',\n fontsize=8, ha='center', va='bottom')\n\n ax.set_xlim(-0.5, self.grid_size - 0.5)\n ax.set_ylim(-0.5, self.grid_size - 0.5)\n\n ax.set_xticks(range(self.grid_size))\n ax.set_yticks(range(self.grid_size))\n plt.savefig(filename, format='png', dpi=150)\n plt.close()\n def feature_vector(self, i, feature_map=\"ident\"):\n \"\"\"\n Get the feature vector associated with a state integer.\n\n i: State int.\n feature_map: Which feature map to use (default ident). String in {ident,\n coord, proxi}.\n -> Feature vector.\n \"\"\"\n\n if feature_map == \"coord\":\n f = np.zeros(self.grid_size)\n x, y = i % self.grid_size, i // self.grid_size\n f[x] += 1\n f[y] += 1\n return f\n if feature_map == \"proxi\":\n f = np.zeros(self.n_states)\n x, y = i % self.grid_size, i // self.grid_size\n for b in range(self.grid_size):\n for a in range(self.grid_size):\n dist = abs(x - a) + abs(y - b)\n f[self.point_to_int((a, b))] = dist\n return f\n # Assume identity map.\n f = np.zeros(self.n_states)\n f[i] = 1\n return f\n\n def feature_matrix(self, feature_map=\"ident\"):\n \"\"\"\n Get the feature matrix for this gridworld.\n\n feature_map: Which feature map to use (default ident). String in {ident,\n coord, proxi}.\n -> NumPy array with shape (n_states, d_states).\n \"\"\"\n\n features = []\n for n in range(self.n_states):\n f = self.feature_vector(n, feature_map)\n features.append(f)\n return np.array(features)\n\n def int_to_point(self, i):\n \"\"\"\n Convert a state int into the corresponding coordinate.\n\n i: State int.\n -> (x, y) int tuple.\n \"\"\"\n\n return (i % self.grid_size, i // self.grid_size)\n\n def point_to_int(self, p):\n \"\"\"\n Convert a coordinate into the corresponding state int.\n\n p: (x, y) tuple.\n -> State int.\n \"\"\"\n\n return p[0] + p[1]*self.grid_size\n\n def neighbouring(self, i, k):\n \"\"\"\n Get whether two points neighbour each other. Also returns true if they\n are the same point.\n\n i: (x, y) int tuple.\n k: (x, y) int tuple.\n -> bool.\n \"\"\"\n\n return abs(i[0] - k[0]) + abs(i[1] - k[1]) <= 1\n\n def _transition_probability(self, i, j, k):\n \"\"\"\n Get the probability of transitioning from state i to state k given\n action j.\n\n i: State int.\n j: Action int.\n k: State int.\n -> p(s_k | s_i, a_j)\n \"\"\"\n\n xi, yi = self.int_to_point(i)\n xj, yj = self.actions[j]\n xk, yk = self.int_to_point(k)\n\n if not self.neighbouring((xi, yi), (xk, yk)):\n return 0.0\n\n # Is k the intended state to move to?\n if (xi + xj, yi + yj) == (xk, yk):\n return 1 - self.wind + self.wind/self.n_actions\n\n # If these are not the same point, then we can move there by wind.\n if (xi, yi) != (xk, yk):\n return self.wind/self.n_actions\n\n # If these are the same point, we can only move here by either moving\n # off the grid or being blown off the grid. Are we on a corner or not?\n if (xi, yi) in {(0, 0), (self.grid_size-1, self.grid_size-1),\n (0, self.grid_size-1), (self.grid_size-1, 0)}:\n # Corner.\n # Can move off the edge in two directions.\n # Did we intend to move off the grid?\n if not (0 <= xi + xj < self.grid_size and\n 0 <= yi + yj < self.grid_size):\n # We intended to move off the grid, so we have the regular\n # success chance of staying here plus an extra chance of blowing\n # onto the *other* off-grid square.\n return 1 - self.wind + 2*self.wind/self.n_actions\n else:\n # We can blow off the grid in either direction only by wind.\n return 2*self.wind/self.n_actions\n else:\n # Not a corner. Is it an edge?\n if (xi not in {0, self.grid_size-1} and\n yi not in {0, self.grid_size-1}):\n # Not an edge.\n return 0.0\n\n # Edge.\n # Can only move off the edge in one direction.\n # Did we intend to move off the grid?\n if not (0 <= xi + xj < self.grid_size and\n 0 <= yi + yj < self.grid_size):\n # We intended to move off the grid, so we have the regular\n # success chance of staying here.\n return 1 - self.wind + self.wind/self.n_actions\n else:\n # We can blow off the grid only by wind.\n return self.wind/self.n_actions\n\n def reward(self, state_int):\n \"\"\"\n Reward for being in state state_int.\n\n state_int: State integer. int.\n -> Reward.\n \"\"\"\n\n# if state_int == self.n_states - 1:\n# return 1\n points = {self.point_to_int((0,0)) : 1,\n self.point_to_int((0,9)) : 1,\n self.point_to_int((9,0)) : 1,\n self.point_to_int((9,9)) : 1}\n if state_int in points:\n return points[state_int]\n return 0\n\n def average_reward(self, n_trajectories, trajectory_length, policy):\n \"\"\"\n Calculate the average total reward obtained by following a given policy\n over n_paths paths.\n\n policy: Map from state integers to action integers.\n n_trajectories: Number of trajectories. int.\n trajectory_length: Length of an episode. int.\n -> Average reward, standard deviation.\n \"\"\"\n\n trajectories = self.generate_trajectories(n_trajectories,\n trajectory_length, policy)\n rewards = [[r for _, _, r in trajectory] for trajectory in trajectories]\n rewards = np.array(rewards)\n\n # Add up all the rewards to find the total reward.\n total_reward = rewards.sum(axis=1)\n\n # Return the average reward and standard deviation.\n return total_reward.mean(), total_reward.std()\n\n def optimal_policy(self, state_int):\n \"\"\"\n The optimal policy for this gridworld.\n\n state_int: What state we are in. int.\n -> Action int.\n \"\"\"\n\n sx, sy = self.int_to_point(state_int)\n\n if sx < self.grid_size and sy < self.grid_size:\n return rn.randint(0, 2)\n if sx < self.grid_size-1:\n return 0\n if sy < self.grid_size-1:\n return 1\n raise ValueError(\"Unexpected state.\")\n\n def optimal_policy_deterministic(self, state_int):\n \"\"\"\n Deterministic version of the optimal policy for this gridworld.\n\n state_int: What state we are in. int.\n -> Action int.\n \"\"\"\n\n sx, sy = self.int_to_point(state_int)\n if sx < sy:\n return 0\n return 1\n\n def generate_trajectories(self, n_trajectories, trajectory_length, policy,\n random_start=False,\n start_state=(0, 0)):\n \"\"\"\n Generate n_trajectories trajectories with length trajectory_length,\n following the given policy.\n\n n_trajectories: Number of trajectories. int.\n trajectory_length: Length of an episode. int.\n policy: Map from state integers to action integers.\n random_start: Whether to start randomly (default False). bool.\n -> [[(state int, action int, reward float)]]\n \"\"\"\n\n trajectories = []\n for _ in range(n_trajectories):\n if random_start:\n sx, sy = rn.randint(self.grid_size), rn.randint(self.grid_size)\n else:\n sx, sy = start_state\n\n trajectory = []\n for _ in range(trajectory_length):\n if rn.random() < self.wind:\n action = self.actions[rn.randint(0, 4)]\n else:\n # Follow the given policy.\n action = self.actions[policy(self.point_to_int((sx, sy)))]\n\n if (0 <= sx + action[0] < self.grid_size and\n 0 <= sy + action[1] < self.grid_size):\n next_sx = sx + action[0]\n next_sy = sy + action[1]\n else:\n next_sx = sx\n next_sy = sy\n\n state_int = self.point_to_int((sx, sy))\n action_int = self.actions.index(action)\n next_state_int = self.point_to_int((next_sx, next_sy))\n reward = self.reward(next_state_int)\n trajectory.append((state_int, action_int, reward))\n\n sx = next_sx\n sy = next_sy\n\n trajectories.append(trajectory)\n\n return np.array(trajectories)\n" ]
[ [ "numpy.zeros", "matplotlib.pyplot.figure", "matplotlib.pyplot.savefig", "numpy.argmax", "numpy.random.random", "matplotlib.pyplot.close", "numpy.array", "numpy.random.randint", "matplotlib.pyplot.Rectangle" ] ]
cfleschhut/virushack
[ "2fe7ded0be8672b066edef7fed52573794db2ba5" ]
[ "hystreet/hystreet_to_s3/compute_station_means.py" ]
[ "import pandas as pd\nfrom datetime import datetime, date\n\n\ndef compute_weekday(timestamp):\n date_str = timestamp.split('+')[0]\n date = datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S.%f')\n return date.weekday()\n\n\ndata = pd.read_csv('data.temp.csv')\n\ndata['weekday'] = float(\"NaN\")\nfor index, row in data.iterrows():\n data.at[index, 'weekday'] = compute_weekday(row['timestamp'])\n\n# compute mean pedestrians for stations by weekday\nstation_means = data.groupby(['station_id', 'weekday']).mean().reset_index().rename(columns={'pedestrians_count': 'mean_pedestrians_count_weekday', 'station_id': 'station_id_mean', 'weekday': 'weekday_mean'})[\n ['station_id_mean', 'weekday_mean', 'mean_pedestrians_count_weekday']]\nstation_means.to_csv('station_means.csv')\n" ]
[ [ "pandas.read_csv" ] ]
OtavioPiza/project-euler
[ "96ca6d5af85ab2c2b911e38d89a78ac2443fbc5f" ]
[ "utils/plotting.py" ]
[ "from matplotlib import pyplot as plt\nfrom typing import Any, NoReturn, Tuple, List\n\n\ndef plot_range(params: Tuple[Tuple[Any], ...], functions: Tuple[(Any, )], x_label: str = 'input',\n x_axis_labeling_function: (Any) = lambda i: i[0]) -> NoReturn:\n \"\"\"\n plots the time each function took to execute each of the provided parameters; if there are more then one parameters,\n the first one is used for the x-axis\n\n :param params: parameters for the functions\n :param functions: functions\n \"\"\"\n x_axis: List[Any] = list(map(x_axis_labeling_function, params))\n y_axes: List[List[float]] = [[function(*param)[1] for param in params] for function in functions]\n index: int = 0\n\n for y_axis in y_axes:\n plt.plot(x_axis, y_axis, label=f'solution {(index := index + 1)}')\n\n plt.xlabel(x_label)\n plt.ylabel('time')\n plt.legend()\n plt.show()\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel" ] ]
skynetera/openpilot
[ "a7e099c946800c7a8b60c47678801d9a95f95549" ]
[ "selfdrive/controls/lib/radar_helpers.py" ]
[ "import numpy as np\nimport platform\nimport os\nimport sys\n\nfrom common.kalman.ekf import FastEKF1D, SimpleSensor\n\n# radar tracks\nSPEED, ACCEL = 0, 1 # Kalman filter states enum\n\nrate, ratev = 20., 20. # model and radar are both at 20Hz\nts = 1./rate\nfreq_v_lat = 0.2 # Hz\nk_v_lat = 2*np.pi*freq_v_lat*ts / (1 + 2*np.pi*freq_v_lat*ts)\n\nfreq_a_lead = .5 # Hz\nk_a_lead = 2*np.pi*freq_a_lead*ts / (1 + 2*np.pi*freq_a_lead*ts)\n\n# stationary qualification parameters\nv_stationary_thr = 4. # objects moving below this speed are classified as stationary\nv_oncoming_thr = -3.9 # needs to be a bit lower in abs value than v_stationary_thr to not leave \"holes\"\nv_ego_stationary = 4. # no stationary object flag below this speed\n\nclass Track(object):\n def __init__(self):\n self.ekf = None\n self.stationary = True\n self.initted = False\n\n def update(self, d_rel, y_rel, v_rel, d_path, v_ego_t_aligned):\n if self.initted:\n self.dPathPrev = self.dPath\n self.vLeadPrev = self.vLead\n self.vRelPrev = self.vRel\n\n # relative values, copy\n self.dRel = d_rel # LONG_DIST\n self.yRel = y_rel # -LAT_DIST\n self.vRel = v_rel # REL_SPEED\n\n # compute distance to path\n self.dPath = d_path\n\n # computed velocity and accelerations\n self.vLead = self.vRel + v_ego_t_aligned\n\n if not self.initted:\n self.aRel = 0. # nidec gives no information about this\n self.vLat = 0.\n self.aLead = 0.\n else:\n # estimate acceleration\n a_rel_unfilt = (self.vRel - self.vRelPrev) / ts\n a_rel_unfilt = np.clip(a_rel_unfilt, -10., 10.)\n self.aRel = k_a_lead * a_rel_unfilt + (1 - k_a_lead) * self.aRel\n\n v_lat_unfilt = (self.dPath - self.dPathPrev) / ts\n self.vLat = k_v_lat * v_lat_unfilt + (1 - k_v_lat) * self.vLat\n\n a_lead_unfilt = (self.vLead - self.vLeadPrev) / ts\n a_lead_unfilt = np.clip(a_lead_unfilt, -10., 10.)\n self.aLead = k_a_lead * a_lead_unfilt + (1 - k_a_lead) * self.aLead\n\n if self.stationary:\n # stationary objects can become non stationary, but not the other way around\n self.stationary = v_ego_t_aligned > v_ego_stationary and abs(self.vLead) < v_stationary_thr\n self.oncoming = self.vLead < v_oncoming_thr\n\n if self.ekf is None:\n self.ekf = FastEKF1D(ts, 1e3, [0.1, 1])\n self.ekf.state[SPEED] = self.vLead\n self.ekf.state[ACCEL] = 0\n self.lead_sensor = SimpleSensor(SPEED, 1, 2)\n\n self.vLeadK = self.vLead\n self.aLeadK = self.aLead\n else:\n self.ekf.update_scalar(self.lead_sensor.read(self.vLead))\n self.ekf.predict(ts)\n self.vLeadK = float(self.ekf.state[SPEED])\n self.aLeadK = float(self.ekf.state[ACCEL])\n\n if not self.initted:\n self.cnt = 1\n self.vision_cnt = 0\n else:\n self.cnt += 1\n\n self.initted = True\n self.vision = False\n\n def mix_vision(self, dist_to_vision, rel_speed_diff):\n # rel speed is very hard to estimate from vision\n if dist_to_vision < 4.0 and rel_speed_diff < 10.:\n # vision point is never stationary\n self.stationary = False\n self.vision = True\n self.vision_cnt += 1\n\n def get_key_for_cluster(self):\n # Weigh y higher since radar is inaccurate in this dimension\n return [self.dRel, self.dPath*2, self.vRel]\n\n# ******************* Cluster *******************\n\nif platform.machine() == 'aarch64':\n for x in sys.path:\n pp = os.path.join(x, \"phonelibs/hierarchy/lib\")\n if os.path.isfile(os.path.join(pp, \"_hierarchy.so\")):\n sys.path.append(pp)\n break\n import _hierarchy\nelse:\n from scipy.cluster import _hierarchy\n\ndef fcluster(Z, t, criterion='inconsistent', depth=2, R=None, monocrit=None):\n # supersimplified function to get fast clustering. Got it from scipy\n Z = np.asarray(Z, order='c')\n n = Z.shape[0] + 1\n T = np.zeros((n,), dtype='i')\n _hierarchy.cluster_dist(Z, T, float(t), int(n))\n return T\n\nRDR_TO_LDR = 2.7\n\ndef mean(l):\n return sum(l)/len(l)\n\nclass Cluster(object):\n def __init__(self):\n self.tracks = set()\n\n def add(self, t):\n # add the first track\n self.tracks.add(t)\n\n # TODO: make generic\n @property\n def dRel(self):\n return mean([t.dRel for t in self.tracks])\n\n @property\n def yRel(self):\n return mean([t.yRel for t in self.tracks])\n\n @property\n def vRel(self):\n return mean([t.vRel for t in self.tracks])\n\n @property\n def aRel(self):\n return mean([t.aRel for t in self.tracks])\n\n @property\n def vLead(self):\n return mean([t.vLead for t in self.tracks])\n\n @property\n def aLead(self):\n return mean([t.aLead for t in self.tracks])\n\n @property\n def dPath(self):\n return mean([t.dPath for t in self.tracks])\n\n @property\n def vLat(self):\n return mean([t.vLat for t in self.tracks])\n\n @property\n def vLeadK(self):\n return mean([t.vLeadK for t in self.tracks])\n\n @property\n def aLeadK(self):\n return mean([t.aLeadK for t in self.tracks])\n\n @property\n def vision(self):\n return any([t.vision for t in self.tracks])\n\n @property\n def vision_cnt(self):\n return max([t.vision_cnt for t in self.tracks])\n\n @property\n def stationary(self):\n return all([t.stationary for t in self.tracks])\n\n @property\n def oncoming(self):\n return all([t.oncoming for t in self.tracks])\n\n def toLive20(self, lead):\n lead.dRel = float(self.dRel) - RDR_TO_LDR\n lead.yRel = float(self.yRel)\n lead.vRel = float(self.vRel)\n lead.aRel = float(self.aRel)\n lead.vLead = float(self.vLead)\n lead.aLead = float(self.aLead)\n lead.dPath = float(self.dPath)\n lead.vLat = float(self.vLat)\n lead.vLeadK = float(self.vLeadK)\n lead.aLeadK = float(self.aLeadK)\n lead.status = True\n lead.fcw = False\n\n def __str__(self):\n ret = \"x: %7.2f y: %7.2f v: %7.2f a: %7.2f\" % (self.dRel, self.yRel, self.vRel, self.aRel)\n if self.stationary:\n ret += \" stationary\"\n if self.vision:\n ret += \" vision\"\n if self.oncoming:\n ret += \" oncoming\"\n if self.vision_cnt > 0:\n ret += \" vision_cnt: %6.0f\" % self.vision_cnt\n return ret\n\n def is_potential_lead(self, v_ego, enabled):\n # predict cut-ins by extrapolating lateral speed by a lookahead time\n # lookahead time depends on cut-in distance. more attentive for close cut-ins\n # also, above 50 meters the predicted path isn't very reliable\n\n # the distance at which v_lat matters is higher at higher speed\n lookahead_dist = 40. + v_ego/1.2 #40m at 0mph, ~70m at 80mph\n\n t_lookahead_v = [1., 0.]\n t_lookahead_bp = [10., lookahead_dist]\n\n # average dist\n d_path = self.dPath\n\n if enabled:\n t_lookahead = np.interp(self.dRel, t_lookahead_bp, t_lookahead_v)\n # correct d_path for lookahead time, considering only cut-ins and no more than 1m impact\n lat_corr = np.clip(t_lookahead * self.vLat, -1, 0)\n else:\n lat_corr = 0.\n d_path = np.maximum(d_path + lat_corr, 0)\n\n if d_path < 1.5 and not self.stationary and not self.oncoming:\n return True\n else:\n return False\n\n def is_potential_lead2(self, lead_clusters):\n if len(lead_clusters) > 0:\n lead_cluster = lead_clusters[0]\n # check if the new lead is too close and roughly at the same speed of the first lead: it might just be the second axle of the same vehicle\n if (self.dRel - lead_cluster.dRel) < 8. and abs(self.vRel - lead_cluster.vRel) < 1.:\n return False\n else:\n return True\n else:\n return False\n" ]
[ [ "numpy.interp", "numpy.zeros", "numpy.asarray", "numpy.clip", "numpy.maximum" ] ]
chw3k5/WaferScreen
[ "c0ca7fe939fe7cd0b722b7d6129b148c03a7505c" ]
[ "waferscreen/plot/band_and_keepout.py" ]
[ "# Copyright (C) 2021 Members of the Simons Observatory collaboration.\n# Please refer to the LICENSE file in the root of this repository.\n\nimport matplotlib.pyplot as plt\nimport matplotlib.transforms as mtransforms\nfrom ref import band_params, smurf_keepout_zones_ghz\n\n\ncolors = ['BlueViolet', 'Brown', 'CadetBlue', 'Coral', 'Crimson',\n 'DarkGoldenRod', 'DarkGreen', 'DarkMagenta', 'DarkOrange',\n 'DarkOrchid', 'DarkRed', 'DarkSalmon', 'DodgerBlue', 'FireBrick']\nhatches = ['/', '*', '\\\\', 'x', 'o']\n\n\ndef band_and_keepout_plot(ax, do_labels=False, y_ticks_off=False):\n trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes)\n if y_ticks_off:\n ax.tick_params(axis='y', # changes apply to the x-axis\n which='both', # both major and minor ticks are affected\n left=False, # ticks along the bottom edge are off\n right=False, # ticks along the top edge are off\n labelleft=False)\n\n # SO band definitions\n for band_int in range(14):\n band_name = F\"Band{'%02i' % band_int}\"\n band_dict = band_params[band_name]\n band_min_ghz = band_dict[\"min_GHz\"]\n band_max_ghz = band_dict[\"max_GHz\"]\n color = colors[band_int]\n ax.fill_between((band_dict['min_GHz'], band_dict['max_GHz']), 0, 1,\n facecolor=color, alpha=0.5, transform=trans)\n band_size_mhz = 1000.0 * (band_max_ghz - band_min_ghz)\n if do_labels:\n plt.text(x=band_dict['min_GHz'], y=0.9 - (band_int * 0.8 / 14.0),\n s=F\"{band_name}\\n size={'%5.1f' % band_size_mhz}MHz\",\n color=\"white\", fontsize=6,\n bbox={\"facecolor\": color, \"alpha\": 0.5}, transform=trans)\n\n # smurf keep out zones\n for keepout_index, keepout_zone in list(enumerate(smurf_keepout_zones_ghz)):\n keepout_min, keepout_max = keepout_zone\n hatch = hatches[keepout_index]\n ax.fill_between((keepout_min, keepout_max), 0, 1,\n facecolor='black', alpha=0.5, transform=trans,\n hatch=hatch)\n if do_labels:\n plt.text(x=keepout_min, y=0.1, s=\"SMURF Keepout Zone\", color=\"white\", fontsize=6,\n bbox={\"facecolor\": 'black', \"alpha\": 0.5}, transform=trans)\n return ax\n\n\nif __name__ == \"__main__\":\n # plot initialization\n fig, ax_band_keepout = plt.subplots(figsize=(12, 8))\n # call the plot function\n ax_band_keepout = band_and_keepout_plot(ax=ax_band_keepout, do_labels=True, y_ticks_off=False)\n # get the plotting axis back to make additions\n ax_band_keepout.set_xlabel(\"Frequency (GHz)\")\n # show the plot\n plt.show(block=True)\n" ]
[ [ "matplotlib.pyplot.show", "matplotlib.transforms.blended_transform_factory", "matplotlib.pyplot.text", "matplotlib.pyplot.subplots" ] ]
andreas-eberle/agents
[ "27b9498689ea5b8f69fc77ada752e05e38192852" ]
[ "tf_agents/networks/network.py" ]
[ "# coding=utf-8\n# Copyright 2018 The TF-Agents Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Base extension to Keras network to simplify copy operations.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\nimport sys\nimport six\nimport tensorflow as tf\n\nfrom tensorflow.keras import layers # pylint: disable=unused-import\nfrom tf_agents.specs import tensor_spec\nfrom tf_agents.trajectories import time_step\n\nfrom tensorflow.python.keras.engine import network as keras_network # TF internal\nfrom tensorflow.python.util import tf_decorator # TF internal\nfrom tensorflow.python.util import tf_inspect # TF internal\n\n\nclass _NetworkMeta(abc.ABCMeta):\n \"\"\"Meta class for Network object.\n\n We mainly use this class to capture all args to `__init__` of all `Network`\n instances, and store them in `instance._saved_kwargs`. This in turn is\n used by the `instance.copy` method.\n \"\"\"\n\n def __new__(mcs, classname, baseclasses, attrs):\n \"\"\"Control the creation of subclasses of the Network class.\n\n Args:\n classname: The name of the subclass being created.\n baseclasses: A tuple of parent classes.\n attrs: A dict mapping new attributes to their values.\n\n Returns:\n The class object.\n\n Raises:\n RuntimeError: if the class __init__ has *args in its signature.\n \"\"\"\n if baseclasses[0] == keras_network.Network:\n # This is just Network below. Return early.\n return abc.ABCMeta.__new__(mcs, classname, baseclasses, attrs)\n\n init = attrs.get(\"__init__\", None)\n\n if not init:\n # This wrapper class does not define an __init__. When someone creates\n # the object, the __init__ of its parent class will be called. We will\n # call that __init__ instead separately since the parent class is also a\n # subclass of Network. Here just create the class and return.\n return abc.ABCMeta.__new__(mcs, classname, baseclasses, attrs)\n\n arg_spec = tf_inspect.getargspec(init)\n if arg_spec.varargs is not None:\n raise RuntimeError(\n \"%s.__init__ function accepts *args. This is not allowed.\" %\n classname)\n\n def capture_init(self, *args, **kwargs):\n if len(args) > len(arg_spec.args) + 1:\n # Error case: more inputs than args. Call init so that the appropriate\n # error can be raised to the user.\n init(self, *args, **kwargs)\n for i, arg in enumerate(args):\n # Add +1 to skip `self` in arg_spec.args.\n kwargs[arg_spec.args[1 + i]] = arg\n init(self, **kwargs)\n setattr(self, \"_saved_kwargs\", kwargs)\n\n attrs[\"__init__\"] = tf_decorator.make_decorator(init, capture_init)\n return abc.ABCMeta.__new__(mcs, classname, baseclasses, attrs)\n\n\[email protected]_metaclass(_NetworkMeta)\nclass Network(keras_network.Network):\n \"\"\"Base extension to Keras network to simplify copy operations.\"\"\"\n\n def __init__(self, input_tensor_spec, state_spec, name):\n super(Network, self).__init__(name=name)\n self._input_tensor_spec = input_tensor_spec\n self._state_spec = state_spec\n\n @property\n def state_spec(self):\n return self._state_spec\n\n def _build(self):\n if not self.built and self.input_tensor_spec is not None:\n random_input = tensor_spec.sample_spec_nest(\n self.input_tensor_spec, outer_dims=(1,))\n step_type = tf.expand_dims(time_step.StepType.FIRST, 0)\n self.__call__(random_input, step_type, None)\n\n @property\n def input_tensor_spec(self):\n \"\"\"Returns the spec of the input to the network of type InputSpec.\"\"\"\n return self._input_tensor_spec\n\n @property\n def variables(self):\n \"\"\"Return the variables for all the network layers.\n\n If the network hasn't been built, builds it on random input (generated\n using self._input_tensor_spec) to build all the layers and their variables.\n\n Raises:\n ValueError: If the network fails to build.\n \"\"\"\n try:\n self._build()\n except ValueError as e:\n traceback = sys.exc_info()[2]\n six.reraise(\n ValueError, \"Failed to call build on the network when accessing \"\n \"variables. Message: {!r}.\".format(e), traceback)\n return self.weights\n\n def copy(self, **kwargs):\n \"\"\"Create a shallow copy of this network.\n\n **NOTE** Network layer weights are *never* copied. This method recreates\n the `Network` instance with the same arguments it was initialized with\n (excepting any new kwargs).\n\n Args:\n **kwargs: Args to override when recreating this network. Commonly\n overridden args include 'name'.\n\n Returns:\n A shallow copy of this network.\n \"\"\"\n return type(self)(**dict(self._saved_kwargs, **kwargs))\n\n def __call__(self, inputs, *args, **kwargs):\n tf.nest.assert_same_structure(inputs, self.input_tensor_spec)\n return super(Network, self).__call__(inputs, *args, **kwargs)\n\n\nclass DistributionNetwork(Network):\n \"\"\"Base class for networks which generate Distributions as their output.\"\"\"\n\n def __init__(self, input_tensor_spec, state_spec, output_spec, name):\n super(DistributionNetwork, self).__init__(\n input_tensor_spec=input_tensor_spec, state_spec=state_spec, name=name)\n self._output_spec = output_spec\n\n @property\n def output_spec(self):\n return self._output_spec\n" ]
[ [ "tensorflow.python.util.tf_inspect.getargspec", "tensorflow.python.util.tf_decorator.make_decorator", "tensorflow.nest.assert_same_structure", "tensorflow.expand_dims" ] ]
ryohachiuma/DFU-challenge
[ "08401bfde9bcb1abcb32ef060e89b8c135e7f3f1" ]
[ "mmdet/datasets/custom.py" ]
[ "import os.path as osp\n\nimport mmcv\nimport numpy as np\nfrom torch.utils.data import Dataset\n\nfrom mmdet.core import eval_map, eval_recalls\nfrom .builder import DATASETS\nfrom .pipelines import Compose\n\n\[email protected]_module()\nclass CustomDataset(Dataset):\n \"\"\"Custom dataset for detection.\n\n The annotation format is shown as follows. The `ann` field is optional for\n testing.\n\n .. code-block:: none\n\n [\n {\n 'filename': 'a.jpg',\n 'width': 1280,\n 'height': 720,\n 'ann': {\n 'bboxes': <np.ndarray> (n, 4),\n 'labels': <np.ndarray> (n, ),\n 'bboxes_ignore': <np.ndarray> (k, 4), (optional field)\n 'labels_ignore': <np.ndarray> (k, 4) (optional field)\n }\n },\n ...\n ]\n \"\"\"\n\n CLASSES = None\n\n def __init__(self,\n ann_file,\n pipeline,\n classes=None,\n data_root=None,\n img_prefix='',\n seg_prefix=None,\n proposal_file=None,\n test_mode=False,\n filter_empty_gt=True):\n self.ann_file = ann_file\n self.data_root = data_root\n self.img_prefix = img_prefix\n self.seg_prefix = seg_prefix\n self.proposal_file = proposal_file\n self.test_mode = test_mode\n self.filter_empty_gt = filter_empty_gt\n self.CLASSES = self.get_classes(classes)\n\n # join paths if data_root is specified\n if self.data_root is not None:\n if not osp.isabs(self.ann_file):\n self.ann_file = osp.join(self.data_root, self.ann_file)\n if not (self.img_prefix is None or osp.isabs(self.img_prefix)):\n self.img_prefix = osp.join(self.data_root, self.img_prefix)\n if not (self.seg_prefix is None or osp.isabs(self.seg_prefix)):\n self.seg_prefix = osp.join(self.data_root, self.seg_prefix)\n if not (self.proposal_file is None\n or osp.isabs(self.proposal_file)):\n self.proposal_file = osp.join(self.data_root,\n self.proposal_file)\n # load annotations (and proposals)\n self.data_infos = self.load_annotations(self.ann_file)\n # filter data infos if classes are customized\n if self.custom_classes:\n self.data_infos = self.get_subset_by_classes()\n\n if self.proposal_file is not None:\n self.proposals = self.load_proposals(self.proposal_file)\n else:\n self.proposals = None\n\n # set group flag for the sampler\n if not self.test_mode:\n self._set_group_flag()\n # processing pipeline\n self.pipeline = Compose(pipeline)\n\n def __len__(self):\n return len(self.data_infos)\n\n def load_annotations(self, ann_file):\n return mmcv.load(ann_file)\n\n def load_proposals(self, proposal_file):\n return mmcv.load(proposal_file)\n\n def get_ann_info(self, idx):\n return self.data_infos[idx]['ann']\n\n def get_cat_ids(self, idx):\n return self.data_infos[idx]['ann']['labels'].astype(np.int).tolist()\n\n def pre_pipeline(self, results):\n results['img_prefix'] = self.img_prefix\n results['seg_prefix'] = self.seg_prefix\n results['proposal_file'] = self.proposal_file\n results['bbox_fields'] = []\n results['mask_fields'] = []\n results['seg_fields'] = []\n\n def _filter_imgs(self, min_size=32):\n \"\"\"Filter images too small.\"\"\"\n valid_inds = []\n for i, img_info in enumerate(self.data_infos):\n if min(img_info['width'], img_info['height']) >= min_size:\n valid_inds.append(i)\n return valid_inds\n\n def _set_group_flag(self):\n \"\"\"Set flag according to image aspect ratio.\n\n Images with aspect ratio greater than 1 will be set as group 1,\n otherwise group 0.\n \"\"\"\n self.flag = np.zeros(len(self), dtype=np.uint8)\n for i in range(len(self)):\n img_info = self.data_infos[i]\n if img_info['width'] / img_info['height'] > 1:\n self.flag[i] = 1\n\n def _rand_another(self, idx):\n pool = np.where(self.flag == self.flag[idx])[0]\n return np.random.choice(pool)\n\n def __getitem__(self, idx):\n #if self.test_mode:\n if 0:\n return self.prepare_test_img(idx)\n while True:\n data = self.prepare_train_img(idx)\n if data is None:\n idx = self._rand_another(idx)\n continue\n return data\n\n def prepare_train_img(self, idx):\n img_info = self.data_infos[idx]\n ann_info = self.get_ann_info(idx)\n results = dict(img_info=img_info, ann_info=ann_info)\n if self.proposals is not None:\n results['proposals'] = self.proposals[idx]\n self.pre_pipeline(results)\n return self.pipeline(results)\n\n def prepare_test_img(self, idx):\n img_info = self.data_infos[idx]\n results = dict(img_info=img_info)\n if self.proposals is not None:\n results['proposals'] = self.proposals[idx]\n self.pre_pipeline(results)\n return self.pipeline(results)\n\n @classmethod\n def get_classes(cls, classes=None):\n \"\"\"Get class names of current dataset\n\n Args:\n classes (Sequence[str] | str | None): If classes is None, use\n default CLASSES defined by builtin dataset. If classes is a\n string, take it as a file name. The file contains the name of\n classes where each line contains one class name. If classes is\n a tuple or list, override the CLASSES defined by the dataset.\n\n \"\"\"\n if classes is None:\n cls.custom_classes = False\n return cls.CLASSES\n\n cls.custom_classes = True\n if isinstance(classes, str):\n # take it as a file path\n class_names = mmcv.list_from_file(classes)\n elif isinstance(classes, (tuple, list)):\n class_names = classes\n else:\n raise ValueError(f'Unsupported type {type(classes)} of classes.')\n\n return class_names\n\n def get_subset_by_classes(self):\n return self.data_infos\n\n def format_results(self, results, **kwargs):\n pass\n\n def evaluate(self,\n results,\n metric='mAP',\n logger=None,\n proposal_nums=(100, 300, 1000),\n iou_thr=0.5,\n scale_ranges=None):\n \"\"\"Evaluate the dataset.\n\n Args:\n results (list): Testing results of the dataset.\n metric (str | list[str]): Metrics to be evaluated.\n logger (logging.Logger | None | str): Logger used for printing\n related information during evaluation. Defaault: None.\n proposal_nums (Sequence[int]): Proposal number used for evaluating\n recalls, such as recall@100, recall@1000.\n Default: (100, 300, 1000).\n iou_thr (float | list[float]): IoU threshold. It must be a float\n when evaluating mAP, and can be a list when evaluating recall.\n Default: 0.5.\n scale_ranges (list[tuple] | None): Scale ranges for evaluating mAP.\n Default: None.\n \"\"\"\n if not isinstance(metric, str):\n assert len(metric) == 1\n metric = metric[0]\n allowed_metrics = ['mAP', 'recall']\n if metric not in allowed_metrics:\n raise KeyError(f'metric {metric} is not supported')\n annotations = [self.get_ann_info(i) for i in range(len(self))]\n\n eval_results = {}\n if metric == 'mAP':\n assert isinstance(iou_thr, float)\n mean_ap, _ = eval_map(\n results,\n annotations,\n scale_ranges=scale_ranges,\n iou_thr=iou_thr,\n dataset=self.CLASSES,\n logger=logger)\n eval_results['mAP'] = mean_ap\n elif metric == 'recall':\n gt_bboxes = [ann['bboxes'] for ann in annotations]\n if isinstance(iou_thr, float):\n iou_thr = [iou_thr]\n recalls = eval_recalls(\n gt_bboxes, results, proposal_nums, iou_thr, logger=logger)\n for i, num in enumerate(proposal_nums):\n for j, iou in enumerate(iou_thr):\n eval_results[f'recall@{num}@{iou}'] = recalls[i, j]\n if recalls.shape[1] > 1:\n ar = recalls.mean(axis=1)\n for i, num in enumerate(proposal_nums):\n eval_results[f'AR@{num}'] = ar[i]\n\n return eval_results\n" ]
[ [ "numpy.where", "numpy.random.choice" ] ]
vanillagorillaa/rednose
[ "7e41d39b71f7888875a2fbf9cea770eabe0a8128" ]
[ "examples/live_kf.py" ]
[ "#!/usr/bin/env python3\nimport sys\nimport numpy as np\nimport sympy as sp\n\nfrom rednose.helpers import KalmanError\nfrom rednose.helpers.ekf_sym import EKF_sym, gen_code\nfrom rednose.helpers.sympy_helpers import (euler_rotate, quat_matrix_r, quat_rotate)\n\nEARTH_GM = 3.986005e14 # m^3/s^2 (gravitational constant * mass of earth)\n\n\nclass ObservationKind():\n UNKNOWN = 0\n NO_OBSERVATION = 1\n GPS_NED = 2\n ODOMETRIC_SPEED = 3\n PHONE_GYRO = 4\n GPS_VEL = 5\n PSEUDORANGE_GPS = 6\n PSEUDORANGE_RATE_GPS = 7\n SPEED = 8\n NO_ROT = 9\n PHONE_ACCEL = 10\n ORB_POINT = 11\n ECEF_POS = 12\n CAMERA_ODO_TRANSLATION = 13\n CAMERA_ODO_ROTATION = 14\n ORB_FEATURES = 15\n MSCKF_TEST = 16\n FEATURE_TRACK_TEST = 17\n LANE_PT = 18\n IMU_FRAME = 19\n PSEUDORANGE_GLONASS = 20\n PSEUDORANGE_RATE_GLONASS = 21\n PSEUDORANGE = 22\n PSEUDORANGE_RATE = 23\n\n names = [\n 'Unknown',\n 'No observation',\n 'GPS NED',\n 'Odometric speed',\n 'Phone gyro',\n 'GPS velocity',\n 'GPS pseudorange',\n 'GPS pseudorange rate',\n 'Speed',\n 'No rotation',\n 'Phone acceleration',\n 'ORB point',\n 'ECEF pos',\n 'camera odometric translation',\n 'camera odometric rotation',\n 'ORB features',\n 'MSCKF test',\n 'Feature track test',\n 'Lane ecef point',\n 'imu frame eulers',\n 'GLONASS pseudorange',\n 'GLONASS pseudorange rate',\n ]\n\n @classmethod\n def to_string(cls, kind):\n return cls.names[kind]\n\n\nclass States():\n ECEF_POS = slice(0, 3) # x, y and z in ECEF in meters\n ECEF_ORIENTATION = slice(3, 7) # quat for pose of phone in ecef\n ECEF_VELOCITY = slice(7, 10) # ecef velocity in m/s\n ANGULAR_VELOCITY = slice(10, 13) # roll, pitch and yaw rates in device frame in radians/s\n GYRO_BIAS = slice(13, 16) # roll, pitch and yaw biases\n ODO_SCALE = slice(16, 17) # odometer scale\n ACCELERATION = slice(17, 20) # Acceleration in device frame in m/s**2\n IMU_OFFSET = slice(20, 23) # imu offset angles in radians\n\n # Error-state has different slices because it is an ESKF\n ECEF_POS_ERR = slice(0, 3)\n ECEF_ORIENTATION_ERR = slice(3, 6) # euler angles for orientation error\n ECEF_VELOCITY_ERR = slice(6, 9)\n ANGULAR_VELOCITY_ERR = slice(9, 12)\n GYRO_BIAS_ERR = slice(12, 15)\n ODO_SCALE_ERR = slice(15, 16)\n ACCELERATION_ERR = slice(16, 19)\n IMU_OFFSET_ERR = slice(19, 22)\n\n\nclass LiveKalman():\n name = 'live'\n\n initial_x = np.array([-2.7e6, 4.2e6, 3.8e6,\n 1, 0, 0, 0,\n 0, 0, 0,\n 0, 0, 0,\n 0, 0, 0,\n 1,\n 0, 0, 0,\n 0, 0, 0])\n\n # state covariance\n initial_P_diag = np.array([10000**2, 10000**2, 10000**2,\n 10**2, 10**2, 10**2,\n 10**2, 10**2, 10**2,\n 1**2, 1**2, 1**2,\n 0.05**2, 0.05**2, 0.05**2,\n 0.02**2,\n 1**2, 1**2, 1**2,\n (0.01)**2, (0.01)**2, (0.01)**2])\n\n # process noise\n Q = np.diag([0.03**2, 0.03**2, 0.03**2,\n 0.0**2, 0.0**2, 0.0**2,\n 0.0**2, 0.0**2, 0.0**2,\n 0.1**2, 0.1**2, 0.1**2,\n (0.005 / 100)**2, (0.005 / 100)**2, (0.005 / 100)**2,\n (0.02 / 100)**2,\n 3**2, 3**2, 3**2,\n (0.05 / 60)**2, (0.05 / 60)**2, (0.05 / 60)**2])\n\n @staticmethod\n def generate_code(generated_dir):\n name = LiveKalman.name\n dim_state = LiveKalman.initial_x.shape[0]\n dim_state_err = LiveKalman.initial_P_diag.shape[0]\n\n state_sym = sp.MatrixSymbol('state', dim_state, 1)\n state = sp.Matrix(state_sym)\n x, y, z = state[States.ECEF_POS, :]\n q = state[States.ECEF_ORIENTATION, :]\n v = state[States.ECEF_VELOCITY, :]\n vx, vy, vz = v\n omega = state[States.ANGULAR_VELOCITY, :]\n vroll, vpitch, vyaw = omega\n roll_bias, pitch_bias, yaw_bias = state[States.GYRO_BIAS, :]\n odo_scale = state[States.ODO_SCALE, :][0,:]\n acceleration = state[States.ACCELERATION, :]\n imu_angles = state[States.IMU_OFFSET, :]\n\n dt = sp.Symbol('dt')\n\n # calibration and attitude rotation matrices\n quat_rot = quat_rotate(*q)\n\n # Got the quat predict equations from here\n # A New Quaternion-Based Kalman Filter for\n # Real-Time Attitude Estimation Using the Two-Step\n # Geometrically-Intuitive Correction Algorithm\n A = 0.5 * sp.Matrix([[0, -vroll, -vpitch, -vyaw],\n [vroll, 0, vyaw, -vpitch],\n [vpitch, -vyaw, 0, vroll],\n [vyaw, vpitch, -vroll, 0]])\n q_dot = A * q\n\n # Time derivative of the state as a function of state\n state_dot = sp.Matrix(np.zeros((dim_state, 1)))\n state_dot[States.ECEF_POS, :] = v\n state_dot[States.ECEF_ORIENTATION, :] = q_dot\n state_dot[States.ECEF_VELOCITY, 0] = quat_rot * acceleration\n\n # Basic descretization, 1st order intergrator\n # Can be pretty bad if dt is big\n f_sym = state + dt * state_dot\n\n state_err_sym = sp.MatrixSymbol('state_err', dim_state_err, 1)\n state_err = sp.Matrix(state_err_sym)\n quat_err = state_err[States.ECEF_ORIENTATION_ERR, :]\n v_err = state_err[States.ECEF_VELOCITY_ERR, :]\n omega_err = state_err[States.ANGULAR_VELOCITY_ERR, :]\n acceleration_err = state_err[States.ACCELERATION_ERR, :]\n\n # Time derivative of the state error as a function of state error and state\n quat_err_matrix = euler_rotate(quat_err[0], quat_err[1], quat_err[2])\n q_err_dot = quat_err_matrix * quat_rot * (omega + omega_err)\n state_err_dot = sp.Matrix(np.zeros((dim_state_err, 1)))\n state_err_dot[States.ECEF_POS_ERR, :] = v_err\n state_err_dot[States.ECEF_ORIENTATION_ERR, :] = q_err_dot\n state_err_dot[States.ECEF_VELOCITY_ERR, :] = quat_err_matrix * quat_rot * (acceleration + acceleration_err)\n f_err_sym = state_err + dt * state_err_dot\n\n # Observation matrix modifier\n H_mod_sym = sp.Matrix(np.zeros((dim_state, dim_state_err)))\n H_mod_sym[States.ECEF_POS, States.ECEF_POS_ERR] = np.eye(States.ECEF_POS.stop - States.ECEF_POS.start)\n H_mod_sym[States.ECEF_ORIENTATION, States.ECEF_ORIENTATION_ERR] = 0.5 * quat_matrix_r(state[3:7])[:, 1:]\n H_mod_sym[States.ECEF_ORIENTATION.stop:, States.ECEF_ORIENTATION_ERR.stop:] = np.eye(dim_state - States.ECEF_ORIENTATION.stop)\n\n # these error functions are defined so that say there\n # is a nominal x and true x:\n # true x = err_function(nominal x, delta x)\n # delta x = inv_err_function(nominal x, true x)\n nom_x = sp.MatrixSymbol('nom_x', dim_state, 1)\n true_x = sp.MatrixSymbol('true_x', dim_state, 1)\n delta_x = sp.MatrixSymbol('delta_x', dim_state_err, 1)\n\n err_function_sym = sp.Matrix(np.zeros((dim_state, 1)))\n delta_quat = sp.Matrix(np.ones((4)))\n delta_quat[1:, :] = sp.Matrix(0.5 * delta_x[States.ECEF_ORIENTATION_ERR, :])\n err_function_sym[States.ECEF_POS, :] = sp.Matrix(nom_x[States.ECEF_POS, :] + delta_x[States.ECEF_POS_ERR, :])\n err_function_sym[States.ECEF_ORIENTATION, 0] = quat_matrix_r(nom_x[States.ECEF_ORIENTATION, 0]) * delta_quat\n err_function_sym[States.ECEF_ORIENTATION.stop:, :] = sp.Matrix(nom_x[States.ECEF_ORIENTATION.stop:, :] + delta_x[States.ECEF_ORIENTATION_ERR.stop:, :])\n\n inv_err_function_sym = sp.Matrix(np.zeros((dim_state_err, 1)))\n inv_err_function_sym[States.ECEF_POS_ERR, 0] = sp.Matrix(-nom_x[States.ECEF_POS, 0] + true_x[States.ECEF_POS, 0])\n delta_quat = quat_matrix_r(nom_x[States.ECEF_ORIENTATION, 0]).T * true_x[States.ECEF_ORIENTATION, 0]\n inv_err_function_sym[States.ECEF_ORIENTATION_ERR, 0] = sp.Matrix(2 * delta_quat[1:])\n inv_err_function_sym[States.ECEF_ORIENTATION_ERR.stop:, 0] = sp.Matrix(-nom_x[States.ECEF_ORIENTATION.stop:, 0] + true_x[States.ECEF_ORIENTATION.stop:, 0])\n\n eskf_params = [[err_function_sym, nom_x, delta_x],\n [inv_err_function_sym, nom_x, true_x],\n H_mod_sym, f_err_sym, state_err_sym]\n #\n # Observation functions\n #\n imu_rot = euler_rotate(*imu_angles)\n h_gyro_sym = imu_rot * sp.Matrix([vroll + roll_bias,\n vpitch + pitch_bias,\n vyaw + yaw_bias])\n\n pos = sp.Matrix([x, y, z])\n gravity = quat_rot.T * ((EARTH_GM / ((x**2 + y**2 + z**2)**(3.0 / 2.0))) * pos)\n h_acc_sym = imu_rot * (gravity + acceleration)\n h_phone_rot_sym = sp.Matrix([vroll, vpitch, vyaw])\n\n speed = sp.sqrt(vx**2 + vy**2 + vz**2)\n h_speed_sym = sp.Matrix([speed * odo_scale])\n\n h_pos_sym = sp.Matrix([x, y, z])\n h_imu_frame_sym = sp.Matrix(imu_angles)\n\n h_relative_motion = sp.Matrix(quat_rot.T * v)\n\n obs_eqs = [[h_speed_sym, ObservationKind.ODOMETRIC_SPEED, None],\n [h_gyro_sym, ObservationKind.PHONE_GYRO, None],\n [h_phone_rot_sym, ObservationKind.NO_ROT, None],\n [h_acc_sym, ObservationKind.PHONE_ACCEL, None],\n [h_pos_sym, ObservationKind.ECEF_POS, None],\n [h_relative_motion, ObservationKind.CAMERA_ODO_TRANSLATION, None],\n [h_phone_rot_sym, ObservationKind.CAMERA_ODO_ROTATION, None],\n [h_imu_frame_sym, ObservationKind.IMU_FRAME, None]]\n\n gen_code(generated_dir, name, f_sym, dt, state_sym, obs_eqs, dim_state, dim_state_err, eskf_params)\n\n def __init__(self, generated_dir):\n self.dim_state = self.initial_x.shape[0]\n self.dim_state_err = self.initial_P_diag.shape[0]\n\n self.obs_noise = {ObservationKind.ODOMETRIC_SPEED: np.atleast_2d(0.2**2),\n ObservationKind.PHONE_GYRO: np.diag([0.025**2, 0.025**2, 0.025**2]),\n ObservationKind.PHONE_ACCEL: np.diag([.5**2, .5**2, .5**2]),\n ObservationKind.CAMERA_ODO_ROTATION: np.diag([0.05**2, 0.05**2, 0.05**2]),\n ObservationKind.IMU_FRAME: np.diag([0.05**2, 0.05**2, 0.05**2]),\n ObservationKind.NO_ROT: np.diag([0.00025**2, 0.00025**2, 0.00025**2]),\n ObservationKind.ECEF_POS: np.diag([5**2, 5**2, 5**2])}\n\n # init filter\n self.filter = EKF_sym(generated_dir, self.name, self.Q, self.initial_x, np.diag(self.initial_P_diag), self.dim_state, self.dim_state_err)\n\n @property\n def x(self):\n return self.filter.state()\n\n @property\n def t(self):\n return self.filter.filter_time\n\n @property\n def P(self):\n return self.filter.covs()\n\n def rts_smooth(self, estimates):\n return self.filter.rts_smooth(estimates, norm_quats=True)\n\n def init_state(self, state, covs_diag=None, covs=None, filter_time=None):\n if covs_diag is not None:\n P = np.diag(covs_diag)\n elif covs is not None:\n P = covs\n else:\n P = self.filter.covs()\n self.filter.init_state(state, P, filter_time)\n\n def predict_and_observe(self, t, kind, data):\n if len(data) > 0:\n data = np.atleast_2d(data)\n if kind == ObservationKind.CAMERA_ODO_TRANSLATION:\n r = self.predict_and_update_odo_trans(data, t, kind)\n elif kind == ObservationKind.CAMERA_ODO_ROTATION:\n r = self.predict_and_update_odo_rot(data, t, kind)\n elif kind == ObservationKind.ODOMETRIC_SPEED:\n r = self.predict_and_update_odo_speed(data, t, kind)\n else:\n r = self.filter.predict_and_update_batch(t, kind, data, self.get_R(kind, len(data)))\n\n # Normalize quats\n quat_norm = np.linalg.norm(self.filter.x[3:7, 0])\n\n # Should not continue if the quats behave this weirdly\n if not (0.1 < quat_norm < 10):\n raise KalmanError(\"Kalman filter quaternions unstable\")\n\n self.filter.x[States.ECEF_ORIENTATION, 0] = self.filter.x[States.ECEF_ORIENTATION, 0] / quat_norm\n\n return r\n\n def get_R(self, kind, n):\n obs_noise = self.obs_noise[kind]\n dim = obs_noise.shape[0]\n R = np.zeros((n, dim, dim))\n for i in range(n):\n R[i, :, :] = obs_noise\n return R\n\n def predict_and_update_odo_speed(self, speed, t, kind):\n z = np.array(speed)\n R = np.zeros((len(speed), 1, 1))\n for i, _ in enumerate(z):\n R[i, :, :] = np.diag([0.2**2])\n return self.filter.predict_and_update_batch(t, kind, z, R)\n\n def predict_and_update_odo_trans(self, trans, t, kind):\n z = trans[:, :3]\n R = np.zeros((len(trans), 3, 3))\n for i, _ in enumerate(z):\n R[i, :, :] = np.diag(trans[i, 3:]**2)\n return self.filter.predict_and_update_batch(t, kind, z, R)\n\n def predict_and_update_odo_rot(self, rot, t, kind):\n z = rot[:, :3]\n R = np.zeros((len(rot), 3, 3))\n for i, _ in enumerate(z):\n R[i, :, :] = np.diag(rot[i, 3:]**2)\n return self.filter.predict_and_update_batch(t, kind, z, R)\n\n\nif __name__ == \"__main__\":\n generated_dir = sys.argv[2]\n LiveKalman.generate_code(generated_dir)\n" ]
[ [ "numpy.eye", "numpy.ones", "numpy.atleast_2d", "numpy.zeros", "numpy.diag", "numpy.array", "numpy.linalg.norm" ] ]
ATMOcanes/tropycal
[ "10cad2e4ff5b9cb1949d315cb328878306a65a74" ]
[ "src/tropycal/recon/dataset.py" ]
[ "import os\nimport numpy as np\nfrom datetime import datetime as dt,timedelta\nimport pandas as pd\nimport requests\nimport pickle\n\nfrom scipy.interpolate import interp1d\nfrom scipy.ndimage import gaussian_filter as gfilt,gaussian_filter1d as gfilt1d\nfrom scipy.ndimage.filters import minimum_filter\nimport matplotlib.dates as mdates\n\ntry:\n import matplotlib as mlib\n import matplotlib.lines as mlines\n import matplotlib.colors as mcolors\n import matplotlib.patheffects as path_effects\n import matplotlib.pyplot as plt\n import matplotlib.ticker as mticker\nexcept:\n warnings.warn(\"Warning: Matplotlib is not installed in your python environment. Plotting functions will not work.\")\n\nfrom .plot import ReconPlot\n\n#Import tools\nfrom .tools import *\nfrom ..utils import *\n\nclass ReconDataset:\n\n r\"\"\"\n Creates an instance of a ReconDataset object containing all recon data for a single storm.\n \n Parameters\n ----------\n stormtuple : tuple or list\n Requested storm. Can be either tuple or list containing storm name and year (e.g., (\"Matthew\",2016)).\n save_path : str, optional\n Filepath to save recon data in. Recommended in order to avoid having to re-read in the data.\n read_path : str, optional\n Filepath to read saved recon data from. If specified, \"save_path\" cannot be passed as an argument.\n \n Returns\n -------\n Dataset\n An instance of ReconDataset, initialized with the following:\n \n * **missiondata** - A dictionary of missions.\n Each entry is a dateframe from a single mission.\n Dictionary keys are given by mission number and agency (e.g. '15_NOAA').\n * **recentered** - A dataframe with all missions concatenated together, and columns 'xdist' and 'ydist'\n indicating the distance (km) of the ob from the interpolated center of the storm.\n \n Notes\n -----\n Recon data is currently read in via Tropical Atlantic. Future releases of Tropycal will incorporate NHC recon archives.\n \"\"\"\n\n def __init__(self, storm, deltap_thresh=8, mission_url_list=None, save_path=\"\", read_path=\"\", update=False):\n \n #Error check\n #if save_path != \"\" and read_path != \"\":\n # raise ValueError(\"Error: Cannot read in and save a file at the same time.\")\n \n #Create URL prefix for reading in recon data\n self.url_prefix = 'http://tropicalatlantic.com/recon/recon.cgi?'\n self.storm_obj = storm\n self.storm = str(storm.name)\n self.year = str(storm.year)\n self.deltap_thresh = deltap_thresh\n self.UPDATE = update\n self.mission_url_list = mission_url_list\n \n #If reading in a pickled file, load it in\n if read_path != \"\":\n self.missiondata = pickle.load(open(read_path,'rb'))\n if self.UPDATE:\n self.missiondata = self.allMissions()\n\n #Otherwise, retrieve all mission data for this storm\n else:\n self.missiondata = self.allMissions()\n\n #Save mission data as a pickle if necessary\n if save_path != \"\": pickle.dump(self.missiondata,open(save_path,'wb'),-1)\n\n #Convert recon data to storm-centered coordinates\n self.recentered = self.recenter()\n\n #print(f'Most recent data: {max(self.recentered['time']):%Y %b %d %H:%M} UTC')\n #print(f'Most recent center pass: {max(self.recentered.loc[self.recentered['iscenter']>0]['time']):%Y %b %d %H:%M} UTC')\n\n def getMission(self,agency,mission_num,url_mission=None):\n if url_mission is None:\n url_mission = f'{self.url_prefix}basin=al&year={self.year}&product=hdob&storm={self.storm}&mission={mission_num}&agency={agency}'\n content = np.array(requests.get(url_mission).content.decode(\"utf-8\").split('\\n'))\n obs = [line.split('\\\"')[1] for line in content if 'option value=' in line][::-1]\n for i,ob in enumerate(obs):\n url_ob = url_mission+'&ob='+ob\n data = pd.read_html(url_ob)[0]\n data = data.rename(columns = {[name for name in data if 'Time' in name][0]:'Time'})\n if i==0:\n mission = data[:-1]\n day0 = dt.strptime(self.year+ob[:5],'%Y%m-%d')\n else:\n mission = mission.append(data[:-1],ignore_index=True)\n \n def getVar(x,name):\n a = np.nan\n if x!='-' and '*' not in x and x!='No Wind':\n if name == 'Time':\n a = x\n if name == 'Coordinates':\n lat,lon = x.split(' ')\n lat = float(lat[:-1])*[1,-1][lat[-1]=='S']\n lon = float(lon[:-1])*[1,-1][lon[-1]=='W']\n a = np.array((lon,lat))\n elif name == 'Aircraft Static Air Pressure':\n a=float(x.split(' mb')[0])\n elif name == 'Aircraft Geo. Height':\n a=float(x.split(' meters')[0].replace(',', ''))\n elif name == 'Extrapolated Sfc. Pressure':\n a=float(x.split(' mb')[0])\n elif name == 'Flight Level Wind (30 sec. Avg.)':\n a=x.split(' ')\n wdir = float(a[1][:-1])\n wspd = float(a[3])\n a = np.array((wdir,wspd))\n elif name == 'Peak (10 sec. Avg.) Flight Level Wind':\n a=float(x.split(' knots')[0])\n elif name == 'SFMR Peak (10s Avg.) Sfc. Wind':\n a=x.split(' knots')\n a=float(a[0])\n if name in ['Coordinates','Flight Level Wind (30 sec. Avg.)'] and type(a)==float:\n a=np.array([a]*2)\n return a\n \n varnames = ['Time','Coordinates','Aircraft Static Air Pressure','Aircraft Geo. Height',\n 'Extrapolated Sfc. Pressure','Flight Level Wind (30 sec. Avg.)',\n 'Peak (10 sec. Avg.) Flight Level Wind','SFMR Peak (10s Avg.) Sfc. Wind']\n mission = {name:[getVar(item,name) for item in mission[name]] for name in varnames}\n for i,t in enumerate(mission['Time']):\n mission['Time'][i] = day0.replace(hour=int(t[:2]),minute=int(t[3:5]),second=int(t[6:8]))\n if i>0 and (mission['Time'][i]-mission['Time'][i-1]).total_seconds()<0:\n mission['Time'][i]+=timedelta(days=1)\n data={}\n data['lon'],data['lat'] = zip(*mission['Coordinates'])\n data['time'] = mission['Time']\n data['p_sfc'] = mission['Extrapolated Sfc. Pressure']\n data['wdir'],data['wspd'] = zip(*mission['Flight Level Wind (30 sec. Avg.)'])\n data['pkwnd'] = mission['Peak (10 sec. Avg.) Flight Level Wind']\n data['sfmr'] = mission['SFMR Peak (10s Avg.) Sfc. Wind']\n data['plane_p'] = mission['Aircraft Static Air Pressure']\n data['plane_z'] = mission['Aircraft Geo. Height']\n return_data = pd.DataFrame.from_dict(data)\n return_data['time'] = [pd.to_datetime(i) for i in return_data['time']]\n \n #remove nan's for lat/lon coordinates\n return_data = return_data.dropna(subset=['lat', 'lon'])\n \n return return_data\n \n\n def allMissions(self):\n url_storm = f'{self.url_prefix}basin=al&year={self.year}&storm={self.storm}&product=hdob'\n if self.mission_url_list is None:\n missions = pd.read_html(url_storm)[0]\n else:\n URL_LIST = self.mission_url_list\n missions = pd.DataFrame.from_dict({'Agency':['listedurl']*len(URL_LIST),'MissionNumber':[f'{n:02}' for n in range(len(URL_LIST))],'URL':URL_LIST})\n if self.UPDATE:\n missiondata = self.missiondata\n lastMissionNumber = max([int(x.split('_')[0]) for x in list(missiondata.keys())])\n idxf = [x for x in missions['MissionNumber']].index(lastMissionNumber)+1\n idxf = min([idxf+1,len(missions)]) # update last two missions\n else:\n idxf = len(missions)\n missiondata={}\n timer_start = dt.now()\n print(f'--> Starting to read in recon missions')\n for i_mission in range(0,idxf):\n if self.mission_url_list is None:\n mission_num = str(missions['MissionNumber'][i_mission]).zfill(2)\n agency = ''.join(filter(str.isalpha, missions['Agency'][i_mission]))\n missiondata[f'{mission_num}_{agency}'] = self.getMission(agency,mission_num)\n else:\n mission_num = missions['MissionNumber'][i_mission]\n agency = missions['Agency'][i_mission]\n url = missions['URL'][i_mission]\n missiondata[f'{mission_num}{agency}'] = self.getMission(agency,mission_num,url)\n print(f'{mission_num}_{agency}')\n print('--> Completed reading in recon missions (%.2f seconds)' % (dt.now()-timer_start).total_seconds())\n return missiondata\n\n def find_centers(self,data):\n \n def fill_nan(A):\n #Interpolate to fill nan values\n A = np.array(A)\n inds = np.arange(len(A))\n good = np.where(np.isfinite(A))\n good_grad = np.gradient(good[0])\n if len(good[0])>=3:\n f = interp1d(inds[good], A[good],bounds_error=False,kind='quadratic')\n B = np.where(np.isfinite(A)[good[0][0]:good[0][-1]+1],\n A[good[0][0]:good[0][-1]+1],\n f(inds[good[0][0]:good[0][-1]+1]))\n return [np.nan]*good[0][0]+list(B)+[np.nan]*(inds[-1]-good[0][-1])\n else:\n return [np.nan]*len(A)\n \n #Check that sfc pressure spread is big enough to identify real minima\n if np.nanpercentile(data['p_sfc'],90)-np.nanpercentile(data['p_sfc'],10)>self.deltap_thresh:\n data['p_sfc'][:20]=[np.nan]*20 #NaN out the first 10 minutes of the flight\n p_sfc_interp = fill_nan(data['p_sfc']) #Interp p_sfc across missing data\n wspd_interp = fill_nan(data['wspd']) #Interp wspd across missing data\n #Smooth p_sfc and wspd\n p_sfc_smooth = [np.nan]*1+list(np.convolve(p_sfc_interp,[1/3]*3,mode='valid'))+[np.nan]*1\n wspd_smooth = [np.nan]*1+list(np.convolve(wspd_interp,[1/3]*3,mode='valid'))+[np.nan]*1\n #Add wspd to p_sfc to encourage finding p mins with wspd mins \n #and prevent finding p mins in intense thunderstorms\n pw_test = np.array(p_sfc_smooth)+np.array(wspd_smooth)*.1\n #Find mins in 15-minute windows\n imin = np.nonzero(pw_test == minimum_filter(pw_test,30))[0]\n #Only use mins if below 15th %ile of mission p_sfc data and when plane p is 500-900mb\n imin = [i for i in imin if 800<p_sfc_interp[i]<np.nanpercentile(data['p_sfc'],15) and \\\n 550<data['plane_p'][i]<950]\n else:\n imin=[]\n data['iscenter'] = np.zeros(len(data['p_sfc']))\n for i in imin:\n j = data.index.values[i]\n data['iscenter'][j] = 1\n return data\n\n def recenter(self,use='all'): \n self.use = use \n def stitchMissions():\n list_of_dfs=[]\n for name in self.missiondata:\n if self.use == 'all' or self.use in name:\n mission = self.missiondata[name]\n tmp = self.find_centers(mission)\n list_of_dfs.append( tmp )\n data_concat = pd.concat(list_of_dfs,ignore_index=True)\n data_chron = data_concat.sort_values(by='time').reset_index(drop=True)\n return data_chron\n\n data = stitchMissions()\n centers = data.loc[data['iscenter']>0]\n \n if len(centers)<2:\n print('Sorry, less than 2 center passes')\n else:\n print(f'Found {len(centers)} center passes!')\n timer_start = dt.now()\n \n #Interpolate center position to time of each ob\n f1 = interp1d(mdates.date2num(centers['time']),centers['lon'],fill_value='extrapolate',kind='linear')\n interp_clon = f1(mdates.date2num(data['time']))\n f2 = interp1d(mdates.date2num(centers['time']),centers['lat'],fill_value='extrapolate',kind='linear')\n interp_clat = f2(mdates.date2num(data['time']))\n\n #Get x,y distance of each ob from coinciding interped center position\n data['xdist'] = [great_circle( (interp_clat[i],interp_clon[i]), \\\n (interp_clat[i],data['lon'][i]) ).kilometers* \\\n [1,-1][int(data['lon'][i] < interp_clon[i])] for i in range(len(data))]\n data['ydist'] = [great_circle( (interp_clat[i],interp_clon[i]), \\\n (data['lat'][i],interp_clon[i]) ).kilometers* \\\n [1,-1][int(data['lat'][i] < interp_clat[i])] for i in range(len(data))]\n \n print('--> Completed recentering recon data (%.2f seconds)' % (dt.now()-timer_start).total_seconds())\n return data\n \n def __getSubTime(self,time):\n \n if isinstance(time,(tuple,list)):\n t1=min(time)\n t2=max(time)\n else:\n t1 = time-timedelta(hours=6)\n t2 = time+timedelta(hours=6)\n subRecon = self.recentered.loc[(self.recentered['time']>=t1) & \\\n (self.recentered['time']<t2)]\n return subRecon\n \n \n def findMission(self,time):\n \n r\"\"\"\n Returns the name of a mission or list of missions given a specified time.\n \n Parameters\n ----------\n time : datetime.datetime or list\n Datetime object or list of datetime objects representing the time of the requested mission.\n \n Returns\n -------\n list\n The names of any/all missions that had in-storm observations during the specified time.\n \"\"\"\n \n if isinstance(time,list):\n t1=min(time)\n t2=max(time)\n else:\n t1 = t2 = time\n selected=[]\n for name in self.missiondata:\n t_start = min(self.missiondata[name]['time'])\n t_end = max(self.missiondata[name]['time'])\n if (t_start<t1<t_end) or (t_start<t2<t_end) or (t1<t_start<t2):\n selected.append(name)\n if len(selected)==0:\n print('There were no in-storm recon missions during this time')\n return selected\n\n\n def plot_points(self,recon_select=None,varname='wspd',domain=\"dynamic\",plane_p_range=None,\\\n ax=None,return_ax=False,cartopy_proj=None,**kwargs):\n \n r\"\"\"\n Creates a plot of recon data points.\n \n Parameters\n ----------\n recon_select : Requested recon data\n pandas.DataFrame or dict,\n or string referencing the mission name (e.g. '12_NOAA'), \n or datetime or list of start/end datetimes.\n varname : str\n Variable to plot. Can be one of the following keys in recon_select dataframe:\n \n * **\"sfmr\"** = SFMR surface wind\n * **\"wspd\"** = 30-second flight level wind (default)\n * **\"pkwnd\"** = 10-second flight level wind\n * **\"p_sfc\"** = extrapolated surface pressure\n domain : str\n Domain for the plot. Default is \"dynamic\". Please refer to :ref:`options-domain` for available domain options.\n ax : axes\n Instance of axes to plot on. If none, one will be generated. Default is none.\n return_ax : bool\n If True, returns the axes instance on which the plot was generated for the user to further modify. Default is False.\n cartopy_proj : ccrs\n Instance of a cartopy projection to use. If none, one will be generated. Default is none.\n \n Other Parameters\n ----------------\n prop : dict\n Customization properties of recon plot. Please refer to :ref:`options-prop-recon-plot` for available options.\n map_prop : dict\n Customization properties of Cartopy map. Please refer to :ref:`options-map-prop` for available options.\n \"\"\"\n \n #Pop kwargs\n prop = kwargs.pop('prop',{})\n map_prop = kwargs.pop('map_prop',{})\n \n #Get plot data\n \n if recon_select is None:\n dfRecon = self.recentered\n elif isinstance(recon_select,pd.core.frame.DataFrame):\n dfRecon = recon_select\n elif isinstance(recon_select,dict):\n dfRecon = pd.DataFrame.from_dict(recon_select)\n elif isinstance(recon_select,str):\n dfRecon = self.missiondata[recon_select]\n else:\n dfRecon = self.__getSubTime(recon_select)\n \n #Apply flight level filter\n if plane_p_range is not None:\n dfRecon = dfRecon.loc[(dfRecon['plane_p']>min(plane_p_range)) & (dfRecon['plane_p']<max(plane_p_range))]\n \n #Create instance of plot object\n self.plot_obj = ReconPlot()\n \n #Create cartopy projection\n if cartopy_proj is None:\n self.plot_obj.create_cartopy(proj='PlateCarree',central_longitude=0.0)\n cartopy_proj = self.plot_obj.proj\n \n #Plot recon\n plot_info = self.plot_obj.plot_points(self.storm_obj,dfRecon,domain,varname=varname,\\\n ax=ax,return_ax=return_ax,prop=prop,map_prop=map_prop)\n \n #Return axis\n if ax is not None or return_ax==True:\n return plot_info\n\n \n def plot_hovmoller(self,recon_select=None,varname='wspd',radlim=None,track_dict=None,plane_p_range=None,\\\n window=6,align='center',ax=None,return_ax=False,**kwargs):\n \n r\"\"\"\n Creates a hovmoller plot of azimuthally-averaged recon data.\n \n Parameters\n ----------\n recon_select : Requested recon data\n pandas.DataFrame or dict,\n or datetime or list of start/end datetimes.\n varname : Variable to average and plot (e.g. 'wspd').\n String\n ax : axes\n Instance of axes to plot on. If none, one will be generated. Default is none.\n return_ax : bool\n If True, returns the axes instance on which the plot was generated for the user to further modify. Default is False.\n cartopy_proj : ccrs\n Instance of a cartopy projection to use. If none, one will be generated. Default is none.\n \n Other Parameters\n ----------------\n prop : dict\n Customization properties for recon plot. Please refer to :ref:`options-prop-recon-hovmoller` for available options.\n \"\"\"\n \n #Pop kwargs\n prop = kwargs.pop('prop',{})\n default_prop = {'cmap':'category','levels':None,'smooth_contourf':False}\n for key in default_prop.keys():\n if key not in prop.keys():\n prop[key]=default_prop[key]\n \n #Get recon data based on recon_select\n if recon_select is None:\n dfRecon = self.recentered\n elif isinstance(recon_select,pd.core.frame.DataFrame):\n dfRecon = recon_select\n elif isinstance(recon_select,dict):\n dfRecon = pd.DataFrame.from_dict(recon_select)\n else:\n dfRecon = self.__getSubTime(recon_select)\n \n #Apply flight level filter\n if plane_p_range is not None:\n dfRecon = dfRecon.loc[(dfRecon['plane_p']>min(plane_p_range)) & (dfRecon['plane_p']<max(plane_p_range))]\n \n #Retrieve track dictionary if none is specified\n if track_dict is None:\n track_dict = self.storm_obj.dict\n \n #Interpolate recon data to a hovmoller\n iRecon = interpRecon(dfRecon,varname,radlim,window=window,align=align)\n Hov_dict = iRecon.interpHovmoller(track_dict)\n\n #title = get_recon_title(varname) #may not be necessary\n #If no contour levels specified, generate levels based on data min and max\n if prop['levels'] is None:\n prop['levels'] = (np.nanmin(Hov_dict['hovmoller']),np.nanmax(Hov_dict['hovmoller']))\n \n #Retrieve updated contour levels and colormap based on input arguments and variable type\n cmap,clevs = get_cmap_levels(varname,prop['cmap'],prop['levels'])\n \n #Retrieve hovmoller times, radii and data\n time = Hov_dict['time']\n radius = Hov_dict['radius']\n vardata = Hov_dict['hovmoller']\n \n #Error check time\n time = [dt.strptime((i.strftime('%Y%m%d%H%M')),'%Y%m%d%H%M') for i in time]\n \n #------------------------------------------------------------------------------\n \n #Create plot \n #plt.figure(figsize=(9,11),dpi=150)\n plt.figure(figsize=(9,9),dpi=150) #CHANGE THIS OR ELSE\n ax = plt.subplot()\n \n #Plot surface category colors individually, necessitating normalizing colormap\n if varname in ['vmax','sfmr','fl_to_sfc'] and prop['cmap'] == 'category':\n norm = mcolors.BoundaryNorm(clevs,cmap.N)\n cf = ax.contourf(radius,time,gfilt1d(vardata,sigma=3,axis=1),\n levels=clevs,cmap=cmap,norm=norm)\n \n #Multiple clevels or without smooth contouring\n elif len(prop['levels']) > 2 or prop['smooth_contourf'] == False:\n cf = ax.contourf(radius,time,gfilt1d(vardata,sigma=3,axis=1),\n levels=clevs,cmap=cmap)\n \n #Automatically generated levels with smooth contouring\n else:\n cf = ax.contourf(radius,time,gfilt1d(vardata,sigma=3,axis=1),\n cmap=cmap,levels=np.linspace(min(prop['levels']),max(prop['levels']),256))\n ax.axis([0,max(radius),min(time),max(time)])\n \n #Plot colorbar\n cbar = plt.colorbar(cf,orientation='horizontal',pad=0.1)\n \n #Format y-label ticks and labels as dates\n ax.yaxis.set_major_formatter(mdates.DateFormatter('%m-%d %H'))\n for tick in ax.xaxis.get_major_ticks():\n tick.label.set_fontsize(14)\n for tick in ax.yaxis.get_major_ticks():\n tick.label.set_fontsize(14)\n \n #Set axes labels\n ax.set_ylabel('UTC Time (MM-DD HH)',fontsize=15)\n ax.set_xlabel('Radius (km)',fontsize=15)\n \n #--------------------------------------------------------------------------------------\n \n #Generate left and right title strings\n title_left, title_right = hovmoller_plot_title(self.storm_obj,Hov_dict,varname)\n ax.set_title(title_left,loc='left',fontsize=16,fontweight='bold')\n ax.set_title(title_right,loc='right',fontsize=12)\n \n #Return axis\n if return_ax:\n return ax\n\n\n #PLOT FUNCTION FOR RECON MAPS\n def plot_maps(self,recon_select=None,varname='wspd',track_dict=None,recon_stats=None,domain=\"dynamic\",\\\n window=6,align='center',radlim=None,plane_p_range=None,ax=None,return_ax=False,savetopath=None,cartopy_proj=None,**kwargs):\n \n #plot_time, plot_mission (only for dots)\n \n r\"\"\"\n Creates maps of interpolated recon data. \n \n Parameters\n ----------\n recon_select : Requested recon data\n pandas.DataFrame or dict,\n or string referencing the mission name (e.g. '12_NOAA'), \n or datetime or list of start/end datetimes.\n varname : str\n Variable to plot. Can be one of the following keys in recon_select dataframe:\n \n * **\"sfmr\"** = SFMR surface wind\n * **\"wspd\"** = 30-second flight level wind (default)\n * **\"pkwnd\"** = 10-second flight level wind\n * **\"p_sfc\"** = extrapolated surface pressure\n domain : str\n Domain for the plot. Default is \"dynamic\". Please refer to :ref:`options-domain` for available domain options.\n ax : axes\n Instance of axes to plot on. If none, one will be generated. Default is none.\n return_ax : bool\n If True, returns the axes instance on which the plot was generated for the user to further modify. Default is False.\n cartopy_proj : ccrs\n Instance of a cartopy projection to use. If none, one will be generated. Default is none.\n \n Other Parameters\n ----------------\n prop : dict\n Customization properties of recon plot. Please refer to :ref:`options-prop-recon-swath` for available options.\n map_prop : dict\n Customization properties of Cartopy map. Please refer to :ref:`options-map-prop` for available options.\n \"\"\"\n \n #Pop kwargs\n prop = kwargs.pop('prop',{})\n map_prop = kwargs.pop('map_prop',{})\n \n #Get plot data\n ONE_MAP = False\n if recon_select is None:\n dfRecon = self.recentered \n elif isinstance(recon_select,pd.core.frame.DataFrame):\n dfRecon = recon_select\n elif isinstance(recon_select,dict):\n dfRecon = pd.DataFrame.from_dict(recon_select)\n elif isinstance(recon_select,str):\n dfRecon = self.missiondata[recon_select]\n else:\n dfRecon = self.__getSubTime(recon_select)\n if not isinstance(recon_select,(tuple,list)):\n ONE_MAP = True\n \n MULTIVAR=False\n if isinstance(varname,(tuple,list)):\n MULTIVAR=True \n \n #Apply flight level filter\n if plane_p_range is not None:\n dfRecon = dfRecon.loc[(dfRecon['plane_p']>min(plane_p_range)) & (dfRecon['plane_p']<max(plane_p_range))]\n \n if track_dict is None:\n track_dict = self.storm_obj.dict\n \n #Error check for time dimension name\n if 'time' not in track_dict.keys():\n track_dict['time'] = track_dict['date']\n \n if ONE_MAP:\n f = interp1d(mdates.date2num(track_dict['time']),track_dict['lon'], fill_value='extrapolate')\n clon = f(mdates.date2num(recon_select))\n f = interp1d(mdates.date2num(track_dict['time']),track_dict['lat'], fill_value='extrapolate')\n clat = f(mdates.date2num(recon_select))\n \n #clon = np.interp(mdates.date2num(recon_select),mdates.date2num(track_dict['time']),track_dict['lon'])\n #clat = np.interp(mdates.date2num(recon_select),mdates.date2num(track_dict['time']),track_dict['lat'])\n track_dict = {'time':recon_select,'lon':clon,'lat':clat}\n \n if MULTIVAR:\n Maps=[]\n for v in varname:\n iRecon = interpRecon(dfRecon,v,radlim,window=window,align=align)\n tmpMaps = iRecon.interpMaps(track_dict)\n Maps.append(tmpMaps)\n else:\n iRecon = interpRecon(dfRecon,varname,radlim,window=window,align=align)\n Maps = iRecon.interpMaps(track_dict)\n \n #titlename,units = get_recon_title(varname)\n \n if 'levels' not in prop.keys() or 'levels' in prop.keys() and prop['levels'] is None:\n prop['levels'] = np.arange(np.floor(np.nanmin(Maps['maps'])/10)*10,\n np.ceil(np.nanmax(Maps['maps'])/10)*10+1,10)\n \n if not ONE_MAP:\n \n if savetopath is True:\n #savetopath = f'{self.storm}{self.year}_{varname}_maps'\n savetopath = f'{self.storm}{self.year}_maps'\n try:\n os.system(f'mkdir {savetopath}')\n except:\n pass\n \n if MULTIVAR:\n Maps2 = Maps[1]\n Maps = Maps[0]\n \n print(np.nanmax(Maps['maps']),np.nanmin(Maps2['maps']))\n \n figs = []\n for i,t in enumerate(Maps['time']):\n Maps_sub = {'time':t,'grid_x':Maps['grid_x'],'grid_y':Maps['grid_y'],'maps':Maps['maps'][i],\\\n 'center_lon':Maps['center_lon'][i],'center_lat':Maps['center_lat'][i],'stats':Maps['stats']}\n\n #Create instance of plot object\n self.plot_obj = ReconPlot()\n \n #Create cartopy projection\n self.plot_obj.create_cartopy(proj='PlateCarree',central_longitude=0.0)\n cartopy_proj = self.plot_obj.proj\n \n #Maintain the same lat / lon dimensions for all dynamic maps\n #Determined by the dynamic domain from the first map\n if i>0 and domain is 'dynamic':\n d1 = {'n':Maps_sub['center_lat']+dlat,\\\n 's':Maps_sub['center_lat']-dlat,\\\n 'e':Maps_sub['center_lon']+dlon,\\\n 'w':Maps_sub['center_lon']-dlon}\n else:\n d1 = domain\n \n #Plot recon\n \n if MULTIVAR:\n Maps_sub1 = dict(Maps_sub)\n Maps_sub2 = dict(Maps_sub)\n Maps_sub = [Maps_sub1,Maps_sub2]\n Maps_sub[1]['maps'] = Maps2['maps'][i]\n \n print(np.nanmax(Maps_sub[0]['maps']),np.nanmin(Maps_sub[1]['maps']))\n \n plot_ax,d0 = self.plot_obj.plot_maps(self.storm_obj,Maps_sub,varname,recon_stats,\\\n domain=d1,ax=ax,return_ax=True,return_domain=True,prop=prop,map_prop=map_prop)\n \n #Get domain dimensions from the first map\n if i==0:\n dlat = .5*(d0['n']-d0['s'])\n dlon = .5*(d0['e']-d0['w'])\n \n figs.append(plot_ax)\n \n if savetopath is not None:\n plt.savefig(f'{savetopath}/{t.strftime(\"%Y%m%d%H%M\")}',bbox_inches='tight')\n plt.close()\n \n if savetopath is None:\n return figs\n \n\n else:\n #Create instance of plot object\n self.plot_obj = ReconPlot()\n \n #Create cartopy projection\n if cartopy_proj is None:\n self.plot_obj.create_cartopy(proj='PlateCarree',central_longitude=0.0)\n cartopy_proj = self.plot_obj.proj\n \n #Plot recon\n plot_info = self.plot_obj.plot_maps(self.storm_obj,Maps,varname,recon_stats,\\\n domain,ax,return_ax,prop=prop,map_prop=map_prop)\n \n #Return axis\n if ax is not None or return_ax:\n return plot_info\n \n \n \n #PLOT FUNCTION FOR RECON SWATH\n def plot_swath(self,recon_select=None,varname='wspd',swathfunc=None,track_dict=None,radlim=None,\\\n domain=\"dynamic\",plane_p_range=None,ax=None,return_ax=False,cartopy_proj=None,**kwargs):\n \n r\"\"\"\n Creates a map plot of a swath of interpolated recon data.\n \n Parameters\n ----------\n recon_select : Requested recon data\n pandas.DataFrame or dict,\n or string referencing the mission name (e.g. '12_NOAA'), \n or datetime or list of start/end datetimes.\n varname : str\n Variable to plot. Can be one of the following keys in recon_select dataframe:\n \n * **\"sfmr\"** = SFMR surface wind\n * **\"wspd\"** = 30-second flight level wind (default)\n * **\"pkwnd\"** = 10-second flight level wind\n * **\"p_sfc\"** = extrapolated surface pressure\n swathfunc : function\n Function to operate on interpolated recon data.\n e.g., np.max, np.min, or percentile function\n domain : str\n Domain for the plot. Default is \"dynamic\". Please refer to :ref:`options-domain` for available domain options.\n ax : axes\n Instance of axes to plot on. If none, one will be generated. Default is none.\n return_ax : bool\n If True, returns the axes instance on which the plot was generated for the user to further modify. Default is False.\n cartopy_proj : ccrs\n Instance of a cartopy projection to use. If none, one will be generated. Default is none.\n \n Other Parameters\n ----------------\n prop : dict\n Customization properties of recon plot. Please refer to :ref:`options-prop-recon-swath` for available options.\n map_prop : dict\n Customization properties of Cartopy map. Please refer to :ref:`options-map-prop` for available options.\n \"\"\"\n \n #Pop kwargs\n prop = kwargs.pop('prop',{})\n map_prop = kwargs.pop('map_prop',{})\n \n #Get plot data\n if recon_select is None:\n dfRecon = self.recentered \n elif isinstance(recon_select,pd.core.frame.DataFrame):\n dfRecon = recon_select\n elif isinstance(recon_select,dict):\n dfRecon = pd.DataFrame.from_dict(recon_select)\n elif isinstance(recon_select,str):\n dfRecon = self.missiondata[recon_select]\n else:\n dfRecon = self.__getSubTime(recon_select)\n\n #Apply flight level filter\n if plane_p_range is not None:\n dfRecon = dfRecon.loc[(dfRecon['plane_p']>min(plane_p_range)) & (dfRecon['plane_p']<max(plane_p_range))]\n \n if track_dict is None:\n track_dict = self.storm_obj.dict\n \n if swathfunc is None:\n if varname == 'p_sfc':\n swathfunc = np.min\n else:\n swathfunc = np.max\n \n iRecon = interpRecon(dfRecon,varname)\n Maps = iRecon.interpMaps(track_dict,interval=.2)\n \n #Create instance of plot object\n self.plot_obj = ReconPlot()\n \n #Create cartopy projection\n if cartopy_proj is None:\n self.plot_obj.create_cartopy(proj='PlateCarree',central_longitude=0.0)\n cartopy_proj = self.plot_obj.proj\n \n #Plot recon\n plot_info = self.plot_obj.plot_swath(self.storm_obj,Maps,varname,swathfunc,track_dict,radlim,\\\n domain,ax,return_ax,prop=prop,map_prop=map_prop)\n \n #Return axis\n if ax is not None or return_ax==True:\n return plot_info\n" ]
[ [ "scipy.interpolate.interp1d", "matplotlib.colors.BoundaryNorm", "numpy.isfinite", "pandas.DataFrame.from_dict", "matplotlib.pyplot.figure", "pandas.to_datetime", "matplotlib.dates.date2num", "scipy.ndimage.gaussian_filter1d", "matplotlib.dates.DateFormatter", "pandas.concat", "matplotlib.pyplot.close", "matplotlib.pyplot.colorbar", "numpy.array", "numpy.nanmax", "scipy.ndimage.filters.minimum_filter", "pandas.read_html", "numpy.nanpercentile", "numpy.nanmin", "matplotlib.pyplot.subplot", "numpy.gradient", "numpy.convolve" ] ]
abditag2/DCGAN-tensorflow
[ "432b0d91bd8252c48869c205b86701993eb37618" ]
[ "utils.py" ]
[ "\"\"\"\nSome codes from https://github.com/Newmu/dcgan_code\n\"\"\"\nfrom __future__ import division\n\nimport math\nimport pprint\nimport random\nfrom time import gmtime, strftime\n\nimport numpy as np\nimport scipy.misc\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nfrom six.moves import xrange\n\npp = pprint.PrettyPrinter()\n\nget_stddev = lambda x, k_h, k_w: 1/math.sqrt(k_w*k_h*x.get_shape()[-1])\n\ndef show_all_variables():\n model_vars = tf.trainable_variables()\n slim.model_analyzer.analyze_vars(model_vars, print_info=True)\n\ndef get_image(image_path, input_height, input_width,\n resize_height=64, resize_width=64,\n crop=True, grayscale=False):\n image = imread(image_path, grayscale)\n return transform(image, input_height, input_width,\n resize_height, resize_width, crop)\n\ndef save_images(images, size, image_path):\n return imsave(inverse_transform(images), size, image_path)\n\ndef imread(path, grayscale = False):\n if (grayscale):\n return scipy.misc.imread(path, flatten = True).astype(np.float)\n else:\n return scipy.misc.imread(path).astype(np.float)\n\ndef merge_images(images, size):\n return inverse_transform(images)\n\ndef merge(images, size):\n h, w = images.shape[1], images.shape[2]\n if (images.shape[3] in (3,4)):\n c = images.shape[3]\n img = np.zeros((h * size[0], w * size[1], c))\n for idx, image in enumerate(images):\n i = idx % size[1]\n j = idx // size[1]\n img[j * h:j * h + h, i * w:i * w + w, :] = image\n return img\n elif images.shape[3]==1:\n img = np.zeros((h * size[0], w * size[1]))\n for idx, image in enumerate(images):\n i = idx % size[1]\n j = idx // size[1]\n img[j * h:j * h + h, i * w:i * w + w] = image[:,:,0]\n return img\n else:\n raise ValueError('in merge(images,size) images parameter '\n 'must have dimensions: HxW or HxWx3 or HxWx4')\n\ndef imsave(images, size, path):\n image = np.squeeze(merge(images, size))\n return scipy.misc.imsave(path, image)\n\ndef center_crop(x, crop_h, crop_w,\n resize_h=64, resize_w=64):\n if crop_w is None:\n crop_w = crop_h\n h, w = x.shape[:2]\n j = int(round((h - crop_h)/2.))\n i = int(round((w - crop_w)/2.))\n return scipy.misc.imresize(\n x[j:j+crop_h, i:i+crop_w], [resize_h, resize_w])\n\ndef transform(image, input_height, input_width, \n resize_height=64, resize_width=64, crop=True):\n if crop:\n cropped_image = center_crop(\n image, input_height, input_width, \n resize_height, resize_width)\n else:\n cropped_image = scipy.misc.imresize(image, [resize_height, resize_width])\n return np.array(cropped_image)/127.5 - 1.\n\ndef inverse_transform(images):\n return (images+1.)/2.\n\ndef to_json(output_path, *layers):\n with open(output_path, \"w\") as layer_f:\n lines = \"\"\n for w, b, bn in layers:\n layer_idx = w.name.split('/')[0].split('h')[1]\n\n B = b.eval()\n\n if \"lin/\" in w.name:\n W = w.eval()\n depth = W.shape[1]\n else:\n W = np.rollaxis(w.eval(), 2, 0)\n depth = W.shape[0]\n\n biases = {\"sy\": 1, \"sx\": 1, \"depth\": depth, \"w\": ['%.2f' % elem for elem in list(B)]}\n if bn != None:\n gamma = bn.gamma.eval()\n beta = bn.beta.eval()\n\n gamma = {\"sy\": 1, \"sx\": 1, \"depth\": depth, \"w\": ['%.2f' % elem for elem in list(gamma)]}\n beta = {\"sy\": 1, \"sx\": 1, \"depth\": depth, \"w\": ['%.2f' % elem for elem in list(beta)]}\n else:\n gamma = {\"sy\": 1, \"sx\": 1, \"depth\": 0, \"w\": []}\n beta = {\"sy\": 1, \"sx\": 1, \"depth\": 0, \"w\": []}\n\n if \"lin/\" in w.name:\n fs = []\n for w in W.T:\n fs.append({\"sy\": 1, \"sx\": 1, \"depth\": W.shape[0], \"w\": ['%.2f' % elem for elem in list(w)]})\n\n lines += \"\"\"\n var layer_%s = {\n \"layer_type\": \"fc\", \n \"sy\": 1, \"sx\": 1, \n \"out_sx\": 1, \"out_sy\": 1,\n \"stride\": 1, \"pad\": 0,\n \"out_depth\": %s, \"in_depth\": %s,\n \"biases\": %s,\n \"gamma\": %s,\n \"beta\": %s,\n \"filters\": %s\n };\"\"\" % (layer_idx.split('_')[0], W.shape[1], W.shape[0], biases, gamma, beta, fs)\n else:\n fs = []\n for w_ in W:\n fs.append({\"sy\": 5, \"sx\": 5, \"depth\": W.shape[3], \"w\": ['%.2f' % elem for elem in list(w_.flatten())]})\n\n lines += \"\"\"\n var layer_%s = {\n \"layer_type\": \"deconv\", \n \"sy\": 5, \"sx\": 5,\n \"out_sx\": %s, \"out_sy\": %s,\n \"stride\": 2, \"pad\": 1,\n \"out_depth\": %s, \"in_depth\": %s,\n \"biases\": %s,\n \"gamma\": %s,\n \"beta\": %s,\n \"filters\": %s\n };\"\"\" % (layer_idx, 2**(int(layer_idx)+2), 2**(int(layer_idx)+2),\n W.shape[0], W.shape[3], biases, gamma, beta, fs)\n layer_f.write(\" \".join(lines.replace(\"'\",\"\").split()))\n\ndef make_gif(images, fname, duration=2, true_image=False):\n import moviepy.editor as mpy\n\n def make_frame(t):\n try:\n x = images[int(len(images)/duration*t)]\n except:\n x = images[-1]\n\n if true_image:\n return x.astype(np.uint8)\n else:\n return ((x+1)/2*255).astype(np.uint8)\n\n clip = mpy.VideoClip(make_frame, duration=duration)\n clip.write_gif(fname, fps = len(images) / duration)\n\ndef visualize(sess, dcgan, config, batch_size, option):\n print('dcgan.z_dim:', dcgan.z_dim)\n print('xrange(dcgan.z_dim):', xrange(dcgan.z_dim))\n print('config.generate_test_images:', config.generate_test_images)\n\n if option == 0:\n z_sample = np.random.uniform(-0.5, 0.5, size=(batch_size, dcgan.z_dim))\n samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample})\n save_images(samples, [config.grid_height, config.grid_width], './samples/test_%s.png' % strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime()))\n elif option == 1:\n values = np.arange(0, 1, 1./batch_size)\n for idx in xrange(config.generate_test_images):\n print(\" [*] %d\" % idx)\n z_sample = np.random.uniform(-1, 1, size=(batch_size, dcgan.z_dim))\n for kdx, z in enumerate(z_sample):\n z[idx] = values[kdx]\n\n if config.dataset == \"mnist\":\n y = np.random.choice(10, batch_size)\n y_one_hot = np.zeros((batch_size, 10))\n y_one_hot[np.arange(batch_size), y] = 1\n\n samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample, dcgan.y: y_one_hot})\n else:\n samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample})\n\n save_images(samples, [config.grid_height, config.grid_width], './samples/test_arange_%s.png' % (idx))\n elif option == 2:\n values = np.arange(0, 1, 1./batch_size)\n for idx in [random.randint(0, dcgan.z_dim - 1) for _ in xrange(dcgan.z_dim)]:\n print(\" [*] %d\" % idx)\n z = np.random.uniform(-0.2, 0.2, size=(dcgan.z_dim))\n z_sample = np.tile(z, (batch_size, 1))\n #z_sample = np.zeros([batch_size, dcgan.z_dim])\n for kdx, z in enumerate(z_sample):\n z[idx] = values[kdx]\n\n if config.dataset == \"mnist\":\n y = np.random.choice(10, batch_size)\n y_one_hot = np.zeros((batch_size, 10))\n y_one_hot[np.arange(batch_size), y] = 1\n\n samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample, dcgan.y: y_one_hot})\n else:\n samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample})\n\n try:\n make_gif(samples, './samples/test_gif_%s.gif' % (idx))\n except:\n save_images(samples, [config.grid_height, config.grid_width], './samples/test_%s.png' % strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime()))\n elif option == 3:\n values = np.arange(0, 1, 1./batch_size)\n for idx in xrange(dcgan.z_dim):\n print(\" [*] %d\" % idx)\n z_sample = np.zeros([batch_size, dcgan.z_dim])\n for kdx, z in enumerate(z_sample):\n z[idx] = values[kdx]\n\n samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample})\n make_gif(samples, './samples/test_gif_%s.gif' % (idx))\n elif option == 4:\n image_set = []\n values = np.arange(0, 1, 1./batch_size)\n\n for idx in xrange(dcgan.z_dim):\n print(\" [*] %d\" % idx)\n z_sample = np.zeros([batch_size, dcgan.z_dim])\n for kdx, z in enumerate(z_sample): z[idx] = values[kdx]\n\n image_set.append(sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample}))\n make_gif(image_set[-1], './samples/test_gif_%s.gif' % (idx))\n\n new_image_set = [merge(np.array([images[idx] for images in image_set]), [10, 10]) \\\n for idx in range(64) + range(63, -1, -1)]\n make_gif(new_image_set, './samples/test_gif_merged.gif', duration=8)\n" ]
[ [ "numpy.random.uniform", "numpy.tile", "numpy.zeros", "numpy.random.choice", "tensorflow.trainable_variables", "tensorflow.contrib.slim.model_analyzer.analyze_vars", "numpy.arange", "numpy.array" ] ]
scikit-spark/scikit-spark
[ "1b1291f14ce0c18d7ea358fe25687649a5b74ecd" ]
[ "python/test/sklearn_version_specific_utils.py" ]
[ "import sklearn\n\n\ndef sklearn_version_is(version):\n if sklearn.__version__.startswith(version):\n return True\n return False\n\n\ndef sklearn_is_at_least(version):\n if sklearn.__version__ >= version:\n return True\n return False\n\n\ndef get_refactored_tests_to_skip():\n \"\"\"These tests have been edited in order to work with spark.\n They have been moved into this repo e.g. in resource_warning_tests.py\"\"\"\n if sklearn_version_is(\"0.19\"):\n return [\n \"test_return_train_score_warn\", # moved to resource_warning_tests.py\n ]\n elif sklearn_version_is(\"0.20\"):\n return [\n \"test_return_train_score_warn\", # moved to resource_warning_tests.py\n \"test_deprecated_grid_search_iid\", # moved to resource_warning_tests.py\n \"test_validate_parameter_grid_input\" # a function, not a test\n ]\n elif sklearn_version_is(\"0.21\"):\n return [\n \"test_refit_callable_out_bound\", # parameterized test, moved to test_parameterised_tests\n \"test_deprecated_grid_search_iid\", # moved to resource_warning_tests.py\n \"test_validate_parameter_grid_input\", # parameterized test, moved to test_parameterised_tests\n ]\n elif sklearn_version_is(\"0.22\"):\n return [\n \"test_refit_callable_out_bound\", # parameterized test, moved to test_parameterised_tests\n \"test_deprecated_grid_search_iid\", # moved to resource_warning_tests.py\n \"test_validate_parameter_grid_input\", # parameterized test, moved to test_parameterised_tests\n \"test_SearchCV_with_fit_params\", # moved to test_parameterised_tests\n \"test_scalar_fit_param\", # moved to test_parameterised_tests\n \"test_scalar_fit_param_compat\", # moved to test_parameterised_tests\n \"test_search_default_iid\", # moved to test_parameterised_tests\n \"test_validate_parameter_input\", # moved to test_parameterised_tests\n ]\n else:\n raise NotImplementedError(\n \"Unsupported sklearn version {}\".format(sklearn.__version__))\n" ]
[ [ "sklearn.__version__.startswith" ] ]
SIOS-Svalbard/darwinsheet
[ "7ac85861156ca195c8a3563df0f08a141d805384" ]
[ "scripts/get_niskin_data.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 21 08:24:22 2021\n\n@author: lukem\n\"\"\"\n\nimport pandas as pd\nimport os\nimport sys\nimport re\nimport uuid\nimport requests\n\nimport os.path\naen_config_dir = (os.path.abspath(\n os.path.join(os.path.dirname(__file__), '..')))\n\nsys.path.append(aen_config_dir+'/scripts')\nimport toktlogger_json_to_df as tl\n\nbtl_files_folder = '/home/pal/kph-ctd/' \n\ncolumns = [\n 'eventID',\n 'parentEventID',\n 'bottleNumber',\n 'sampleDepthInMeters',\n 'eventDate',\n 'eventTime',\n 'decimalLatitude',\n 'decimalLongitude',\n 'bottomDepthInMeters',\n 'sampleType',\n 'gearType',\n 'eventRemarks',\n 'stationName',\n 'statID',\n 'samplingProtocol',\n 'recordedBy',\n 'pi_name',\n 'pi_institution',\n 'pi_email',\n 'sampleLocation',\n 'dataFilename'\n ]\n\ndef get_cruise_number():\n '''\n Getting the cruise number from the toklogger\n\n Returns\n -------\n cruiseNum: Integer of cruise number\n\n '''\n \n toktlogger = 'toktlogger-khaakon.hi.no'\n url = \"http://\"+toktlogger+\"/api/cruises/current?format=json\"\n response = requests.get(url)\n json_cruise = response.json()\n cruisenum = int(json_cruise['cruiseNumber'])\n return cruisenum\n\ndef create_dataframe():\n '''\n Create empty dataframe to append data from each file to\n\n Returns\n -------\n df : pandas dataframe\n '''\n \n df = pd.DataFrame(columns=columns)\n \n return df\n\ndef generate_UUID(id_url):\n '''\n Generates a v5 UUID. This can be repeatedly generated from the same string.\n\n Parameters\n ----------\n id_url : string, text to be used to generate UUID\n\n Returns\n -------\n Version 5 UUID, string\n\n '''\n return str(uuid.uuid5(uuid.NAMESPACE_URL,id_url))\n\ndef pull_columns(df_ctd,ctd_file):\n '''\n Pull columns from .btl file to a pandas dataframe\n '''\n # Creating a new temporary file to read from as .btl file needs cleaning to be understood by Pandas.\n # Note that some columns that I am not interested in are still merged together.\n with open(ctd_file, 'r') as f:\n n = 0 # counter of lines in new temporary file\n try:\n os.remove('/tmp/'+ctd_file)\n except OSError:\n pass\n with open('/tmp/'+ctd_file, 'a') as tmpfile:\n for line in f: # Iterate over lines\n if not line.startswith('*') and not line.startswith('#'): # Ignore header rows\n if 'sdev' not in line and 'Position' not in line:\n line = line.replace('(avg)','') # Removing (avg) from end of line - not a column value\n line = re.sub(r\"^\\s+\", \"\", line) # Removing whitespace at beginning of line\n if n == 0: # For header line only\n line = re.sub(\"\\s+\", \",\", line)\n line = re.sub(\"\\s\\s+\" , \",\", line)\n tmpfile.write(line+'\\n')\n n += 1\n \n data = pd.read_csv('/tmp/'+ctd_file, delimiter=',', usecols=['Bottle', 'PrDM'])\n \n df_ctd['bottleNumber'] = data['Bottle']\n df_ctd['sampleDepthInMeters'] = data['PrDM']\n \n cruisenum = get_cruise_number()\n \n data['eventID'] = ''\n for index, row in data.iterrows():\n id_url = f'File {ctd_file} niskin bottle {row[\"Bottle\"]} cruise {cruisenum}' \n eventID = generate_UUID(id_url)\n df_ctd['eventID'].iloc[index] = eventID\n #df_ctd['sampleDepthInMeters'].iloc[index] = row['sampleDepthInMeters']\n\n return df_ctd\n\n\ndef pull_from_toktlogger():\n '''\n Pull data from toktlogger to a dataframe that can be used to generate attributes consistent for each activity.\n '''\n df_tl = tl.json_to_df('toktlogger-khaakon.hi.no')\n \n return df_tl\n\n\ndef pull_global_attributes(df_ctd,ctd_file, df_tl):\n '''\n Add global attributes that are constant for each individual .btl file (corresponding to one CTD cast)\n\n Parameters\n ----------\n df_ctd : pandas dataframe\n Dataframe to be written to niskin log, for a single CTD deployment \n ctd_file : string\n Name of .btl file\n df_tl : pandas dataframe\n Data from toktlogger\n\n Returns\n -------\n df_ctd : pandas dataframe\n Dataframe to be written to niskin log, for a single CTD deployment \n\n '''\n df_ctd['dataFilename'] = ctd_file\n \n localStationNumber = int(ctd_file.split('.')[0].split('sta')[1])\n #with open(ctd_file, \"rt\") as f:\n # for line in f:\n # print(line)\n \n df_tmp = df_tl.loc[df_tl['statID'] == localStationNumber]\n \n df_ctd['statID'] = localStationNumber\n df_ctd['eventDate'] = df_tmp.loc[df_tmp['gearType'] == 'CTD w/bottles', 'eventDate'].item()\n df_ctd['parentEventID'] = df_tmp.loc[df_tmp['gearType'] == 'CTD w/bottles', 'eventID'].item()\n df_ctd['eventTime'] = df_tmp.loc[df_tmp['gearType'] == 'CTD w/bottles', 'eventTime'].item()\n df_ctd['decimalLatitude'] = df_tmp.loc[df_tmp['gearType'] == 'CTD w/bottles', 'decimalLatitude'].item()\n df_ctd['decimalLongitude'] = df_tmp.loc[df_tmp['gearType'] == 'CTD w/bottles', 'decimalLongitude'].item()\n df_ctd['bottomDepthInMeters'] = df_tmp.loc[df_tmp['gearType'] == 'CTD w/bottles', 'bottomDepthInMeters'].item()\n \n return df_ctd\n\n\ndef get_niskin_data():\n '''\n Read data from Niskin files into a single pandas dataframe\n This dataframe can be used to create a sample log.\n\n Returns\n -------\n df_cruise : pandas dataframe\n Dataframe to be written to niskin log \n\n '''\n df_cruise = create_dataframe()\n df_tl = pull_from_toktlogger()\n \n for ctd_file in sorted(os.listdir(btl_files_folder)):\n if ctd_file.endswith('.btl'):\n df_ctd = create_dataframe()\n df_ctd = pull_columns(df_ctd, ctd_file)\n df_ctd = pull_global_attributes(df_ctd, ctd_file, df_tl)\n df_cruise = df_cruise.append(df_ctd, ignore_index=True)\n \n df_cruise['stationName'] = ''\n df_cruise['sampleLocation'] = 'Water distributed around children of this event'\n df_cruise['eventRemarks'] = ''\n df_cruise['recordedBy'] = ''\n df_cruise['pi_name'] = ''\n df_cruise['pi_institution'] = ''\n df_cruise['pi_email'] = ''\n df_cruise['sampleType'] = 'Niskin Bottle'\n df_cruise['gearType'] = 'Niskin'\n \n return df_cruise\n\n\n#df_cruise = get_niskin_data()\n\n#df_cruise.to_csv('niskin_test.csv')\n" ]
[ [ "pandas.read_csv", "pandas.DataFrame" ] ]
NihalHarish/datasets
[ "67574a8d74796bc065a8b9b49ec02f7b1200c172" ]
[ "src/datasets/utils/py_utils.py" ]
[ "# coding=utf-8\n# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"Some python utils function and classes.\n\n\"\"\"\n\nimport contextlib\nimport functools\nimport itertools\nimport os\nimport pickle\nimport sys\nimport types\nfrom io import BytesIO as StringIO\nfrom multiprocessing import Pool, RLock\nfrom shutil import disk_usage\nfrom types import CodeType, FunctionType\nfrom typing import Callable, ClassVar, Generic, Optional, Tuple, Union\n\nimport dill\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom .logging import INFO, WARNING, get_logger, get_verbosity, set_verbosity_warning\n\n\ntry: # pragma: no branch\n import typing_extensions as _typing_extensions\n from typing_extensions import Final, Literal\nexcept ImportError:\n _typing_extensions = Literal = Final = None\n\n\nlogger = get_logger(__name__)\n\n\n# NOTE: When used on an instance method, the cache is shared across all\n# instances and IS NOT per-instance.\n# See\n# https://stackoverflow.com/questions/14946264/python-lru-cache-decorator-per-instance\n# For @property methods, use @memoized_property below.\nmemoize = functools.lru_cache\n\n\ndef size_str(size_in_bytes):\n \"\"\"Returns a human readable size string.\n\n If size_in_bytes is None, then returns \"Unknown size\".\n\n For example `size_str(1.5 * datasets.units.GiB) == \"1.50 GiB\"`.\n\n Args:\n size_in_bytes: `int` or `None`, the size, in bytes, that we want to\n format as a human-readable size string.\n \"\"\"\n if not size_in_bytes:\n return \"Unknown size\"\n\n _NAME_LIST = [(\"PiB\", 2 ** 50), (\"TiB\", 2 ** 40), (\"GiB\", 2 ** 30), (\"MiB\", 2 ** 20), (\"KiB\", 2 ** 10)]\n\n size_in_bytes = float(size_in_bytes)\n for (name, size_bytes) in _NAME_LIST:\n value = size_in_bytes / size_bytes\n if value >= 1.0:\n return \"{:.2f} {}\".format(value, name)\n return \"{} {}\".format(int(size_in_bytes), \"bytes\")\n\n\[email protected]\ndef temporary_assignment(obj, attr, value):\n \"\"\"Temporarily assign obj.attr to value.\"\"\"\n original = getattr(obj, attr, None)\n setattr(obj, attr, value)\n try:\n yield\n finally:\n setattr(obj, attr, original)\n\n\ndef zip_dict(*dicts):\n \"\"\"Iterate over items of dictionaries grouped by their keys.\"\"\"\n for key in set(itertools.chain(*dicts)): # set merge all keys\n # Will raise KeyError if the dict don't have the same keys\n yield key, tuple(d[key] for d in dicts)\n\n\nclass NonMutableDict(dict):\n \"\"\"Dict where keys can only be added but not modified.\n\n Will raise an error if the user try to overwrite one key. The error message\n can be customized during construction. It will be formatted using {key} for\n the overwritten key.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n self._error_msg = kwargs.pop(\n \"error_msg\",\n \"Try to overwrite existing key: {key}\",\n )\n if kwargs:\n raise ValueError(\"NonMutableDict cannot be initialized with kwargs.\")\n super(NonMutableDict, self).__init__(*args, **kwargs)\n\n def __setitem__(self, key, value):\n if key in self:\n raise ValueError(self._error_msg.format(key=key))\n return super(NonMutableDict, self).__setitem__(key, value)\n\n def update(self, other):\n if any(k in self for k in other):\n raise ValueError(self._error_msg.format(key=set(self) & set(other)))\n return super(NonMutableDict, self).update(other)\n\n\nclass classproperty(property): # pylint: disable=invalid-name\n \"\"\"Descriptor to be used as decorator for @classmethods.\"\"\"\n\n def __get__(self, obj, objtype=None):\n return self.fget.__get__(None, objtype)()\n\n\ndef _single_map_nested(args):\n \"\"\"Apply a function recursively to each element of a nested data struct.\"\"\"\n function, data_struct, types, rank, disable_tqdm = args\n\n # Singleton first to spare some computation\n if not isinstance(data_struct, dict) and not isinstance(data_struct, types):\n return function(data_struct)\n\n # Reduce logging to keep things readable in multiprocessing with tqdm\n if rank is not None and get_verbosity() < WARNING:\n set_verbosity_warning()\n # Print at least one thing to fix tqdm in notebooks in multiprocessing\n # see https://github.com/tqdm/tqdm/issues/485#issuecomment-473338308\n if rank is not None and \"notebook\" in tqdm.__name__:\n print(\" \", end=\"\", flush=True)\n\n # Loop over single examples or batches and write to buffer/file if examples are to be updated\n pbar_iterable = data_struct.items() if isinstance(data_struct, dict) else data_struct\n pbar_desc = \"#\" + str(rank) if rank is not None else None\n pbar = tqdm(pbar_iterable, disable=disable_tqdm, position=rank, unit=\"obj\", desc=pbar_desc)\n\n if isinstance(data_struct, dict):\n return {k: _single_map_nested((function, v, types, None, True)) for k, v in pbar}\n else:\n mapped = [_single_map_nested((function, v, types, None, True)) for v in pbar]\n if isinstance(data_struct, list):\n return mapped\n elif isinstance(data_struct, tuple):\n return tuple(mapped)\n else:\n return np.array(mapped)\n\n\ndef map_nested(\n function,\n data_struct,\n dict_only: bool = False,\n map_list: bool = True,\n map_tuple: bool = False,\n map_numpy: bool = False,\n num_proc: Optional[int] = None,\n types=None,\n):\n \"\"\"Apply a function recursively to each element of a nested data struct.\n If num_proc > 1 and the length of data_struct is longer than num_proc: use multi-processing\n \"\"\"\n if types is None:\n types = []\n if not dict_only:\n if map_list:\n types.append(list)\n if map_tuple:\n types.append(tuple)\n if map_numpy:\n types.append(np.ndarray)\n types = tuple(types)\n\n # Singleton\n if not isinstance(data_struct, dict) and not isinstance(data_struct, types):\n return function(data_struct)\n\n disable_tqdm = bool(logger.getEffectiveLevel() > INFO)\n iterable = list(data_struct.values()) if isinstance(data_struct, dict) else data_struct\n\n if num_proc is None:\n num_proc = 1\n if num_proc <= 1 or len(iterable) <= num_proc:\n mapped = [\n _single_map_nested((function, obj, types, None, True)) for obj in tqdm(iterable, disable=disable_tqdm)\n ]\n else:\n split_kwds = [] # We organize the splits ourselve (contiguous splits)\n for index in range(num_proc):\n div = len(iterable) // num_proc\n mod = len(iterable) % num_proc\n start = div * index + min(index, mod)\n end = start + div + (1 if index < mod else 0)\n split_kwds.append((function, iterable[start:end], types, index, disable_tqdm))\n assert len(iterable) == sum(len(i[1]) for i in split_kwds), (\n f\"Error dividing inputs iterable among processes. \"\n f\"Total number of objects {len(iterable)}, \"\n f\"length: {sum(len(i[1]) for i in split_kwds)}\"\n )\n logger.info(\n \"Spawning {} processes for {} objects in slices of {}\".format(\n num_proc, len(iterable), [len(i[1]) for i in split_kwds]\n )\n )\n with Pool(num_proc, initargs=(RLock(),), initializer=tqdm.set_lock) as pool:\n mapped = pool.map(_single_map_nested, split_kwds)\n logger.info(\"Finished {} processes\".format(num_proc))\n mapped = [obj for proc_res in mapped for obj in proc_res]\n logger.info(\"Unpacked {} objects\".format(len(mapped)))\n\n if isinstance(data_struct, dict):\n return dict(zip(data_struct.keys(), mapped))\n else:\n if isinstance(data_struct, list):\n return mapped\n elif isinstance(data_struct, tuple):\n return tuple(mapped)\n else:\n return np.array(mapped)\n\n\ndef zip_nested(arg0, *args, **kwargs):\n \"\"\"Zip data struct together and return a data struct with the same shape.\"\"\"\n # Python 2 do not support kwargs only arguments\n dict_only = kwargs.pop(\"dict_only\", False)\n assert not kwargs\n\n # Could add support for more exotic data_struct, like OrderedDict\n if isinstance(arg0, dict):\n return {k: zip_nested(*a, dict_only=dict_only) for k, a in zip_dict(arg0, *args)}\n elif not dict_only:\n if isinstance(arg0, list):\n return [zip_nested(*a, dict_only=dict_only) for a in zip(arg0, *args)]\n # Singleton\n return (arg0,) + args\n\n\ndef flatten_nest_dict(d):\n \"\"\"Return the dict with all nested keys flattened joined with '/'.\"\"\"\n # Use NonMutableDict to ensure there is no collision between features keys\n flat_dict = NonMutableDict()\n for k, v in d.items():\n if isinstance(v, dict):\n flat_dict.update({\"{}/{}\".format(k, k2): v2 for k2, v2 in flatten_nest_dict(v).items()})\n else:\n flat_dict[k] = v\n return flat_dict\n\n\nclass NestedDataStructure:\n def __init__(self, data=None):\n self.data = data if data is not None else []\n\n def flatten(self, data=None):\n data = data if data is not None else self.data\n if isinstance(data, dict):\n return self.flatten(list(data.values()))\n elif isinstance(data, (list, tuple)):\n return [flattened for item in data for flattened in self.flatten(item)]\n else:\n return [data]\n\n\ndef has_sufficient_disk_space(needed_bytes, directory=\".\"):\n try:\n free_bytes = disk_usage(os.path.abspath(directory)).free\n except OSError:\n return True\n return needed_bytes < free_bytes\n\n\nclass Pickler(dill.Pickler):\n \"\"\"Same Pickler as the one from dill, but improved for notebooks and shells\"\"\"\n\n dispatch = dill._dill.MetaCatchingDict(dill.Pickler.dispatch.copy())\n\n def save_global(self, obj, name=None):\n if sys.version_info[:2] < (3, 7) and _CloudPickleTypeHintFix._is_parametrized_type_hint(\n obj\n ): # noqa # pragma: no branch\n # Parametrized typing constructs in Python < 3.7 are not compatible\n # with type checks and ``isinstance`` semantics. For this reason,\n # it is easier to detect them using a duck-typing-based check\n # (``_is_parametrized_type_hint``) than to populate the Pickler's\n # dispatch with type-specific savers.\n _CloudPickleTypeHintFix._save_parametrized_type_hint(self, obj)\n else:\n dill.Pickler.save_global(self, obj, name=name)\n\n\ndef dump(obj, file):\n \"\"\"pickle an object to a file\"\"\"\n Pickler(file, recurse=True).dump(obj)\n return\n\n\[email protected]\ndef _no_cache_fields(obj):\n try:\n import transformers as tr\n\n if (\n hasattr(tr, \"PreTrainedTokenizerBase\")\n and isinstance(obj, tr.PreTrainedTokenizerBase)\n and hasattr(obj, \"cache\")\n and isinstance(obj.cache, dict)\n ):\n with temporary_assignment(obj, \"cache\", {}):\n yield\n else:\n yield\n\n except ImportError:\n yield\n\n\ndef dumps(obj):\n \"\"\"pickle an object to a string\"\"\"\n file = StringIO()\n with _no_cache_fields(obj):\n dump(obj, file)\n return file.getvalue()\n\n\ndef pklregister(t):\n def proxy(func):\n Pickler.dispatch[t] = func\n return func\n\n return proxy\n\n\nclass _CloudPickleTypeHintFix:\n \"\"\"\n Type hints can't be properly pickled in python < 3.7\n CloudPickle provided a way to make it work in older versions.\n This class provide utilities to fix pickling of type hints in older versions.\n from https://github.com/cloudpipe/cloudpickle/pull/318/files\n \"\"\"\n\n def _is_parametrized_type_hint(obj):\n # This is very cheap but might generate false positives.\n origin = getattr(obj, \"__origin__\", None) # typing Constructs\n values = getattr(obj, \"__values__\", None) # typing_extensions.Literal\n type_ = getattr(obj, \"__type__\", None) # typing_extensions.Final\n return origin is not None or values is not None or type_ is not None\n\n def _create_parametrized_type_hint(origin, args):\n return origin[args]\n\n def _save_parametrized_type_hint(pickler, obj):\n # The distorted type check sematic for typing construct becomes:\n # ``type(obj) is type(TypeHint)``, which means \"obj is a\n # parametrized TypeHint\"\n if type(obj) is type(Literal): # pragma: no branch\n initargs = (Literal, obj.__values__)\n elif type(obj) is type(Final): # pragma: no branch\n initargs = (Final, obj.__type__)\n elif type(obj) is type(ClassVar):\n initargs = (ClassVar, obj.__type__)\n elif type(obj) in [type(Union), type(Tuple), type(Generic)]:\n initargs = (obj.__origin__, obj.__args__)\n elif type(obj) is type(Callable):\n args = obj.__args__\n if args[0] is Ellipsis:\n initargs = (obj.__origin__, args)\n else:\n initargs = (obj.__origin__, (list(args[:-1]), args[-1]))\n else: # pragma: no cover\n raise pickle.PicklingError(\"Datasets pickle Error: Unknown type {}\".format(type(obj)))\n pickler.save_reduce(_CloudPickleTypeHintFix._create_parametrized_type_hint, initargs, obj=obj)\n\n\n@pklregister(CodeType)\ndef _save_code(pickler, obj):\n \"\"\"\n From dill._dill.save_code\n This is a modified version that removes the origin (filename + line no.)\n of functions created in notebooks or shells for example.\n \"\"\"\n dill._dill.log.info(\"Co: %s\" % obj)\n # The filename of a function is the .py file where it is defined.\n # Filenames of functions created in notebooks or shells start with '<'\n # ex: <ipython-input-13-9ed2afe61d25> for ipython, and <stdin> for shell\n # Moreover lambda functions have a special name: '<lambda>'\n # ex: (lambda x: x).__code__.co_name == \"<lambda>\" # True\n # For the hashing mechanism we ignore where the function has been defined\n # More specifically:\n # - we ignore the filename of special functions (filename starts with '<')\n # - we always ignore the line number\n # Only those two lines are different from the original implementation:\n co_filename = \"\" if obj.co_filename.startswith(\"<\") or obj.co_name == \"<lambda>\" else obj.co_filename\n co_firstlineno = 1\n # The rest is the same as in the original dill implementation\n if dill._dill.PY3:\n if hasattr(obj, \"co_posonlyargcount\"):\n args = (\n obj.co_argcount,\n obj.co_posonlyargcount,\n obj.co_kwonlyargcount,\n obj.co_nlocals,\n obj.co_stacksize,\n obj.co_flags,\n obj.co_code,\n obj.co_consts,\n obj.co_names,\n obj.co_varnames,\n co_filename,\n obj.co_name,\n co_firstlineno,\n obj.co_lnotab,\n obj.co_freevars,\n obj.co_cellvars,\n )\n else:\n args = (\n obj.co_argcount,\n obj.co_kwonlyargcount,\n obj.co_nlocals,\n obj.co_stacksize,\n obj.co_flags,\n obj.co_code,\n obj.co_consts,\n obj.co_names,\n obj.co_varnames,\n co_filename,\n obj.co_name,\n co_firstlineno,\n obj.co_lnotab,\n obj.co_freevars,\n obj.co_cellvars,\n )\n else:\n args = (\n obj.co_argcount,\n obj.co_nlocals,\n obj.co_stacksize,\n obj.co_flags,\n obj.co_code,\n obj.co_consts,\n obj.co_names,\n obj.co_varnames,\n co_filename,\n obj.co_name,\n co_firstlineno,\n obj.co_lnotab,\n obj.co_freevars,\n obj.co_cellvars,\n )\n pickler.save_reduce(CodeType, args, obj=obj)\n dill._dill.log.info(\"# Co\")\n return\n\n\n@pklregister(FunctionType)\ndef save_function(pickler, obj):\n \"\"\"\n From dill._dill.save_function\n This is a modified version that make globs deterministic since the order of\n the keys in the output dictionary of globalvars can change.\n \"\"\"\n if not dill._dill._locate_function(obj):\n dill._dill.log.info(\"F1: %s\" % obj)\n if getattr(pickler, \"_recurse\", False):\n # recurse to get all globals referred to by obj\n globalvars = dill.detect.globalvars\n globs = globalvars(obj, recurse=True, builtin=True)\n if id(obj) in dill._dill.stack:\n globs = obj.__globals__ if dill._dill.PY3 else obj.func_globals\n else:\n globs = obj.__globals__ if dill._dill.PY3 else obj.func_globals\n # globs is a dictionary with keys = var names (str) and values = python objects\n # however the dictionary is not always loaded in the same order\n # therefore we have to sort the keys to make deterministic.\n # This is important to make `dump` deterministic.\n # Only this line is different from the original implementation:\n globs = {k: globs[k] for k in sorted(globs.keys())}\n # The rest is the same as in the original dill implementation\n _byref = getattr(pickler, \"_byref\", None)\n _recurse = getattr(pickler, \"_recurse\", None)\n _memo = (id(obj) in dill._dill.stack) and (_recurse is not None)\n dill._dill.stack[id(obj)] = len(dill._dill.stack), obj\n if dill._dill.PY3:\n _super = (\"super\" in getattr(obj.__code__, \"co_names\", ())) and (_byref is not None)\n if _super:\n pickler._byref = True\n if _memo:\n pickler._recurse = False\n fkwdefaults = getattr(obj, \"__kwdefaults__\", None)\n pickler.save_reduce(\n dill._dill._create_function,\n (obj.__code__, globs, obj.__name__, obj.__defaults__, obj.__closure__, obj.__dict__, fkwdefaults),\n obj=obj,\n )\n else:\n _super = (\n (\"super\" in getattr(obj.func_code, \"co_names\", ()))\n and (_byref is not None)\n and getattr(pickler, \"_recurse\", False)\n )\n if _super:\n pickler._byref = True\n if _memo:\n pickler._recurse = False\n pickler.save_reduce(\n dill._dill._create_function,\n (obj.func_code, globs, obj.func_name, obj.func_defaults, obj.func_closure, obj.__dict__),\n obj=obj,\n )\n if _super:\n pickler._byref = _byref\n if _memo:\n pickler._recurse = _recurse\n if (\n dill._dill.OLDER\n and not _byref\n and (_super or (not _super and _memo) or (not _super and not _memo and _recurse))\n ):\n pickler.clear_memo()\n dill._dill.log.info(\"# F1\")\n else:\n dill._dill.log.info(\"F2: %s\" % obj)\n name = getattr(obj, \"__qualname__\", getattr(obj, \"__name__\", None))\n dill._dill.StockPickler.save_global(pickler, obj, name=name)\n dill._dill.log.info(\"# F2\")\n return\n\n\ndef copyfunc(func):\n result = types.FunctionType(func.__code__, func.__globals__, func.__name__, func.__defaults__, func.__closure__)\n result.__kwdefaults__ = func.__kwdefaults__\n return result\n\n\ntry:\n import regex\n\n @pklregister(type(regex.Regex(\"\", 0)))\n def _save_regex(pickler, obj):\n dill._dill.log.info(\"Re: %s\" % obj)\n args = (\n obj.pattern,\n obj.flags,\n )\n pickler.save_reduce(regex.compile, args, obj=obj)\n dill._dill.log.info(\"# Re\")\n return\n\n\nexcept ImportError:\n pass\n" ]
[ [ "numpy.array" ] ]
zhaogev5/BBAVectors-Oriented-Object-Detection
[ "b9e86404082761dd49a652670898f6d3a98c30aa" ]
[ "DOTA_devkit/DOTA.py" ]
[ "#The code is used for visulization, inspired from cocoapi\n# Licensed under the Simplified BSD License [see bsd.txt]\n\nimport os\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import PatchCollection\nfrom matplotlib.patches import Polygon, Circle\nimport numpy as np\nimport dota_utils as util\nfrom collections import defaultdict\nimport cv2\n\ndef _isArrayLike(obj):\n if type(obj) == str:\n return False\n return hasattr(obj, '__iter__') and hasattr(obj, '__len__')\n\nclass DOTA:\n def __init__(self, basepath):\n self.basepath = basepath\n self.labelpath = os.path.join(basepath, 'labelTxt')\n self.imagepath = os.path.join(basepath, 'images')\n self.imgpaths = util.GetFileFromThisRootDir(self.labelpath)\n self.imglist = [util.custombasename(x) for x in self.imgpaths]\n self.catToImgs = defaultdict(list)\n self.ImgToAnns = defaultdict(list)\n self.createIndex()\n\n def createIndex(self):\n for filename in self.imgpaths:\n objects = util.parse_dota_poly(filename)\n imgid = util.custombasename(filename)\n self.ImgToAnns[imgid] = objects\n for obj in objects:\n cat = obj['name']\n self.catToImgs[cat].append(imgid)\n\n def getImgIds(self, catNms=[]):\n \"\"\"\n :param catNms: category names\n :return: all the image ids contain the categories\n \"\"\"\n catNms = catNms if _isArrayLike(catNms) else [catNms]\n if len(catNms) == 0:\n return self.imglist\n else:\n imgids = []\n for i, cat in enumerate(catNms):\n if i == 0:\n imgids = set(self.catToImgs[cat])\n else:\n imgids &= set(self.catToImgs[cat])\n return list(imgids)\n\n def loadAnns(self, catNms=[], imgId = None, difficult=None):\n \"\"\"\n :param catNms: category names\n :param imgId: the img to load anns\n :return: objects\n \"\"\"\n catNms = catNms if _isArrayLike(catNms) else [catNms]\n objects = self.ImgToAnns[imgId]\n if len(catNms) == 0:\n return objects\n outobjects = [obj for obj in objects if (obj['name'] in catNms)]\n return outobjects\n def showAnns(self, objects, imgId, range, out_dir):\n \"\"\"\n :param catNms: category names\n :param objects: objects to show\n :param imgId: img to show\n :param range: display range in the img\n :return:\n \"\"\"\n plt.cla()\n img = self.loadImgs(imgId)[0]\n ypixels, xpixels, bands = img.shape\n dpi = 72.\n xinch = xpixels / dpi\n yinch = ypixels / dpi\n plt.figure(figsize=(xinch,yinch))\n plt.imshow(img)\n plt.axis('off')\n\n ax = plt.gca()\n ax.set_autoscale_on(False)\n polygons = []\n color = []\n circles = []\n r = 5\n for obj in objects:\n c = (np.random.random((1, 3)) * 0.6 + 0.4).tolist()[0]\n poly = obj['poly']\n polygons.append(Polygon(poly))\n color.append(c)\n point = poly[0]\n circle = Circle((point[0], point[1]), r)\n circles.append(circle)\n p = PatchCollection(polygons, facecolors=color, linewidths=0, alpha=0.4)\n ax.add_collection(p)\n p = PatchCollection(polygons, facecolors='none', edgecolors=color, linewidths=2)\n ax.add_collection(p)\n p = PatchCollection(circles, facecolors='red')\n ax.add_collection(p)\n out_path = os.path.join(out_dir,imgId+'.jpg')\n plt.savefig(out_path,dpi=dpi,transparent=True)\n def loadImgs(self, imgids=[]):\n \"\"\"\n :param imgids: integer ids specifying img\n :return: loaded img objects\n \"\"\"\n print('isarralike:', _isArrayLike(imgids))\n imgids = imgids if _isArrayLike(imgids) else [imgids]\n print('imgids:', imgids)\n imgs = []\n for imgid in imgids:\n filename = os.path.join(self.imagepath, imgid + '.jpg')\n print('filename:', filename)\n img = cv2.imread(filename)\n imgs.append(img)\n return imgs\n\n# if __name__ == '__main__':\n# examplesplit = DOTA('data/tianzhi_demo_data')\n# imgids = examplesplit.getImgIds(catNms=['obj'])\n# img = examplesplit.loadImgs(imgids)\n# for imgid in imgids:\n# anns = examplesplit.loadAnns(imgId=imgid)\n# examplesplit.showAnns(anns, imgid, 2)" ]
[ [ "matplotlib.pyplot.cla", "matplotlib.pyplot.figure", "matplotlib.pyplot.gca", "matplotlib.pyplot.axis", "matplotlib.pyplot.savefig", "numpy.random.random", "matplotlib.pyplot.imshow", "matplotlib.patches.Circle", "matplotlib.patches.Polygon", "matplotlib.collections.PatchCollection" ] ]
mojones/pandas
[ "3d4f9dc19d784526f71a197bfb6e36b0409e0760" ]
[ "pandas/core/array_algos/transforms.py" ]
[ "\"\"\"\ntransforms.py is for shape-preserving functions.\n\"\"\"\n\nimport numpy as np\n\nfrom pandas.core.dtypes.common import ensure_platform_int\n\n\ndef shift(values: np.ndarray, periods: int, axis: int, fill_value) -> np.ndarray:\n new_values = values\n\n # make sure array sent to np.roll is c_contiguous\n f_ordered = values.flags.f_contiguous\n if f_ordered:\n new_values = new_values.T\n axis = new_values.ndim - axis - 1\n\n if np.prod(new_values.shape):\n new_values = np.roll(new_values, ensure_platform_int(periods), axis=axis)\n\n axis_indexer = [slice(None)] * values.ndim\n if periods > 0:\n axis_indexer[axis] = slice(None, periods)\n else:\n axis_indexer[axis] = slice(periods, None)\n new_values[tuple(axis_indexer)] = fill_value\n\n # restore original order\n if f_ordered:\n new_values = new_values.T\n\n return new_values\n" ]
[ [ "pandas.core.dtypes.common.ensure_platform_int", "numpy.prod" ] ]
sandialabs/Spitfire
[ "65670e3ba5d1ccb4ac72524b77957706345c5bf6" ]
[ "tests/tabulation/adiabatic_slfm/rebless.py" ]
[ "from os.path import abspath, join\n\n\ndef run():\n from spitfire.chemistry.mechanism import ChemicalMechanismSpec\n from spitfire.chemistry.tabulation import build_adiabatic_slfm_library\n import spitfire.chemistry.analysis as sca\n import numpy as np\n\n test_xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.xml'))\n m = ChemicalMechanismSpec(cantera_xml=test_xml, group_name='h2-burke')\n pressure = 101325.\n air = m.stream(stp_air=True)\n air.TP = 1200., pressure\n fuel = m.stream('TPY', (300., pressure, 'H2:1'))\n\n flamelet_specs = {'mech_spec': m, 'oxy_stream': air, 'fuel_stream': fuel, 'grid_points': 34}\n\n l = build_adiabatic_slfm_library(flamelet_specs, verbose=False, diss_rate_values=np.logspace(0, 1, 8), diss_rate_log_scaled=True)\n l = sca.compute_specific_enthalpy(m, l)\n l = sca.compute_isochoric_specific_heat(m, l)\n l = sca.compute_isobaric_specific_heat(m, l)\n l = sca.compute_density(m, l)\n l = sca.compute_pressure(m, l)\n l = sca.compute_viscosity(m, l)\n\n return l\n\n\nif __name__ == '__main__':\n gold_pkl = abspath(join('tests', 'tabulation', 'adiabatic_slfm', 'gold.pkl'))\n output_library = run()\n output_library.save_to_file(gold_pkl)\n" ]
[ [ "numpy.logspace" ] ]
me-grimjoww/Covid-Sutra
[ "ef07bf61ae3b1adc19affe5e040a9ba2f06fb5a8" ]
[ "Django_mask_attendance/main_base/face_verification.py" ]
[ " \r\nimport os\r\nfrom django.urls import path, include\r\nimport face_recognition\r\nimport cv2\r\nfrom imutils.video import VideoStream\r\nimport imutils\r\nimport numpy as np\r\nfrom tensorflow.keras.models import load_model\r\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\r\nfrom tensorflow.keras.preprocessing.image import img_to_array\r\n\r\n\r\n\r\n# load our serialized face detector model from disk\r\nprototxtPath = r\"face_detector\\deploy.prototxt\"\r\nweightsPath = r\"face_detector\\res10_300x300_ssd_iter_140000.caffemodel\"\r\nfaceNet = cv2.dnn.readNet(prototxtPath, weightsPath)\r\n\r\n# load the face mask detector model from disk\r\nmaskNet = load_model(r\"C:\\Users\\mkjsr\\OneDrive\\Desktop\\Django_mask_attendance\\main_base\\mask_detector.model\")\r\n\r\n\r\ndef detect_faces(frame,email):\r\n # grab the dimensions of the frame and then construct a blob\r\n # from it\r\n (h, w) = frame.shape[:2]\r\n blob = cv2.dnn.blobFromImage(frame, 1.0, (224, 224),\r\n (104.0, 177.0, 123.0))\r\n\r\n # pass the blob through the network and obtain the face detections\r\n faceNet.setInput(blob)\r\n detections = faceNet.forward()\r\n print(detections.shape)\r\n\r\n # initialize our list of faces, their corresponding locations,\r\n # and the list of predictions from our face mask network\r\n faces = []\r\n locs = []\r\n lable = \"Not Verified\"\r\n\r\n BASE_DIR = os.path.dirname(os.path.abspath(__file__))\r\n MEDIA_ROOT = os.path.join(BASE_DIR,'face_dataset')\r\n loc=(str(MEDIA_ROOT)+'\\\\'+str(email)+'.jpg')\r\n face_1_image = face_recognition.load_image_file(loc)\r\n small_frame_1 = cv2.resize(face_1_image, (0, 0), fx=0.25, fy=0.25)\r\n rgb_small_frame_1 = small_frame_1[:, :, ::-1]\r\n face_1_face_encoding = face_recognition.face_encodings(rgb_small_frame_1)[0]\r\n\r\n # loop over the detections\r\n for i in range(0, detections.shape[2]):\r\n # extract the confidence (i.e., probability) associated with\r\n # the detection\r\n confidence = detections[0, 0, i, 2]\r\n\r\n # filter out weak detections by ensuring the confidence is\r\n # greater than the minimum confidence\r\n if confidence > 0.5:\r\n # compute the (x, y)-coordinates of the bounding box for\r\n # the object\r\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\r\n (startX, startY, endX, endY) = box.astype(\"int\")\r\n\r\n # ensure the bounding boxes fall within the dimensions of\r\n # the frame\r\n (startX, startY) = (max(0, startX), max(0, startY))\r\n (endX, endY) = (min(w - 1, endX), min(h - 1, endY))\r\n\r\n # extract the face ROI, convert it from BGR to RGB channel\r\n # ordering, resize it to 224x224, and preprocess it\r\n face = frame[startY:endY, startX:endX]\r\n face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)\r\n face = cv2.resize(face, (224, 224))\r\n face = img_to_array(face)\r\n face = preprocess_input(face)\r\n\r\n # add the face and bounding boxes to their respective\r\n # lists\r\n faces.append(face)\r\n locs.append((startX, startY, endX, endY))\r\n\r\n if len(faces) > 0:\r\n\t\t# for faster inference we'll make batch predictions on *all*\r\n\t\t# faces at the same time rather than one-by-one predictions\r\n # in the above `for` loop\r\n faces = np.array(faces, dtype=\"float32\")\r\n rgb_small_frame = frame[:, :, ::-1]\r\n face_locations = face_recognition.face_locations(rgb_small_frame)\r\n face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)\r\n if len(face_encodings):\r\n\r\n check = face_recognition.compare_faces(face_1_face_encoding, face_encodings)\r\n if check[0]:\r\n lable = 'Verified'\r\n print(lable)\r\n\r\n else :\r\n lable = 'Not Verified'\r\n print(lable)\r\n\r\n\r\n return (locs,lable)\r\n\r\n# initialize the camera\r\ndef facedect(email):\r\n\r\n cam = VideoStream(src=0).start() # 0 -> index of camera\r\n lab = 'Not Verified'\r\n while True:\r\n img = cam.read()\r\n small_frame = imutils.resize(img, width=400)\r\n # rgb_small_frame = small_frame[:, :, ::-1]\r\n # face_locations = face_recognition.face_locations(rgb_small_frame)\r\n # face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)\r\n # check=face_recognition.compare_faces(face_1_face_encoding, face_encodings)\r\n\r\n \r\n # if check[0]:\r\n # label = 'Verified'\r\n # print(label)\r\n\r\n # else :\r\n # label = 'Verified'\r\n # print(label)\r\n\r\n \r\n (locs,lable) = detect_faces(small_frame,email)\r\n\r\n # loop over the detected face locations and their corresponding\r\n # locations\r\n for box in locs:\r\n # unpack the bounding box and predictions\r\n (startX, startY, endX, endY) = box\r\n\r\n # determine the class label and color we'll use to draw\r\n # the bounding box and text\r\n # display the label and bounding box rectangle on the output\r\n # frame\r\n color = (0, 255, 0) if lable == \"Verified\" else (0, 0, 255)\r\n\r\n cv2.putText(small_frame, lable, (startX, startY - 10),\r\n cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)\r\n cv2.rectangle(small_frame, (startX, startY), (endX, endY), color, 2)\r\n\r\n cv2.imshow(\"Frame\", small_frame)\r\n key = cv2.waitKey(2) & 0xFF\r\n\r\n # if the `q` key was pressed, break from the loop\r\n if key == ord(\"q\"):\r\n lab = lable\r\n break\r\n cv2.destroyAllWindows()\r\n cam.stop()\r\n return lab\r\n\r\n" ]
[ [ "numpy.array", "tensorflow.keras.preprocessing.image.img_to_array", "tensorflow.keras.models.load_model", "tensorflow.keras.applications.mobilenet_v2.preprocess_input" ] ]
fgulan/masters-seminar
[ "cd14b305170fa619dc6e6cc9661fa213822e4faa" ]
[ "source/clcd.py" ]
[ "import sys\nimport cro_mapper\nimport os\nimport unicodedata\nimport numpy as np\nfrom scipy import misc\n\ndef _get_all_file_paths(path):\n file_paths = []\n for root, dirs, files in os.walk(path):\n for file_ in files:\n full_path = os.path.join(root, file_)\n if os.path.isfile(full_path) and full_path.endswith(\".png\"):\n file_paths.append(unicodedata.normalize('NFC', full_path))\n return file_paths\n \ndef load_dataset(path):\n print(\"Loading dataset at path:\", path)\n files = _get_all_file_paths(path)\n X = []\n y = []\n for file in files:\n image = misc.imread(file, mode='F')\n X.append(image)\n folder_path = os.path.dirname(file)\n letter = os.path.basename(folder_path)\n letter_int = cro_mapper.map_letter_to_int(letter)\n y.append(letter_int)\n return np.asarray(X), np.asarray(y)\n " ]
[ [ "scipy.misc.imread", "numpy.asarray" ] ]
Praveenstein/bigGanMicro
[ "d669874c0226907fa41b2140cdc8c46bdef2a283" ]
[ "app/gan_app.py" ]
[ "import numpy as np\nimport os\nimport json\nfrom PIL import Image\nimport pickle\nimport streamlit as st\nfrom streamlit.hashing import _CodeHasher\nfrom streamlit.report_thread import get_report_ctx\nfrom streamlit.server.server import Server\nimport sys\nimport urllib\nimport torch\nimport random\nimport biggan\nfrom torchvision.utils import make_grid\nfrom io import BytesIO\nimport base64\n\nclass NumpyEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.ndarray):\n return obj.tolist()\n return json.JSONEncoder.default(self, obj)\n\n\ndef main():\n first_run = not os.path.exists('state.json') \n state = {}\n st.title(\"Microstructure GAN demo\")\n \"\"\"This is a demonstration of conditional image generation of micrographs using [BigGAN-deep architecture](https://arxiv.org/abs/1809.11096)\n The images generated are using three conditional inputs Annealing Temperature, Annealing Time and the type of cooling used.\n GAN is trained using [Omni Loss](https://arxiv.org/abs/2011.13074) on [UHCSDB](http://uhcsdb.materials.cmu.edu/) images\"\"\"\n \n st.sidebar.title('Processing Conditions',)\n state['anneal_temp'] = st.sidebar.selectbox('Annealing Temperature °C',[700,750,800,900,970,1000,1100])\n state['anneal_time'] = st.sidebar.selectbox('Annealing Time (M: Minutes, H: Hours)',['5M','90M','1H','3H','8H','24H','48H','85H'])\n state['cooling'] = st.sidebar.selectbox('Cooling Type',['Quench','Furnace Cool','Air Cool','650C-1H'])\n temp_dict = {970: 0, 800: 1, 900: 2, 1100: 3, 1000: 4, 700: 5, 750: 6}\n time_dict = {'90M': 0, '24H': 1, '3H': 2, '5M': 3, '8H': 4, '85H': 5, '1H': 6, '48H': 7}\n cool_dict = {'Quench': 0, 'Air Cool': 1, 'Furnace Cool': 2, '650C-1H': 3}\n model = load_gan()\n st.sidebar.subheader('Generate a new latent Vector')\n state['seed'] = 7\n if st.sidebar.button('New z'):\n state['seed'] = random.randint(0,1000)\n rng = np.random.RandomState(state['seed'])\n noise = torch.tensor(rng.normal(0, 1, (1, 384))).float()\n state['noise'] = noise.numpy()\n y_temp = temp_dict[state['anneal_temp']]\n y_time = time_dict[state['anneal_time']]\n y_cool = cool_dict[state['cooling']]\n\n state['image_out'] = generate_img(model, noise, y_temp, y_time, y_cool)\n st.subheader('Generated Microstructure for the given processing conditions')\n st.text(\"\")\n st.text(f\"Random seed: {state['seed']}\")\n st.image(np.array(state['image_out']), use_column_width=False)\n\n save_bool = st.button('Save Image')\n if save_bool:\n with open('state.json', 'r') as fp:\n state_old = json.load(fp)\n st.text(f\"The following image was saved. It was generated using a random seed: {state_old['seed']}\")\n st.image(np.array(state_old['image_out']), use_column_width=False)\n if not os.path.exists('Generated Images'):\n os.makedirs('Generated Images')\n im = Image.fromarray((np.array(state_old['image_out']).reshape(256,256) * 255).astype(np.uint8))\n im.save(f\"./Generated Images/{state_old['anneal_temp']}-{state_old['anneal_time']}-{state_old['cooling']}-{state_old['seed']}.png\")\n \n state['save_bool'] = save_bool\n with open('state.json', 'w') as fp:\n json.dump(state, fp, cls=NumpyEncoder)\n \[email protected](suppress_st_warning=True)\ndef load_gan():\n model = biggan.Generator()\n model.load_state_dict(torch.load('BigGAN-deep.pth', map_location=torch.device('cpu')))\n return model\n\[email protected](suppress_st_warning=True)\ndef generate_img(model,noise, y_temp, y_time, y_cool):\n\ty_temp = torch.tensor([y_temp])\n\ty_time = torch.tensor([y_time])\n\ty_cool = torch.tensor([y_cool])\n\twith torch.no_grad():\n\t\tsynthetic = model(noise, y_temp, y_time, y_cool)[0]\n\t\tsynthetic = 0.5 * synthetic + 0.5\n\t#synthetic = make_grid(synthetic, normalize=True)\n\treturn np.transpose(synthetic.numpy() ,(1,2,0))\n\n\nmain()" ]
[ [ "torch.no_grad", "torch.tensor", "numpy.random.RandomState", "numpy.array", "torch.device" ] ]
shivachawala/PumpItUp
[ "41c8f3be0808009dbd13fda7a6f6f1ebfd916646" ]
[ "Code/Final/GridSearch/SVM.py" ]
[ "\n# coding: utf-8\n\n# In[ ]:\n\n\n#[GridSearch] SVM Learning Classification\nimport pandas as pd\nimport numpy as np\nimport sys\n# Read dataset\ndata_values = pd.read_csv(\"../../../Datasets/train_values_processed.csv\")\ndata_labels = data_values[\"status_group\"]\ndata_values.drop(['status_group'], axis=1, inplace=True)\n\n\n# In[ ]:\n\n\nfrom sklearn import metrics\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.svm import SVC\n\n#Splitting the dataset in to train and test, splitting percentage taken is 25%\nX_train, X_test, y_train, y_test = train_test_split(data_values, data_labels, test_size=0.25, random_state=42)\n\n\n# In[ ]:\n\n\n#[Model]: SVM \nmodels ={\"SVM\":SVC()}\n#[Grid Search]: Combination of features based on our trails which are best suit for this model \nparameters = {\"SVM\":{\"C\":[1,10,100],\n \"kernel\":('sigmoid', 'rbf'),\n \"gamma\":(0.01,0.1,0.5,1),\n \"max_iter\":[2000,5000,10000],\n \"random_state\":[10]}}\nclassifier = [\"SVM\"]\n#Running Grid Search on the parameters mentioned above\nfor c in classifier:\n SvmClf = GridSearchCV(models[c],parameters[c],cv=5)\n SvmClf = SvmClf.fit(X_train,y_train)\n score = SvmClf.score(X_test,y_test)\n prediction = SvmClf.predict(X_test)\n print(\"Accuracy using \",c,\" classifier is: \",score)\n print(\"-------------------------------------------\")\n print(\"Below is the confusion Matrix for \",c )\n print(metrics.confusion_matrix(y_test,prediction))\n print(\"-------------------------------------------\")\n print(\"Classification Report for \",c,\" is below\")\n print(classification_report(prediction, y_test))\n print(\"-------------------------------------------\")\n\n\n# In[ ]:\n\n\nSvmClf.best_params_\nSvmClf.best_estimator_\nSvmClf.best_score_\n\n\n# In[ ]:\n\n\nscore = SvmClf.score(X_test, y_test)\nprint(score)\n\n" ]
[ [ "sklearn.svm.SVC", "sklearn.metrics.classification_report", "pandas.read_csv", "sklearn.metrics.confusion_matrix", "sklearn.model_selection.GridSearchCV", "sklearn.model_selection.train_test_split" ] ]
maskjp/mmdetection3d
[ "98f332372b1a4c82bc2d57588a5d764f4176c869" ]
[ "mmdet3d/datasets/lyft_dataset.py" ]
[ "# Copyright (c) OpenMMLab. All rights reserved.\nimport os\nimport tempfile\nfrom os import path as osp\n\nimport mmcv\nimport numpy as np\nimport pandas as pd\nfrom lyft_dataset_sdk.lyftdataset import LyftDataset as Lyft\nfrom lyft_dataset_sdk.utils.data_classes import Box as LyftBox\nfrom pyquaternion import Quaternion\n\nfrom mmdet3d.core.evaluation.lyft_eval import lyft_eval\nfrom mmdet.datasets import DATASETS\nfrom ..core import show_result\nfrom ..core.bbox import Box3DMode, Coord3DMode, LiDARInstance3DBoxes\nfrom .custom_3d import Custom3DDataset\nfrom .pipelines import Compose\n\n\[email protected]_module()\nclass LyftDataset(Custom3DDataset):\n r\"\"\"Lyft Dataset.\n\n This class serves as the API for experiments on the Lyft Dataset.\n\n Please refer to\n `<https://www.kaggle.com/c/3d-object-detection-for-autonomous-vehicles/data>`_\n for data downloading.\n\n Args:\n ann_file (str): Path of annotation file.\n pipeline (list[dict], optional): Pipeline used for data processing.\n Defaults to None.\n data_root (str): Path of dataset root.\n classes (tuple[str], optional): Classes used in the dataset.\n Defaults to None.\n load_interval (int, optional): Interval of loading the dataset. It is\n used to uniformly sample the dataset. Defaults to 1.\n modality (dict, optional): Modality to specify the sensor data used\n as input. Defaults to None.\n box_type_3d (str, optional): Type of 3D box of this dataset.\n Based on the `box_type_3d`, the dataset will encapsulate the box\n to its original format then converted them to `box_type_3d`.\n Defaults to 'LiDAR' in this dataset. Available options includes\n\n - 'LiDAR': Box in LiDAR coordinates.\n - 'Depth': Box in depth coordinates, usually for indoor dataset.\n - 'Camera': Box in camera coordinates.\n filter_empty_gt (bool, optional): Whether to filter empty GT.\n Defaults to True.\n test_mode (bool, optional): Whether the dataset is in test mode.\n Defaults to False.\n \"\"\" # noqa: E501\n NameMapping = {\n 'bicycle': 'bicycle',\n 'bus': 'bus',\n 'car': 'car',\n 'emergency_vehicle': 'emergency_vehicle',\n 'motorcycle': 'motorcycle',\n 'other_vehicle': 'other_vehicle',\n 'pedestrian': 'pedestrian',\n 'truck': 'truck',\n 'animal': 'animal'\n }\n DefaultAttribute = {\n 'car': 'is_stationary',\n 'truck': 'is_stationary',\n 'bus': 'is_stationary',\n 'emergency_vehicle': 'is_stationary',\n 'other_vehicle': 'is_stationary',\n 'motorcycle': 'is_stationary',\n 'bicycle': 'is_stationary',\n 'pedestrian': 'is_stationary',\n 'animal': 'is_stationary'\n }\n CLASSES = ('car', 'truck', 'bus', 'emergency_vehicle', 'other_vehicle',\n 'motorcycle', 'bicycle', 'pedestrian', 'animal')\n\n def __init__(self,\n ann_file,\n pipeline=None,\n data_root=None,\n classes=None,\n load_interval=1,\n modality=None,\n box_type_3d='LiDAR',\n filter_empty_gt=True,\n test_mode=False):\n self.load_interval = load_interval\n super().__init__(\n data_root=data_root,\n ann_file=ann_file,\n pipeline=pipeline,\n classes=classes,\n modality=modality,\n box_type_3d=box_type_3d,\n filter_empty_gt=filter_empty_gt,\n test_mode=test_mode)\n\n if self.modality is None:\n self.modality = dict(\n use_camera=False,\n use_lidar=True,\n use_radar=False,\n use_map=False,\n use_external=False,\n )\n\n def load_annotations(self, ann_file):\n \"\"\"Load annotations from ann_file.\n\n Args:\n ann_file (str): Path of the annotation file.\n\n Returns:\n list[dict]: List of annotations sorted by timestamps.\n \"\"\"\n data = mmcv.load(ann_file)\n data_infos = list(sorted(data['infos'], key=lambda e: e['timestamp']))\n data_infos = data_infos[::self.load_interval]\n self.metadata = data['metadata']\n self.version = self.metadata['version']\n return data_infos\n\n def get_data_info(self, index):\n \"\"\"Get data info according to the given index.\n\n Args:\n index (int): Index of the sample data to get.\n\n Returns:\n dict: Data information that will be passed to the data\n preprocessing pipelines. It includes the following keys:\n\n - sample_idx (str): sample index\n - pts_filename (str): filename of point clouds\n - sweeps (list[dict]): infos of sweeps\n - timestamp (float): sample timestamp\n - img_filename (str, optional): image filename\n - lidar2img (list[np.ndarray], optional): transformations\n from lidar to different cameras\n - ann_info (dict): annotation info\n \"\"\"\n info = self.data_infos[index]\n\n # standard protocol modified from SECOND.Pytorch\n input_dict = dict(\n sample_idx=info['token'],\n pts_filename=info['lidar_path'],\n sweeps=info['sweeps'],\n timestamp=info['timestamp'] / 1e6,\n )\n\n if self.modality['use_camera']:\n image_paths = []\n lidar2img_rts = []\n for cam_type, cam_info in info['cams'].items():\n image_paths.append(cam_info['data_path'])\n # obtain lidar to image transformation matrix\n lidar2cam_r = np.linalg.inv(cam_info['sensor2lidar_rotation'])\n lidar2cam_t = cam_info[\n 'sensor2lidar_translation'] @ lidar2cam_r.T\n lidar2cam_rt = np.eye(4)\n lidar2cam_rt[:3, :3] = lidar2cam_r.T\n lidar2cam_rt[3, :3] = -lidar2cam_t\n intrinsic = cam_info['cam_intrinsic']\n viewpad = np.eye(4)\n viewpad[:intrinsic.shape[0], :intrinsic.shape[1]] = intrinsic\n lidar2img_rt = (viewpad @ lidar2cam_rt.T)\n lidar2img_rts.append(lidar2img_rt)\n\n input_dict.update(\n dict(\n img_filename=image_paths,\n lidar2img=lidar2img_rts,\n ))\n\n if not self.test_mode:\n annos = self.get_ann_info(index)\n input_dict['ann_info'] = annos\n\n return input_dict\n\n def get_ann_info(self, index):\n \"\"\"Get annotation info according to the given index.\n\n Args:\n index (int): Index of the annotation data to get.\n\n Returns:\n dict: Annotation information consists of the following keys:\n\n - gt_bboxes_3d (:obj:`LiDARInstance3DBoxes`):\n 3D ground truth bboxes.\n - gt_labels_3d (np.ndarray): Labels of ground truths.\n - gt_names (list[str]): Class names of ground truths.\n \"\"\"\n info = self.data_infos[index]\n gt_bboxes_3d = info['gt_boxes']\n gt_names_3d = info['gt_names']\n gt_labels_3d = []\n for cat in gt_names_3d:\n if cat in self.CLASSES:\n gt_labels_3d.append(self.CLASSES.index(cat))\n else:\n gt_labels_3d.append(-1)\n gt_labels_3d = np.array(gt_labels_3d)\n\n if 'gt_shape' in info:\n gt_shape = info['gt_shape']\n gt_bboxes_3d = np.concatenate([gt_bboxes_3d, gt_shape], axis=-1)\n\n # the lyft box center is [0.5, 0.5, 0.5], we change it to be\n # the same as KITTI (0.5, 0.5, 0)\n gt_bboxes_3d = LiDARInstance3DBoxes(\n gt_bboxes_3d,\n box_dim=gt_bboxes_3d.shape[-1],\n origin=(0.5, 0.5, 0.5)).convert_to(self.box_mode_3d)\n\n anns_results = dict(\n gt_bboxes_3d=gt_bboxes_3d,\n gt_labels_3d=gt_labels_3d,\n )\n return anns_results\n\n def _format_bbox(self, results, jsonfile_prefix=None):\n \"\"\"Convert the results to the standard format.\n\n Args:\n results (list[dict]): Testing results of the dataset.\n jsonfile_prefix (str): The prefix of the output jsonfile.\n You can specify the output directory/filename by\n modifying the jsonfile_prefix. Default: None.\n\n Returns:\n str: Path of the output json file.\n \"\"\"\n lyft_annos = {}\n mapped_class_names = self.CLASSES\n\n print('Start to convert detection format...')\n for sample_id, det in enumerate(mmcv.track_iter_progress(results)):\n annos = []\n boxes = output_to_lyft_box(det)\n sample_token = self.data_infos[sample_id]['token']\n boxes = lidar_lyft_box_to_global(self.data_infos[sample_id], boxes)\n for i, box in enumerate(boxes):\n name = mapped_class_names[box.label]\n lyft_anno = dict(\n sample_token=sample_token,\n translation=box.center.tolist(),\n size=box.wlh.tolist(),\n rotation=box.orientation.elements.tolist(),\n name=name,\n score=box.score)\n annos.append(lyft_anno)\n lyft_annos[sample_token] = annos\n lyft_submissions = {\n 'meta': self.modality,\n 'results': lyft_annos,\n }\n\n mmcv.mkdir_or_exist(jsonfile_prefix)\n res_path = osp.join(jsonfile_prefix, 'results_lyft.json')\n print('Results writes to', res_path)\n mmcv.dump(lyft_submissions, res_path)\n return res_path\n\n def _evaluate_single(self,\n result_path,\n logger=None,\n metric='bbox',\n result_name='pts_bbox'):\n \"\"\"Evaluation for a single model in Lyft protocol.\n\n Args:\n result_path (str): Path of the result file.\n logger (logging.Logger | str, optional): Logger used for printing\n related information during evaluation. Default: None.\n metric (str, optional): Metric name used for evaluation.\n Default: 'bbox'.\n result_name (str, optional): Result name in the metric prefix.\n Default: 'pts_bbox'.\n\n Returns:\n dict: Dictionary of evaluation details.\n \"\"\"\n\n output_dir = osp.join(*osp.split(result_path)[:-1])\n lyft = Lyft(\n data_path=osp.join(self.data_root, self.version),\n json_path=osp.join(self.data_root, self.version, self.version),\n verbose=True)\n eval_set_map = {\n 'v1.01-train': 'val',\n }\n metrics = lyft_eval(lyft, self.data_root, result_path,\n eval_set_map[self.version], output_dir, logger)\n\n # record metrics\n detail = dict()\n metric_prefix = f'{result_name}_Lyft'\n\n for i, name in enumerate(metrics['class_names']):\n AP = float(metrics['mAPs_cate'][i])\n detail[f'{metric_prefix}/{name}_AP'] = AP\n\n detail[f'{metric_prefix}/mAP'] = metrics['Final mAP']\n return detail\n\n def format_results(self, results, jsonfile_prefix=None, csv_savepath=None):\n \"\"\"Format the results to json (standard format for COCO evaluation).\n\n Args:\n results (list[dict]): Testing results of the dataset.\n jsonfile_prefix (str): The prefix of json files. It includes\n the file path and the prefix of filename, e.g., \"a/b/prefix\".\n If not specified, a temp file will be created. Default: None.\n csv_savepath (str): The path for saving csv files.\n It includes the file path and the csv filename,\n e.g., \"a/b/filename.csv\". If not specified,\n the result will not be converted to csv file.\n\n Returns:\n tuple: Returns (result_files, tmp_dir), where `result_files` is a\n dict containing the json filepaths, `tmp_dir` is the temporal\n directory created for saving json files when\n `jsonfile_prefix` is not specified.\n \"\"\"\n assert isinstance(results, list), 'results must be a list'\n assert len(results) == len(self), (\n 'The length of results is not equal to the dataset len: {} != {}'.\n format(len(results), len(self)))\n\n if jsonfile_prefix is None:\n tmp_dir = tempfile.TemporaryDirectory()\n jsonfile_prefix = osp.join(tmp_dir.name, 'results')\n else:\n tmp_dir = None\n\n # currently the output prediction results could be in two formats\n # 1. list of dict('boxes_3d': ..., 'scores_3d': ..., 'labels_3d': ...)\n # 2. list of dict('pts_bbox' or 'img_bbox':\n # dict('boxes_3d': ..., 'scores_3d': ..., 'labels_3d': ...))\n # this is a workaround to enable evaluation of both formats on Lyft\n # refer to https://github.com/open-mmlab/mmdetection3d/issues/449\n if not ('pts_bbox' in results[0] or 'img_bbox' in results[0]):\n result_files = self._format_bbox(results, jsonfile_prefix)\n else:\n # should take the inner dict out of 'pts_bbox' or 'img_bbox' dict\n result_files = dict()\n for name in results[0]:\n print(f'\\nFormating bboxes of {name}')\n results_ = [out[name] for out in results]\n tmp_file_ = osp.join(jsonfile_prefix, name)\n result_files.update(\n {name: self._format_bbox(results_, tmp_file_)})\n if csv_savepath is not None:\n self.json2csv(result_files['pts_bbox'], csv_savepath)\n return result_files, tmp_dir\n\n def evaluate(self,\n results,\n metric='bbox',\n logger=None,\n jsonfile_prefix=None,\n csv_savepath=None,\n result_names=['pts_bbox'],\n show=False,\n out_dir=None,\n pipeline=None):\n \"\"\"Evaluation in Lyft protocol.\n\n Args:\n results (list[dict]): Testing results of the dataset.\n metric (str | list[str], optional): Metrics to be evaluated.\n Default: 'bbox'.\n logger (logging.Logger | str, optional): Logger used for printing\n related information during evaluation. Default: None.\n jsonfile_prefix (str, optional): The prefix of json files including\n the file path and the prefix of filename, e.g., \"a/b/prefix\".\n If not specified, a temp file will be created. Default: None.\n csv_savepath (str, optional): The path for saving csv files.\n It includes the file path and the csv filename,\n e.g., \"a/b/filename.csv\". If not specified,\n the result will not be converted to csv file.\n result_names (list[str], optional): Result names in the\n metric prefix. Default: ['pts_bbox'].\n show (bool, optional): Whether to visualize.\n Default: False.\n out_dir (str, optional): Path to save the visualization results.\n Default: None.\n pipeline (list[dict], optional): raw data loading for showing.\n Default: None.\n\n Returns:\n dict[str, float]: Evaluation results.\n \"\"\"\n result_files, tmp_dir = self.format_results(results, jsonfile_prefix,\n csv_savepath)\n\n if isinstance(result_files, dict):\n results_dict = dict()\n for name in result_names:\n print(f'Evaluating bboxes of {name}')\n ret_dict = self._evaluate_single(result_files[name])\n results_dict.update(ret_dict)\n elif isinstance(result_files, str):\n results_dict = self._evaluate_single(result_files)\n\n if tmp_dir is not None:\n tmp_dir.cleanup()\n\n if show or out_dir:\n self.show(results, out_dir, show=show, pipeline=pipeline)\n return results_dict\n\n def _build_default_pipeline(self):\n \"\"\"Build the default pipeline for this dataset.\"\"\"\n pipeline = [\n dict(\n type='LoadPointsFromFile',\n coord_type='LIDAR',\n load_dim=5,\n use_dim=5,\n file_client_args=dict(backend='disk')),\n dict(\n type='LoadPointsFromMultiSweeps',\n sweeps_num=10,\n file_client_args=dict(backend='disk')),\n dict(\n type='DefaultFormatBundle3D',\n class_names=self.CLASSES,\n with_label=False),\n dict(type='Collect3D', keys=['points'])\n ]\n return Compose(pipeline)\n\n def show(self, results, out_dir, show=False, pipeline=None):\n \"\"\"Results visualization.\n\n Args:\n results (list[dict]): List of bounding boxes results.\n out_dir (str): Output directory of visualization result.\n show (bool): Whether to visualize the results online.\n Default: False.\n pipeline (list[dict], optional): raw data loading for showing.\n Default: None.\n \"\"\"\n assert out_dir is not None, 'Expect out_dir, got none.'\n pipeline = self._get_pipeline(pipeline)\n for i, result in enumerate(results):\n if 'pts_bbox' in result.keys():\n result = result['pts_bbox']\n data_info = self.data_infos[i]\n pts_path = data_info['lidar_path']\n file_name = osp.split(pts_path)[-1].split('.')[0]\n points = self._extract_data(i, pipeline, 'points').numpy()\n points = Coord3DMode.convert_point(points, Coord3DMode.LIDAR,\n Coord3DMode.DEPTH)\n inds = result['scores_3d'] > 0.1\n gt_bboxes = self.get_ann_info(i)['gt_bboxes_3d'].tensor.numpy()\n show_gt_bboxes = Box3DMode.convert(gt_bboxes, Box3DMode.LIDAR,\n Box3DMode.DEPTH)\n pred_bboxes = result['boxes_3d'][inds].tensor.numpy()\n show_pred_bboxes = Box3DMode.convert(pred_bboxes, Box3DMode.LIDAR,\n Box3DMode.DEPTH)\n show_result(points, show_gt_bboxes, show_pred_bboxes, out_dir,\n file_name, show)\n\n def json2csv(self, json_path, csv_savepath):\n \"\"\"Convert the json file to csv format for submission.\n\n Args:\n json_path (str): Path of the result json file.\n csv_savepath (str): Path to save the csv file.\n \"\"\"\n results = mmcv.load(json_path)['results']\n sample_list_path = osp.join(self.data_root, 'sample_submission.csv')\n data = pd.read_csv(sample_list_path)\n Id_list = list(data['Id'])\n pred_list = list(data['PredictionString'])\n cnt = 0\n print('Converting the json to csv...')\n for token in results.keys():\n cnt += 1\n predictions = results[token]\n prediction_str = ''\n for i in range(len(predictions)):\n prediction_str += \\\n str(predictions[i]['score']) + ' ' + \\\n str(predictions[i]['translation'][0]) + ' ' + \\\n str(predictions[i]['translation'][1]) + ' ' + \\\n str(predictions[i]['translation'][2]) + ' ' + \\\n str(predictions[i]['size'][0]) + ' ' + \\\n str(predictions[i]['size'][1]) + ' ' + \\\n str(predictions[i]['size'][2]) + ' ' + \\\n str(Quaternion(list(predictions[i]['rotation']))\n .yaw_pitch_roll[0]) + ' ' + \\\n predictions[i]['name'] + ' '\n prediction_str = prediction_str[:-1]\n idx = Id_list.index(token)\n pred_list[idx] = prediction_str\n df = pd.DataFrame({'Id': Id_list, 'PredictionString': pred_list})\n mmcv.mkdir_or_exist(os.path.dirname(csv_savepath))\n df.to_csv(csv_savepath, index=False)\n\n\ndef output_to_lyft_box(detection):\n \"\"\"Convert the output to the box class in the Lyft.\n\n Args:\n detection (dict): Detection results.\n\n Returns:\n list[:obj:`LyftBox`]: List of standard LyftBoxes.\n \"\"\"\n box3d = detection['boxes_3d']\n scores = detection['scores_3d'].numpy()\n labels = detection['labels_3d'].numpy()\n\n box_gravity_center = box3d.gravity_center.numpy()\n box_dims = box3d.dims.numpy()\n box_yaw = box3d.yaw.numpy()\n\n # our LiDAR coordinate system -> Lyft box coordinate system\n lyft_box_dims = box_dims[:, [1, 0, 2]]\n\n box_list = []\n for i in range(len(box3d)):\n quat = Quaternion(axis=[0, 0, 1], radians=box_yaw[i])\n box = LyftBox(\n box_gravity_center[i],\n lyft_box_dims[i],\n quat,\n label=labels[i],\n score=scores[i])\n box_list.append(box)\n return box_list\n\n\ndef lidar_lyft_box_to_global(info, boxes):\n \"\"\"Convert the box from ego to global coordinate.\n\n Args:\n info (dict): Info for a specific sample data, including the\n calibration information.\n boxes (list[:obj:`LyftBox`]): List of predicted LyftBoxes.\n\n Returns:\n list: List of standard LyftBoxes in the global\n coordinate.\n \"\"\"\n box_list = []\n for box in boxes:\n # Move box to ego vehicle coord system\n box.rotate(Quaternion(info['lidar2ego_rotation']))\n box.translate(np.array(info['lidar2ego_translation']))\n # Move box to global coord system\n box.rotate(Quaternion(info['ego2global_rotation']))\n box.translate(np.array(info['ego2global_translation']))\n box_list.append(box)\n return box_list\n" ]
[ [ "numpy.eye", "numpy.linalg.inv", "pandas.read_csv", "pandas.DataFrame", "numpy.array", "numpy.concatenate" ] ]
Martin36/FEVER2021_SharedTask
[ "4dd49e0ddf2909a93d44dab22eae988a067fc355" ]
[ "src/entailment/entailment_with_t5.py" ]
[ "import argparse\nfrom collections import defaultdict\nimport torch\n\nfrom transformers import T5ForConditionalGeneration, T5Tokenizer\nfrom tqdm import tqdm\nfrom util.util_funcs import load_jsonl\n\nmodel = T5ForConditionalGeneration.from_pretrained(\"t5-small\")\ntokenizer = T5Tokenizer.from_pretrained(\"t5-small\")\n\nMNLI_TO_FEVER_MAP = {\n \"▁entailment\": \"SUPPORTS\",\n \"▁neutral\": \"NOT ENOUGH INFO\",\n \"▁contradiction\": \"REFUTES\",\n}\n\nstats = defaultdict(int)\n\n\ndef predict_veracity(claim, evidence):\n # task = \"rte\"\n task = \"mnli\"\n if task == \"mnli\":\n input_str = \"{} premise: {} hypothesis: {}\".format(task, evidence, claim)\n if task == \"rte\":\n input_str = \"{} sentence1: {} sentence2: {}\".format(task, claim, evidence)\n\n input_ids = tokenizer(input_str, return_tensors=\"pt\").input_ids\n\n result = model.generate(input_ids)\n result = torch.squeeze(result)\n target = tokenizer.convert_ids_to_tokens(result, skip_special_tokens=True)\n\n return target\n\n\ndef get_veracity_label(claim, evidence):\n predicted_label = predict_veracity(claim, evidence)\n predicted_label = \"\".join(predicted_label)\n if predicted_label not in MNLI_TO_FEVER_MAP.keys():\n return \"NOT ENOUGH INFO\"\n else:\n return MNLI_TO_FEVER_MAP[predicted_label]\n\n\ndef test_model(data):\n num_correct = 0\n counter = 0\n for d in tqdm(data):\n # if counter > 200: break\n claim = d[\"claim\"]\n evidence = d[\"evidence\"]\n label = d[\"label\"]\n stats[\"nr_of_{}_samples\".format(label)] += 1\n predicted_label = predict_veracity(claim, evidence)\n predicted_label = \"\".join(predicted_label)\n if predicted_label not in MNLI_TO_FEVER_MAP.keys():\n # Assume that all invalid predicted labels means not enough information\n if label == \"NOT ENOUGH INFO\":\n stats[\"nr_of_correct_{}_samples\".format(label)] += 1\n num_correct += 1\n else:\n if label == MNLI_TO_FEVER_MAP[predicted_label]:\n stats[\"nr_of_correct_{}_samples\".format(label)] += 1\n num_correct += 1\n counter += 1\n accuracy = num_correct / counter\n\n print(\"Accuracy for {} samples: {}\".format(len(data), accuracy))\n print()\n print(\"========== STATS ============\")\n for label in MNLI_TO_FEVER_MAP.values():\n print(\n \"Nr of {} samples: {}\".format(\n label, stats[\"nr_of_{}_samples\".format(label)]\n )\n )\n print(\n \"Nr of correct {} samples: {}\".format(\n label, stats[\"nr_of_correct_{}_samples\".format(label)]\n )\n )\n if stats[\"nr_of_{}_samples\".format(label)] > 0:\n amount_correct = (\n stats[\"nr_of_correct_{}_samples\".format(label)]\n / stats[\"nr_of_{}_samples\".format(label)]\n )\n else:\n amount_correct = 1.0\n print(\"Amount of correct {} samples: {}\".format(label, amount_correct))\n print()\n print(\"=============================\")\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Extracts the text from the feverous db and creates a corpus\"\n )\n parser.add_argument(\n \"--data_path\",\n default=None,\n type=str,\n help=\"Path to the file containing the training data\",\n )\n\n args = parser.parse_args()\n\n if not args.data_path:\n raise RuntimeError(\"Invalid train data path\")\n\n data = load_jsonl(args.data_path)\n test_model(data)\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "torch.squeeze" ] ]
wangyum/anaconda
[ "6e5a0dbead3327661d73a61e85414cf92aa52be6" ]
[ "pkgs/statsmodels-0.6.1-np110py27_0/lib/python2.7/site-packages/statsmodels/emplike/aft_el.py" ]
[ "\"\"\"\n\nAccelerated Failure Time (AFT) Model with empirical likelihood inference.\n\nAFT regression analysis is applicable when the researcher has access\nto a randomly right censored dependent variable, a matrix of exogenous\nvariables and an indicatior variable (delta) that takes a value of 0 if the\nobservation is censored and 1 otherwise.\n\nAFT References\n--------------\n\nStute, W. (1993). \"Consistent Estimation Under Random Censorship when\nCovariables are Present.\" Journal of Multivariate Analysis.\nVol. 45. Iss. 1. 89-103\n\nEL and AFT References\n---------------------\n\nZhou, Kim And Bathke. \"Empirical Likelihood Analysis for the Heteroskedastic\nAccelerated Failure Time Model.\" Manuscript:\nURL: www.ms.uky.edu/~mai/research/CasewiseEL20080724.pdf\n\nZhou, M. (2005). Empirical Likelihood Ratio with Arbitrarily Censored/\nTruncated Data by EM Algorithm. Journal of Computational and Graphical\nStatistics. 14:3, 643-656.\n\n\n\"\"\"\n\nimport numpy as np\nfrom statsmodels.regression.linear_model import OLS, WLS\nfrom statsmodels.tools import add_constant\n#from elregress import ElReg\nfrom scipy import optimize\nfrom scipy.stats import chi2\nfrom .descriptive import _OptFuncts\nimport warnings\nfrom statsmodels.tools.sm_exceptions import IterationLimitWarning\n\nclass OptAFT(_OptFuncts):\n \"\"\"\n Provides optimization functions used in estimating and conducting\n inference in an AFT model.\n\n Methods\n ------\n\n _opt_wtd_nuis_regress:\n Function optimized over nuisance parameters to compute\n the profile likelihood\n\n _EM_test:\n Uses the modified Em algorithm of Zhou 2005 to maximize the\n likelihood of a parameter vector.\n\n \"\"\"\n def __init__(self):\n pass\n\n def _opt_wtd_nuis_regress(self, test_vals):\n \"\"\"\n A function that is optimized over nuisance parameters to conduct a\n hypothesis test for the parameters of interest\n\n Parameters\n ----------\n\n params: 1d array\n The regression coefficients of the model. This includes the\n nuisance and parameters of interests.\n\n Returns\n -------\n\n llr: float\n -2 times the log likelihood of the nuisance parameters and the\n hypothesized value of the parameter(s) of interest.\n\n \"\"\"\n test_params = test_vals.reshape(self.model.nvar, 1)\n est_vect = self.model.uncens_exog * (self.model.uncens_endog -\n np.dot(self.model.uncens_exog,\n test_params))\n eta_star = self._modif_newton(np.zeros(self.model.nvar), est_vect,\n self.model._fit_weights)\n denom = np.sum(self.model._fit_weights) + np.dot(eta_star, est_vect.T)\n self.new_weights = self.model._fit_weights / denom\n return -1 * np.sum(np.log(self.new_weights))\n\n def _EM_test(self, nuisance_params, params=None, param_nums=None,\n b0_vals=None, F=None, survidx=None, uncens_nobs=None,\n numcensbelow=None, km=None, uncensored=None, censored=None,\n maxiter=None, ftol=None):\n \"\"\"\n Uses EM algorithm to compute the maximum likelihood of a test\n\n Parameters\n ---------\n\n Nuisance Params: array\n Vector of values to be used as nuisance params.\n\n maxiter: int\n Number of iterations in the EM algorithm for a parameter vector\n\n Returns\n -------\n -2 ''*'' log likelihood ratio at hypothesized values and\n nuisance params\n\n Notes\n -----\n Optional parameters are provided by the test_beta function.\n \"\"\"\n iters = 0\n params[param_nums] = b0_vals\n\n nuis_param_index = np.int_(np.delete(np.arange(self.model.nvar),\n param_nums))\n params[nuis_param_index] = nuisance_params\n to_test = params.reshape(self.model.nvar, 1)\n opt_res = np.inf\n diff = np.inf\n while iters < maxiter and diff > ftol:\n F = F.flatten()\n death = np.cumsum(F[::-1])\n survivalprob = death[::-1]\n surv_point_mat = np.dot(F.reshape(-1, 1),\n 1. / survivalprob[survidx].reshape(1, - 1))\n surv_point_mat = add_constant(surv_point_mat)\n summed_wts = np.cumsum(surv_point_mat, axis=1)\n wts = summed_wts[np.int_(np.arange(uncens_nobs)),\n numcensbelow[uncensored]]\n # ^E step\n # See Zhou 2005, section 3.\n self.model._fit_weights = wts\n new_opt_res = self._opt_wtd_nuis_regress(to_test)\n # ^ Uncensored weights' contribution to likelihood value.\n F = self.new_weights\n # ^ M step\n diff = np.abs(new_opt_res - opt_res)\n opt_res = new_opt_res\n iters = iters + 1\n death = np.cumsum(F.flatten()[::-1])\n survivalprob = death[::-1]\n llike = -opt_res + np.sum(np.log(survivalprob[survidx]))\n wtd_km = km.flatten() / np.sum(km)\n survivalmax = np.cumsum(wtd_km[::-1])[::-1]\n llikemax = np.sum(np.log(wtd_km[uncensored])) + \\\n np.sum(np.log(survivalmax[censored]))\n if iters == maxiter:\n warnings.warn('The EM reached the maximum number of iterations',\n IterationLimitWarning)\n return -2 * (llike - llikemax)\n\n def _ci_limits_beta(self, b0, param_num=None):\n \"\"\"\n Returns the difference between the log likelihood for a\n parameter and some critical value.\n\n Parameters\n ---------\n b0: float\n Value of a regression parameter\n\n param_num: int\n Parameter index of b0\n \"\"\"\n return self.test_beta([b0], [param_num])[0] - self.r0\n\n\nclass emplikeAFT(object):\n \"\"\"\n\n Class for estimating and conducting inference in an AFT model.\n\n Parameters\n ---------\n\n endog: nx1 array\n Response variables that are subject to random censoring\n\n exog: nxk array\n Matrix of covariates\n\n censors: nx1 array\n array with entries 0 or 1. 0 indicates a response was\n censored.\n\n Attributes\n ----------\n\n nobs: float\n Number of observations\n\n endog: array\n Endog attay\n\n exog: array\n Exogenous variable matrix\n\n censors\n Censors array but sets the max(endog) to uncensored\n\n nvar: float\n Number of exogenous variables\n\n uncens_nobs: float\n Number of uncensored observations\n\n uncens_endog: array\n Uncensored response variables\n\n uncens_exog: array\n Exogenous variables of the uncensored observations\n\n Methods\n -------\n\n params:\n Fits model parameters\n\n test_beta:\n Tests if beta = b0 for any vector b0.\n\n Notes\n -----\n\n The data is immediately sorted in order of increasing endogenous\n variables\n\n The last observation is assumed to be uncensored which makes\n estimation and inference possible.\n \"\"\"\n def __init__(self, endog, exog, censors):\n self.nobs = float(np.shape(exog)[0])\n self.endog = endog.reshape(self.nobs, 1)\n self.exog = exog.reshape(self.nobs, -1)\n self.censors = censors.reshape(self.nobs, 1)\n self.nvar = self.exog.shape[1]\n idx = np.lexsort((-self.censors[:, 0], self.endog[:, 0]))\n self.endog = self.endog[idx]\n self.exog = self.exog[idx]\n self.censors = self.censors[idx]\n self.censors[-1] = 1 # Sort in init, not in function\n self.uncens_nobs = np.sum(self.censors)\n mask = self.censors.ravel().astype(bool)\n self.uncens_endog = self.endog[mask, :].reshape(-1, 1)\n self.uncens_exog = self.exog[mask, :]\n\n\n def _is_tied(self, endog, censors):\n \"\"\"\n Indicated if an observation takes the same value as the next\n ordered observation.\n\n Parameters\n ----------\n endog: array\n Models endogenous variable\n censors: array\n arrat indicating a censored array\n\n Returns\n -------\n indic_ties: array\n ties[i]=1 if endog[i]==endog[i+1] and\n censors[i]=censors[i+1]\n \"\"\"\n nobs = int(self.nobs)\n endog_idx = endog[np.arange(nobs - 1)] == (\n endog[np.arange(nobs - 1) + 1])\n censors_idx = censors[np.arange(nobs - 1)] == (\n censors[np.arange(nobs - 1) + 1])\n indic_ties = endog_idx * censors_idx # Both true\n return np.int_(indic_ties)\n\n def _km_w_ties(self, tie_indic, untied_km):\n \"\"\"\n Computes KM estimator value at each observation, taking into acocunt\n ties in the data.\n\n Parameters\n ----------\n tie_indic: 1d array\n Indicates if the i'th observation is the same as the ith +1\n untied_km: 1d array\n Km estimates at each observation assuming no ties.\n\n \"\"\"\n # TODO: Vectorize, even though it is only 1 pass through for any\n # function call\n num_same = 1\n idx_nums = []\n for obs_num in np.arange(int(self.nobs - 1))[::-1]:\n if tie_indic[obs_num] == 1:\n idx_nums.append(obs_num)\n num_same = num_same + 1\n untied_km[obs_num] = untied_km[obs_num + 1]\n elif tie_indic[obs_num] == 0 and num_same > 1:\n idx_nums.append(max(idx_nums) + 1)\n idx_nums = np.asarray(idx_nums)\n untied_km[idx_nums] = untied_km[idx_nums]\n num_same = 1\n idx_nums = []\n return untied_km.reshape(self.nobs, 1)\n\n def _make_km(self, endog, censors):\n \"\"\"\n\n Computes the Kaplan-Meier estimate for the weights in the AFT model\n\n Parameters\n ----------\n endog: nx1 array\n Array of response variables\n censors: nx1 array\n Censor-indicating variable\n\n Returns\n -------\n Kaplan Meier estimate for each observation\n\n Notes\n -----\n\n This function makes calls to _is_tied and km_w_ties to handle ties in\n the data.If a censored observation and an uncensored observation has\n the same value, it is assumed that the uncensored happened first.\n\n \"\"\"\n nobs = self.nobs\n num = (nobs - (np.arange(nobs) + 1.))\n denom = ((nobs - (np.arange(nobs) + 1.) + 1.))\n km = (num / denom).reshape(nobs, 1)\n km = km ** np.abs(censors - 1.)\n km = np.cumprod(km) # If no ties, this is kaplan-meier\n tied = self._is_tied(endog, censors)\n wtd_km = self._km_w_ties(tied, km)\n return (censors / wtd_km).reshape(nobs, 1)\n\n def fit(self):\n \"\"\"\n\n Fits an AFT model and returns results instance\n\n Parameters\n ---------\n None\n\n\n Returns\n -------\n Results instance.\n\n Notes\n -----\n To avoid dividing by zero, max(endog) is assumed to be uncensored.\n \"\"\"\n return AFTResults(self)\n\n def predict(self, params, endog=None):\n if endog is None:\n endog = self.endog\n return np.dot(endog, params)\n\n\nclass AFTResults(OptAFT):\n def __init__(self, model):\n self.model = model\n\n def params(self):\n \"\"\"\n\n Fits an AFT model and returns parameters.\n\n Parameters\n ---------\n None\n\n\n Returns\n -------\n Fitted params\n\n Notes\n -----\n To avoid dividing by zero, max(endog) is assumed to be uncensored.\n \"\"\"\n self.model.modif_censors = np.copy(self.model.censors)\n self.model.modif_censors[-1] = 1\n wts = self.model._make_km(self.model.endog, self.model.modif_censors)\n res = WLS(self.model.endog, self.model.exog, wts).fit()\n params = res.params\n return params\n\n def test_beta(self, b0_vals, param_nums, ftol=10 ** - 5, maxiter=30,\n print_weights=1):\n \"\"\"\n Returns the profile log likelihood for regression parameters\n 'param_num' at 'b0_vals.'\n\n Parameters\n ----------\n b0_vals: list\n The value of parameters to be tested\n\n param_num: list\n Which parameters to be tested\n\n maxiter: int, optional\n How many iterations to use in the EM algorithm. Default is 30\n\n ftol: float, optional\n The function tolerance for the EM optimization.\n Default is 10''**''-5\n\n print_weights: bool\n If true, returns the weights tate maximize the profile\n log likelihood. Default is False\n\n Returns\n -------\n\n test_results: tuple\n The log-likelihood and p-pvalue of the test.\n\n Notes\n ----\n\n The function will warn if the EM reaches the maxiter. However, when\n optimizing over nuisance parameters, it is possible to reach a\n maximum number of inner iterations for a specific value for the\n nuisance parameters while the resultsof the function are still valid.\n This usually occurs when the optimization over the nuisance parameters\n selects paramater values that yield a log-likihood ratio close to\n infinity.\n\n Examples\n -------\n\n import statsmodels.api as sm\n import numpy as np\n\n # Test parameter is .05 in one regressor no intercept model\n data=sm.datasets.heart.load()\n y = np.log10(data.endog)\n x = data.exog\n cens = data.censors\n model = sm.emplike.emplikeAFT(y, x, cens)\n res=model.test_beta([0], [0])\n >>>res\n >>>(1.4657739632606308, 0.22601365256959183)\n\n #Test slope is 0 in model with intercept\n\n data=sm.datasets.heart.load()\n y = np.log10(data.endog)\n x = data.exog\n cens = data.censors\n model = sm.emplike.emplikeAFT(y, sm.add_constant(x), cens)\n res=model.test_beta([0], [1])\n >>>res\n >>>(4.623487775078047, 0.031537049752572731)\n\n \"\"\"\n censors = self.model.censors\n endog = self.model.endog\n exog = self.model.exog\n uncensored = (censors == 1).flatten()\n censored = (censors == 0).flatten()\n uncens_endog = endog[uncensored]\n uncens_exog = exog[uncensored, :]\n reg_model = OLS(uncens_endog, uncens_exog).fit()\n llr, pval, new_weights = reg_model.el_test(b0_vals, param_nums,\n return_weights=True) # Needs to be changed\n km = self.model._make_km(endog, censors).flatten() # when merged\n uncens_nobs = self.model.uncens_nobs\n F = np.asarray(new_weights).reshape(uncens_nobs)\n # Step 0 ^\n params = self.params()\n survidx = np.where(censors == 0)\n survidx = survidx[0] - np.arange(len(survidx[0]))\n numcensbelow = np.int_(np.cumsum(1 - censors))\n if len(param_nums) == len(params):\n llr = self._EM_test([], F=F, params=params,\n param_nums=param_nums,\n b0_vals=b0_vals, survidx=survidx,\n uncens_nobs=uncens_nobs,\n numcensbelow=numcensbelow, km=km,\n uncensored=uncensored, censored=censored,\n ftol=ftol, maxiter=25)\n return llr, chi2.sf(llr, self.model.nvar)\n else:\n x0 = np.delete(params, param_nums)\n try:\n res = optimize.fmin(self._EM_test, x0,\n (params, param_nums, b0_vals, F, survidx,\n uncens_nobs, numcensbelow, km, uncensored,\n censored, maxiter, ftol), full_output=1,\n disp=0)\n\n llr = res[1]\n return llr, chi2.sf(llr, len(param_nums))\n except np.linalg.linalg.LinAlgError:\n return np.inf, 0\n\n def ci_beta(self, param_num, beta_high, beta_low, sig=.05):\n \"\"\"\n Returns the confidence interval for a regression\n parameter in the AFT model.\n\n Parameters\n ---------\n\n param_num: int\n Parameter number of interest\n\n beta_high: float\n Upper bound for the confidence interval\n\n beta_low:\n Lower bound for the confidence interval\n\n sig: float, optional\n Significance level. Default is .05\n\n Notes\n ----\n If the function returns f(a) and f(b) must have different signs,\n consider widening the search area by adjusting beta_low and\n beta_high.\n\n Also note that this process is computational intensive. There\n are 4 levels of optimization/solving. From outer to inner:\n\n 1) Solving so that llr-critical value = 0\n 2) maximizing over nuisance parameters\n 3) Using EM at each value of nuisamce parameters\n 4) Using the _modified_Newton optimizer at each iteration\n of the EM algorithm.\n\n Also, for very unlikely nuisance parameters, it is possible for\n the EM algorithm to not converge. This is not an indicator\n that the solver did not find the correct solution. It just means\n for a specific iteration of the nuisance parameters, the optimizer\n was unable to converge.\n\n If the user desires to verify the success of the optimization,\n it is recommended to test the limits using test_beta.\n\n \"\"\"\n params = self.params()\n self.r0 = chi2.ppf(1 - sig, 1)\n ll = optimize.brentq(self._ci_limits_beta, beta_low,\n params[param_num], (param_num))\n ul = optimize.brentq(self._ci_limits_beta,\n params[param_num], beta_high, (param_num))\n return ll, ul\n" ]
[ [ "numpy.sum", "numpy.asarray", "numpy.int_", "numpy.copy", "numpy.log", "numpy.abs", "numpy.delete", "scipy.optimize.fmin", "numpy.where", "numpy.zeros", "scipy.stats.chi2.ppf", "numpy.lexsort", "numpy.cumprod", "numpy.arange", "numpy.cumsum", "scipy.optimize.brentq", "numpy.shape", "scipy.stats.chi2.sf", "numpy.dot" ] ]
mberaha/ProjectedWasserstein
[ "20d19fc49f20124762eb497031cba0918b5eaadb" ]
[ "pwass/regression/simplicial.py" ]
[ "import numpy as np\nfrom sklearn.base import BaseEstimator\n\nfrom pwass.spline import SplineBasis\nfrom pwass.distributions import Distribution\n\n\nclass SimpliciadDistribOnDistrib(BaseEstimator):\n def __init__(self, fit_intercept=True, nbasis=-1, spline_basis=None,\n compute_spline=True):\n self.fit_intercept = fit_intercept\n self.nbasis = nbasis\n self.spline_basis = spline_basis\n self.compute_spline = compute_spline\n\n def _initialize(self, X):\n if self.spline_basis is None:\n self.spline_basis = SplineBasis(\n 2, nbasis=self.nbasis, xgrid=X[0].pdf_grid)\n else:\n self.nbasis = self.spline_basis.nbasis\n\n self.spline_basis.eval_metric()\n\n def fit(self, X, Y):\n self._initialize(X)\n self.n_samples = len(X)\n self.X = X\n self.Y = Y\n\n if self.compute_spline:\n for x in self.X:\n x.xbasis = self.spline_basis\n x.compute_spline_expansions()\n\n for y in self.Y:\n y.xbasis = self.spline_basis\n y.compute_spline_expansions()\n\n self.Xmat = self.get_spline_mat(self.X)\n self.Ymat = self.get_spline_mat(self.Y)\n if self.fit_intercept:\n self.Xmat = np.hstack(\n [np.ones(self.n_samples).reshape(-1, 1), self.Xmat])\n\n self.beta = np.linalg.solve(\n np.matmul(self.Xmat.T, self.Xmat),\n np.matmul(self.Xmat.T, self.Ymat))\n\n def predict(self, Xnew):\n if self.compute_spline:\n for x in Xnew:\n x.xbasis = self.spline_basis\n x.compute_spline_expansions()\n\n Xmat = self.get_spline_mat(Xnew)\n Ypred = np.zeros_like(Xmat)\n\n if self.fit_intercept:\n Xmat = np.hstack(\n [np.ones(Xmat.shape[0]).reshape(-1, 1), Xmat])\n\n out = []\n for i in range(Xmat.shape[0]):\n y_ = np.matmul(Xmat[i, :], self.beta)\n curr = Distribution(smooth_sigma=Xnew[0].smooth_sigma)\n curr.init_from_clr(\n self.spline_basis.xgrid, self.spline_basis.eval_spline(y_))\n out.append(curr)\n\n return out\n\n def get_spline_mat(self, distribs):\n \"\"\"Stacks all the coefficient of the spline expansions by row\n \"\"\"\n out = np.zeros((len(distribs), self.nbasis))\n for i, d in enumerate(distribs):\n out[i, :] = d.clr_coeffs\n\n eps = np.ones(out.shape[1]) * 1e-6\n for i in range(out.shape[1]):\n out[:, i] += np.sum(eps[:i])\n\n return out\n" ]
[ [ "numpy.zeros_like", "numpy.matmul", "numpy.sum", "numpy.ones" ] ]
Ursinus-IDS301-S2020/Week9Class
[ "c8173f9f793fedb1cee6e71d272282766861a8eb" ]
[ "ClassMDS.py" ]
[ "\"\"\"\nPurpose: To show how to use \"Multidimensional Scaling\" (MDS)\nto find a set of coordinates in 2D that best respect a matrix.\n\nIn this particular example, students gave a distance matrix\nwhere they expressed how similar they thought different majors \nwere to each other. This code loops through all student\nsubmissions and plots the results of MDS so we can see\nspatially where the students place these majors in relation\nto each other\n\"\"\"\nfrom sklearn.manifold import MDS\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import pairwise_distances\nimport glob\n\ndef draw_distance_matrix(D, labels, vmax = None):\n \"\"\"\n Plot a distance matrix with labels in each element\n Parameters\n ----------\n D: narray(N, N)\n A distance matrix\n labels: list (N)\n A list of strings to label each row\n vmax: float\n The max distance to which to scale the plots\n (by default, just the max distance of the matrix,\n but this can be used to make sure colorbars are\n consistent across plots)\n \"\"\"\n if not vmax:\n vmax = np.max(D)\n N = D.shape[0]\n plt.imshow(D, interpolation='none', cmap='magma_r', vmin=0, vmax=vmax)\n plt.colorbar()\n for i in range(N):\n for j in range(N):\n plt.text(j-0.4, i, \"%.2g\"%D[i, j], c='white')\n plt.xticks(np.arange(N), labels, rotation=90)\n plt.yticks(np.arange(N), labels)\n plt.ylim([N, -1])\n\n\nlabels = [\"Art History\", \"English\", \"Math\", \"CS\", \"Physics\", \"Philosophy\", \"Politics\"]\n\n# The \"glob\" library can be used to list all of the files\n# in a directory that match a specified pattern. In this\n# case, we want all of the csv files in the ratings directory\nfiles = glob.glob(\"Ratings/*.csv\")\n\n# Loop through each student's ratings\nfor f in files:\n # Load in the rating that a particular student gave\n D = np.loadtxt(f, delimiter=',')\n # Use the filename to figure out the student's name\n student = f.split(\"/\")[-1][0:-4]\n # Just in case the student didn't make a symmetric matrix\n # (where Dij = Dji), make it symmetric now by averaging\n # all pairs Dij and Dji\n D = 0.5*(D+D.T)\n \n # Compute multidimensional scaling to find coordinates\n # in 2D that best respect the desired distances\n embedding = MDS(n_components=2, dissimilarity='precomputed')\n X = embedding.fit_transform(D)\n # Compute the distances of the points after MDS\n # so we can compare how close they are to the spec\n DMDS = pairwise_distances(X)\n\n # Plot the results\n plt.figure(figsize=(16, 5))\n plt.subplot(131)\n draw_distance_matrix(D, labels, vmax=1)\n plt.title(\"%s's Original Distances\"%student)\n\n plt.subplot(132)\n draw_distance_matrix(DMDS, labels, vmax=1)\n plt.title(\"MDS distances Distances\")\n\n plt.subplot(133)\n plt.scatter(X[:, 0], X[:, 1])\n for i, label in enumerate(labels):\n plt.text(X[i, 0], X[i, 1], label)\n plt.title(\"MDS Coordinates\")\n plt.tight_layout()\n plt.show()" ]
[ [ "matplotlib.pyplot.scatter", "sklearn.manifold.MDS", "matplotlib.pyplot.figure", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.title", "numpy.arange", "matplotlib.pyplot.imshow", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "numpy.max", "matplotlib.pyplot.ylim", "matplotlib.pyplot.text", "matplotlib.pyplot.colorbar", "numpy.loadtxt", "sklearn.metrics.pairwise_distances" ] ]
HiramHerrera/desisim
[ "3ae76e4c921f72b71ff7522462740e904136f428" ]
[ "etc/sim_quercus/mpi_newexp_random.py" ]
[ "\nfrom mpi4py import MPI\n\nimport sys\nimport os\nimport argparse\nimport traceback\n\nimport numpy as np\n\nfrom desispec.util import option_list\n\nfrom desispec.parallel import stdouterr_redirected\n\nfrom desisim import obs\n\nimport desisim.scripts.newexp_random as newexp\n\n\nflavors = ['arc', 'arc', 'arc', \n 'flat', 'flat', 'flat', \n 'dark', 'gray', 'bright'\n ]\n\nnights = [\n '20191001',\n '20191002',\n '20191003',\n '20191004',\n '20191005'\n]\n\nntask = len(flavors) * len(nights)\n\ncomm = MPI.COMM_WORLD\nif comm.size < ntask:\n if comm.rank == 0:\n print(\"Communicator size ({}) too small for {} tasks\".format(comm.size, ntask), flush=True)\n comm.Abort()\n\nnp.random.seed(123456)\nseeds = np.random.randint(2**32, size=ntask)\n\nexpids = None\nif comm.rank == 0:\n expids = obs.get_next_expid(ntask)\nexpids = comm.bcast(expids, root=0)\n\ntileids = list()\nif comm.rank == 0:\n for nt in nights:\n for fl in flavors:\n flavor = fl.lower()\n t = obs.get_next_tileid(program=flavor)\n tileids.append(t)\n if flavor in ('arc', 'flat'):\n obs.update_obslog(obstype=flavor, program='calib', tileid=t)\n elif flavor in ('bright', 'bgs', 'mws'):\n obs.update_obslog(obstype='science', program='bright', tileid=t)\n elif flavor in ('gray', 'grey'):\n obs.update_obslog(obstype='science', program='gray', tileid=t)\n else:\n obs.update_obslog(obstype='science', program='dark', tileid=t)\n\ntileids = comm.bcast(tileids, root=0)\n\nif comm.rank == 0:\n simdir = os.path.join(os.environ['DESI_SPECTRO_SIM'], \n os.environ['PIXPROD'])\n etcdir = os.path.join(simdir, 'etc')\n if not os.path.isdir(etcdir):\n os.makedirs(etcdir)\n for nt in nights:\n ntdir = os.path.join(simdir, nt)\n if not os.path.isdir(ntdir):\n os.makedirs(ntdir)\n\ncomm.barrier()\n\ntaskproc = 1\n\ncomm_group = comm\ncomm_rank = None\ngroup = comm.rank\nngroup = comm.size\ngroup_rank = 0\nif comm is not None:\n if taskproc > 1:\n ngroup = int(nproc / taskproc)\n group = int(rank / taskproc)\n group_rank = rank % taskproc\n comm_group = comm.Split(color=group, key=group_rank)\n comm_rank = comm.Split(color=group_rank, key=group)\n else:\n comm_group = MPI.COMM_SELF\n comm_rank = comm\n\nlog_root = \"newexp_\"\n\ntask = 0\nfor nt in nights:\n for fl in flavors:\n tasklog = \"{}{}-{:08d}.log\".format(log_root, nt, expids[task])\n if task == group:\n with stdouterr_redirected(to=tasklog, comm=comm_group):\n try:\n options = {}\n options[\"program\"] = fl\n options[\"night\"] = nt\n options[\"expid\"] = expids[task]\n options[\"tileid\"] = tileids[task]\n options[\"seed\"] = seeds[task]\n #options[\"nproc\"] = 1\n optarray = option_list(options)\n args = newexp.parse(optarray)\n newexp.main(args)\n except:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(\"\".join(lines), flush=True)\n task += 1\n\n" ]
[ [ "numpy.random.randint", "numpy.random.seed" ] ]