repo_name
stringlengths 6
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence | possible_versions
list |
---|---|---|---|---|---|
CMU-Light-Curtains/SafetyEnvelopes | [
"e2b32f99437ea36c8b22f97470c5a7f406d3ec78"
] | [
"policies/actors/nn/features/residual.py"
] | [
"from dataclasses import dataclass\nfrom typing import Optional, List\nimport numpy as np\n\nfrom devices.light_curtain import LCReturn\nimport utils\n\n\ndef _components_from_size(np_array: np.ndarray,\n sizes: List[int]):\n sizes = np.array(sizes, dtype=np.int)\n ends = sizes.cumsum()\n starts = ends - sizes\n components = [np_array[:, start:end] for start, end in zip(starts, ends)]\n return components\n\n\n@dataclass\nclass CurtainInfo:\n i: Optional[np.ndarray] # intensity for each camera ray, shape = (B, C)\n x: Optional[np.ndarray] # x coord for each camera ray, shape = (B, C)\n z: Optional[np.ndarray] # z coord for each camera ray, shape = (B, C)\n r: Optional[np.ndarray] # range for each camera ray, shape = (B, C)\n t: Optional[np.ndarray] # theta for each camera ray, shape = (B, C)\n\n def __getitem__(self, s):\n return CurtainInfo(self.i[s],\n self.x[s],\n self.z[s],\n self.r[s],\n self.t[s])\n\n def __sub__(self, other):\n return CurtainInfo(None, # difference of intensities doesn't make sense, shouldn't be used\n self.x - other.x,\n self.z - other.z,\n self.r - other.r,\n self.t - other.t)\n\n def to_numpy(self) -> np.ndarray:\n return np.hstack([\n self.i,\n self.x,\n self.z,\n self.r,\n self.t\n ]).astype(np.float32) # (B, 5C)\n\n @staticmethod\n def from_numpy(np_array: np.ndarray) -> 'CurtainInfo':\n assert np_array.ndim == 2\n assert (np_array.shape[1]) % 5 == 0, f\"CurtainInfo.from_numpy(): shape is {np_array.shape}\"\n C = np_array.shape[1] // 5\n\n components = _components_from_size(np_array, sizes=[C, C, C, C, C])\n return CurtainInfo(*components)\n\n\n@dataclass\nclass NNResidualFeatures:\n c1: CurtainInfo\n c2: CurtainInfo\n rb: np.ndarray # ranges of base policy action\n\n def to_numpy(self) -> np.ndarray:\n return np.hstack([\n self.c1.to_numpy(), # (B, 5C)\n self.c2.to_numpy(), # (B, 5C)\n self.rb # (B, C)\n ]).astype(np.float32)\n\n @staticmethod\n def from_numpy(np_array: np.ndarray) -> 'NNResidualFeatures':\n assert np_array.ndim == 2\n assert np_array.shape[1] % 11 == 0, f\"NNResidualFeatures.from_numpy(): shape is {np_array.shape}\"\n C = np_array.shape[1] // 11\n\n components = _components_from_size(np_array, sizes=[5*C, 5*C, C])\n\n c1 = CurtainInfo.from_numpy(components[0])\n c2 = CurtainInfo.from_numpy(components[1])\n rb = components[2]\n\n return NNResidualFeatures(c1, c2, rb)\n\n def feat_dim(C: int):\n return 11 * C\n\n\nclass NNResidualFeaturizer:\n def __init__(self,\n thetas: np.ndarray):\n \"\"\"\n Args:\n thetas (np.ndarray, dtype=np.float32, shape=(C,)): thetas of the camera rays (in degrees).\n \"\"\"\n self._thetas = thetas\n\n # parameters\n self._LC_INTENSITY_THRESH = 200\n\n @property\n def C(self):\n return len(self._thetas)\n\n @property\n def feat_dim(self):\n return NNResidualFeatures.feat_dim(self.C)\n\n def obs_to_curtain_info(self,\n lc_return: LCReturn) -> CurtainInfo:\n i = lc_return.bev_hits(ithresh=self._LC_INTENSITY_THRESH) # (C,)\n r = lc_return.lc_ranges # (C,)\n t = self._thetas\n design_pts = utils.design_pts_from_ranges(r, t) # (C, 2)\n x, z = design_pts[:, 0], design_pts[:, 1] # (C,) and (C,)\n\n i, x, z, r, t = [np.atleast_2d(e).astype(np.float32) for e in [i, x, z, r, t]] # (1, C) each\n\n return CurtainInfo(i, x, z, r, t)\n\n @staticmethod\n def cinfos2feats(c1: CurtainInfo,\n c2: CurtainInfo,\n base_act: np.ndarray) -> NNResidualFeatures:\n \"\"\"\n Computing the features for predicting actions at time t.\n NNResidualFeatures are extracted from curtain info at times t-1 and t-2.\n\n Args:\n c1 (CurtainInfo): info about the curtain placed at time t-2.\n c2 (CurtainInfo): info about the curtain placed at time t-1.\n base_act (np.ndarray, dtype=np.float32, shape=(C,)): action of the base policy at time t-1 using input2.\n \"\"\"\n base_act = np.atleast_2d(base_act).astype(np.float32) # (1, C)\n feats = NNResidualFeatures(c1, c2, base_act)\n return feats\n\n def cinfos2numpy(self,\n c1: CurtainInfo,\n c2: CurtainInfo,\n base_act: np.ndarray) -> np.ndarray:\n feats = self.cinfos2feats(c1, c2, base_act)\n return feats.to_numpy()\n"
] | [
[
"numpy.hstack",
"numpy.array",
"numpy.atleast_2d"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
afcarl/fed-rates-bot | [
"2c65fb834075ce9a1b145394fd4297bdaa803487"
] | [
"fed_bot/tests/tests.py"
] | [
"__author__ = 'allentran'\n\nimport numpy as np\n\nfrom ..scraper import Scraper\nfrom ..model import lstm, lstm_lasagne\n\ndef model_test():\n\n n_sentences = 6\n T = 21\n n_batch = 7\n vocab_size=55\n word_vector_size=111\n\n test_ob = dict(\n word_vectors=np.random.randint(0, vocab_size, size=(T, n_sentences, n_batch)).astype('int32'),\n rates=np.ones((n_batch, 3)).astype('float32'),\n max_mask=np.ones((T, n_sentences, n_batch)).astype('float32'),\n regimes=np.ones(n_batch).astype('int32'),\n doc_types=np.ones(n_batch).astype('int32')\n )\n\n word_embeddings = np.random.normal(0, 1, size=(vocab_size, word_vector_size)).astype('float32')\n\n assert word_embeddings[test_ob['word_vectors']].shape == (T, n_sentences, n_batch, word_vector_size)\n\n model = lstm.FedLSTM(\n vocab_size=vocab_size,\n hidden_size=9,\n lstm_size=12,\n n_mixtures=2,\n word_vectors=word_embeddings,\n doctype_size=7,\n regime_size=4,\n input_size=word_vector_size\n )\n\n first_cost = model.get_cost_and_update(\n test_ob['word_vectors'],\n test_ob['rates'],\n test_ob['max_mask'],\n test_ob['regimes'],\n test_ob['doc_types']\n )\n\n for _ in xrange(5):\n last_cost = model.get_cost_and_update(\n test_ob['word_vectors'],\n test_ob['rates'],\n test_ob['max_mask'],\n test_ob['regimes'],\n test_ob['doc_types']\n )\n\n assert first_cost > last_cost\n\ndef lasagne_test():\n\n n_batch = 5\n n_sentence = 4\n n_words = 11\n n_targets = 3\n n_mixtures = 2\n vocab_size = 20\n word_size = 6\n\n word_vectors = np.random.randn(vocab_size, word_size).astype('float32')\n\n fedlstm_model = lstm_lasagne.FedLSTMLasagne(vocab_size, word_size, 50, 13, 10, target_size=n_targets, n_mixtures=n_mixtures, init_word_vectors=word_vectors)\n\n targets = np.random.randn(n_batch, n_targets).astype('float32')\n words = np.random.randint(0, 10, size=(n_batch, n_sentence, n_words)).astype('int32')\n\n first_cost = fedlstm_model._train(\n words,\n 10 * np.ones((n_batch, n_sentence)).astype('int32'),\n 3 * np.ones((n_batch)).astype('int32'),\n np.ones(5).astype('int32'),\n np.ones(5).astype('int32'),\n targets\n )\n\n for _ in xrange(10):\n last_cost = fedlstm_model._train(\n words,\n 10 * np.ones((n_batch, n_sentence)).astype('int32'),\n 3 * np.ones((n_batch)).astype('int32'),\n np.ones(5).astype('int32'),\n np.ones(5).astype('int32'),\n targets\n )\n\n assert first_cost > last_cost\n\ndef scraper_test():\n\n scraper = Scraper()\n assert len(scraper.get_docs(limit=1)) == 1\n\n"
] | [
[
"numpy.random.normal",
"numpy.ones",
"numpy.random.randn",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
NadimKawwa/CybersecurityThreatIdentification | [
"e088dbb861342676337b4c9d385e6abfb6463291"
] | [
"combine_wild_cve.py"
] | [
"import os\nimport glob\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\nimport pickle\nfrom copy import copy\n\n\ndef load_obj(path ):\n with open(path, 'rb') as f:\n return pickle.load(f)\n\n\ndef main():\n \"\"\"\n combines everything into one csv file\n \"\"\"\n #reading from manually curated sources\n sources_with_data_text = os.path.join('data', 'sources_with_data.txt')\n with open (sources_with_data_text, mode='r') as f:\n lines = f.readlines()\n\n #check we closed the file\n assert f.closed\n\n #strip the spaces at the end\n lines = [l.strip() for l in lines]\n #keep only CVEs and drop the rest\n lines = [l for l in lines if 'CVE' in l]\n #remove redundants\n unique_cve = (set(lines))\n \n \n #create list of dicts\n broadcom_arr=[]\n for file in tqdm(glob.glob('broadcom_dicts/*.pkl')):\n obj = load_obj(file)\n #if array is not empty\n if obj['CVE']:\n broadcom_arr.extend(obj['CVE'])\n\n #make a set to remove duplicates\n broadcom_cve = (set(broadcom_arr))\n \n #make deep copy\n cve_in_wild = copy(broadcom_cve)\n #combine the two sets\n cve_in_wild.update(unique_cve)\n #some stats\n print(\"Found {} unique CVEs overall\".format(len(cve_in_wild)))\n \n \n \n #########################################################################################\n #NOTE!!!!!\n # This section involves manual cleaning for data\n # Corrections for edge cases\n \n \n #fix some inconsistencies in data collection\n #manual fixes\n cve_in_wild = [cve.replace('1)', '') for cve in cve_in_wild]\n cve_in_wild = [cve.replace('service', '') for cve in cve_in_wild]\n cve_in_wild = [cve.replace('3)', '') for cve in cve_in_wild]\n cve_in_wild = [cve.replace('_3', '') for cve in cve_in_wild]\n cve_in_wild = [cve for cve in cve_in_wild if len(cve)>=11]\n cve_in_wild = [cve.replace('(', '') for cve in cve_in_wild]\n cve_in_wild = [cve.replace(')', '') for cve in cve_in_wild]\n\n\n ## more manual fixes to corrupted data\n cve_in_wild = [cve.replace('CVE2019-7278', 'CVE-2019-7278') for cve in cve_in_wild]\n cve_in_wild = [cve.replace('2CVE-2006-3643', 'CVE-2006-3643') for cve in cve_in_wild]\n cve_in_wild = [cve.replace('CVE2019-7279', 'CVE-2019-7279') for cve in cve_in_wild]\n cve_in_wild = [cve.replace('CVE-2018_16858', 'CVE-2018-16858') for cve in cve_in_wild]\n cve_in_wild = [cve.replace('CVE 2014-6278', 'CVE-2014-6278') for cve in cve_in_wild]\n cve_in_wild = [cve.replace('CVE-209-18935', 'CVE-2019-18935') for cve in cve_in_wild]\n cve_in_wild = [cve.replace('CVE_2009-3729', 'CVE-2009-3729') for cve in cve_in_wild]\n cve_in_wild = [cve.replace('CVE-20190-11539', 'CVE-2019-11539') for cve in cve_in_wild]\n cve_in_wild = [cve.replace('CVE-2190-11539', 'CVE-2019-11539') for cve in cve_in_wild]\n\n \n #########################################################################################\n \n \n \n #more stats\n dates = set([x.split('-')[1] for x in cve_in_wild])\n print(\"First exploit was recorded in {}\".format(min(dates)))\n print(\"Last exploit was recorded in {}\".format(max(dates)))\n \n #make empty dict to create target variable\n target_cve_dict = {}\n #read the main reference: NVD\n df_nvd = pd.read_csv(os.path.join('data', 'nvdcve_combined.csv'))\n #for each CVE\n for cve in df_nvd['ID']:\n if cve in cve_in_wild:\n target_cve_dict[cve] = 1\n else:\n target_cve_dict[cve] = 0\n\n #make adataframe\n df_target = pd.DataFrame.from_dict(target_cve_dict, orient='index', columns=['in_the_wild'])\n #index to column\n df_target['ID'] = df_target.index\n #drop index when done\n df_target = df_target.reset_index(drop=True)\n\n #rearrange\n df_target = df_target[['ID', 'in_the_wild']]\n \n #to csv\n save_path = os.path.join('data', 'target_cve.csv')\n \n \n df_target.to_csv(save_path, index=False)\n print(\"saved to... {}\".format(save_path))\n\n\n \nif __name__ == \"__main__\":\n main()\n \n \n\n \n \n \n "
] | [
[
"pandas.DataFrame.from_dict"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
code4days/URLNet | [
"e5119168d6d1b681e74a8807d8b4075811b2b78a"
] | [
"test.py"
] | [
"from utils import * \nimport pickle \nimport time \nfrom tqdm import tqdm\nimport argparse\nimport numpy as np \nimport pickle \nimport tensorflow as tf \nfrom tensorflow.contrib import learn \nfrom tflearn.data_utils import to_categorical, pad_sequences\n\nparser = argparse.ArgumentParser(description=\"Test URLNet model\")\n\n# data args\ndefault_max_len_words = 200\nparser.add_argument('--data.max_len_words', type=int, default=default_max_len_words, metavar=\"MLW\",\n help=\"maximum length of url in words (default: {})\".format(default_max_len_words))\ndefault_max_len_chars = 200\nparser.add_argument('--data.max_len_chars', type=int, default=default_max_len_chars, metavar=\"MLC\",\n help=\"maximum length of url in characters (default: {})\".format(default_max_len_chars))\ndefault_max_len_subwords = 20\nparser.add_argument('--data.max_len_subwords', type=int, default=default_max_len_subwords, metavar=\"MLSW\",\n help=\"maxium length of word in subwords/ characters (default: {})\".format(default_max_len_subwords))\nparser.add_argument('--data.data_dir', type=str, default='train_10000.txt', metavar=\"DATADIR\",\n help=\"location of data file\")\ndefault_delimit_mode = 1\nparser.add_argument(\"--data.delimit_mode\", type=int, default=default_delimit_mode, metavar=\"DLMODE\",\n help=\"0: delimit by special chars, 1: delimit by special chars + each char as a word (default: {})\".format(default_delimit_mode))\nparser.add_argument('--data.subword_dict_dir', type=str, default=\"runs/10000/subwords_dict.p\", metavar=\"SUBWORD_DICT\", \n\thelp=\"directory of the subword dictionary\")\nparser.add_argument('--data.word_dict_dir', type=str, default=\"runs/10000/word_dict.p\", metavar=\"WORD_DICT\",\n\thelp=\"directory of the word dictionary\")\nparser.add_argument('--data.char_dict_dir', type=str, default=\"runs/10000/char_dict.p\", metavar=\"\tCHAR_DICT\",\n\thelp=\"directory of the character dictionary\")\n\n# model args \ndefault_emb_dim = 32\nparser.add_argument('--model.emb_dim', type=int, default=default_emb_dim, metavar=\"EMBDIM\",\n help=\"embedding dimension size (default: {})\".format(default_emb_dim))\ndefault_emb_mode = 1\nparser.add_argument('--model.emb_mode', type=int, default=default_emb_mode, metavar=\"EMBMODE\",\n help=\"1: charCNN, 2: wordCNN, 3: char + wordCNN, 4: char-level wordCNN, 5: char + char-level wordCNN (default: {})\".format(default_emb_mode))\n\n# test args \ndefault_batch_size = 128\nparser.add_argument('--test.batch_size', type=int, default=default_batch_size, metavar=\"BATCHSIZE\",\n help=\"Size of each test batch (default: {})\".format(default_batch_size))\n\n# log args \nparser.add_argument('--log.output_dir', type=str, default=\"runs/10000/\", metavar=\"OUTPUTDIR\",\n help=\"directory to save the test results\")\nparser.add_argument('--log.checkpoint_dir', type=str, default=\"runs/10000/checkpoints/\", metavar=\"CHECKPOINTDIR\",\n\thelp=\"directory of the learned model\")\n\nFLAGS = vars(parser.parse_args())\nfor key, val in FLAGS.items():\n\tprint(\"{}={}\".format(key, val))\n\nurls, labels = read_data(FLAGS[\"data.data_dir\"]) \n \nx, word_reverse_dict = get_word_vocab(urls, FLAGS[\"data.max_len_words\"]) \nword_x = get_words(x, word_reverse_dict, FLAGS[\"data.delimit_mode\"], urls) \n\nngram_dict = pickle.load(open(FLAGS[\"data.subword_dict_dir\"], \"rb\")) \nprint(\"Size of subword vocabulary (train): {}\".format(len(ngram_dict)))\nword_dict = pickle.load(open(FLAGS[\"data.word_dict_dir\"], \"rb\"))\nprint(\"size of word vocabulary (train): {}\".format(len(word_dict)))\nngramed_id_x, worded_id_x = ngram_id_x_from_dict(word_x, FLAGS[\"data.max_len_subwords\"], ngram_dict, word_dict) \nchars_dict = pickle.load(open(FLAGS[\"data.char_dict_dir\"], \"rb\")) \nchared_id_x = char_id_x(urls, chars_dict, FLAGS[\"data.max_len_chars\"]) \n\nprint(\"Number of testing urls: {}\".format(len(labels)))\n\n######################## EVALUATION ########################### \n\ndef test_step(x, emb_mode):\n p = 1.0\n if emb_mode == 1: \n feed_dict = {\n input_x_char_seq: x[0],\n dropout_keep_prob: p} \n elif emb_mode == 2: \n feed_dict = {\n input_x_word: x[0],\n dropout_keep_prob: p}\n elif emb_mode == 3: \n feed_dict = {\n input_x_char_seq: x[0],\n input_x_word: x[1],\n dropout_keep_prob: p}\n elif emb_mode == 4: \n feed_dict = {\n input_x_word: x[0],\n input_x_char: x[1],\n input_x_char_pad_idx: x[2],\n dropout_keep_prob: p}\n elif emb_mode == 5: \n feed_dict = {\n input_x_char_seq: x[0],\n input_x_word: x[1],\n input_x_char: x[2],\n input_x_char_pad_idx: x[3],\n dropout_keep_prob: p}\n preds, s = sess.run([predictions, scores], feed_dict)\n return preds, s\n\ncheckpoint_file = tf.train.latest_checkpoint(FLAGS[\"log.checkpoint_dir\"])\ngraph = tf.Graph() \nwith graph.as_default(): \n session_conf = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)\n session_conf.gpu_options.allow_growth=True \n sess = tf.Session(config=session_conf)\n with sess.as_default(): \n saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file))\n saver.restore(sess, checkpoint_file) \n \n if FLAGS[\"model.emb_mode\"] in [1, 3, 5]: \n input_x_char_seq = graph.get_operation_by_name(\"input_x_char_seq\").outputs[0]\n if FLAGS[\"model.emb_mode\"] in [2, 3, 4, 5]:\n input_x_word = graph.get_operation_by_name(\"input_x_word\").outputs[0]\n if FLAGS[\"model.emb_mode\"] in [4, 5]:\n input_x_char = graph.get_operation_by_name(\"input_x_char\").outputs[0]\n input_x_char_pad_idx = graph.get_operation_by_name(\"input_x_char_pad_idx\").outputs[0]\n dropout_keep_prob = graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0] \n\n predictions = graph.get_operation_by_name(\"output/predictions\").outputs[0]\n scores = graph.get_operation_by_name(\"output/scores\").outputs[0]\n \n if FLAGS[\"model.emb_mode\"] == 1: \n batches = batch_iter(list(chared_id_x), FLAGS[\"test.batch_size\"], 1, shuffle=False) \n elif FLAGS[\"model.emb_mode\"] == 2: \n batches = batch_iter(list(worded_id_x), FLAGS[\"test.batch_size\"], 1, shuffle=False) \n elif FLAGS[\"model.emb_mode\"] == 3: \n batches = batch_iter(list(zip(chared_id_x, worded_id_x)), FLAGS[\"test.batch_size\"], 1, shuffle=False)\n elif FLAGS[\"model.emb_mode\"] == 4: \n batches = batch_iter(list(zip(ngramed_id_x, worded_id_x)), FLAGS[\"test.batch_size\"], 1, shuffle=False)\n elif FLAGS[\"model.emb_mode\"] == 5: \n batches = batch_iter(list(zip(ngramed_id_x, worded_id_x, chared_id_x)), FLAGS[\"test.batch_size\"], 1, shuffle=False) \n all_predictions = []\n all_scores = []\n \n nb_batches = int(len(labels) / FLAGS[\"test.batch_size\"])\n if len(labels) % FLAGS[\"test.batch_size\"] != 0: \n nb_batches += 1 \n print(\"Number of batches in total: {}\".format(nb_batches))\n it = tqdm(range(nb_batches), desc=\"emb_mode {} delimit_mode {} test_size {}\".format(FLAGS[\"model.emb_mode\"], FLAGS[\"data.delimit_mode\"], len(labels)), ncols=0)\n for idx in it:\n #for batch in batches:\n batch = next(batches)\n\n if FLAGS[\"model.emb_mode\"] == 1: \n x_char_seq = batch \n elif FLAGS[\"model.emb_mode\"] == 2: \n x_word = batch \n elif FLAGS[\"model.emb_mode\"] == 3: \n x_char_seq, x_word = zip(*batch) \n elif FLAGS[\"model.emb_mode\"] == 4: \n x_char, x_word = zip(*batch)\n elif FLAGS[\"model.emb_mode\"] == 5: \n x_char, x_word, x_char_seq = zip(*batch) \n\n x_batch = [] \n if FLAGS[\"model.emb_mode\"] in[1, 3, 5]: \n x_char_seq = pad_seq_in_word(x_char_seq, FLAGS[\"data.max_len_chars\"]) \n x_batch.append(x_char_seq)\n if FLAGS[\"model.emb_mode\"] in [2, 3, 4, 5]:\n x_word = pad_seq_in_word(x_word, FLAGS[\"data.max_len_words\"]) \n x_batch.append(x_word)\n if FLAGS[\"model.emb_mode\"] in [4, 5]:\n x_char, x_char_pad_idx = pad_seq(x_char, FLAGS[\"data.max_len_words\"], FLAGS[\"data.max_len_subwords\"], FLAGS[\"model.emb_dim\"])\n x_batch.extend([x_char, x_char_pad_idx])\n \n batch_predictions, batch_scores = test_step(x_batch, FLAGS[\"model.emb_mode\"]) \n all_predictions = np.concatenate([all_predictions, batch_predictions]) \n all_scores.extend(batch_scores) \n\n it.set_postfix()\n\nif labels is not None: \n correct_preds = float(sum(all_predictions == labels)) \n print(\"Accuracy: {}\".format(correct_preds/float(len(labels))))\n\nsave_test_result(labels, all_predictions, all_scores, FLAGS[\"log.output_dir\"]) \n"
] | [
[
"tensorflow.Graph",
"tensorflow.train.latest_checkpoint",
"tensorflow.ConfigProto",
"numpy.concatenate",
"tensorflow.Session"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
ymjiang/imagenet18 | [
"c8c3806156d93c0c1fef1054803a241b89034ccb"
] | [
"training/dist_utils.py"
] | [
"import torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel\nimport os\nimport byteps.torch as bps\n\nclass DDP(DistributedDataParallel):\n # Distributed wrapper. Supports asynchronous evaluation and model saving\n def forward(self, *args, **kwargs):\n # DDP has a sync point on forward. No need to do this for eval. This allows us to have different batch sizes\n if self.training: return super().forward(*args, **kwargs)\n else: return self.module(*args, **kwargs)\n\n def load_state_dict(self, *args, **kwargs):\n self.module.load_state_dict(*args, **kwargs)\n\n def state_dict(self, *args, **kwargs):\n return self.module.state_dict(*args, **kwargs)\n \n\n\n\ndef reduce_tensor(tensor): return sum_tensor(tensor)/env_world_size()\ndef sum_tensor(tensor):\n rt = tensor.clone()\n dist.all_reduce(rt, op=dist.reduce_op.SUM)\n return rt\n\ndef env_world_size():\n return bps.size()\ndef env_rank():\n return bps.rank()\n\n"
] | [
[
"torch.distributed.all_reduce"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rk2900/Unbiased-Learning-to-Rank-with-Unbiased-Propensity-Estimation | [
"85bb4241f18e4d118ac46961f55f6edb47509bc7"
] | [
"Unbiased_LTR/DLA/main.py"
] | [
"\"\"\"Training and testing the dual learning algorithm for unbiased learning to rank.\n\nSee the following paper for more information on the dual learning algorithm.\n\t\n\t* Qingyao Ai, Keping Bi, Cheng Luo, Jiafeng Guo, W. Bruce Croft. 2018. Unbiased Learning to Rank with Unbiased Propensity Estimation. In Proceedings of SIGIR '18\n\t\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport os\nimport random\nimport sys\nimport time\nimport numpy as np\nfrom six.moves import xrange\t# pylint: disable=redefined-builtin\nimport tensorflow as tf\nimport json\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nimport data_utils\nfrom DLA_model import DLA\nimport click_models as cm\n\n#rank list size should be read from data\ntf.app.flags.DEFINE_string(\"data_dir\", \"/tmp/\", \"Data directory\")\ntf.app.flags.DEFINE_string(\"train_dir\", \"./tmp/\", \"Training directory.\")\ntf.app.flags.DEFINE_string(\"test_dir\", \"./tmp/\", \"Directory for output test results.\")\ntf.app.flags.DEFINE_string(\"click_model_json\", \"\", \"Josn file for the click model used to generate clicks.\")\ntf.app.flags.DEFINE_string(\"hparams\", \"\", \"Hyper-parameters for models.\")\n\ntf.app.flags.DEFINE_integer(\"batch_size\", 256,\n\t\t\t\t\t\t\t\"Batch size to use during training.\")\ntf.app.flags.DEFINE_integer(\"train_list_cutoff\", 10,\n\t\t\t\t\t\t\t\"The number of documents to consider in each list during training.\")\ntf.app.flags.DEFINE_integer(\"max_train_iteration\", 0,\n\t\t\t\t\t\t\t\"Limit on the iterations of training (0: no limit).\")\ntf.app.flags.DEFINE_integer(\"steps_per_checkpoint\", 200,\n\t\t\t\t\t\t\t\"How many training steps to do per checkpoint.\")\ntf.app.flags.DEFINE_boolean(\"use_non_clicked_data\", False,\n\t\t\t\t\t\t\t\"Set to True for estimating propensity weights for non-click data.\")\ntf.app.flags.DEFINE_boolean(\"decode\", False,\n\t\t\t\t\t\t\t\"Set to True for decoding data.\")\ntf.app.flags.DEFINE_boolean(\"decode_train\", False,\n\t\t\t\t\t\t\t\"Set to True for decoding training data.\")\n# To be discarded.\ntf.app.flags.DEFINE_boolean(\"feed_previous\", False,\n \"Set to True for feed previous internal output for training.\")\n\n\n\nFLAGS = tf.app.flags.FLAGS\n\n\ndef create_model(session, data_set, forward_only):\n\t\"\"\"Create model and initialize or load parameters in session.\"\"\"\n\tclick_model = None\n\twith open(FLAGS.click_model_json) as fin:\n\t\tmodel_desc = json.load(fin)\n\t\tclick_model = cm.loadModelFromJson(model_desc)\n\t\n\tmodel = DLA(click_model, data_set.rank_list_size, \n\t\tdata_set.embed_size, FLAGS.batch_size, FLAGS.hparams, forward_only, FLAGS.feed_previous)\n\n\tckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)\n\tif ckpt:\n\t\tprint(\"Reading model parameters from %s\" % ckpt.model_checkpoint_path)\n\t\tmodel.saver.restore(session, ckpt.model_checkpoint_path)\n\telse:\n\t\tprint(\"Created model with fresh parameters.\")\n\t\tsession.run(tf.global_variables_initializer())\n\treturn model\n\n\ndef train():\n\t# Prepare data.\n\tprint(\"Reading data in %s\" % FLAGS.data_dir)\n\t\n\ttrain_set = data_utils.read_data(FLAGS.data_dir, 'train', FLAGS.train_list_cutoff)\n\tvalid_set = data_utils.read_data(FLAGS.data_dir, 'valid', FLAGS.train_list_cutoff)\n\tprint(\"Rank list size %d\" % train_set.rank_list_size)\n\n\tconfig = tf.ConfigProto()\n\tconfig.gpu_options.allow_growth = True\n\twith tf.Session(config=config) as sess:\n\t\t# Create model.\n\t\tprint(\"Creating model...\")\n\t\tmodel = create_model(sess, train_set, False)\n\t\tprint(\"Created %d layers of %d units.\" % (model.hparams.num_layers, model.embed_size))\n\n\t\t# Create tensorboard summarizations.\n\t\ttrain_writer = tf.summary.FileWriter(FLAGS.train_dir + '/train_log',\n\t\t\t\t\t\t\t\t\t\tsess.graph)\n\t\tvalid_writer = tf.summary.FileWriter(FLAGS.train_dir + '/valid_log')\n\n\t\t#pad data\n\t\ttrain_set.pad(train_set.rank_list_size)\n\t\tvalid_set.pad(valid_set.rank_list_size)\n\n\n\t\t# This is the training loop.\n\t\tstep_time, loss = 0.0, 0.0\n\t\tcurrent_step = 0\n\t\tprevious_losses = []\n\t\tbest_loss = None\n\t\twhile True:\n\t\t\t# Get a batch and make a step.\n\t\t\tstart_time = time.time()\n\t\t\tinput_feed, _ = model.get_batch(train_set)\n\t\t\tstep_loss, _, summary = model.step(sess, input_feed, False)\n\t\t\tstep_time += (time.time() - start_time) / FLAGS.steps_per_checkpoint\n\t\t\tloss += step_loss / FLAGS.steps_per_checkpoint\n\t\t\tcurrent_step += 1\n\t\t\ttrain_writer.add_summary(summary, current_step)\n\n\t\t\t# Once in a while, we save checkpoint, print statistics, and run evals.\n\t\t\tif current_step % FLAGS.steps_per_checkpoint == 0:\n\t\t\t\t\n\t\t\t\t# Print statistics for the previous epoch.\n\t\t\t\t#loss = math.exp(loss) if loss < 300 else float('inf')\n\t\t\t\tprint (\"global step %d learning rate %.4f step-time %.2f loss \"\n\t\t\t\t\t\t\t \"%.2f\" % (model.global_step.eval(), model.learning_rate.eval(),\n\t\t\t\t\t\t\t\t\t\t\t\t step_time, loss))\n\t\t\t\t#train_writer.add_summary({'step-time':step_time, 'loss':loss}, current_step)\n\n\t\t\t\t# Decrease learning rate if no improvement was seen over last 3 times.\n\t\t\t\t#if len(previous_losses) > 2 and loss > max(previous_losses[-3:]):\n\t\t\t\t#\tsess.run(model.learning_rate_decay_op)\n\t\t\t\tprevious_losses.append(loss)\n\n\t\t\t\t# Validate model\n\t\t\t\tit = 0\n\t\t\t\tcount_batch = 0.0\n\t\t\t\tvalid_loss = 0\n\t\t\t\twhile it < len(valid_set.initial_list) - model.batch_size:\n\t\t\t\t\tinput_feed, _ = model.get_next_batch(it, valid_set)\n\t\t\t\t\tv_loss, results, summary = model.step(sess, input_feed, True)\n\t\t\t\t\tit += model.batch_size\n\t\t\t\t\tvalid_loss += v_loss\n\t\t\t\t\tcount_batch += 1.0\n\t\t\t\tvalid_writer.add_summary(summary, current_step)\n\t\t\t\tvalid_loss /= count_batch\n\t\t\t\t#valid_loss = math.exp(valid_loss) if valid_loss < 300 else float('inf')\n\t\t\t\tprint(\" eval: loss %.2f\" % (valid_loss))\n\n\t\t\t\t# Save checkpoint and zero timer and loss. # need to rethink\n\t\t\t\t#if best_loss == None or best_loss >= eval_ppx:\n\t\t\t\t#\tbest_loss = eval_ppx\n\t\t\t\tcheckpoint_path = os.path.join(FLAGS.train_dir, \"DLA.ckpt\")\n\t\t\t\tmodel.saver.save(sess, checkpoint_path, global_step=model.global_step)\n\t\t\t\t\n\t\t\t\tif loss == float('inf'):\n\t\t\t\t\tbreak\n\n\t\t\t\tstep_time, loss = 0.0, 0.0\n\t\t\t\tsys.stdout.flush()\n\n\t\t\t\tif FLAGS.max_train_iteration > 0 and current_step > FLAGS.max_train_iteration:\n\t\t\t\t\tbreak\n\n\n\ndef decode():\n\tconfig = tf.ConfigProto()\n\tconfig.gpu_options.allow_growth = True\n\twith tf.Session(config=config) as sess:\n\t\t# Load test data.\n\t\tprint(\"Reading data in %s\" % FLAGS.data_dir)\n\t\ttest_set = None\n\t\tif FLAGS.decode_train:\n\t\t\ttest_set = data_utils.read_data(FLAGS.data_dir,'train')\n\t\telse:\n\t\t\ttest_set = data_utils.read_data(FLAGS.data_dir,'test')\n\n\t\t# Create model and load parameters.\n\t\tmodel = create_model(sess, test_set, True)\n\t\tmodel.batch_size = 1\t# We decode one sentence at a time.\n\n\t\ttest_set.pad(test_set.rank_list_size)\n\n\t\trerank_scores = []\n\n\t\t# Decode from test data.\n\t\tfor i in xrange(len(test_set.initial_list)):\n\t\t\tinput_feed, _ = model.get_data_by_index(test_set, i)\n\t\t\ttest_loss, output_logits, summary = model.step(sess, input_feed, True)\n\n\t\t\t#The output is a list of rerank index for decoder_inputs (which represents the gold rank list)\n\t\t\trerank_scores.append(output_logits[0])\n\t\t\tif i % FLAGS.steps_per_checkpoint == 0:\n\t\t\t\tprint(\"Decoding %.2f \\r\" % (float(i)/len(test_set.initial_list))),\n\n\t\t#get rerank indexes with new scores\n\t\trerank_lists = []\n\t\tfor i in xrange(len(rerank_scores)):\n\t\t\tscores = rerank_scores[i]\n\t\t\trerank_lists.append(sorted(range(len(scores)), key=lambda k: scores[k], reverse=True))\n\n\t\tif FLAGS.decode_train:\n\t\t\tdata_utils.output_ranklist(test_set, rerank_scores, FLAGS.test_dir, 'train')\n\t\telse:\n\t\t\tdata_utils.output_ranklist(test_set, rerank_scores, FLAGS.test_dir, 'test')\n\n\treturn\n\n#done\ndef self_test():\n\t\"\"\"Test the DLA model.\"\"\"\n\tprint('Self Test')\n\tos.system('rm -r ./tmp/*')\n\t# Prepare data.\n\tFLAGS.data_dir += 'sample_500/'\n\tprint(\"Reading data in %s\" % FLAGS.data_dir)\n\ttrain_set = data_utils.read_data(FLAGS.data_dir, 'train', FLAGS.train_list_cutoff)\n\tvalid_set = data_utils.read_data(FLAGS.data_dir, 'valid', FLAGS.train_list_cutoff)\n\tprint(\"Rank list size %d\" % train_set.rank_list_size)\n\n\tconfig = tf.ConfigProto()\n\tconfig.gpu_options.allow_growth = True\n\twith tf.Session(config=config) as sess:\n\t\t# Create model.\n\t\tprint(\"Creating model...\")\n\t\tmodel = create_model(sess, train_set, False)\n\t\tprint(\"Created %d layers of %d units.\" % (model.hparams.num_layers, model.embed_size))\n\t\t# Create tensorboard summarizations.\n\t\ttrain_writer = tf.summary.FileWriter(FLAGS.train_dir + '/train_log',\n\t\t\t\t\t\t\t\t\t\tsess.graph)\n\t\tvalid_writer = tf.summary.FileWriter(FLAGS.train_dir + '/valid_log')\n\t\t#pad data\n\t\ttrain_set.pad(train_set.rank_list_size)\n\t\tvalid_set.pad(valid_set.rank_list_size)\n\n\t\t# This is the training loop.\n\t\tstep_time, loss = 0.0, 0.0\n\t\tcurrent_step = 0\n\t\tprevious_losses = []\n\t\tbest_loss = None\n\t\tprint('Start Training')\n\t\twhile True:\n\t\t\t# Get a batch and make a step.\n\t\t\tstart_time = time.time()\n\t\t\tinput_feed, others = model.get_batch(train_set)\n\t\t\tstep_loss, _, summary = model.step(sess, input_feed, False)\n\t\t\tstep_time += (time.time() - start_time) / FLAGS.steps_per_checkpoint\n\t\t\tloss += step_loss / FLAGS.steps_per_checkpoint\n\t\t\tcurrent_step += 1\n\t\t\ttrain_writer.add_summary(summary, current_step)\n\n\n\t\t\t# Once in a while, we save checkpoint, print statistics, and run evals.\n\t\t\tif current_step % FLAGS.steps_per_checkpoint == 0:\n\t\t\t\t'''\n\t\t\t\tfor k in xrange(3):\n\t\t\t\t\tq_idx = others['rank_list_idxs'][k]\n\t\t\t\t\tprint('Initial list')\n\t\t\t\t\tprint(train_set.initial_list[q_idx])\n\t\t\t\t\tprint('Features')\n\t\t\t\t\tprint(train_set.features[train_set.initial_list[q_idx][5]][4:10])\n\t\t\t\t\tprint('Embeddings')\n\t\t\t\t\tprint(others['embeddings'][others['input_list'][k][5]][4:10])\n\t\t\t\t\tprint('Encoder Inputs')\n\t\t\t\t\tprint(others['input_list'][k])\n\t\t\t\t\tprint('Gold labels')\n\t\t\t\t\tprint(train_set.gold_weights[q_idx])\n\t\t\t\t\t#print('Outputs')\n\t\t\t\t\t#print(results[k])\n\t\t\t\t\tprint('Decoder Clicks')\n\t\t\t\t\tprint(others['click_list'][k])\n\t\t\t\t\tprint('Propensity Weights')\n\t\t\t\t\tprint(others['propensity_weights'][k])\n\t\t\t\t\tprint('\\n')\n\t\t\t\t'''\n\n\t\t\t\t# Print statistics for the previous epoch.\n\t\t\t\t#loss = math.exp(loss) if loss < 300 else float('inf')\n\t\t\t\tprint (\"global step %d learning rate %.4f step-time %.2f loss \"\n\t\t\t\t\t\t\t \"%.2f\" % (model.global_step.eval(), model.learning_rate.eval(),\n\t\t\t\t\t\t\t\t\t\t\t\t step_time, loss))\n\t\t\t\t\n\n\t\t\t\t# Decrease learning rate if no improvement was seen over last 3 times.\n\t\t\t\t#if len(previous_losses) > 2 and loss > max(previous_losses[-3:]):\n\t\t\t\t#\tsess.run(model.learning_rate_decay_op)\n\t\t\t\tprevious_losses.append(loss)\n\n\t\t\t\tif loss == float('inf'):\n\t\t\t\t\tbreak\n\n\t\t\t\t# Validate model\n\t\t\t\tit = 0\n\t\t\t\tcount_batch = 0.0\n\t\t\t\tvalid_loss = 0\n\t\t\t\twhile it < len(valid_set.initial_list) - model.batch_size:\n\t\t\t\t\tinput_feed, others = model.get_batch(valid_set)\n\t\t\t\t\tv_loss, results, summary = model.step(sess, input_feed, True)\n\t\t\t\t\tit += model.batch_size\n\t\t\t\t\tvalid_loss += v_loss\n\t\t\t\t\tcount_batch += 1.0\n\t\t\t\tvalid_writer.add_summary(summary, current_step)\n\t\t\t\tvalid_loss /= count_batch\n\t\t\t\t#valid_loss = math.exp(valid_loss) if valid_loss < 300 else float('inf')\n\t\t\t\tprint(\" eval: loss %.2f\" % (valid_loss))\n\n\t\t\t\t# Debug print\n\t\t\t\tq_idx = others['rank_list_idxs'][0]\n\t\t\t\tprint('Gold labels')\n\t\t\t\tprint(valid_set.gold_weights[q_idx])\n\t\t\t\tprint('Outputs')\n\t\t\t\tprint(results[0])\n\t\t\t\tprint('Decoder Clicks')\n\t\t\t\tprint(others['click_list'][0])\n\t\t\t\tprint('\\n')\n\n\n\t\t\t\tcheckpoint_path = os.path.join(FLAGS.train_dir, \"DLA.ckpt\")\n\t\t\t\tmodel.saver.save(sess, checkpoint_path, global_step=model.global_step)\n\t\t\t\t\n\t\t\t\tstep_time, loss = 0.0, 0.0\n\t\t\t\tsys.stdout.flush()\n\n\t\t\t\t# Save checkpoint and zero timer and loss.\n\t\t\t\t#if best_loss == None or best_loss >= eval_ppx:\n\t\t\t\t#\tbest_loss = eval_ppx\n\t\t\t\tcheckpoint_path = os.path.join(FLAGS.train_dir, \"DLA.ckpt\")\n\t\t\t\tmodel.saver.save(sess, checkpoint_path, global_step=model.global_step)\n\n\t\t\t\tif FLAGS.max_train_iteration > 0 and current_step > FLAGS.max_train_iteration:\n\t\t\t\t\tbreak\n\n\ndef main(_):\n\tif FLAGS.self_test:\n\t\tself_test()\n\telif FLAGS.decode:\n\t\tdecode()\n\telse:\n\t\ttrain()\n\nif __name__ == \"__main__\":\n\ttf.app.run()\n"
] | [
[
"tensorflow.train.get_checkpoint_state",
"tensorflow.summary.FileWriter",
"tensorflow.app.flags.DEFINE_integer",
"tensorflow.ConfigProto",
"tensorflow.global_variables_initializer",
"tensorflow.app.flags.DEFINE_string",
"tensorflow.Session",
"tensorflow.app.flags.DEFINE_boolean",
"tensorflow.app.run"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
kyungkoo70/keras-image-captioning | [
"47be86a6de4c5747debb52c54789b44ef0934cd1"
] | [
"keras_image_captioning/dataset_providers.py"
] | [
"import numpy as np\n\nfrom copy import copy\nfrom math import ceil\nfrom operator import attrgetter\n\nfrom common_utils import flatten_list_2d\nfrom config import active_config\nfrom datasets import get_dataset_instance\nfrom preprocessors import CaptionPreprocessor, ImagePreprocessor\n\n\nclass DatasetProvider(object):\n \"\"\"Acts as an adapter of `Dataset` for Keras' `fit_generator` method.\"\"\"\n def __init__(self,\n batch_size=None,\n dataset=None,\n image_preprocessor=None,\n caption_preprocessor=None,\n single_caption=False):\n \"\"\"\n If an arg is None, it will get its value from config.active_config.\n \"\"\"\n self._batch_size = batch_size or active_config().batch_size\n self._dataset = (dataset or\n get_dataset_instance(single_caption=single_caption))\n self._image_preprocessor = image_preprocessor or ImagePreprocessor()\n self._caption_preprocessor = (caption_preprocessor or\n CaptionPreprocessor())\n self._single_caption = single_caption\n self._build()\n\n @property\n def vocabs(self):\n return self._caption_preprocessor.vocabs\n\n @property\n def vocab_size(self):\n return self._caption_preprocessor.vocab_size\n\n @property\n def training_steps(self):\n return int(ceil(1. * self._dataset.training_set_size /\n self._batch_size))\n\n @property\n def validation_steps(self):\n return int(ceil(1. * self._dataset.validation_set_size /\n self._batch_size))\n\n @property\n def test_steps(self):\n return int(ceil(1. * self._dataset.test_set_size /\n self._batch_size))\n\n @property\n def training_results_dir(self):\n return self._dataset.training_results_dir\n\n @property\n def caption_preprocessor(self):\n return self._caption_preprocessor\n\n def training_set(self, include_datum=False):\n for batch in self._batch_generator(self._dataset.training_set, include_datum, random_transform=True):\n yield batch\n\n def validation_set(self, include_datum=False):\n for batch in self._batch_generator(self._dataset.validation_set,\n include_datum,\n random_transform=False):\n yield batch\n\n def test_set(self, include_datum=False):\n for batch in self._batch_generator(self._dataset.test_set,\n include_datum,\n random_transform=False):\n yield batch\n\n def _build(self):\n training_set = self._dataset.training_set\n if self._single_caption:\n training_captions = map(attrgetter('all_captions_txt'),\n training_set)\n training_captions = flatten_list_2d(training_captions)\n else:\n training_captions = map(attrgetter('caption_txt'), training_set)\n self._caption_preprocessor.fit_on_captions(training_captions)\n\n def _batch_generator(self, datum_list, include_datum=False, random_transform=True):\n # TODO Make it thread-safe. Currently only suitable for workers=1 in\n # fit_generator.\n datum_list = copy(datum_list)\n while True:\n np.random.shuffle(datum_list)\n datum_batch = []\n for datum in datum_list:\n datum_batch.append(datum)\n if len(datum_batch) >= self._batch_size:\n yield self._preprocess_batch(datum_batch, include_datum,\n random_transform)\n datum_batch = []\n if datum_batch:\n yield self._preprocess_batch(datum_batch, include_datum,\n random_transform)\n\n def _preprocess_batch(self, datum_batch, include_datum=False,\n random_transform=True):\n imgs_path = list(map(attrgetter('img_path'), datum_batch))\n captions_txt = list(map(attrgetter('caption_txt'), datum_batch))\n\n # for debugging\n # print('imgs_path: {}'.format(len(imgs_path)))\n # print('captions_txt: {}'.format(len(captions_txt)))\n # print(captions_txt)\n\n img_batch = self._image_preprocessor.preprocess_images(imgs_path,\n random_transform)\n\n # debugging\n # print('img_batch: type: {}'.format(type(img_batch)))\n # print('img_batch: len: {}'.format(len(list(img_batch))))\n\n caption_batch = self._caption_preprocessor.encode_captions(captions_txt)\n\n # debugging\n # print('caption_batch: type: {}'.format(type(caption_batch)))\n # print('caption_batch: len: {}'.format(len(caption_batch)))\n\n imgs_input = self._image_preprocessor.preprocess_batch(list(img_batch))\n captions = self._caption_preprocessor.preprocess_batch(caption_batch)\n # debugging\n # print('imgs_input: type: {}'.format(type(imgs_input)))\n # print('imgs_input: shape: {}'.format(imgs_input.shape))\n # print('captions: type: {}'.format(type(captions)))\n # print('captions: len: {}'.format(len(captions)))\n # print(captions)\n\n captions_input, captions_output = captions\n X, y = [imgs_input, captions_input], captions_output\n\n # debuggin\n # print('X info: type: {}, len: {}'.format(type(X), len(X)))\n # print(list(X))\n\n if include_datum:\n return X, y, datum_batch\n else:\n return X, y\n"
] | [
[
"numpy.random.shuffle"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MasazI/cnn_depth_tensorflow | [
"7959165c8924394154c4229a4b24c163e6dc70e4"
] | [
"task.py"
] | [
"#encoding: utf-8\n\nfrom datetime import datetime\nfrom tensorflow.python.platform import gfile\nimport numpy as np\nimport tensorflow as tf\nfrom dataset import DataSet\nfrom dataset import output_predict\nimport model\nimport train_operation as op\n\nMAX_STEPS = 10000000\nLOG_DEVICE_PLACEMENT = True\nBATCH_SIZE = 8\nTRAIN_FILE = \"train.csv\"\nCOARSE_DIR = \"coarse\"\nREFINE_DIR = \"refine\"\n\nREFINE_TRAIN = True\nFINE_TUNE = True\n\ndef train():\n with tf.Graph().as_default():\n global_step = tf.Variable(0, trainable=False)\n dataset = DataSet(BATCH_SIZE)\n images, depths, invalid_depths = dataset.csv_inputs(TRAIN_FILE)\n keep_conv = tf.placeholder(tf.float32)\n keep_hidden = tf.placeholder(tf.float32)\n if REFINE_TRAIN:\n print(\"refine train.\")\n coarse = model.inference(images, keep_conv, trainable=False)\n logits = model.inference_refine(images, coarse, keep_conv, keep_hidden)\n else:\n print(\"coarse train.\")\n logits = model.inference(images, keep_conv, keep_hidden)\n loss = model.loss(logits, depths, invalid_depths)\n train_op = op.train(loss, global_step, BATCH_SIZE)\n init_op = tf.global_variables_initializer()#tf.initialize_all_variables()\n\n # Session\n sess = tf.Session(config=tf.ConfigProto(log_device_placement=LOG_DEVICE_PLACEMENT))\n sess.run(init_op)\n\n # parameters\n coarse_params = {}\n refine_params = {}\n if REFINE_TRAIN:\n for variable in tf.global_variables():#tf.all_variables():\n variable_name = variable.name\n print(\"parameter: %s\" % (variable_name))\n if variable_name.find(\"/\") < 0 or variable_name.count(\"/\") != 1:\n continue\n if variable_name.find('coarse') >= 0:\n coarse_params[variable_name] = variable\n print(\"parameter: %s\" %(variable_name))\n if variable_name.find('fine') >= 0:\n refine_params[variable_name] = variable\n else:\n for variable in tf.trainable_variables():\n variable_name = variable.name\n print(\"parameter: %s\" %(variable_name))\n if variable_name.find(\"/\") < 0 or variable_name.count(\"/\") != 1:\n continue\n if variable_name.find('coarse') >= 0:\n coarse_params[variable_name] = variable\n if variable_name.find('fine') >= 0:\n refine_params[variable_name] = variable\n # define saver\n print(coarse_params)\n saver_coarse = tf.train.Saver(coarse_params)\n if REFINE_TRAIN:\n saver_refine = tf.train.Saver(refine_params)\n # fine tune\n if FINE_TUNE:\n coarse_ckpt = tf.train.get_checkpoint_state(COARSE_DIR)\n if coarse_ckpt and coarse_ckpt.model_checkpoint_path:\n print(\"Pretrained coarse Model Loading.\")\n saver_coarse.restore(sess, coarse_ckpt.model_checkpoint_path)\n print(\"Pretrained coarse Model Restored.\")\n else:\n print(\"No Pretrained coarse Model.\")\n if REFINE_TRAIN:\n refine_ckpt = tf.train.get_checkpoint_state(REFINE_DIR)\n if refine_ckpt and refine_ckpt.model_checkpoint_path:\n print(\"Pretrained refine Model Loading.\")\n saver_refine.restore(sess, refine_ckpt.model_checkpoint_path)\n print(\"Pretrained refine Model Restored.\")\n else:\n print(\"No Pretrained refine Model.\")\n\n # train\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n for step in range(MAX_STEPS):\n index = 0\n for i in range(1000):\n _, loss_value, logits_val, images_val = sess.run([train_op, loss, logits, images], feed_dict={keep_conv: 0.8, keep_hidden: 0.5})\n if index % 10 == 0:\n print(\"%s: %d[epoch]: %d[iteration]: train loss %f\" % (datetime.now(), step, index, loss_value))\n assert not np.isnan(loss_value), 'Model diverged with loss = NaN'\n if index % 500 == 0:\n if REFINE_TRAIN:\n output_predict(logits_val, images_val, \"data/predict_refine_%05d_%05d\" % (step, i))\n else:\n output_predict(logits_val, images_val, \"data/predict_%05d_%05d\" % (step, i))\n index += 1\n\n if step % 5 == 0 or (step * 1) == MAX_STEPS:\n if REFINE_TRAIN:\n refine_checkpoint_path = REFINE_DIR + '/model.ckpt'\n saver_refine.save(sess, refine_checkpoint_path, global_step=step)\n else:\n coarse_checkpoint_path = COARSE_DIR + '/model.ckpt'\n saver_coarse.save(sess, coarse_checkpoint_path, global_step=step)\n coord.request_stop()\n coord.join(threads)\n sess.close()\n\n\ndef main(argv=None):\n if not gfile.Exists(COARSE_DIR):\n gfile.MakeDirs(COARSE_DIR)\n if not gfile.Exists(REFINE_DIR):\n gfile.MakeDirs(REFINE_DIR)\n train()\n\n\nif __name__ == '__main__':\n tf.app.run()\n"
] | [
[
"tensorflow.train.get_checkpoint_state",
"tensorflow.Graph",
"tensorflow.Variable",
"numpy.isnan",
"tensorflow.train.start_queue_runners",
"tensorflow.train.Coordinator",
"tensorflow.global_variables",
"tensorflow.placeholder",
"tensorflow.trainable_variables",
"tensorflow.python.platform.gfile.MakeDirs",
"tensorflow.ConfigProto",
"tensorflow.global_variables_initializer",
"tensorflow.python.platform.gfile.Exists",
"tensorflow.train.Saver",
"tensorflow.app.run"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
brent-lemieux/fsdl-text-recognizer-2021-labs | [
"42529f580fb9d9995bfc94b30e63cc42af5753cf"
] | [
"lab3/text_recognizer/lit_models/base.py"
] | [
"import argparse\nimport pytorch_lightning as pl\nimport torch\n\n\nOPTIMIZER = \"Adam\"\nLR = 1e-3\nLOSS = \"cross_entropy\"\nONE_CYCLE_TOTAL_STEPS = 100\n\n\nclass Accuracy(pl.metrics.Accuracy):\n \"\"\"Accuracy Metric with a hack.\"\"\"\n\n def update(self, preds: torch.Tensor, target: torch.Tensor) -> None:\n \"\"\"\n Metrics in Pytorch-lightning 1.2+ versions expect preds to be between 0 and 1 else fails with the ValueError:\n \"The `preds` should be probabilities, but values were detected outside of [0,1] range.\"\n This is being tracked as a bug in https://github.com/PyTorchLightning/metrics/issues/60.\n This method just hacks around it by normalizing preds before passing it in.\n Normalized preds are not necessary for accuracy computation as we just care about argmax().\n \"\"\"\n print(preds.shape, target.shape)\n if preds.min() < 0 or preds.max() > 1:\n preds = torch.nn.functional.softmax(preds, dim=-1)\n super().update(preds=preds, target=target)\n\n\nclass BaseLitModel(pl.LightningModule): # pylint: disable=too-many-ancestors\n \"\"\"\n Generic PyTorch-Lightning class that must be initialized with a PyTorch module.\n \"\"\"\n\n def __init__(self, model, args: argparse.Namespace = None):\n super().__init__()\n self.model = model\n self.args = vars(args) if args is not None else {}\n\n optimizer = self.args.get(\"optimizer\", OPTIMIZER)\n self.optimizer_class = getattr(torch.optim, optimizer)\n\n self.lr = self.args.get(\"lr\", LR)\n\n loss = self.args.get(\"loss\", LOSS)\n if loss not in (\"ctc\", \"transformer\"):\n self.loss_fn = getattr(torch.nn.functional, loss)\n\n self.one_cycle_max_lr = self.args.get(\"one_cycle_max_lr\", None)\n self.one_cycle_total_steps = self.args.get(\"one_cycle_total_steps\", ONE_CYCLE_TOTAL_STEPS)\n\n self.train_acc = Accuracy()\n self.val_acc = Accuracy()\n self.test_acc = Accuracy()\n\n @staticmethod\n def add_to_argparse(parser):\n parser.add_argument(\"--optimizer\", type=str, default=OPTIMIZER, help=\"optimizer class from torch.optim\")\n parser.add_argument(\"--lr\", type=float, default=LR)\n parser.add_argument(\"--one_cycle_max_lr\", type=float, default=None)\n parser.add_argument(\"--one_cycle_total_steps\", type=int, default=ONE_CYCLE_TOTAL_STEPS)\n parser.add_argument(\"--loss\", type=str, default=LOSS, help=\"loss function from torch.nn.functional\")\n return parser\n\n def configure_optimizers(self):\n optimizer = self.optimizer_class(self.parameters(), lr=self.lr)\n if self.one_cycle_max_lr is None:\n return optimizer\n scheduler = torch.optim.lr_scheduler.OneCycleLR(\n optimizer=optimizer, max_lr=self.one_cycle_max_lr, total_steps=self.one_cycle_total_steps\n )\n return {\"optimizer\": optimizer, \"lr_scheduler\": scheduler, \"monitor\": \"val_loss\"}\n\n def forward(self, x):\n return self.model(x)\n\n def training_step(self, batch, batch_idx): # pylint: disable=unused-argument\n x, y = batch\n logits = self(x)\n loss = self.loss_fn(logits, y)\n self.log(\"train_loss\", loss)\n self.train_acc(logits, y)\n self.log(\"train_acc\", self.train_acc, on_step=False, on_epoch=True)\n return loss\n\n def validation_step(self, batch, batch_idx): # pylint: disable=unused-argument\n x, y = batch\n logits = self(x)\n loss = self.loss_fn(logits, y)\n self.log(\"val_loss\", loss, prog_bar=True)\n self.val_acc(logits, y)\n self.log(\"val_acc\", self.val_acc, on_step=False, on_epoch=True, prog_bar=True)\n\n def test_step(self, batch, batch_idx): # pylint: disable=unused-argument\n x, y = batch\n logits = self(x)\n self.test_acc(logits, y)\n self.log(\"test_acc\", self.test_acc, on_step=False, on_epoch=True)\n"
] | [
[
"torch.optim.lr_scheduler.OneCycleLR",
"torch.nn.functional.softmax"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
arkmagus/tensor_rnn | [
"aa74a2414d6e46cc8ddf9be81f38eb262348194b"
] | [
"tensor_rnn/utils/data_util.py"
] | [
"import numpy as np\n\ndef iter_minibatches(indices, batchsize, shuffle=True, pad=False, excludes=None):\n \"\"\"\n Args:\n datasize : total number of data or list of indices\n batchsize : mini-batchsize\n shuffle :\n use_padding : pad the dataset if dataset can't divided by batchsize equally\n\n Return :\n list of index for current epoch (randomized or not depends on shuffle)\n \"\"\"\n if isinstance(indices, list) :\n indices = indices\n elif isinstance(indices, int) :\n indices = list(range(indices))\n if excludes is not None :\n indices = [x for x in indices if x not in excludes]\n if shuffle:\n np.random.shuffle(indices)\n\n if pad :\n indices = pad_idx(indices, batchsize)\n\n for ii in range(0, len(indices), batchsize):\n yield indices[ii:ii + batchsize]\n pass\n"
] | [
[
"numpy.random.shuffle"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Vrroom/IRL | [
"56caab14cc5084077e1db40995f778a0bbc9fe31"
] | [
"IRL.py"
] | [
"\"\"\" Main reward optimization loop \"\"\"\nimport Config as C\nimport numpy as np\nnp.random.seed(C.SEED)\nimport random\nrandom.seed(C.SEED)\nfrom RewardFnSpace import *\nimport pickle\nimport more_itertools\nfrom AcrobotUtils import *\nfrom scipy.spatial.distance import pdist, squareform\nimport os\nimport os.path as osp\nfrom A2C import *\nfrom PlotUtils import *\nfrom Eval import *\nfrom rlpyt.samplers.serial.sampler import SerialSampler\nfrom rlpyt.samplers.parallel.gpu.sampler import GpuSampler\n\ndef findSamplesInTrajs (stateSamples, trajs) : \n \"\"\" \n For each state sample, find all indices (i, j) such that\n the jth state in ith trajectory is approximately the state\n sample\n \"\"\"\n nSamples = stateSamples.shape[0]\n stateOccurenceIndices = [[] for _ in range(nSamples)]\n allStates = [np.stack([s for s, _, _ in t]) for t in trajs]\n for i, traj in enumerate(trajs) : \n trajLen = len(traj)\n D = squareform(pdist(np.concatenate((stateSamples, allStates[i]), axis=0)))\n D = D[:nSamples, nSamples:]\n indices = np.where(D < C.STATE_SIMILARITY_THRESH)\n for j, k in zip(*indices) : \n stateOccurenceIndices[j].append((i, k))\n return stateOccurenceIndices\n\ndef generateStateSamples (trajs, nSamples) : \n \"\"\" get the distribution of start states \"\"\"\n allStates = [[s for s, _, _ in t] for t in trajs[:10]]\n allStates = list(more_itertools.flatten(allStates))\n states = random.sample(allStates, k=nSamples)\n states = np.array(states)\n return states\n\ndef estimateValueFromTrajs (stateIndices, trajs, rewardFn) :\n \"\"\" \n Estimate the value for each state from expert \n trajectories.\n \"\"\"\n def computeReturnOnTraj (traj) : \n R = [rewardFn(s) for s, _, _ in traj]\n return computeReturns(R, C.DISCOUNT)[0]\n values = []\n for i, indices in enumerate(stateIndices) : \n truncatedTrajs = [trajs[i][j:] for i, j in indices] \n vhat = np.mean([computeReturnOnTraj(t) for t in truncatedTrajs])\n values.append(vhat)\n return values\n\ndef estimateValueFromAgent (stateSamples, agent, rewardFn) : \n \"\"\"\n Use the learnt value function network through\n A2C to estimate value for states.\n \"\"\"\n def estimateForState (s) : \n cpus = list(range(C.N_PARALLEL))\n affinity = dict(cuda_idx=C.CUDA_IDX, workers_cpus=cpus)\n agent_ = CategoricalPgAgent(\n AcrobotNet, \n initial_model_state_dict=agent.state_dict())\n sampler = SerialSampler(\n EnvCls=rlpyt_make,\n env_kwargs=dict(\n id=C.ENV, \n reward=rewardFn, \n internalStateFn=C.INTERNAL_STATE_FN, \n s0=s),\n batch_T=C.HORIZON,\n batch_B=C.BATCH_B,\n max_decorrelation_steps=0,\n )\n sampler.initialize(\n agent=agent_,\n affinity=affinity,\n seed=C.SEED\n )\n _, traj_info = sampler.obtain_samples(0)\n returns = [t['DiscountedReturn'] for t in traj_info]\n return np.mean(returns)\n estimates = list(map(estimateForState, stateSamples))\n return estimates\n\ndef getAllTraj () : \n \"\"\" get all trajectories from C.TRAJ_DIR \"\"\"\n def loadPickle (f) : \n with open(osp.join(C.TRAJ_DIR, f), 'rb') as fd : \n return pickle.load(fd)\n return list(map(loadPickle, os.listdir(C.TRAJ_DIR)))\n\ndef irl (rewardFnSpace) :\n \"\"\"\n Find the explanatory reward function for expert's \n policy in the space of reward functions.\n \"\"\"\n trajs = getAllTraj()\n stateSamples = generateStateSamples(trajs, C.IRL_STATE_SAMPLES)\n indices = findSamplesInTrajs(stateSamples, trajs) \n for i in range(C.IRL_ITR) : \n rewardFn = rewardFnSpace.current()\n agent = findOptimalAgent(rewardFn)\n env = rlpyt_make('Acrobot-v1', internalStateFn=C.INTERNAL_STATE_FN)\n expertValues = [estimateValueFromTrajs(indices, trajs, _) \n for _ in rewardFnSpace.rewardBases]\n inferiorValues = [estimateValueFromAgent(stateSamples, agent, _)\n for _ in rewardFnSpace.rewardBases]\n rewardFnSpace.refine(expertValues, inferiorValues)\n return agent, rewardFn\n\nif __name__ == \"__main__\" :\n agent, rewardFn = irl(RewardFnSpace(acrobotRewardBases(np.pi / 2, np.pi / 2)))\n xRange = np.arange(-np.pi, np.pi, 0.1)\n yRange = np.arange(-np.pi, np.pi, 0.1)\n toExternal = lambda x, y : toExternalStateRep([x, y, 0, 0])\n RFn = compose(rewardFn, toExternal)\n plotFunction(RFn, xRange, yRange, 'theta1', 'theta2', 'R')\n plt.savefig('recovered.png')\n plt.show()\n simulateAgent(agent, render=True)\n"
] | [
[
"numpy.random.seed",
"numpy.arange",
"numpy.stack",
"numpy.concatenate",
"numpy.mean",
"numpy.array",
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kuihao/KuihaoFL | [
"69c9161497f2a82ab8ef2d785a0c7e2e6975a328"
] | [
"Implement_google_AdaptiveFL/Print_Result_AvgLast100round.py"
] | [
"import numpy as np\n\ndef Result_AvgLast100round(forderpath, filename,):\n results_np = np.load(f\"{forderpath}/{filename}\", allow_pickle=True)\n '''解壓縮、匯入'''\n #print(results_np.files) # ['arr_0']\n #print(results_np['arr_0']) # {'loss': [], 'accuracy': [], 'top_k_categorical_accuracy': []}\n \n # 出現 0-d array error,解法: https://chunchengwei.github.io/ruan-jian/jie-jue-numpy-0d-arrays-error/\n results_np = np.atleast_1d(results_np['arr_0'])\n results_dict = dict(results_np[0])\n\n rounds = len(results_dict['loss'])\n if rounds < 100:\n prompt_str = f'Last round '\n print(prompt_str+'loss',np.mean(results_dict['loss'][-1]))\n print(prompt_str+'Acc',np.mean(results_dict['accuracy'][-1]))\n print(prompt_str+'TopK Acc',np.mean(results_dict['sparse_top_k_categorical_accuracy'][-1]))\n else:\n prompt_str = f'Last {100} avg '\n print(prompt_str+'loss',np.mean(results_dict['loss'][-100:]))\n print(prompt_str+'Acc',np.mean(results_dict['accuracy'][-100:]))\n print(prompt_str+'TopK Acc',np.mean(results_dict['sparse_top_k_categorical_accuracy'][-100:]))\n\ndef main():\n forderpath = r\"D:\\KuihaoFL\\Implement_google_AdaptiveFL\\FL_Results\\11_26_2021__22_12_08_cifar100_noniid_resnet18_fedadagrad\"\n print(\"Train:\")\n Result_AvgLast100round(forderpath, \"Training_result_distributed.npz\")\n print(\"Test:\")\n Result_AvgLast100round(forderpath, \"Testing_result_distributed.npz\")\n\nmain()\n"
] | [
[
"numpy.atleast_1d",
"numpy.load",
"numpy.mean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
N-SPC700/corrscope | [
"9e85a33fbede1e53c20f4e05d71384d276c9f9a9"
] | [
"corrscope/triggers.py"
] | [
"from abc import ABC, abstractmethod\nfrom typing import TYPE_CHECKING, Type, Optional, ClassVar, Union\n\nimport attr\nimport numpy as np\n\nimport corrscope.utils.scipy.signal as signal\nimport corrscope.utils.scipy.windows as windows\nfrom corrscope.config import KeywordAttrs, CorrError, Alias, with_units\nfrom corrscope.spectrum import SpectrumConfig, DummySpectrum, LogFreqSpectrum\nfrom corrscope.util import find, obj_name, iround\nfrom corrscope.utils.trigger_util import (\n get_period,\n normalize_buffer,\n lerp,\n MIN_AMPLITUDE,\n abs_max,\n)\nfrom corrscope.utils.windows import leftpad, midpad, rightpad, gaussian_or_zero\nfrom corrscope.wave import FLOAT\n\nif TYPE_CHECKING:\n from corrscope.wave import Wave\n from corrscope.renderer import RendererFrontend\n\n\n# Abstract classes\n\n\nclass _TriggerConfig:\n cls: ClassVar[Type[\"_Trigger\"]]\n\n def __call__(self, wave: \"Wave\", *args, **kwargs) -> \"_Trigger\":\n return self.cls(wave, self, *args, **kwargs)\n\n\nclass MainTriggerConfig(\n _TriggerConfig, KeywordAttrs, always_dump=\"edge_direction post_trigger post_radius\"\n):\n # Must be 1 or -1.\n # MainTrigger.__init__() multiplies `wave.amplification *= edge_direction`.\n # get_trigger() should ignore `edge_direction` and look for rising edges.\n edge_direction: int = 1\n\n # Optional trigger for postprocessing\n post_trigger: Optional[\"PostTriggerConfig\"] = None\n post_radius: Optional[int] = with_units(\"smp\", default=3)\n\n def __attrs_post_init__(self):\n if self.edge_direction not in [-1, 1]:\n raise CorrError(f\"{obj_name(self)}.edge_direction must be {{-1, 1}}\")\n\n if self.post_trigger:\n self.post_trigger.parent = self\n if self.post_radius is None:\n name = obj_name(self)\n raise CorrError(\n f\"Cannot supply {name}.post_trigger without supplying {name}.post_radius\"\n )\n\n\nclass PostTriggerConfig(_TriggerConfig, KeywordAttrs):\n parent: MainTriggerConfig = attr.ib(init=False) # TODO Unused\n pass\n\n\ndef register_trigger(config_t: Type[_TriggerConfig]):\n \"\"\" @register_trigger(FooTriggerConfig)\n def FooTrigger(): ...\n \"\"\"\n\n def inner(trigger_t: Type[_Trigger]):\n config_t.cls = trigger_t\n return trigger_t\n\n return inner\n\n\nclass _Trigger(ABC):\n def __init__(\n self,\n wave: \"Wave\",\n cfg: _TriggerConfig,\n tsamp: int,\n stride: int,\n fps: float,\n renderer: Optional[\"RendererFrontend\"] = None,\n wave_idx: int = 0,\n ):\n self.cfg = cfg\n self._wave = wave\n\n # TODO rename tsamp to buffer_nsamp\n self._tsamp = tsamp\n self._stride = stride\n self._fps = fps\n\n # Only used for debug plots\n self._renderer = renderer\n self._wave_idx = wave_idx\n\n # Subsamples per second\n self.subsmp_s = self._wave.smp_s / self._stride\n\n frame_dur = 1 / fps\n # Subsamples per frame\n self._tsamp_frame = self.time2tsamp(frame_dur)\n\n def time2tsamp(self, time: float) -> int:\n return round(time * self.subsmp_s)\n\n def custom_line(\n self, name: str, data: np.ndarray, offset: bool, invert: bool = True\n ):\n \"\"\"\n :param offset:\n - True, for untriggered wave data:\n - line will be shifted and triggered (by offset_viewport()).\n - False, for triggered data and buffers:\n - line is immune to offset_viewport().\n\n :param invert:\n - True, for wave (data and buffers):\n - If wave data is inverted (edge_direction = -1),\n data will be plotted inverted.\n - False, for buffers and autocorrelated wave data:\n - Data is plotted as-is.\n \"\"\"\n if self._renderer is None:\n return\n data = data / abs_max(data, 0.01) / 2\n if invert:\n data *= np.copysign(1, self._wave.amplification)\n self._renderer.update_custom_line(\n name, self._wave_idx, self._stride, data, offset=offset\n )\n\n def custom_vline(self, name: str, x: int, offset: bool):\n \"\"\"See above for `offset`.\"\"\"\n if self._renderer is None:\n return\n self._renderer.update_vline(\n name, self._wave_idx, self._stride, x, offset=offset\n )\n\n def offset_viewport(self, offset: int):\n if self._renderer is None:\n return\n self._renderer.offset_viewport(self._wave_idx, offset)\n\n @abstractmethod\n def get_trigger(self, index: int, cache: \"PerFrameCache\") -> int:\n \"\"\"\n :param index: sample index\n :param cache: Information shared across all stacked triggers,\n May be mutated by function.\n :return: new sample index, corresponding to rising edge\n \"\"\"\n ...\n\n @abstractmethod\n def do_not_inherit__Trigger_directly(self):\n pass\n\n\nclass MainTrigger(_Trigger, ABC):\n cfg: MainTriggerConfig\n post: Optional[\"PostTrigger\"]\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._wave.amplification *= self.cfg.edge_direction\n\n cfg = self.cfg\n if cfg.post_trigger:\n # Create a post-processing trigger, with narrow nsamp and stride=1.\n # This improves speed and precision.\n self.post = cfg.post_trigger(\n self._wave,\n cfg.post_radius,\n 1,\n self._fps,\n self._renderer,\n self._wave_idx,\n )\n else:\n self.post = None\n\n def set_renderer(self, renderer: \"RendererFrontend\"):\n self._renderer = renderer\n if self.post:\n self.post._renderer = renderer\n\n def do_not_inherit__Trigger_directly(self):\n pass\n\n\nclass PostTrigger(_Trigger, ABC):\n \"\"\" A post-processing trigger should have stride=1,\n and no more post triggers. This is subject to change. \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n if self._stride != 1:\n raise CorrError(\n f\"{obj_name(self)} with stride != 1 is not allowed \"\n f\"(supplied {self._stride})\"\n )\n\n def do_not_inherit__Trigger_directly(self):\n pass\n\n\[email protected](slots=True)\nclass PerFrameCache:\n \"\"\"\n The estimated period of a wave region (Wave.get_around())\n is approximately constant, even when multiple triggers are stacked\n and each is called at a slightly different point.\n\n For each unique (frame, channel), all stacked triggers are passed the same\n TriggerFrameCache object.\n \"\"\"\n\n # NOTE: period is a *non-subsampled* period.\n # The period of subsampled data must be multiplied by stride.\n period: Optional[int] = None\n mean: Optional[float] = None\n\n\n# CorrelationTrigger\n\n\nclass LagPrevention(KeywordAttrs):\n max_frames: float = 1\n transition_frames: float = 0.25\n\n def __attrs_post_init__(self):\n validate_param(self, \"max_frames\", 0, 1)\n validate_param(self, \"transition_frames\", 0, self.max_frames)\n\n\nclass CorrelationTriggerConfig(\n MainTriggerConfig,\n always_dump=\"\"\"\n pitch_tracking\n slope_strength slope_width\n \"\"\"\n # deprecated\n \" buffer_falloff \",\n):\n # get_trigger()\n # Edge/area finding\n sign_strength: float = 0\n edge_strength: float\n\n # Slope detection\n slope_strength: float = 0\n slope_width: float = with_units(\"period\", default=0.07)\n\n # Correlation detection (meow~ =^_^=)\n buffer_strength: float = 1\n\n # Both data and buffer uses Gaussian windows. std = wave_period * falloff.\n # get_trigger()\n data_falloff: float = 1.5\n\n # _update_buffer()\n buffer_falloff: float = 0.5\n\n # Maximum distance to move\n trigger_diameter: Optional[float] = 0.5\n\n recalc_semitones: float = 1.0\n lag_prevention: LagPrevention = attr.ib(factory=LagPrevention)\n\n # _update_buffer\n responsiveness: float\n\n # Period/frequency estimation (not in GUI)\n max_freq: float = with_units(\"Hz\", default=4000)\n\n # Pitch tracking = compute spectrum.\n pitch_tracking: Optional[\"SpectrumConfig\"] = None\n\n # region Legacy Aliases\n trigger_strength = Alias(\"edge_strength\")\n falloff_width = Alias(\"buffer_falloff\")\n # endregion\n\n def __attrs_post_init__(self) -> None:\n MainTriggerConfig.__attrs_post_init__(self)\n\n validate_param(self, \"slope_width\", 0, 0.5)\n\n validate_param(self, \"responsiveness\", 0, 1)\n # TODO trigger_falloff >= 0\n validate_param(self, \"buffer_falloff\", 0, np.inf)\n\n\ndef validate_param(self, key: str, begin: float, end: float) -> None:\n value = getattr(self, key)\n if not begin <= value <= end:\n raise CorrError(f\"Invalid {key}={value} (should be within [{begin}, {end}])\")\n\n\n@register_trigger(CorrelationTriggerConfig)\nclass CorrelationTrigger(MainTrigger):\n \"\"\"\n Assume that if get_trigger(x) == x, then data[[x-1, x]] == [<0, >0].\n - edge detectors [halfN = N//2] > 0.\n - So wave.get_around(x)[N//2] > 0.\n - So wave.get_around(x) = [x - N//2 : ...]\n\n test_trigger() checks that get_around() works properly, for even/odd N.\n See Wave.get_around() docstring.\n \"\"\"\n\n cfg: CorrelationTriggerConfig\n\n @property\n def scfg(self) -> SpectrumConfig:\n return self.cfg.pitch_tracking\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Correlation-based trigger which looks at a window of `trigger_tsamp` samples.\n it's complicated\n \"\"\"\n super().__init__(*args, **kwargs)\n self._buffer_nsamp = self._tsamp\n\n # (const) Multiplied by each frame of input audio.\n # Zeroes out all data older than 1 frame old.\n self._lag_prevention_window = self._calc_lag_prevention()\n assert self._lag_prevention_window.dtype == FLOAT\n\n # (mutable) Correlated with data (for triggering).\n # Updated with tightly windowed old data at various pitches.\n self._buffer = np.zeros(\n self._buffer_nsamp, dtype=FLOAT\n ) # type: np.ndarray[FLOAT]\n\n # (const) Added to self._buffer. Nonzero if edge triggering is nonzero.\n # Left half is -edge_strength, right half is +edge_strength.\n # ASCII art: --._|‾'--\n self._edge_finder = self._calc_step()\n assert self._edge_finder.dtype == FLOAT\n\n # Will be overwritten on the first frame.\n self._prev_period: Optional[int] = None\n self._prev_window: Optional[np.ndarray] = None\n self._prev_slope_finder: Optional[np.ndarray] = None\n\n self._prev_trigger: int = 0\n\n # (mutable) Log-scaled spectrum\n self.frames_since_spectrum = 0\n\n if self.scfg:\n self._spectrum_calc = LogFreqSpectrum(\n scfg=self.scfg, subsmp_s=self.subsmp_s, dummy_data=self._buffer\n )\n else:\n self._spectrum_calc = DummySpectrum()\n\n def _calc_lag_prevention(self) -> np.ndarray:\n \"\"\" Returns input-data window,\n which zeroes out all data older than 1-ish frame old.\n See https://github.com/jimbo1qaz/corrscope/wiki/Correlation-Trigger\n \"\"\"\n N = self._buffer_nsamp\n halfN = N // 2\n\n # - Create a cosine taper of `width` <= 1 frame\n # - Right-pad(value=1, len=1 frame)\n # - Place in left half of N-sample buffer.\n\n # To avoid cutting off data, use a narrow transition zone (invariant to stride).\n lag_prevention = self.cfg.lag_prevention\n tsamp_frame = self._tsamp_frame\n transition_nsamp = round(tsamp_frame * lag_prevention.transition_frames)\n\n # Left half of a Hann cosine taper\n # Width (type=subsample) = min(frame * lag_prevention, 1 frame)\n assert transition_nsamp <= tsamp_frame\n width = transition_nsamp\n taper = windows.hann(width * 2)[:width]\n\n # Right-pad=1 taper to lag_prevention.max_frames long [t-#*f, t]\n taper = rightpad(taper, iround(tsamp_frame * lag_prevention.max_frames))\n\n # Left-pad=0 taper to left `halfN` of data_taper [t-halfN, t]\n taper = leftpad(taper, halfN)\n\n # Generate left half-taper to prevent correlating with 1-frame-old data.\n # Right-pad=1 taper to [t-halfN, t-halfN+N]\n # TODO switch to rightpad()? Does it return FLOAT or not?\n data_taper = np.ones(N, dtype=FLOAT)\n data_taper[:halfN] = np.minimum(data_taper[:halfN], taper)\n\n return data_taper\n\n def _calc_step(self) -> np.ndarray:\n \"\"\" Step function used for approximate edge triggering. \"\"\"\n\n # Increasing buffer_falloff (width of buffer)\n # causes buffer to affect triggering, more than the step function.\n # So we multiply edge_strength (step function height) by buffer_falloff.\n\n cfg = self.cfg\n edge_strength = cfg.edge_strength * cfg.buffer_falloff\n\n N = self._buffer_nsamp\n halfN = N // 2\n\n step = np.empty(N, dtype=FLOAT) # type: np.ndarray[FLOAT]\n step[:halfN] = -edge_strength / 2\n step[halfN:] = edge_strength / 2\n step *= windows.gaussian(N, std=halfN / 3)\n return step\n\n def _calc_slope_finder(self, period: float) -> np.ndarray:\n \"\"\" Called whenever period changes substantially.\n Returns a kernel to be correlated with input data,\n to find positive slopes.\"\"\"\n\n N = self._buffer_nsamp\n halfN = N // 2\n slope_finder = np.zeros(N)\n\n cfg = self.cfg\n slope_width = max(iround(cfg.slope_width * period), 1)\n slope_strength = cfg.slope_strength * cfg.buffer_falloff\n\n slope_finder[halfN - slope_width : halfN] = -slope_strength\n slope_finder[halfN : halfN + slope_width] = slope_strength\n return slope_finder\n\n # end setup\n\n # begin per-frame\n def get_trigger(self, index: int, cache: \"PerFrameCache\") -> int:\n N = self._buffer_nsamp\n cfg = self.cfg\n\n # Get data (1D, downmixed to mono)\n stride = self._stride\n data = self._wave.get_around(index, N, stride)\n\n if cfg.sign_strength != 0:\n signs = sign_times_peak(data)\n data += cfg.sign_strength * signs\n\n # Remove mean from data\n data -= np.add.reduce(data) / N\n\n # Window data\n period = get_period(data, self.subsmp_s, self.cfg.max_freq, self)\n cache.period = period * stride\n\n semitones = self._is_window_invalid(period)\n # If pitch changed...\n if semitones:\n # Gaussian window\n period_symmetric_window = gaussian_or_zero(N, period * cfg.data_falloff)\n\n # Left-sided falloff\n lag_prevention_window = self._lag_prevention_window\n\n # Both combined.\n window = np.minimum(period_symmetric_window, lag_prevention_window)\n\n # Slope finder\n slope_finder = self._calc_slope_finder(period)\n\n data *= window\n\n # If pitch tracking enabled, rescale buffer to match data's pitch.\n if self.scfg and (data != 0).any():\n # Mutates self._buffer.\n self.spectrum_rescale_buffer(data)\n\n self._prev_period = period\n self._prev_window = window\n self._prev_slope_finder = slope_finder\n else:\n window = self._prev_window\n slope_finder = self._prev_slope_finder\n\n data *= window\n\n prev_buffer: np.ndarray = self._buffer * self.cfg.buffer_strength\n prev_buffer += self._edge_finder + slope_finder\n\n # Calculate correlation\n if self.cfg.trigger_diameter is not None:\n radius = round(N * self.cfg.trigger_diameter / 2)\n else:\n radius = None\n\n trigger_score = correlate_data(data, prev_buffer, radius)\n peak_offset = trigger_score.peak\n trigger = index + (stride * peak_offset)\n\n del data\n\n if self.post:\n new_data = self._wave.get_around(trigger, N, stride)\n cache.mean = np.add.reduce(new_data) / N\n\n # Apply post trigger (before updating correlation buffer)\n trigger = self.post.get_trigger(trigger, cache)\n\n # Avoid time traveling backwards.\n self._prev_trigger = trigger = max(trigger, self._prev_trigger)\n\n # Update correlation buffer (distinct from visible area)\n aligned = self._wave.get_around(trigger, N, stride)\n if cache.mean is None:\n cache.mean = np.add.reduce(aligned) / N\n self._update_buffer(aligned, cache)\n\n self.frames_since_spectrum += 1\n\n self.offset_viewport(peak_offset)\n return trigger\n\n def spectrum_rescale_buffer(self, data: np.ndarray) -> None:\n \"\"\"\n - Cross-correlate the log-frequency spectrum of `data` with `buffer`.\n - Rescale `buffer` until its pitch matches `data`.\n \"\"\"\n\n # Setup\n scfg = self.scfg\n N = self._buffer_nsamp\n if self.frames_since_spectrum < self.scfg.min_frames_between_recompute:\n return\n self.frames_since_spectrum = 0\n\n calc_spectrum = self._spectrum_calc.calc_spectrum\n\n # Compute log-frequency spectrum of `data`.\n spectrum = calc_spectrum(data)\n normalize_buffer(spectrum)\n assert not np.any(np.isnan(spectrum))\n\n # Compute log-frequency spectrum of `self._buffer`.\n prev_spectrum = calc_spectrum(self._buffer)\n # Don't normalize self._spectrum. It was already normalized when being assigned.\n\n # Rescale `self._buffer` until its pitch matches `data`.\n resample_notes = correlate_spectrum(\n spectrum, prev_spectrum, scfg.max_notes_to_resample\n ).peak\n if resample_notes != 0:\n # If we want to double pitch, we must divide data length by 2.\n new_len = iround(N / 2 ** (resample_notes / scfg.notes_per_octave))\n\n def rescale_mut(in_buf):\n buf = np.interp(\n np.linspace(0, 1, new_len), np.linspace(0, 1, N), in_buf\n )\n # assert len(buf) == new_len\n buf = midpad(buf, N)\n in_buf[:] = buf\n\n # Copy+resample self._buffer.\n rescale_mut(self._buffer)\n\n def _is_window_invalid(self, period: int) -> Union[bool, float]:\n \"\"\"\n Returns number of semitones,\n if pitch has changed more than `recalc_semitones`.\n\n Preconditions:\n - self._prev_period is assigned whenever this function returns True.\n - If period cannot be estimated, period == 0.\n\n Postconditions:\n - On frame 0, MUST return True (to initialize self._prev_window).\n - This is the only way self._prev_period == 0.\n - Elif period is 0 (cannot be estimated), return False.\n \"\"\"\n\n prev = self._prev_period\n if prev is None:\n return True\n elif period == 0:\n return False\n elif prev == 0:\n return True\n else:\n # When period doubles, semitones are -12.\n semitones = np.log(period / prev) / np.log(2) * -12\n # If semitones == recalc_semitones == 0, do NOT recalc.\n if abs(semitones) <= self.cfg.recalc_semitones:\n return False\n return semitones\n\n def _update_buffer(self, data: np.ndarray, cache: PerFrameCache) -> None:\n \"\"\"\n Update self._buffer by adding `data` and a step function.\n Data is reshaped to taper away from the center.\n\n :param data: Wave data. WILL BE MODIFIED.\n \"\"\"\n assert cache.mean is not None\n assert cache.period is not None\n buffer_falloff = self.cfg.buffer_falloff\n responsiveness = self.cfg.responsiveness\n\n N = len(data)\n if N != self._buffer_nsamp:\n raise ValueError(\n f\"invalid data length {len(data)} does not match \"\n f\"CorrelationTrigger {self._buffer_nsamp}\"\n )\n\n # New waveform\n data -= cache.mean\n normalize_buffer(data)\n window = gaussian_or_zero(N, std=(cache.period / self._stride) * buffer_falloff)\n data *= window\n\n # Old buffer\n normalize_buffer(self._buffer)\n self._buffer = lerp(self._buffer, data, responsiveness)\n\n\[email protected]\nclass CorrelationResult:\n peak: int\n corr: np.ndarray\n\n\[email protected]\nclass InterpolatedCorrelationResult:\n peak: float\n corr: np.ndarray\n\n\ndef correlate_data(\n data: np.ndarray, prev_buffer: np.ndarray, radius: Optional[int]\n) -> CorrelationResult:\n \"\"\"\n This is confusing.\n\n If data index < optimal, data will be too far to the right,\n and we need to `index += positive`.\n - The peak will appear near the right of `data`.\n\n Either we must slide prev_buffer to the right,\n or we must slide data to the left (by sliding index to the right):\n - correlate(data, prev_buffer)\n - trigger = index + peak_offset\n \"\"\"\n N = len(data)\n corr = signal.correlate(data, prev_buffer) # returns double, not single/FLOAT\n Ncorr = 2 * N - 1\n assert len(corr) == Ncorr\n\n # Find optimal offset\n mid = N - 1\n\n if radius is not None:\n left = max(mid - radius, 0)\n right = min(mid + radius + 1, Ncorr)\n\n corr = corr[left:right]\n mid = mid - left\n\n # argmax(corr) == mid + peak_offset == (data >> peak_offset)\n # peak_offset == argmax(corr) - mid\n peak_offset = np.argmax(corr) - mid # type: int\n return CorrelationResult(peak_offset, corr)\n\n\ndef correlate_spectrum(\n data: np.ndarray, prev_buffer: np.ndarray, radius: Optional[int]\n) -> CorrelationResult:\n \"\"\"\n I used to use parabolic() on the return value,\n but unfortunately it was unreliable and caused Plok Beach bass to jitter,\n so I turned it off (resulting in the same code as correlate_data).\n \"\"\"\n return correlate_data(data, prev_buffer, radius)\n\n\ndef parabolic(xint: int, ys: np.ndarray) -> float:\n \"\"\"\n Quadratic interpolation for estimating the true position of an inter-sample maximum\n when nearby samples are known.\n \"\"\"\n\n if xint - 1 < 0 or xint + 1 >= len(ys):\n return float(xint)\n\n left = ys[xint - 1]\n mid = ys[xint]\n right = ys[xint + 1]\n\n # https://ccrma.stanford.edu/~jos/sasp/Quadratic_Interpolation_Spectral_Peaks.html\n dx = 0.5 * (+left - right) / (+left - 2 * mid + right)\n assert -1 < dx < 1\n return xint + dx\n\n\nSIGN_AMPLIFICATION = 1000\n\n\ndef sign_times_peak(data: np.ndarray) -> np.ndarray:\n \"\"\"\n Computes peak = max(abs(data)).\n Returns `peak` for positive parts of data, and `-peak` for negative parts,\n and heavily amplifies parts of the wave near zero.\n \"\"\"\n data = data.copy()\n\n peak = abs_max(data)\n data *= SIGN_AMPLIFICATION / (peak + MIN_AMPLITUDE)\n\n sign_data = np.tanh(data)\n sign_data *= peak\n\n return sign_data\n\n\n#### Post-processing triggers\n# ZeroCrossingTrigger\n\n\nclass ZeroCrossingTriggerConfig(PostTriggerConfig):\n pass\n\n\n# Edge finding trigger\n@register_trigger(ZeroCrossingTriggerConfig)\nclass ZeroCrossingTrigger(PostTrigger):\n # ZeroCrossingTrigger is only used as a postprocessing trigger.\n # stride is only passed 1, for improved precision.\n cfg: ZeroCrossingTriggerConfig\n\n def get_trigger(self, index: int, cache: \"PerFrameCache\") -> int:\n radius = self._tsamp\n\n wave = self._wave.with_offset(-cache.mean)\n\n if not 0 <= index < wave.nsamp:\n return index\n\n if wave[index] < 0:\n direction = 1\n test = lambda a: a >= 0\n\n elif wave[index] > 0:\n direction = -1\n test = lambda a: a <= 0\n\n else: # self._wave[sample] == 0\n return index + 1\n\n data = wave[index : index + direction * (radius + 1) : direction]\n # TODO remove unnecessary complexity, since diameter is probably under 10.\n intercepts = find(data, test)\n try:\n (delta,), value = next(intercepts)\n return index + (delta * direction) + int(value <= 0)\n\n except StopIteration: # No zero-intercepts\n return index + (direction * radius)\n\n # noinspection PyUnreachableCode\n \"\"\"\n `value <= 0` produces poor results on on sine waves, since it erroneously\n increments the exact idx of the zero-crossing sample.\n\n `value < 0` produces poor results on impulse24000, since idx = 23999 which\n doesn't match CorrelationTrigger. (scans left looking for a zero-crossing)\n\n CorrelationTrigger tries to maximize @trigger - @(trigger-1). I think always\n incrementing zeros (impulse24000 = 24000) is acceptable.\n\n - To be consistent, we should increment zeros whenever we *start* there.\n \"\"\"\n\n\n# NullTrigger\n\n\nclass NullTriggerConfig(MainTriggerConfig):\n pass\n\n\n@register_trigger(NullTriggerConfig)\nclass NullTrigger(MainTrigger):\n def get_trigger(self, index: int, cache: \"PerFrameCache\") -> int:\n return index\n"
] | [
[
"numpy.log",
"numpy.minimum",
"numpy.linspace",
"numpy.isnan",
"numpy.add.reduce",
"numpy.ones",
"numpy.argmax",
"numpy.copysign",
"numpy.tanh",
"numpy.zeros",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
haochen12/dpPython | [
"c6b58c12786e8b17728b9683f665efebcada43ec"
] | [
"myworkspace/translate_tutorial/ch15.py"
] | [
"# Visualize training history\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nimport matplotlib.pyplot as plt\nimport numpy\n\n# fix random seed for reproducibility\nseed = 7\nnumpy.random.seed(seed)\n# load pima indians dataset\ndataset = numpy.loadtxt(\"pima-indians-diabetes.csv\", delimiter=\",\")\n# split into input (X) and output (Y) variables\nX = dataset[:, 0:8]\nY = dataset[:, 8]\n# create model\nmodel = Sequential()\nmodel.add(Dense(12, input_dim=8, activation=\"relu\"))\nmodel.add(Dense(8, activation=\"relu\"))\nmodel.add(Dense(1, activation=\"sigmoid\"))\n# Compile model\nmodel.compile(loss=\"binary_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n# Fit the model\nhistory = model.fit(X, Y, validation_split=0.33, epochs=150, batch_size=10, verbose=0)\n# list all data in history\nprint(history.history.keys())\n# summarize history for accuracy\nplt.plot(history.history[\"accuracy\"])\nplt.plot(history.history[\"val_accuracy\"])\nplt.title(\"model accuracy\")\nplt.ylabel(\"accuracy\")\nplt.xlabel(\"epoch\")\nplt.legend([\"train\", \"test\"], loc=\"upper left\")\nplt.show()\n# summarize history for loss\nplt.plot(history.history[\"loss\"])\nplt.plot(history.history[\"val_loss\"])\nplt.title(\"model loss\")\nplt.ylabel(\"loss\")\nplt.xlabel(\"epoch\")\nplt.legend([\"train\", \"test\"], loc=\"upper left\")\nplt.show()\n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"numpy.random.seed",
"tensorflow.keras.layers.Dense",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"tensorflow.keras.models.Sequential",
"numpy.loadtxt",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
SachinVarghese/edge-cloud-inference | [
"ddf7de798d6e4dee2294df41c8ffde1b94b41dbc"
] | [
"src/train.py"
] | [
"from src.data import IrisData\nfrom sklearn.linear_model import LogisticRegression\nfrom xgboost import XGBClassifier\nimport joblib\n\nEdgeModelFolder = \"edge\"\nCloudModelFolder = \"cloud\"\n\n\ndef train_edge_model(data: IrisData, artifacts_folder: str):\n logreg = LogisticRegression(C=1e5)\n logreg.fit(data.X, data.y)\n with open(f\"{artifacts_folder}/{EdgeModelFolder}/model.joblib\", \"wb\") as f:\n joblib.dump(logreg, f)\n\n\ndef train_cloud_model(data: IrisData, artifacts_folder: str):\n clf = XGBClassifier()\n clf.fit(data.X, data.y)\n clf.save_model(f\"{artifacts_folder}/{CloudModelFolder}/model.bst\")\n"
] | [
[
"sklearn.linear_model.LogisticRegression"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
RaphDal/GraphNAS | [
"acb1fb978e10481b4417b7b4a22aec0482d8ff6b"
] | [
"graphnas_variants/macro_graphnas/pyg/pyg_gnn_layer.py"
] | [
"import torch\nimport torch.nn.functional as F\nfrom torch.nn import Parameter\nfrom torch_geometric.nn.inits import glorot, zeros\nfrom torch_geometric.utils import remove_self_loops, add_self_loops, softmax\nfrom torch_geometric.utils.num_nodes import maybe_num_nodes\n\nfrom torch_scatter import scatter_add\n\nfrom graphnas_variants.macro_graphnas.pyg.message_passing import MessagePassing\n\n\nclass GeoLayer(MessagePassing):\n\n def __init__(self,\n in_channels,\n out_channels,\n heads=1,\n concat=True,\n negative_slope=0.2,\n dropout=0,\n bias=True,\n att_type=\"gat\",\n agg_type=\"sum\",\n pool_dim=0):\n if agg_type in [\"sum\", \"mlp\"]:\n super(GeoLayer, self).__init__('add')\n elif agg_type in [\"mean\", \"max\"]:\n super(GeoLayer, self).__init__(agg_type)\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.heads = heads\n self.concat = concat\n self.negative_slope = negative_slope\n self.dropout = dropout\n self.att_type = att_type\n self.agg_type = agg_type\n\n # GCN weight\n self.gcn_weight = None\n\n self.weight = Parameter(\n torch.Tensor(in_channels, heads * out_channels))\n self.att = Parameter(torch.Tensor(1, heads, 2 * out_channels))\n\n if bias and concat:\n self.bias = Parameter(torch.Tensor(heads * out_channels))\n elif bias and not concat:\n self.bias = Parameter(torch.Tensor(out_channels))\n else:\n self.register_parameter('bias', None)\n\n if self.att_type in [\"generalized_linear\"]:\n self.general_att_layer = torch.nn.Linear(out_channels, 1, bias=False)\n\n if self.agg_type in [\"mean\", \"max\", \"mlp\"]:\n if pool_dim <= 0:\n pool_dim = 128\n self.pool_dim = pool_dim\n if pool_dim != 0:\n self.pool_layer = torch.nn.ModuleList()\n self.pool_layer.append(torch.nn.Linear(self.out_channels, self.pool_dim))\n self.pool_layer.append(torch.nn.Linear(self.pool_dim, self.out_channels))\n else:\n pass\n self.reset_parameters()\n\n @staticmethod\n def norm(edge_index, num_nodes, edge_weight, improved=False, dtype=None):\n if edge_weight is None:\n edge_weight = torch.ones((edge_index.size(1), ),\n dtype=dtype,\n device=edge_index.device)\n\n fill_value = 1 if not improved else 2\n\n num_nodes = maybe_num_nodes(edge_index, num_nodes)\n row, col = edge_index\n\n mask = row != col\n inv_mask = ~mask\n loop_weight = torch.full(\n (num_nodes, ),\n fill_value,\n dtype=None if edge_weight is None else edge_weight.dtype,\n device=edge_index.device)\n\n if edge_weight is not None:\n assert edge_weight.numel() == edge_index.size(1)\n loop_weight[row[inv_mask]] = edge_weight[inv_mask].view(-1)\n edge_weight = torch.cat([edge_weight[mask], loop_weight], dim=0)\n\n loop_index = torch.arange(0,\n num_nodes,\n dtype=torch.long,\n device=row.device)\n loop_index = loop_index.unsqueeze(0).repeat(2, 1)\n edge_index = torch.cat([edge_index[:, mask], loop_index], dim=1)\n\n row, col = edge_index\n deg = scatter_add(edge_weight, row, dim=0, dim_size=num_nodes)\n deg_inv_sqrt = deg.pow(-0.5)\n deg_inv_sqrt[deg_inv_sqrt == float('inf')] = 0\n\n return edge_index, deg_inv_sqrt[row] * edge_weight * deg_inv_sqrt[col]\n\n def reset_parameters(self):\n glorot(self.weight)\n glorot(self.att)\n zeros(self.bias)\n\n if self.att_type in [\"generalized_linear\"]:\n glorot(self.general_att_layer.weight)\n\n if self.pool_dim != 0:\n for layer in self.pool_layer:\n glorot(layer.weight)\n zeros(layer.bias)\n\n def forward(self, x, edge_index):\n \"\"\"\"\"\"\n edge_index, _ = remove_self_loops(edge_index)\n edge_index, _ = add_self_loops(edge_index, num_nodes=x.size(0))\n # prepare\n x = torch.mm(x, self.weight).view(-1, self.heads, self.out_channels)\n return self.propagate(edge_index, x=x, num_nodes=x.size(0))\n\n def message(self, x_i, x_j, edge_index, num_nodes):\n\n if self.att_type == \"const\":\n if self.training and self.dropout > 0:\n x_j = F.dropout(x_j, p=self.dropout, training=True)\n neighbor = x_j\n elif self.att_type == \"gcn\":\n if self.gcn_weight is None or self.gcn_weight.size(0) != x_j.size(0): # 对于不同的图gcn_weight需要重新计算\n _, norm = self.norm(edge_index, num_nodes, None)\n self.gcn_weight = norm\n neighbor = self.gcn_weight.view(-1, 1, 1) * x_j\n else:\n # Compute attention coefficients.\n alpha = self.apply_attention(edge_index, num_nodes, x_i, x_j)\n alpha = softmax(alpha, edge_index[0], num_nodes)\n # Sample attention coefficients stochastically.\n if self.training and self.dropout > 0:\n alpha = F.dropout(alpha, p=self.dropout, training=True)\n\n neighbor = x_j * alpha.view(-1, self.heads, 1)\n if self.pool_dim > 0:\n for layer in self.pool_layer:\n neighbor = layer(neighbor)\n return neighbor\n\n def apply_attention(self, edge_index, num_nodes, x_i, x_j):\n if self.att_type == \"gat\":\n alpha = (torch.cat([x_i, x_j], dim=-1) * self.att).sum(dim=-1)\n alpha = F.leaky_relu(alpha, self.negative_slope)\n\n elif self.att_type == \"gat_sym\":\n wl = self.att[:, :, :self.out_channels] # weight left\n wr = self.att[:, :, self.out_channels:] # weight right\n alpha = (x_i * wl).sum(dim=-1) + (x_j * wr).sum(dim=-1)\n alpha_2 = (x_j * wl).sum(dim=-1) + (x_i * wr).sum(dim=-1)\n alpha = F.leaky_relu(alpha, self.negative_slope) + F.leaky_relu(alpha_2, self.negative_slope)\n\n elif self.att_type == \"linear\":\n wl = self.att[:, :, :self.out_channels] # weight left\n wr = self.att[:, :, self.out_channels:] # weight right\n al = x_j * wl\n ar = x_j * wr\n alpha = al.sum(dim=-1) + ar.sum(dim=-1)\n alpha = torch.tanh(alpha)\n elif self.att_type == \"cos\":\n wl = self.att[:, :, :self.out_channels] # weight left\n wr = self.att[:, :, self.out_channels:] # weight right\n alpha = x_i * wl * x_j * wr\n alpha = alpha.sum(dim=-1)\n\n elif self.att_type == \"generalized_linear\":\n wl = self.att[:, :, :self.out_channels] # weight left\n wr = self.att[:, :, self.out_channels:] # weight right\n al = x_i * wl\n ar = x_j * wr\n alpha = al + ar\n alpha = torch.tanh(alpha)\n alpha = self.general_att_layer(alpha)\n else:\n raise Exception(\"Wrong attention type:\", self.att_type)\n return alpha\n\n def update(self, aggr_out):\n if self.concat is True:\n aggr_out = aggr_out.view(-1, self.heads * self.out_channels)\n else:\n aggr_out = aggr_out.mean(dim=1)\n\n if self.bias is not None:\n aggr_out = aggr_out + self.bias\n return aggr_out\n\n def __repr__(self):\n return '{}({}, {}, heads={})'.format(self.__class__.__name__,\n self.in_channels,\n self.out_channels, self.heads)\n\n def get_param_dict(self):\n params = {}\n key = f\"{self.att_type}_{self.agg_type}_{self.in_channels}_{self.out_channels}_{self.heads}\"\n weight_key = key + \"_weight\"\n att_key = key + \"_att\"\n agg_key = key + \"_agg\"\n bais_key = key + \"_bais\"\n\n params[weight_key] = self.weight\n params[att_key] = self.att\n params[bais_key] = self.bias\n if hasattr(self, \"pool_layer\"):\n params[agg_key] = self.pool_layer.state_dict()\n\n return params\n\n def load_param(self, params):\n key = f\"{self.att_type}_{self.agg_type}_{self.in_channels}_{self.out_channels}_{self.heads}\"\n weight_key = key + \"_weight\"\n att_key = key + \"_att\"\n agg_key = key + \"_agg\"\n bais_key = key + \"_bais\"\n\n if weight_key in params:\n self.weight = params[weight_key]\n\n if att_key in params:\n self.att = params[att_key]\n\n if bais_key in params:\n self.bias = params[bais_key]\n\n if agg_key in params and hasattr(self, \"pool_layer\"):\n self.pool_layer.load_state_dict(params[agg_key])\n"
] | [
[
"torch.mm",
"torch.Tensor",
"torch.cat",
"torch.full",
"torch.nn.functional.dropout",
"torch.nn.ModuleList",
"torch.tanh",
"torch.nn.Linear",
"torch.nn.functional.leaky_relu",
"torch.arange"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
KaenChan/ProbFace | [
"80a4de290ae583c81714bd3e3446c039a010e095",
"80a4de290ae583c81714bd3e3446c039a010e095"
] | [
"evaluation/lfw.py",
"evaluation/ijba.py"
] | [
"\"\"\"Test protocols on LFW dataset\n\"\"\"\n# MIT License\n# \n# Copyright (c) 2017 Yichun Shi\n# Copyright (c) 2021 Kaen Chan\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport os\nimport numpy as np\nimport scipy.io as sio\nfrom evaluation import metrics\nfrom collections import namedtuple\n\nStandardFold = namedtuple('StandardFold', ['indices1', 'indices2', 'labels'])\n\nclass LFWTest:\n def __init__(self, image_paths):\n self.image_paths = np.array(image_paths).astype(np.object).flatten()\n self.images = None\n self.labels = None\n self.standard_folds = None\n self.blufr_folds = None\n self.queue_idx = None\n\n def init_standard_proto(self, lfw_pairs_file):\n index_dict = {}\n for i, image_path in enumerate(self.image_paths):\n image_name, image_ext = os.path.splitext(os.path.basename(image_path))\n index_dict[image_name] = i\n\n pairs = []\n with open(lfw_pairs_file, 'r') as f:\n for line in f.readlines()[1:]:\n pair = line.strip().split()\n pairs.append(pair)\n\n # 10 folds\n self.standard_folds = []\n for i in range(10):\n indices1 = np.zeros(600, dtype=np.int32)\n indices2 = np.zeros(600, dtype=np.int32)\n labels = np.array([True]*300+[False]*300, dtype=np.bool)\n # 300 positive pairs, 300 negative pairs in order\n for j in range(600):\n pair = pairs[600*i+j]\n if j < 300:\n assert len(pair) == 3\n img1 = pair[0] + '_' + '%04d' % int(pair[1])\n img2 = pair[0] + '_' + '%04d' % int(pair[2])\n else:\n assert len(pair) == 4\n img1 = pair[0] + '_' + '%04d' % int(pair[1])\n img2 = pair[2] + '_' + '%04d' % int(pair[3]) \n indices1[j] = index_dict[img1]\n indices2[j] = index_dict[img2]\n fold = StandardFold(indices1, indices2, labels)\n self.standard_folds.append(fold)\n\n def test_standard_proto(self, features, compare_func):\n\n assert self.standard_folds is not None\n \n accuracies = np.zeros(10, dtype=np.float32)\n thresholds = np.zeros(10, dtype=np.float32)\n\n features1 = []\n features2 = []\n\n for i in range(10):\n # Training\n train_indices1 = np.concatenate([self.standard_folds[j].indices1 for j in range(10) if j!=i])\n train_indices2 = np.concatenate([self.standard_folds[j].indices2 for j in range(10) if j!=i])\n train_labels = np.concatenate([self.standard_folds[j].labels for j in range(10) if j!=i])\n\n train_features1 = features[train_indices1,:]\n train_features2 = features[train_indices2,:]\n \n train_score = compare_func(train_features1, train_features2)\n acc, thresholds[i] = metrics.accuracy(train_score, train_labels)\n # print('train acc', acc, thresholds[i])\n\n # Testing\n fold = self.standard_folds[i]\n test_features1 = features[fold.indices1,:]\n test_features2 = features[fold.indices2,:]\n \n test_score = compare_func(test_features1, test_features2)\n accuracies[i], _ = metrics.accuracy(test_score, fold.labels, np.array([thresholds[i]]))\n\n accuracy = np.mean(accuracies)\n threshold = np.mean(thresholds)\n return accuracy, threshold\n\n",
"\"\"\"Test protocol for IJB-A.\n\"\"\"\n# MIT License\n# \n# Copyright (c) 2019 Yichun Shi\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport sys\nimport os\nimport numpy as np\nimport utils\n\nfrom collections import namedtuple\n\nfrom evaluation import metrics\n\nVerificationFold = namedtuple('VerificationFold', ['train_indices', 'test_indices', 'train_templates', 'templates1','templates2'])\n\nclass Template:\n def __init__(self, subject_id, label, indices, medias):\n self.subject_id = subject_id\n self.label = label\n self.indices = np.array(indices)\n self.medias = np.array(medias)\n \n\ndef build_subject_dict(image_list):\n subject_dict = {}\n for i, line in enumerate(image_list):\n # subject_id, image = tuple(line.split('/')[-2:])\n subject_id, image = tuple(line.split('\\\\')[-2:])\n # subject_id = int(subject_id)\n image, _ = os.path.splitext(image)\n # image = image.replace('_','/',1) # Recover filenames\n # if not subject_id in subject_dict:\n # subject_dict[subject_id] = {}\n # subject_dict[subject_id][image] = i\n subject_dict[subject_id + '/' + image] = i\n return subject_dict\n\ndef build_templates(subject_dict, meta_file):\n with open(meta_file, 'r') as f:\n meta_list = f.readlines()\n meta_list = [x.split('\\n')[0] for x in meta_list]\n meta_list = meta_list[1:]\n\n templates = []\n template_id = None\n template_label = None\n template_indices = None \n template_medias = None\n count = 0\n for line in meta_list:\n temp_id, subject_id, image, media = tuple(line.split(',')[0:4])\n temp_id = int(temp_id)\n subject_id = int(subject_id)\n image, _ = os.path.splitext(image)\n # if subject_id in subject_dict and image in subject_dict[subject_id]:\n if image in subject_dict:\n index = subject_dict[image]\n count += 1\n else:\n index = None\n\n if temp_id != template_id:\n if template_id is not None:\n templates.append(Template(template_id, template_label, template_indices, template_medias))\n template_id = temp_id\n template_label = subject_id\n template_indices = []\n template_medias = []\n if index is not None:\n template_indices.append(index) \n template_medias.append(media) \n\n # last template\n templates.append(Template(template_id, template_label, template_indices, template_medias))\n return templates\n\ndef read_pairs(pair_file):\n with open(pair_file, 'r') as f:\n pairs = f.readlines()\n pairs = [x.split('\\n')[0] for x in pairs]\n pairs = [pair.split(',') for pair in pairs]\n pairs = [(int(pair[0]), int(pair[1])) for pair in pairs]\n return pairs\n\nclass IJBATest:\n\n def __init__(self, image_paths):\n self.image_paths = image_paths\n self.subject_dict = build_subject_dict(image_paths)\n self.verification_folds = None\n self.verification_templates = None\n\n def init_verification_proto(self, protofolder):\n self.verification_folds = []\n self.verification_templates = []\n for split in range(10):\n splitfolder = os.path.join(protofolder,'split%d'%(split+1))\n train_file = os.path.join(splitfolder,'train_%d.csv'%(split+1))\n meta_file = os.path.join(splitfolder,'verify_metadata_%d.csv'%(split+1))\n pair_file = os.path.join(splitfolder,'verify_comparisons_%d.csv'%(split+1))\n\n train_templates = build_templates(self.subject_dict, train_file)\n train_indices = list(np.unique(np.concatenate([t.indices for t in train_templates])).astype(int))\n\n test_templates = build_templates(self.subject_dict, meta_file)\n test_indices = list(np.unique(np.concatenate([t.indices for t in test_templates])).astype(int))\n template_dict = {}\n for t in test_templates:\n template_dict[t.subject_id] = t\n pairs = read_pairs(pair_file)\n templates1 = []\n templates2 = []\n for p in pairs:\n templates1.append(template_dict[p[0]])\n templates2.append(template_dict[p[1]])\n\n train_templates = np.array(train_templates, dtype=np.object)\n templates1 = np.array(templates1, dtype=np.object)\n templates2 = np.array(templates2, dtype=np.object)\n\n self.verification_folds.append(VerificationFold(\\\n train_indices=train_indices, test_indices=test_indices,\n train_templates=train_templates, templates1=templates1, templates2=templates2))\n\n self.verification_templates.extend(train_templates)\n self.verification_templates.extend(templates1)\n self.verification_templates.extend(templates2)\n\n def init_proto(self, protofolder):\n self.init_verification_proto(os.path.join(protofolder, 'IJB-A_11_sets'))\n\n def test_verification_fold(self, compare_func, fold_idx, FARs=None, get_false_indices=False):\n\n FARs = [0.001, 0.01] if FARs is None else FARs\n\n fold = self.verification_folds[fold_idx]\n\n templates1 = fold.templates1\n templates2 = fold.templates2\n\n features1 = [t.feature for t in templates1]\n features2 = [t.feature for t in templates2]\n labels1 = np.array([t.label for t in templates1])\n labels2 = np.array([t.label for t in templates2])\n\n score_vec = compare_func(features1, features2)\n label_vec = labels1 == labels2\n\n score_neg = score_vec[~label_vec] \n\n return metrics.ROC(score_vec, label_vec, \n FARs=FARs, get_false_indices=get_false_indices)\n\n def test_verification(self, compare_func, FARs=None):\n \n TARs_all = []\n FARs_all = []\n for i in range(10):\n TARs, FARs, thresholds = self.test_verification_fold(compare_func, i, FARs=FARs)\n TARs_all.append(TARs)\n FARs_all.append(FARs)\n\n TARs_all = np.stack(TARs_all)\n FARs_all = np.stack(FARs_all)\n\n\n return np.mean(TARs_all, axis=0), np.std(TARs_all, axis=0), np.mean(FARs_all, axis=0)\n"
] | [
[
"numpy.array",
"numpy.zeros",
"numpy.mean"
],
[
"numpy.stack",
"numpy.concatenate",
"numpy.std",
"numpy.mean",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rpradal/cvxpy | [
"86307f271819bb78fcdf64a9c3a424773e8269fa",
"222ae345d2df67040346267f55369d8433d2e50f"
] | [
"cvxpy/tests/test_qp_solvers.py",
"cvxpy/tests/test_problem.py"
] | [
"\"\"\"\n\nCopyright 2013 Steven Diamond, 2017 Robin Verschueren\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\"\"\"\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.linalg import lstsq\n\nfrom cvxpy import Minimize, Problem, Parameter, Maximize\nfrom cvxpy.atoms import (QuadForm, abs, power,\n quad_over_lin, sum, sum_squares,\n norm,\n huber,\n matrix_frac)\nfrom cvxpy.reductions.solvers.defines import QP_SOLVERS, INSTALLED_SOLVERS\nfrom cvxpy.expressions.variable import Variable\nfrom cvxpy.tests.base_test import BaseTest\n\n\nclass TestQp(BaseTest):\n \"\"\" Unit tests for the domain module. \"\"\"\n\n def setUp(self) -> None:\n self.a = Variable(name='a')\n self.b = Variable(name='b')\n self.c = Variable(name='c')\n\n self.x = Variable(2, name='x')\n self.y = Variable(3, name='y')\n self.z = Variable(2, name='z')\n self.w = Variable(5, name='w')\n\n self.A = Variable((2, 2), name='A')\n self.B = Variable((2, 2), name='B')\n self.C = Variable((3, 2), name='C')\n\n self.slope = Variable(1, name='slope')\n self.offset = Variable(1, name='offset')\n self.quadratic_coeff = Variable(1, name='quadratic_coeff')\n\n T = 100\n self.position = Variable((2, T), name='position')\n self.velocity = Variable((2, T), name='velocity')\n self.force = Variable((2, T - 1), name='force')\n\n self.xs = Variable(80, name='xs')\n self.xsr = Variable(200, name='xsr')\n self.xef = Variable(80, name='xef')\n\n # Check for all installed QP solvers\n self.solvers = [x for x in QP_SOLVERS if x in INSTALLED_SOLVERS]\n if 'MOSEK' in INSTALLED_SOLVERS:\n self.solvers.append('MOSEK')\n\n def solve_QP(self, problem, solver_name):\n return problem.solve(solver=solver_name, verbose=False)\n\n def test_all_solvers(self) -> None:\n for solver in self.solvers:\n self.quad_over_lin(solver)\n self.power(solver)\n self.power_matrix(solver)\n self.square_affine(solver)\n self.quad_form(solver)\n self.affine_problem(solver)\n self.maximize_problem(solver)\n self.abs(solver)\n\n # Do we need the following functionality?\n # self.norm_2(solver)\n # self.mat_norm_2(solver)\n\n self.quad_form_coeff(solver)\n self.quad_form_bound(solver)\n self.regression_1(solver)\n self.regression_2(solver)\n self.rep_quad_form(solver)\n\n # slow tests:\n self.control(solver)\n self.sparse_system(solver)\n self.smooth_ridge(solver)\n self.huber_small(solver)\n self.huber(solver)\n self.equivalent_forms_1(solver)\n self.equivalent_forms_2(solver)\n self.equivalent_forms_3(solver)\n\n def quad_over_lin(self, solver) -> None:\n p = Problem(Minimize(0.5 * quad_over_lin(abs(self.x-1), 1)),\n [self.x <= -1])\n self.solve_QP(p, solver)\n for var in p.variables():\n self.assertItemsAlmostEqual(np.array([-1., -1.]),\n var.value, places=4)\n for con in p.constraints:\n self.assertItemsAlmostEqual(np.array([2., 2.]),\n con.dual_value, places=4)\n\n def abs(self, solver) -> None:\n u = Variable(2)\n constr = []\n constr += [abs(u[1] - u[0]) <= 100]\n prob = Problem(Minimize(sum_squares(u)), constr)\n print(\"The problem is QP: \", prob.is_qp())\n self.assertEqual(prob.is_qp(), True)\n result = prob.solve(solver=solver)\n self.assertAlmostEqual(result, 0)\n\n def power(self, solver) -> None:\n p = Problem(Minimize(sum(power(self.x, 2))), [])\n self.solve_QP(p, solver)\n for var in p.variables():\n self.assertItemsAlmostEqual([0., 0.], var.value, places=4)\n\n def power_matrix(self, solver) -> None:\n p = Problem(Minimize(sum(power(self.A - 3., 2))), [])\n self.solve_QP(p, solver)\n for var in p.variables():\n self.assertItemsAlmostEqual([3., 3., 3., 3.],\n var.value, places=4)\n\n def square_affine(self, solver) -> None:\n A = np.random.randn(10, 2)\n b = np.random.randn(10)\n p = Problem(Minimize(sum_squares(A @ self.x - b)))\n self.solve_QP(p, solver)\n for var in p.variables():\n self.assertItemsAlmostEqual(lstsq(A, b)[0].flatten(),\n var.value,\n places=1)\n\n def quad_form(self, solver) -> None:\n np.random.seed(0)\n A = np.random.randn(5, 5)\n z = np.random.randn(5)\n P = A.T.dot(A)\n q = -2*P.dot(z)\n p = Problem(Minimize(QuadForm(self.w, P) + q.T @ self.w))\n self.solve_QP(p, solver)\n for var in p.variables():\n self.assertItemsAlmostEqual(z, var.value, places=4)\n\n def rep_quad_form(self, solver) -> None:\n \"\"\"A problem where the quad_form term is used multiple times.\n \"\"\"\n np.random.seed(0)\n A = np.random.randn(5, 5)\n z = np.random.randn(5)\n P = A.T.dot(A)\n q = -2*P.dot(z)\n qf = QuadForm(self.w, P)\n p = Problem(Minimize(0.5*qf + 0.5*qf + q.T @ self.w))\n self.solve_QP(p, solver)\n for var in p.variables():\n self.assertItemsAlmostEqual(z, var.value, places=4)\n\n def affine_problem(self, solver) -> None:\n A = np.random.randn(5, 2)\n A = np.maximum(A, 0)\n b = np.random.randn(5)\n b = np.maximum(b, 0)\n p = Problem(Minimize(sum(self.x)), [self.x >= 0, A @ self.x <= b])\n self.solve_QP(p, solver)\n for var in p.variables():\n self.assertItemsAlmostEqual([0., 0.], var.value, places=3)\n\n def maximize_problem(self, solver) -> None:\n A = np.random.randn(5, 2)\n A = np.maximum(A, 0)\n b = np.random.randn(5)\n b = np.maximum(b, 0)\n p = Problem(Maximize(-sum(self.x)), [self.x >= 0, A @ self.x <= b])\n self.solve_QP(p, solver)\n for var in p.variables():\n self.assertItemsAlmostEqual([0., 0.], var.value, places=3)\n\n def norm_2(self, solver) -> None:\n A = np.random.randn(10, 5)\n b = np.random.randn(10)\n p = Problem(Minimize(norm(A @ self.w - b, 2)))\n self.solve_QP(p, solver)\n for var in p.variables():\n self.assertItemsAlmostEqual(lstsq(A, b)[0].flatten(), var.value,\n places=1)\n\n def mat_norm_2(self, solver) -> None:\n A = np.random.randn(5, 3)\n B = np.random.randn(5, 2)\n p = Problem(Minimize(norm(A @ self.C - B, 2)))\n s = self.solve_QP(p, solver)\n for var in p.variables():\n self.assertItemsAlmostEqual(lstsq(A, B)[0],\n s.primal_vars[var.id], places=1)\n\n def quad_form_coeff(self, solver) -> None:\n np.random.seed(0)\n A = np.random.randn(5, 5)\n z = np.random.randn(5)\n P = A.T.dot(A)\n q = -2*P.dot(z)\n p = Problem(Minimize(QuadForm(self.w, P) + q.T @ self.w))\n self.solve_QP(p, solver)\n for var in p.variables():\n self.assertItemsAlmostEqual(z, var.value, places=4)\n\n def quad_form_bound(self, solver) -> None:\n P = np.array([[13, 12, -2], [12, 17, 6], [-2, 6, 12]])\n q = np.array([[-22], [-14.5], [13]])\n r = 1\n y_star = np.array([[1], [0.5], [-1]])\n p = Problem(Minimize(0.5*QuadForm(self.y, P) + q.T @ self.y + r),\n [self.y >= -1, self.y <= 1])\n self.solve_QP(p, solver)\n for var in p.variables():\n self.assertItemsAlmostEqual(y_star, var.value, places=4)\n\n def regression_1(self, solver) -> None:\n np.random.seed(1)\n # Number of examples to use\n n = 100\n # Specify the true value of the variable\n true_coeffs = np.array([[2, -2, 0.5]]).T\n # Generate data\n x_data = np.random.rand(n) * 5\n x_data = np.atleast_2d(x_data)\n x_data_expanded = np.vstack([np.power(x_data, i)\n for i in range(1, 4)])\n x_data_expanded = np.atleast_2d(x_data_expanded)\n y_data = x_data_expanded.T.dot(true_coeffs) + 0.5 * np.random.rand(n, 1)\n y_data = np.atleast_2d(y_data)\n\n line = self.offset + x_data * self.slope\n residuals = line.T - y_data\n fit_error = sum_squares(residuals)\n p = Problem(Minimize(fit_error), [])\n self.solve_QP(p, solver)\n self.assertAlmostEqual(1171.60037715, p.value, places=4)\n\n def regression_2(self, solver) -> None:\n np.random.seed(1)\n # Number of examples to use\n n = 100\n # Specify the true value of the variable\n true_coeffs = np.array([2, -2, 0.5])\n # Generate data\n x_data = np.random.rand(n) * 5\n x_data_expanded = np.vstack([np.power(x_data, i)\n for i in range(1, 4)])\n print(x_data_expanded.shape, true_coeffs.shape)\n y_data = x_data_expanded.T.dot(true_coeffs) + 0.5 * np.random.rand(n)\n\n quadratic = self.offset + x_data * self.slope + \\\n self.quadratic_coeff*np.power(x_data, 2)\n residuals = quadratic.T - y_data\n fit_error = sum_squares(residuals)\n p = Problem(Minimize(fit_error), [])\n self.solve_QP(p, solver)\n\n self.assertAlmostEqual(139.225660756, p.value, places=4)\n\n def control(self, solver) -> None:\n # Some constraints on our motion\n # The object should start from the origin, and end at rest\n initial_velocity = np.array([-20, 100])\n final_position = np.array([100, 100])\n T = 100 # The number of timesteps\n h = 0.1 # The time between time intervals\n mass = 1 # Mass of object\n drag = 0.1 # Drag on object\n g = np.array([0, -9.8]) # Gravity on object\n # Create a problem instance\n constraints = []\n # Add constraints on our variables\n for i in range(T - 1):\n constraints += [self.position[:, i + 1] == self.position[:, i] +\n h * self.velocity[:, i]]\n acceleration = self.force[:, i]/mass + g - \\\n drag * self.velocity[:, i]\n constraints += [self.velocity[:, i + 1] == self.velocity[:, i] +\n h * acceleration]\n\n # Add position constraints\n constraints += [self.position[:, 0] == 0]\n constraints += [self.position[:, -1] == final_position]\n # Add velocity constraints\n constraints += [self.velocity[:, 0] == initial_velocity]\n constraints += [self.velocity[:, -1] == 0]\n # Solve the problem\n p = Problem(Minimize(.01 * sum_squares(self.force)), constraints)\n self.solve_QP(p, solver)\n self.assertAlmostEqual(178.500, p.value, places=1)\n\n def sparse_system(self, solver) -> None:\n m = 100\n n = 80\n np.random.seed(1)\n density = 0.4\n A = sp.rand(m, n, density)\n b = np.random.randn(m)\n\n p = Problem(Minimize(sum_squares(A @ self.xs - b)), [self.xs == 0])\n self.solve_QP(p, solver)\n self.assertAlmostEqual(b.T.dot(b), p.value, places=4)\n\n def smooth_ridge(self, solver) -> None:\n np.random.seed(1)\n n = 200\n k = 50\n eta = 1\n\n A = np.ones((k, n))\n b = np.ones((k))\n obj = sum_squares(A @ self.xsr - b) + \\\n eta*sum_squares(self.xsr[:-1]-self.xsr[1:])\n p = Problem(Minimize(obj), [])\n self.solve_QP(p, solver)\n self.assertAlmostEqual(0, p.value, places=4)\n\n def huber_small(self, solver) -> None:\n # Solve the Huber regression problem\n x = Variable(3)\n objective = sum(huber(x))\n\n # Solve problem with QP\n p = Problem(Minimize(objective), [x[2] >= 3])\n self.solve_QP(p, solver)\n self.assertAlmostEqual(3, x.value[2], places=4)\n self.assertAlmostEqual(5, objective.value, places=4)\n\n def huber(self, solver) -> None:\n # Generate problem data\n np.random.seed(2)\n n = 3\n m = 5\n A = sp.random(m, n, density=0.8, format='csc')\n x_true = np.random.randn(n) / np.sqrt(n)\n ind95 = (np.random.rand(m) < 0.95).astype(float)\n b = A.dot(x_true) + np.multiply(0.5*np.random.randn(m), ind95) \\\n + np.multiply(10.*np.random.rand(m), 1. - ind95)\n\n # Solve the Huber regression problem\n x = Variable(n)\n objective = sum(huber(A @ x - b))\n\n # Solve problem with QP\n p = Problem(Minimize(objective))\n self.solve_QP(p, solver)\n self.assertAlmostEqual(1.327429461061672, objective.value, places=3)\n self.assertItemsAlmostEqual(x.value,\n [-1.03751745, 0.86657204, -0.9649172],\n places=3)\n\n def equivalent_forms_1(self, solver) -> None:\n m = 100\n n = 80\n r = 70\n np.random.seed(1)\n A = np.random.randn(m, n)\n b = np.random.randn(m)\n G = np.random.randn(r, n)\n h = np.random.randn(r)\n\n obj1 = .1 * sum((A @ self.xef - b) ** 2)\n cons = [G @ self.xef == h]\n\n p1 = Problem(Minimize(obj1), cons)\n self.solve_QP(p1, solver)\n self.assertAlmostEqual(p1.value, 68.1119420108, places=4)\n\n def equivalent_forms_2(self, solver) -> None:\n m = 100\n n = 80\n r = 70\n np.random.seed(1)\n A = np.random.randn(m, n)\n b = np.random.randn(m)\n G = np.random.randn(r, n)\n h = np.random.randn(r)\n\n # ||Ax-b||^2 = x^T (A^T A) x - 2(A^T b)^T x + ||b||^2\n P = np.dot(A.T, A)\n q = -2*np.dot(A.T, b)\n r = np.dot(b.T, b)\n\n obj2 = .1*(QuadForm(self.xef, P)+q.T @ self.xef+r)\n cons = [G @ self.xef == h]\n\n p2 = Problem(Minimize(obj2), cons)\n self.solve_QP(p2, solver)\n self.assertAlmostEqual(p2.value, 68.1119420108, places=4)\n\n def equivalent_forms_3(self, solver) -> None:\n m = 100\n n = 80\n r = 70\n np.random.seed(1)\n A = np.random.randn(m, n)\n b = np.random.randn(m)\n G = np.random.randn(r, n)\n h = np.random.randn(r)\n\n # ||Ax-b||^2 = x^T (A^T A) x - 2(A^T b)^T x + ||b||^2\n P = np.dot(A.T, A)\n q = -2*np.dot(A.T, b)\n r = np.dot(b.T, b)\n Pinv = np.linalg.inv(P)\n\n obj3 = .1 * (matrix_frac(self.xef, Pinv)+q.T @ self.xef+r)\n cons = [G @ self.xef == h]\n\n p3 = Problem(Minimize(obj3), cons)\n self.solve_QP(p3, solver)\n self.assertAlmostEqual(p3.value, 68.1119420108, places=4)\n\n def test_warm_start(self) -> None:\n \"\"\"Test warm start.\n \"\"\"\n m = 200\n n = 100\n np.random.seed(1)\n A = np.random.randn(m, n)\n b = Parameter(m)\n\n # Construct the problem.\n x = Variable(n)\n prob = Problem(Minimize(sum_squares(A @ x - b)))\n\n b.value = np.random.randn(m)\n result = prob.solve(warm_start=False)\n result2 = prob.solve(warm_start=True)\n self.assertAlmostEqual(result, result2)\n b.value = np.random.randn(m)\n result = prob.solve(warm_start=True)\n result2 = prob.solve(warm_start=False)\n self.assertAlmostEqual(result, result2)\n pass\n\n def test_parametric(self) -> None:\n \"\"\"Test solve parametric problem vs full problem\"\"\"\n x = Variable()\n a = 10\n # b_vec = [-10, -2., 2., 3., 10.]\n b_vec = [-10, -2.]\n\n for solver in self.solvers:\n\n print(solver)\n # Solve from scratch with no parameters\n x_full = []\n obj_full = []\n for b in b_vec:\n obj = Minimize(a * (x ** 2) + b * x)\n constraints = [0 <= x, x <= 1]\n prob = Problem(obj, constraints)\n prob.solve(solver=solver)\n x_full += [x.value]\n obj_full += [prob.value]\n\n # Solve parametric\n x_param = []\n obj_param = []\n b = Parameter()\n obj = Minimize(a * (x ** 2) + b * x)\n constraints = [0 <= x, x <= 1]\n prob = Problem(obj, constraints)\n for b_value in b_vec:\n b.value = b_value\n prob.solve(solver=solver)\n x_param += [x.value]\n obj_param += [prob.value]\n\n print(x_full)\n print(x_param)\n for i in range(len(b_vec)):\n self.assertItemsAlmostEqual(x_full[i], x_param[i], places=3)\n self.assertAlmostEqual(obj_full[i], obj_param[i])\n\n def test_square_param(self) -> None:\n \"\"\"Test issue arising with square plus parameter.\n \"\"\"\n a = Parameter(value=1)\n b = Variable()\n\n obj = Minimize(b ** 2 + abs(a))\n prob = Problem(obj)\n prob.solve()\n self.assertAlmostEqual(obj.value, 1.0)\n\n def test_gurobi_time_limit_no_solution(self) -> None:\n \"\"\"Make sure that if Gurobi terminates due to a time limit before finding a solution:\n 1) no error is raised,\n 2) solver stats are returned.\n The test is skipped if something changes on Gurobi's side so that:\n - a solution is found despite a time limit of zero,\n - a different termination criteria is hit first.\n \"\"\"\n from cvxpy import GUROBI\n if GUROBI in INSTALLED_SOLVERS:\n import gurobipy\n objective = Minimize(self.x[0])\n constraints = [self.x[0] >= 1]\n prob = Problem(objective, constraints)\n try:\n prob.solve(solver=GUROBI, TimeLimit=0.0)\n except Exception as e:\n self.fail(\"An exception %s is raised instead of returning a result.\" % e)\n\n extra_stats = None\n solver_stats = getattr(prob, \"solver_stats\", None)\n if solver_stats:\n extra_stats = getattr(solver_stats, \"extra_stats\", None)\n self.assertTrue(extra_stats, \"Solver stats have not been returned.\")\n\n nb_solutions = getattr(extra_stats, \"SolCount\", None)\n if nb_solutions:\n self.skipTest(\"Gurobi has found a solution, the test is not relevant anymore.\")\n\n solver_status = getattr(extra_stats, \"Status\", None)\n if solver_status != gurobipy.StatusConstClass.TIME_LIMIT:\n self.skipTest(\"Gurobi terminated for a different reason than reaching time limit, \"\n \"the test is not relevant anymore.\")\n\n else:\n with self.assertRaises(Exception) as cm:\n prob = Problem(Minimize(norm(self.x, 1)), [self.x == 0])\n prob.solve(solver=GUROBI, TimeLimit=0)\n self.assertEqual(str(cm.exception), \"The solver %s is not installed.\" % GUROBI)\n",
"\"\"\"\nCopyright 2017 Steven Diamond\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\"\"\"\n\nfrom fractions import Fraction\nimport cvxpy.settings as s\nimport cvxpy as cp\nfrom cvxpy.constraints import NonPos, Zero, ExpCone, PSD\nfrom cvxpy.error import DCPError, ParameterError, SolverError\nfrom cvxpy.expressions.constants import Constant, Parameter\nfrom cvxpy.expressions.variable import Variable\nfrom cvxpy.problems.problem import Problem\nfrom cvxpy.reductions.solvers.conic_solvers.conic_solver import ConicSolver\nfrom cvxpy.reductions.solvers.conic_solvers import ecos_conif, scs_conif\nfrom cvxpy.reductions.solvers.defines import SOLVER_MAP_CONIC, INSTALLED_SOLVERS\nimport cvxpy.interface as intf\nfrom cvxpy.tests.base_test import BaseTest\nfrom numpy import linalg as LA\nimport numpy\nimport numpy as np\nimport scipy.sparse as sp\nimport builtins\nimport sys\nimport pickle\n# Solvers.\nimport scs\nimport ecos\nimport warnings\nfrom io import StringIO\n\n\nclass TestProblem(BaseTest):\n \"\"\"Unit tests for the expression/expression module.\n \"\"\"\n\n def setUp(self) -> None:\n self.a = Variable(name='a')\n self.b = Variable(name='b')\n self.c = Variable(name='c')\n\n self.x = Variable(2, name='x')\n self.y = Variable(3, name='y')\n self.z = Variable(2, name='z')\n\n self.A = Variable((2, 2), name='A')\n self.B = Variable((2, 2), name='B')\n self.C = Variable((3, 2), name='C')\n\n def test_to_str(self) -> None:\n \"\"\"Test string representations.\n \"\"\"\n obj = cp.Minimize(self.a)\n prob = Problem(obj)\n self.assertEqual(repr(prob), \"Problem(%s, %s)\" % (repr(obj), repr([])))\n constraints = [self.x*2 == self.x, self.x == 0]\n prob = Problem(obj, constraints)\n self.assertEqual(repr(prob), \"Problem(%s, %s)\" % (repr(obj), repr(constraints)))\n\n # Test str.\n result = (\n \"minimize %(name)s\\nsubject to %(name)s == 0\\n %(name)s <= 0\" % {\n \"name\": self.a.name()\n }\n )\n prob = Problem(cp.Minimize(self.a), [Zero(self.a), NonPos(self.a)])\n self.assertEqual(str(prob), result)\n\n def test_variables(self) -> None:\n \"\"\"Test the variables method.\n \"\"\"\n p = Problem(cp.Minimize(self.a), [self.a <= self.x, self.b <= self.A + 2])\n vars_ = p.variables()\n ref = [self.a, self.x, self.b, self.A]\n self.assertCountEqual(vars_, ref)\n\n def test_var_dict(self) -> None:\n p = Problem(cp.Minimize(self.a), [self.a <= self.x, self.b <= self.A + 2])\n assert p.var_dict == {\"a\": self.a, \"x\": self.x, \"b\": self.b, \"A\": self.A}\n\n def test_parameters(self) -> None:\n \"\"\"Test the parameters method.\n \"\"\"\n p1 = Parameter()\n p2 = Parameter(3, nonpos=True)\n p3 = Parameter((4, 4), nonneg=True)\n p = Problem(cp.Minimize(p1), [self.a + p1 <= p2, self.b <= p3 + p3 + 2])\n params = p.parameters()\n ref = [p1, p2, p3]\n self.assertCountEqual(params, ref)\n\n def test_param_dict(self) -> None:\n p1 = Parameter(name=\"p1\")\n p2 = Parameter(3, nonpos=True, name=\"p2\")\n p3 = Parameter((4, 4), nonneg=True, name=\"p3\")\n p = Problem(cp.Minimize(p1), [self.a + p1 <= p2, self.b <= p3 + p3 + 2])\n assert p.param_dict == {\"p1\": p1, \"p2\": p2, \"p3\": p3}\n\n def test_solving_a_problem_with_unspecified_parameters(self) -> None:\n param = cp.Parameter(name=\"lambda\")\n problem = cp.Problem(cp.Minimize(param), [])\n with self.assertRaises(\n ParameterError, msg=\"A Parameter (whose name is 'lambda').*\"):\n problem.solve()\n\n def test_constants(self) -> None:\n \"\"\"Test the constants method.\n \"\"\"\n c1 = numpy.random.randn(1, 2)\n c2 = numpy.random.randn(2)\n p = Problem(cp.Minimize(c1 @ self.x), [self.x >= c2])\n constants_ = p.constants()\n ref = [c1, c2]\n self.assertEqual(len(ref), len(constants_))\n for c, r in zip(constants_, ref):\n self.assertTupleEqual(c.shape, r.shape)\n self.assertTrue((c.value == r).all())\n # Allows comparison between numpy matrices and numpy arrays\n # Necessary because of the way cvxpy handles numpy arrays and constants\n\n # Single scalar constants\n p = Problem(cp.Minimize(self.a), [self.x >= 1])\n constants_ = p.constants()\n ref = [numpy.array(1)]\n self.assertEqual(len(ref), len(constants_))\n for c, r in zip(constants_, ref):\n self.assertEqual(c.shape, r.shape) and \\\n self.assertTrue((c.value == r).all())\n # Allows comparison between numpy matrices and numpy arrays\n # Necessary because of the way cvxpy handles numpy arrays and constants\n\n def test_size_metrics(self) -> None:\n \"\"\"Test the size_metrics method.\n \"\"\"\n p1 = Parameter()\n p2 = Parameter(3, nonpos=True)\n p3 = Parameter((4, 4), nonneg=True)\n\n c1 = numpy.random.randn(2, 1)\n c2 = numpy.random.randn(1, 2)\n constants = [2, c2.dot(c1)]\n\n p = Problem(cp.Minimize(p1), [self.a + p1 <= p2,\n self.b <= p3 + p3 + constants[0],\n self.c == constants[1]])\n # num_scalar_variables\n n_variables = p.size_metrics.num_scalar_variables\n ref = self.a.size + self.b.size + self.c.size\n self.assertEqual(n_variables, ref)\n\n # num_scalar_data\n n_data = p.size_metrics.num_scalar_data\n # 2 and c2.dot(c1) are both single scalar constants.\n ref = numpy.prod(p1.size) + numpy.prod(p2.size) + numpy.prod(p3.size) + len(constants)\n self.assertEqual(n_data, ref)\n\n # num_scalar_eq_constr\n n_eq_constr = p.size_metrics.num_scalar_eq_constr\n ref = c2.dot(c1).size\n self.assertEqual(n_eq_constr, ref)\n\n # num_scalar_leq_constr\n n_leq_constr = p.size_metrics.num_scalar_leq_constr\n ref = numpy.prod(p3.size) + numpy.prod(p2.size)\n self.assertEqual(n_leq_constr, ref)\n\n # max_data_dimension\n max_data_dim = p.size_metrics.max_data_dimension\n ref = max(p3.shape)\n self.assertEqual(max_data_dim, ref)\n\n def test_solver_stats(self) -> None:\n \"\"\"Test the solver_stats method.\n \"\"\"\n prob = Problem(cp.Minimize(cp.norm(self.x)), [self.x == 0])\n prob.solve(solver=s.ECOS)\n stats = prob.solver_stats\n self.assertGreater(stats.solve_time, 0)\n self.assertGreater(stats.setup_time, 0)\n self.assertGreater(stats.num_iters, 0)\n self.assertIn('info', stats.extra_stats)\n\n prob = Problem(cp.Minimize(cp.norm(self.x)), [self.x == 0])\n prob.solve(solver=s.SCS)\n stats = prob.solver_stats\n self.assertGreater(stats.solve_time, 0)\n self.assertGreater(stats.setup_time, 0)\n self.assertGreater(stats.num_iters, 0)\n self.assertIn('info', stats.extra_stats)\n\n prob = Problem(cp.Minimize(cp.sum(self.x)), [self.x == 0])\n prob.solve(solver=s.OSQP)\n stats = prob.solver_stats\n self.assertGreater(stats.solve_time, 0)\n # We do not populate setup_time for OSQP (OSQP decomposes time\n # into setup, solve, and polish; these are summed to obtain solve_time)\n self.assertGreater(stats.num_iters, 0)\n self.assertTrue(hasattr(stats.extra_stats, 'info'))\n\n def test_get_problem_data(self) -> None:\n \"\"\"Test get_problem_data method.\n \"\"\"\n data, _, _ = Problem(cp.Minimize(cp.exp(self.a) + 2)).get_problem_data(s.SCS)\n dims = data[ConicSolver.DIMS]\n self.assertEqual(dims.exp, 1)\n self.assertEqual(data[\"c\"].shape, (2,))\n self.assertEqual(data[\"A\"].shape, (3, 2))\n\n data, _, _ = Problem(cp.Minimize(cp.norm(self.x) + 3)).get_problem_data(s.ECOS)\n dims = data[ConicSolver.DIMS]\n self.assertEqual(dims.soc, [3])\n self.assertEqual(data[\"c\"].shape, (3,))\n self.assertIsNone(data[\"A\"])\n self.assertEqual(data[\"G\"].shape, (3, 3))\n\n if s.CVXOPT in INSTALLED_SOLVERS:\n data, _, _ = Problem(cp.Minimize(cp.norm(self.x) + 3)).get_problem_data(\n s.CVXOPT)\n dims = data[ConicSolver.DIMS]\n self.assertEqual(dims.soc, [3])\n # TODO(akshayka): We cannot test whether the coefficients or\n # offsets were correctly parsed until we update the CVXOPT\n # interface.\n\n def test_unpack_results(self) -> None:\n \"\"\"Test unpack results method.\n \"\"\"\n prob = Problem(cp.Minimize(cp.exp(self.a)), [self.a == 0])\n args, chain, inv = prob.get_problem_data(s.SCS)\n data = {\"c\": args[\"c\"], \"A\": args[\"A\"], \"b\": args[\"b\"]}\n cones = scs_conif.dims_to_solver_dict(args[ConicSolver.DIMS])\n solution = scs.solve(data, cones)\n prob = Problem(cp.Minimize(cp.exp(self.a)), [self.a == 0])\n prob.unpack_results(solution, chain, inv)\n self.assertAlmostEqual(self.a.value, 0, places=3)\n self.assertAlmostEqual(prob.value, 1, places=3)\n self.assertAlmostEqual(prob.status, s.OPTIMAL)\n\n prob = Problem(cp.Minimize(cp.norm(self.x)), [self.x == 0])\n args, chain, inv = prob.get_problem_data(s.ECOS)\n cones = ecos_conif.dims_to_solver_dict(args[ConicSolver.DIMS])\n solution = ecos.solve(args[\"c\"], args[\"G\"], args[\"h\"],\n cones, args[\"A\"], args[\"b\"])\n prob = Problem(cp.Minimize(cp.norm(self.x)), [self.x == 0])\n prob.unpack_results(solution, chain, inv)\n self.assertItemsAlmostEqual(self.x.value, [0, 0])\n self.assertAlmostEqual(prob.value, 0)\n self.assertAlmostEqual(prob.status, s.OPTIMAL)\n\n def test_verbose(self) -> None:\n \"\"\"Test silencing and enabling solver messages.\n \"\"\"\n # From http://stackoverflow.com/questions/5136611/capture-stdout-from-a-script-in-python\n # setup the environment\n outputs = {True: [], False: []}\n backup = sys.stdout\n ######\n for solver in INSTALLED_SOLVERS:\n for verbose in [True, False]:\n # Don't test GLPK because there's a race\n # condition in setting CVXOPT solver options.\n if solver in [cp.GLPK, cp.GLPK_MI, cp.MOSEK, cp.CBC]:\n continue\n sys.stdout = StringIO() # capture output\n\n p = Problem(cp.Minimize(self.a + self.x[0]),\n [self.a >= 2, self.x >= 2])\n p.solve(verbose=verbose, solver=solver)\n\n if solver in SOLVER_MAP_CONIC:\n if SOLVER_MAP_CONIC[solver].MIP_CAPABLE:\n p.constraints.append(Variable(boolean=True) == 0)\n p.solve(verbose=verbose, solver=solver)\n\n if ExpCone in SOLVER_MAP_CONIC[solver].SUPPORTED_CONSTRAINTS:\n p = Problem(cp.Minimize(self.a), [cp.log(self.a) >= 2])\n p.solve(verbose=verbose, solver=solver)\n\n if PSD in SOLVER_MAP_CONIC[solver].SUPPORTED_CONSTRAINTS:\n a_mat = cp.reshape(self.a, shape=(1, 1))\n p = Problem(cp.Minimize(self.a), [cp.lambda_min(a_mat) >= 2])\n p.solve(verbose=verbose, solver=solver)\n\n out = sys.stdout.getvalue() # release output\n sys.stdout.close() # close the stream\n sys.stdout = backup # restore original stdout\n\n outputs[verbose].append((out, solver))\n\n for output, solver in outputs[True]:\n print(solver)\n assert len(output) > 0\n for output, solver in outputs[False]:\n print(solver)\n assert len(output) == 0\n\n # Test registering other solve methods.\n def test_register_solve(self) -> None:\n Problem.register_solve(\"test\", lambda self: 1)\n p = Problem(cp.Minimize(1))\n result = p.solve(method=\"test\")\n self.assertEqual(result, 1)\n\n def test(self, a, b=2):\n return (a, b)\n Problem.register_solve(\"test\", test)\n p = Problem(cp.Minimize(0))\n result = p.solve(1, b=3, method=\"test\")\n self.assertEqual(result, (1, 3))\n result = p.solve(1, method=\"test\")\n self.assertEqual(result, (1, 2))\n result = p.solve(1, method=\"test\", b=4)\n self.assertEqual(result, (1, 4))\n\n # def test_consistency(self):\n # \"\"\"Test that variables and constraints keep a consistent order.\n # \"\"\"\n # # TODO(akshayka): Adapt this test to the reduction infrastructure.\n # import itertools\n # num_solves = 4\n # vars_lists = []\n # ineqs_lists = []\n # var_ids_order_created = []\n # for k in range(num_solves):\n # sum = 0\n # constraints = []\n # var_ids = []\n # for i in range(100):\n # var = Variable(name=str(i))\n # var_ids.append(var.id)\n # sum += var\n # constraints.append(var >= i)\n # var_ids_order_created.append(var_ids)\n # obj = cp.Minimize(sum)\n # p = Problem(obj, constraints)\n # objective, constraints = p.canonicalize()\n # sym_data = SymData(objective, constraints, SOLVERS[s.ECOS])\n # # Sort by offset.\n # vars_ = sorted(sym_data.var_offsets.items(),\n # key=lambda key_val: key_val[1])\n # vars_ = [var_id for (var_id, offset) in vars_]\n # vars_lists.append(vars_)\n # ineqs_lists.append(sym_data.constr_map[s.LEQ])\n\n # # Verify order of variables is consistent.\n # for i in range(num_solves):\n # self.assertEqual(var_ids_order_created[i],\n # vars_lists[i])\n # for i in range(num_solves):\n # for idx, constr in enumerate(ineqs_lists[i]):\n # var_id, _ = lu.get_expr_vars(constr.expr)[0]\n # self.assertEqual(var_ids_order_created[i][idx],\n # var_id)\n\n # Test removing duplicate constraint objects.\n # def test_duplicate_constraints(self):\n # # TODO(akshayka): Adapt this test to the reduction infrastructure.\n # eq = (self.x == 2)\n # le = (self.x <= 2)\n # obj = 0\n\n # def test(self):\n # objective, constraints = self.canonicalize()\n # sym_data = SymData(objective, constraints, SOLVERS[s.CVXOPT])\n # return (len(sym_data.constr_map[s.EQ]),\n # len(sym_data.constr_map[s.LEQ]))\n # Problem.register_solve(\"test\", test)\n # p = Problem(cp.Minimize(obj), [eq, eq, le, le])\n # result = p.solve(method=\"test\")\n # self.assertEqual(result, (1, 1))\n\n # # Internal constraints.\n # X = Variable((2, 2), PSD=True)\n # obj = sum(X + X)\n # p = Problem(cp.Minimize(obj))\n # result = p.solve(method=\"test\")\n # self.assertEqual(result, (0, 1))\n\n # # Duplicates from non-linear constraints.\n # exp = norm(self.x, 2)\n # prob = Problem(cp.Minimize(0), [exp <= 1, exp <= 2])\n # result = prob.solve(method=\"test\")\n # self.assertEqual(result, (0, 3))\n\n # Test the is_dcp method.\n def test_is_dcp(self) -> None:\n p = Problem(cp.Minimize(cp.norm_inf(self.a)))\n self.assertEqual(p.is_dcp(), True)\n\n p = Problem(cp.Maximize(cp.norm_inf(self.a)))\n self.assertEqual(p.is_dcp(), False)\n with self.assertRaises(DCPError):\n p.solve()\n\n # Test the is_qp method.\n def test_is_qp(self) -> None:\n A = numpy.random.randn(4, 3)\n b = numpy.random.randn(4)\n Aeq = numpy.random.randn(2, 3)\n beq = numpy.random.randn(2)\n F = numpy.random.randn(2, 3)\n g = numpy.random.randn(2)\n obj = cp.sum_squares(A @ self.y - b)\n qpwa_obj = 3*cp.sum_squares(-cp.abs(A @ self.y)) +\\\n cp.quad_over_lin(cp.maximum(cp.abs(A @ self.y), [3., 3., 3., 3.]), 2.)\n not_qpwa_obj = 3*cp.sum_squares(cp.abs(A @ self.y)) +\\\n cp.quad_over_lin(cp.minimum(cp.abs(A @ self.y), [3., 3., 3., 3.]), 2.)\n\n p = Problem(cp.Minimize(obj), [])\n self.assertEqual(p.is_qp(), True)\n\n p = Problem(cp.Minimize(qpwa_obj), [])\n self.assertEqual(p.is_qp(), True)\n\n p = Problem(cp.Minimize(not_qpwa_obj), [])\n self.assertEqual(p.is_qp(), False)\n\n p = Problem(cp.Minimize(obj),\n [Aeq @ self.y == beq, F @ self.y <= g])\n self.assertEqual(p.is_qp(), True)\n\n p = Problem(cp.Minimize(qpwa_obj),\n [Aeq @ self.y == beq, F @ self.y <= g])\n self.assertEqual(p.is_qp(), True)\n\n p = Problem(cp.Minimize(obj), [cp.maximum(1, 3 * self.y) <= 200,\n cp.abs(2 * self.y) <= 100,\n cp.norm(2 * self.y, 1) <= 1000,\n Aeq @ self.y == beq])\n self.assertEqual(p.is_qp(), True)\n\n p = Problem(cp.Minimize(qpwa_obj), [cp.maximum(1, 3 * self.y) <= 200,\n cp.abs(2 * self.y) <= 100,\n cp.norm(2 * self.y, 1) <= 1000,\n Aeq @ self.y == beq])\n self.assertEqual(p.is_qp(), True)\n\n p = Problem(cp.Minimize(obj), [cp.maximum(1, 3 * self.y ** 2) <= 200])\n self.assertEqual(p.is_qp(), False)\n\n p = Problem(cp.Minimize(qpwa_obj), [cp.maximum(1, 3 * self.y ** 2) <= 200])\n self.assertEqual(p.is_qp(), False)\n\n # Test problems involving variables with the same name.\n def test_variable_name_conflict(self) -> None:\n var = Variable(name='a')\n p = Problem(cp.Maximize(self.a + var), [var == 2 + self.a, var <= 3])\n result = p.solve()\n self.assertAlmostEqual(result, 4.0)\n self.assertAlmostEqual(self.a.value, 1)\n self.assertAlmostEqual(var.value, 3)\n\n # Test adding problems\n def test_add_problems(self) -> None:\n prob1 = Problem(cp.Minimize(self.a), [self.a >= self.b])\n prob2 = Problem(cp.Minimize(2*self.b), [self.a >= 1, self.b >= 2])\n prob_minimize = prob1 + prob2\n self.assertEqual(len(prob_minimize.constraints), 3)\n self.assertAlmostEqual(prob_minimize.solve(), 6)\n prob3 = Problem(cp.Maximize(self.a), [self.b <= 1])\n prob4 = Problem(cp.Maximize(2*self.b), [self.a <= 2])\n prob_maximize = prob3 + prob4\n self.assertEqual(len(prob_maximize.constraints), 2)\n self.assertAlmostEqual(prob_maximize.solve(), 4)\n\n # Test using sum function\n prob5 = Problem(cp.Minimize(3*self.a))\n prob_sum = sum([prob1, prob2, prob5])\n self.assertEqual(len(prob_sum.constraints), 3)\n self.assertAlmostEqual(prob_sum.solve(), 12)\n prob_sum = sum([prob1])\n self.assertEqual(len(prob_sum.constraints), 1)\n\n # Test cp.Minimize + cp.Maximize\n with self.assertRaises(DCPError) as cm:\n prob1 + prob3\n self.assertEqual(str(cm.exception), \"Problem does not follow DCP rules.\")\n\n # Test problem multiplication by scalar\n def test_mul_problems(self) -> None:\n prob1 = Problem(cp.Minimize(pow(self.a, 2)), [self.a >= 2])\n answer = prob1.solve()\n factors = [0, 1, 2.3, -4.321]\n for f in factors:\n self.assertAlmostEqual((f * prob1).solve(), f * answer)\n self.assertAlmostEqual((prob1 * f).solve(), f * answer)\n\n # Test problem linear combinations\n def test_lin_combination_problems(self) -> None:\n prob1 = Problem(cp.Minimize(self.a), [self.a >= self.b])\n prob2 = Problem(cp.Minimize(2*self.b), [self.a >= 1, self.b >= 2])\n prob3 = Problem(cp.Maximize(-pow(self.b + self.a, 2)), [self.b >= 3])\n\n # simple addition and multiplication\n combo1 = prob1 + 2 * prob2\n combo1_ref = Problem(cp.Minimize(self.a + 4 * self.b),\n [self.a >= self.b, self.a >= 1, self.b >= 2])\n self.assertAlmostEqual(combo1.solve(), combo1_ref.solve())\n\n # division and subtraction\n combo2 = prob1 - prob3/2\n combo2_ref = Problem(cp.Minimize(self.a + pow(self.b + self.a, 2)/2),\n [self.b >= 3, self.a >= self.b])\n self.assertAlmostEqual(combo2.solve(), combo2_ref.solve())\n\n # multiplication with 0 (prob2's constraints should still hold)\n combo3 = prob1 + 0 * prob2 - 3 * prob3\n combo3_ref = Problem(cp.Minimize(self.a + 3 * pow(self.b + self.a, 2)),\n [self.a >= self.b, self.a >= 1, self.b >= 3])\n self.assertAlmostEqual(combo3.solve(), combo3_ref.solve())\n\n # Test scalar LP problems.\n def test_scalar_lp(self) -> None:\n p = Problem(cp.Minimize(3*self.a), [self.a >= 2])\n result = p.solve()\n self.assertAlmostEqual(result, 6)\n self.assertAlmostEqual(self.a.value, 2)\n\n p = Problem(cp.Maximize(3*self.a - self.b),\n [self.a <= 2, self.b == self.a, self.b <= 5])\n result = p.solve()\n self.assertAlmostEqual(result, 4.0)\n self.assertAlmostEqual(self.a.value, 2)\n self.assertAlmostEqual(self.b.value, 2)\n\n # With a constant in the objective.\n p = Problem(cp.Minimize(3*self.a - self.b + 100),\n [self.a >= 2,\n self.b + 5*self.c - 2 == self.a,\n self.b <= 5 + self.c])\n result = p.solve()\n self.assertAlmostEqual(result, 101 + 1.0/6)\n self.assertAlmostEqual(self.a.value, 2)\n self.assertAlmostEqual(self.b.value, 5-1.0/6)\n self.assertAlmostEqual(self.c.value, -1.0/6)\n\n # Test status and value.\n exp = cp.Maximize(self.a)\n p = Problem(exp, [self.a <= 2])\n result = p.solve(solver=s.ECOS)\n self.assertEqual(result, p.value)\n self.assertEqual(p.status, s.OPTIMAL)\n assert self.a.value is not None\n assert p.constraints[0].dual_value is not None\n\n # Unbounded problems.\n p = Problem(cp.Maximize(self.a), [self.a >= 2])\n p.solve(solver=s.ECOS)\n self.assertEqual(p.status, s.UNBOUNDED)\n assert numpy.isinf(p.value)\n assert p.value > 0\n assert self.a.value is None\n assert p.constraints[0].dual_value is None\n\n if s.CVXOPT in INSTALLED_SOLVERS:\n p = Problem(cp.Minimize(-self.a), [self.a >= 2])\n result = p.solve(solver=s.CVXOPT)\n self.assertEqual(result, p.value)\n self.assertEqual(p.status, s.UNBOUNDED)\n assert numpy.isinf(p.value)\n assert p.value < 0\n\n # Infeasible problems.\n p = Problem(cp.Maximize(self.a), [self.a >= 2, self.a <= 1])\n self.a.save_value(2)\n p.constraints[0].save_dual_value(2)\n\n result = p.solve(solver=s.ECOS)\n self.assertEqual(result, p.value)\n self.assertEqual(p.status, s.INFEASIBLE)\n assert numpy.isinf(p.value)\n assert p.value < 0\n assert self.a.value is None\n assert p.constraints[0].dual_value is None\n\n p = Problem(cp.Minimize(-self.a), [self.a >= 2, self.a <= 1])\n result = p.solve(solver=s.ECOS)\n self.assertEqual(result, p.value)\n self.assertEqual(p.status, s.INFEASIBLE)\n assert numpy.isinf(p.value)\n assert p.value > 0\n\n # Test vector LP problems.\n def test_vector_lp(self) -> None:\n c = Constant(numpy.array([[1, 2]]).T).value\n p = Problem(cp.Minimize(c.T @ self.x), [self.x[:, None] >= c])\n result = p.solve()\n self.assertAlmostEqual(result, 5)\n self.assertItemsAlmostEqual(self.x.value, [1, 2])\n\n A = Constant(numpy.array([[3, 5], [1, 2]]).T).value\n Imat = Constant([[1, 0], [0, 1]])\n p = Problem(cp.Minimize(c.T @ self.x + self.a),\n [A @ self.x >= [-1, 1],\n 4*Imat @ self.z == self.x,\n self.z >= [2, 2],\n self.a >= 2])\n result = p.solve()\n self.assertAlmostEqual(result, 26, places=3)\n obj = (c.T @ self.x + self.a).value[0]\n self.assertAlmostEqual(obj, result)\n self.assertItemsAlmostEqual(self.x.value, [8, 8], places=3)\n self.assertItemsAlmostEqual(self.z.value, [2, 2], places=3)\n\n def test_ecos_noineq(self) -> None:\n \"\"\"Test ECOS with no inequality constraints.\n \"\"\"\n T = Constant(numpy.ones((2, 2))).value\n p = Problem(cp.Minimize(1), [self.A == T])\n result = p.solve(solver=s.ECOS)\n self.assertAlmostEqual(result, 1)\n self.assertItemsAlmostEqual(self.A.value, T)\n\n # Test matrix LP problems.\n def test_matrix_lp(self) -> None:\n T = Constant(numpy.ones((2, 2))).value\n p = Problem(cp.Minimize(1), [self.A == T])\n result = p.solve()\n self.assertAlmostEqual(result, 1)\n self.assertItemsAlmostEqual(self.A.value, T)\n\n T = Constant(numpy.ones((2, 3))*2).value\n p = Problem(cp.Minimize(1), [self.A >= T @ self.C,\n self.A == self.B, self.C == T.T])\n result = p.solve(solver=cp.ECOS)\n self.assertAlmostEqual(result, 1)\n self.assertItemsAlmostEqual(self.A.value, self.B.value)\n self.assertItemsAlmostEqual(self.C.value, T)\n assert (self.A.value >= (T @ self.C).value).all()\n\n # Test variables are dense.\n self.assertEqual(type(self.A.value), intf.DEFAULT_INTF.TARGET_MATRIX)\n\n # Test variable promotion.\n def test_variable_promotion(self) -> None:\n p = Problem(cp.Minimize(self.a), [self.x <= self.a, self.x == [1, 2]])\n result = p.solve()\n self.assertAlmostEqual(result, 2)\n self.assertAlmostEqual(self.a.value, 2)\n\n p = Problem(cp.Minimize(self.a),\n [self.A <= self.a,\n self.A == [[1, 2], [3, 4]]\n ])\n result = p.solve()\n self.assertAlmostEqual(result, 4)\n self.assertAlmostEqual(self.a.value, 4)\n\n # Promotion must happen before the multiplication.\n p = Problem(cp.Minimize([[1], [1]] @ (self.x + self.a + 1)),\n [self.a + self.x >= [1, 2]])\n result = p.solve()\n self.assertAlmostEqual(result, 5)\n\n # Test parameter promotion.\n def test_parameter_promotion(self) -> None:\n a = Parameter()\n exp = [[1, 2], [3, 4]] * a\n a.value = 2\n assert not (exp.value - 2*numpy.array([[1, 2], [3, 4]]).T).any()\n\n def test_parameter_problems(self) -> None:\n \"\"\"Test problems with parameters.\n \"\"\"\n p1 = Parameter()\n p2 = Parameter(3, nonpos=True)\n p3 = Parameter((4, 4), nonneg=True)\n p = Problem(cp.Maximize(p1*self.a), [self.a + p1 <= p2, self.b <= p3 + p3 + 2])\n p1.value = 2\n p2.value = -numpy.ones((3,))\n p3.value = numpy.ones((4, 4))\n result = p.solve()\n self.assertAlmostEqual(result, -6)\n\n p1.value = None\n with self.assertRaises(ParameterError):\n p.solve()\n\n # Test problems with norm_inf\n def test_norm_inf(self) -> None:\n # Constant argument.\n p = Problem(cp.Minimize(cp.norm_inf(-2)))\n result = p.solve()\n self.assertAlmostEqual(result, 2)\n\n # Scalar arguments.\n p = Problem(cp.Minimize(cp.norm_inf(self.a)), [self.a >= 2])\n result = p.solve()\n self.assertAlmostEqual(result, 2)\n self.assertAlmostEqual(self.a.value, 2)\n\n p = Problem(cp.Minimize(3*cp.norm_inf(self.a + 2*self.b) + self.c),\n [self.a >= 2, self.b <= -1, self.c == 3])\n result = p.solve()\n self.assertAlmostEqual(result, 3)\n self.assertAlmostEqual(self.a.value + 2*self.b.value, 0)\n self.assertAlmostEqual(self.c.value, 3)\n\n # cp.Maximize\n p = Problem(cp.Maximize(-cp.norm_inf(self.a)), [self.a <= -2])\n result = p.solve()\n self.assertAlmostEqual(result, -2)\n self.assertAlmostEqual(self.a.value, -2)\n\n # Vector arguments.\n p = Problem(cp.Minimize(cp.norm_inf(self.x - self.z) + 5),\n [self.x >= [2, 3], self.z <= [-1, -4]])\n result = p.solve(solver=cp.ECOS)\n self.assertAlmostEqual(float(result), 12)\n self.assertAlmostEqual(float(list(self.x.value)[1] - list(self.z.value)[1]), 7)\n\n # Test problems with norm1\n def test_norm1(self) -> None:\n # Constant argument.\n p = Problem(cp.Minimize(cp.norm1(-2)))\n result = p.solve()\n self.assertAlmostEqual(result, 2)\n\n # Scalar arguments.\n p = Problem(cp.Minimize(cp.norm1(self.a)), [self.a <= -2])\n result = p.solve()\n self.assertAlmostEqual(result, 2)\n self.assertAlmostEqual(self.a.value, -2)\n\n # cp.Maximize\n p = Problem(cp.Maximize(-cp.norm1(self.a)), [self.a <= -2])\n result = p.solve()\n self.assertAlmostEqual(result, -2)\n self.assertAlmostEqual(self.a.value, -2)\n\n # Vector arguments.\n p = Problem(cp.Minimize(cp.norm1(self.x - self.z) + 5),\n [self.x >= [2, 3], self.z <= [-1, -4]])\n result = p.solve()\n self.assertAlmostEqual(float(result), 15)\n self.assertAlmostEqual(float(list(self.x.value)[1] - list(self.z.value)[1]), 7)\n\n # Test problems with norm2\n def test_norm2(self) -> None:\n # Constant argument.\n p = Problem(cp.Minimize(cp.pnorm(-2, p=2)))\n result = p.solve()\n self.assertAlmostEqual(result, 2)\n\n # Scalar arguments.\n p = Problem(cp.Minimize(cp.pnorm(self.a, p=2)), [self.a <= -2])\n result = p.solve()\n self.assertAlmostEqual(result, 2)\n self.assertAlmostEqual(self.a.value, -2)\n\n # cp.Maximize\n p = Problem(cp.Maximize(-cp.pnorm(self.a, p=2)), [self.a <= -2])\n result = p.solve()\n self.assertAlmostEqual(result, -2)\n self.assertAlmostEqual(self.a.value, -2)\n\n # Vector arguments.\n p = Problem(cp.Minimize(cp.pnorm(self.x - self.z, p=2) + 5),\n [self.x >= [2, 3], self.z <= [-1, -4]])\n result = p.solve()\n self.assertAlmostEqual(result, 12.61577)\n self.assertItemsAlmostEqual(self.x.value, [2, 3])\n self.assertItemsAlmostEqual(self.z.value, [-1, -4])\n\n # Row arguments.\n p = Problem(cp.Minimize(cp.pnorm((self.x - self.z).T, p=2) + 5),\n [self.x >= [2, 3], self.z <= [-1, -4]])\n result = p.solve()\n self.assertAlmostEqual(result, 12.61577)\n self.assertItemsAlmostEqual(self.x.value, [2, 3])\n self.assertItemsAlmostEqual(self.z.value, [-1, -4])\n\n # Test problems with abs\n def test_abs(self) -> None:\n p = Problem(cp.Minimize(cp.sum(cp.abs(self.A))), [-2 >= self.A])\n result = p.solve()\n self.assertAlmostEqual(result, 8)\n self.assertItemsAlmostEqual(self.A.value, [-2, -2, -2, -2])\n\n # Test problems with quad_form.\n def test_quad_form(self) -> None:\n with self.assertRaises(Exception) as cm:\n Problem(cp.Minimize(cp.quad_form(self.x, self.A))).solve()\n self.assertEqual(\n str(cm.exception),\n \"At least one argument to quad_form must be non-variable.\"\n )\n\n with self.assertRaises(Exception) as cm:\n Problem(cp.Minimize(cp.quad_form(1, self.A))).solve()\n self.assertEqual(str(cm.exception), \"Invalid dimensions for arguments.\")\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n with self.assertRaises(Exception) as cm:\n Problem(cp.Minimize(cp.quad_form(self.x, [[-1, 0], [0, 9]]))).solve()\n self.assertTrue(\"Problem does not follow DCP rules.\"\n in str(cm.exception))\n\n P = [[4, 0], [0, 9]]\n p = Problem(cp.Minimize(cp.quad_form(self.x, P)), [self.x >= 1])\n result = p.solve()\n self.assertAlmostEqual(result, 13, places=3)\n\n c = [1, 2]\n p = Problem(cp.Minimize(cp.quad_form(c, self.A)), [self.A >= 1])\n result = p.solve()\n self.assertAlmostEqual(result, 9)\n\n c = [1, 2]\n P = [[4, 0], [0, 9]]\n p = Problem(cp.Minimize(cp.quad_form(c, P)))\n result = p.solve()\n self.assertAlmostEqual(result, 40)\n\n # Test combining atoms\n def test_mixed_atoms(self) -> None:\n p = Problem(cp.Minimize(cp.pnorm(5 + cp.norm1(self.z)\n + cp.norm1(self.x) +\n cp.norm_inf(self.x - self.z), p=2)),\n [self.x >= [2, 3], self.z <= [-1, -4], cp.pnorm(self.x + self.z, p=2) <= 2])\n result = p.solve()\n self.assertAlmostEqual(result, 22)\n self.assertItemsAlmostEqual(self.x.value, [2, 3])\n self.assertItemsAlmostEqual(self.z.value, [-1, -4])\n\n # Test multiplying by constant atoms.\n def test_mult_constant_atoms(self) -> None:\n p = Problem(cp.Minimize(cp.pnorm([3, 4], p=2)*self.a), [self.a >= 2])\n result = p.solve()\n self.assertAlmostEqual(result, 10)\n self.assertAlmostEqual(self.a.value, 2)\n\n def test_dual_variables(self) -> None:\n \"\"\"Test recovery of dual variables.\n \"\"\"\n for solver in [s.ECOS, s.SCS, s.CVXOPT]:\n if solver in INSTALLED_SOLVERS:\n if solver == s.SCS:\n acc = 1\n else:\n acc = 5\n p = Problem(cp.Minimize(cp.norm1(self.x + self.z)),\n [self.x >= [2, 3],\n [[1, 2], [3, 4]] @ self.z == [-1, -4],\n cp.pnorm(self.x + self.z, p=2) <= 100])\n result = p.solve(solver=solver)\n self.assertAlmostEqual(result, 4, places=acc)\n self.assertItemsAlmostEqual(self.x.value, [4, 3], places=acc)\n self.assertItemsAlmostEqual(self.z.value, [-4, 1], places=acc)\n # Dual values\n self.assertItemsAlmostEqual(p.constraints[0].dual_value, [0, 1], places=acc)\n self.assertItemsAlmostEqual(p.constraints[1].dual_value, [-1, 0.5], places=acc)\n self.assertAlmostEqual(p.constraints[2].dual_value, 0, places=acc)\n\n T = numpy.ones((2, 3))*2\n p = Problem(cp.Minimize(1),\n [self.A >= T @ self.C,\n self.A == self.B,\n self.C == T.T])\n result = p.solve(solver=solver)\n # Dual values\n self.assertItemsAlmostEqual(p.constraints[0].dual_value, 4*[0], places=acc)\n self.assertItemsAlmostEqual(p.constraints[1].dual_value, 4*[0], places=acc)\n self.assertItemsAlmostEqual(p.constraints[2].dual_value, 6*[0], places=acc)\n\n # Test problems with indexing.\n def test_indexing(self) -> None:\n # Vector variables\n p = Problem(cp.Maximize(self.x[0]), [self.x[0] <= 2, self.x[1] == 3])\n result = p.solve()\n self.assertAlmostEqual(result, 2)\n self.assertItemsAlmostEqual(self.x.value, [2, 3])\n\n n = 10\n A = numpy.arange(n*n)\n A = numpy.reshape(A, (n, n))\n x = Variable((n, n))\n p = Problem(cp.Minimize(cp.sum(x)), [x == A])\n result = p.solve()\n answer = n*n*(n*n+1)/2 - n*n\n self.assertAlmostEqual(result, answer)\n\n # Matrix variables\n p = Problem(cp.Maximize(sum(self.A[i, i] + self.A[i, 1-i] for i in range(2))),\n [self.A <= [[1, -2], [-3, 4]]])\n result = p.solve()\n self.assertAlmostEqual(result, 0)\n self.assertItemsAlmostEqual(self.A.value, [1, -2, -3, 4])\n\n # Indexing arithmetic expressions.\n expr = [[1, 2], [3, 4]] @ self.z + self.x\n p = Problem(cp.Minimize(expr[1]), [self.x == self.z, self.z == [1, 2]])\n result = p.solve()\n self.assertAlmostEqual(result, 12)\n self.assertItemsAlmostEqual(self.x.value, self.z.value)\n\n def test_non_python_int_index(self) -> None:\n \"\"\"Test problems that have special types as indices.\n \"\"\"\n import sys\n if sys.version_info > (3,):\n my_long = int\n else:\n my_long = long # noqa: F821\n # Test with long indices.\n cost = self.x[0:my_long(2)][0]\n p = Problem(cp.Minimize(cost), [self.x == 1])\n result = p.solve()\n self.assertAlmostEqual(result, 1)\n self.assertItemsAlmostEqual(self.x.value, [1, 1])\n\n # Test with numpy64 indices.\n cost = self.x[0:numpy.int64(2)][0]\n p = Problem(cp.Minimize(cost), [self.x == 1])\n result = p.solve()\n self.assertAlmostEqual(result, 1)\n self.assertItemsAlmostEqual(self.x.value, [1, 1])\n\n # Test problems with slicing.\n def test_slicing(self) -> None:\n p = Problem(cp.Maximize(cp.sum(self.C)), [self.C[1:3, :] <= 2, self.C[0, :] == 1])\n result = p.solve()\n self.assertAlmostEqual(result, 10)\n self.assertItemsAlmostEqual(self.C.value, 2*[1, 2, 2])\n\n p = Problem(cp.Maximize(cp.sum(self.C[0:3:2, 1])),\n [self.C[1:3, :] <= 2, self.C[0, :] == 1])\n result = p.solve()\n self.assertAlmostEqual(result, 3)\n self.assertItemsAlmostEqual(self.C.value[0:3:2, 1], [1, 2])\n\n p = Problem(cp.Maximize(cp.sum((self.C[0:2, :] + self.A)[:, 0:2])),\n [self.C[1:3, :] <= 2, self.C[0, :] == 1,\n (self.A + self.B)[:, 0] == 3, (self.A + self.B)[:, 1] == 2,\n self.B == 1])\n result = p.solve()\n self.assertAlmostEqual(result, 12)\n self.assertItemsAlmostEqual(self.C.value[0:2, :], [1, 2, 1, 2])\n self.assertItemsAlmostEqual(self.A.value, [2, 2, 1, 1])\n\n p = Problem(cp.Maximize([[3], [4]] @ (self.C[0:2, :] + self.A)[:, 0]),\n [self.C[1:3, :] <= 2, self.C[0, :] == 1,\n [[1], [2]] @ (self.A + self.B)[:, 0] == 3, (self.A + self.B)[:, 1] == 2,\n self.B == 1, 3*self.A[:, 0] <= 3])\n result = p.solve()\n self.assertAlmostEqual(result, 12)\n self.assertItemsAlmostEqual(self.C.value[0:2, 0], [1, 2])\n self.assertItemsAlmostEqual(self.A.value, [1, -.5, 1, 1])\n\n p = Problem(cp.Minimize(cp.pnorm((self.C[0:2, :] + self.A)[:, 0], p=2)),\n [self.C[1:3, :] <= 2, self.C[0, :] == 1,\n (self.A + self.B)[:, 0] == 3, (self.A + self.B)[:, 1] == 2,\n self.B == 1])\n result = p.solve()\n self.assertAlmostEqual(result, 3)\n self.assertItemsAlmostEqual(self.C.value[0:2, 0], [1, -2], places=3)\n self.assertItemsAlmostEqual(self.A.value, [2, 2, 1, 1])\n\n # Transpose of slice.\n p = Problem(cp.Maximize(cp.sum(self.C)), [self.C[1:3, :].T <= 2, self.C[0, :].T == 1])\n result = p.solve()\n self.assertAlmostEqual(result, 10)\n self.assertItemsAlmostEqual(self.C.value, 2*[1, 2, 2])\n\n # Test the vstack atom.\n def test_vstack(self) -> None:\n a = Variable((1, 1), name='a')\n b = Variable((1, 1), name='b')\n\n x = Variable((2, 1), name='x')\n y = Variable((3, 1), name='y')\n\n c = numpy.ones((1, 5))\n p = Problem(cp.Minimize(c @ cp.vstack([x, y])),\n [x == [[1, 2]],\n y == [[3, 4, 5]]])\n result = p.solve()\n self.assertAlmostEqual(result, 15)\n\n c = numpy.ones((1, 4))\n p = Problem(cp.Minimize(c @ cp.vstack([x, x])),\n [x == [[1, 2]]])\n result = p.solve()\n self.assertAlmostEqual(result, 6)\n\n c = numpy.ones((2, 2))\n p = Problem(cp.Minimize(cp.sum(cp.vstack([self.A, self.C]))),\n [self.A >= 2*c,\n self.C == -2])\n result = p.solve()\n self.assertAlmostEqual(result, -4)\n\n c = numpy.ones((1, 2))\n p = Problem(cp.Minimize(cp.sum(cp.vstack([c @ self.A, c @ self.B]))),\n [self.A >= 2,\n self.B == -2])\n result = p.solve()\n self.assertAlmostEqual(result, 0)\n\n c = numpy.array([[1, -1]]).T\n p = Problem(cp.Minimize(c.T @ cp.vstack([cp.square(a), cp.sqrt(b)])),\n [a == 2,\n b == 16])\n with self.assertRaises(Exception) as cm:\n p.solve()\n self.assertTrue(\"Problem does not follow DCP rules.\"\n in str(cm.exception))\n\n # Test the hstack atom.\n def test_hstack(self) -> None:\n a = Variable((1, 1), name='a')\n b = Variable((1, 1), name='b')\n\n x = Variable((2, 1), name='x')\n y = Variable((3, 1), name='y')\n\n c = numpy.ones((1, 5))\n p = Problem(cp.Minimize(c @ cp.hstack([x.T, y.T]).T),\n [x == [[1, 2]],\n y == [[3, 4, 5]]])\n result = p.solve()\n self.assertAlmostEqual(result, 15)\n\n c = numpy.ones((1, 4))\n p = Problem(cp.Minimize(c @ cp.hstack([x.T, x.T]).T),\n [x == [[1, 2]]])\n result = p.solve()\n self.assertAlmostEqual(result, 6)\n\n c = numpy.ones((2, 2))\n p = Problem(cp.Minimize(cp.sum(cp.hstack([self.A.T, self.C.T]))),\n [self.A >= 2*c,\n self.C == -2])\n result = p.solve()\n self.assertAlmostEqual(result, -4)\n\n D = Variable((3, 3))\n expr = cp.hstack([self.C, D])\n p = Problem(cp.Minimize(expr[0, 1] + cp.sum(cp.hstack([expr, expr]))),\n [self.C >= 0,\n D >= 0, D[0, 0] == 2, self.C[0, 1] == 3])\n result = p.solve()\n self.assertAlmostEqual(result, 13)\n\n c = numpy.array([[1, -1]]).T\n p = Problem(cp.Minimize(c.T @ cp.hstack([cp.square(a).T, cp.sqrt(b).T]).T),\n [a == 2,\n b == 16])\n with self.assertRaises(Exception) as cm:\n p.solve()\n self.assertTrue(\"Problem does not follow DCP rules.\"\n in str(cm.exception))\n\n def test_bad_objective(self) -> None:\n \"\"\"Test using a cvxpy expression as an objective.\n \"\"\"\n with self.assertRaises(Exception) as cm:\n Problem(self.x+2)\n self.assertEqual(str(cm.exception), \"Problem objective must be Minimize or Maximize.\")\n\n # Test variable transpose.\n def test_transpose(self) -> None:\n p = Problem(cp.Minimize(cp.sum(self.x)),\n [self.x[None, :] >= numpy.array([[1, 2]])])\n result = p.solve()\n self.assertAlmostEqual(result, 3)\n self.assertItemsAlmostEqual(self.x.value, [1, 2])\n\n p = Problem(cp.Minimize(cp.sum(self.C)),\n [numpy.array([[1, 1]]) @ self.C.T >= numpy.array([[0, 1, 2]])])\n result = p.solve()\n value = self.C.value\n\n constraints = [1*self.C[i, 0] + 1*self.C[i, 1] >= i for i in range(3)]\n p = Problem(cp.Minimize(cp.sum(self.C)), constraints)\n result2 = p.solve()\n self.assertAlmostEqual(result, result2)\n self.assertItemsAlmostEqual(self.C.value, value)\n\n p = Problem(cp.Minimize(self.A[0, 1] - self.A.T[1, 0]),\n [self.A == [[1, 2], [3, 4]]])\n result = p.solve()\n self.assertAlmostEqual(result, 0)\n\n p = Problem(cp.Minimize(cp.sum(self.x)), [(-self.x).T <= 1])\n result = p.solve()\n self.assertAlmostEqual(result, -2)\n\n c = numpy.array([[1, -1]]).T\n p = Problem(cp.Minimize(cp.maximum(c.T, 2, 2 + c.T)[0, 1]))\n result = p.solve()\n self.assertAlmostEqual(result, 2)\n\n c = numpy.array([[1, -1, 2], [1, -1, 2]]).T\n p = Problem(cp.Minimize(cp.sum(cp.maximum(c, 2, 2 + c).T[:, 0])))\n result = p.solve()\n self.assertAlmostEqual(result, 6)\n\n c = numpy.array([[1, -1, 2], [1, -1, 2]]).T\n p = Problem(cp.Minimize(cp.sum(cp.square(c.T).T[:, 0])))\n result = p.solve()\n self.assertAlmostEqual(result, 6)\n\n # Slice of transpose.\n p = Problem(cp.Maximize(cp.sum(self.C)), [self.C.T[:, 1:3] <= 2, self.C.T[:, 0] == 1])\n result = p.solve()\n self.assertAlmostEqual(result, 10)\n self.assertItemsAlmostEqual(self.C.value, 2*[1, 2, 2])\n\n def test_multiplication_on_left(self) -> None:\n \"\"\"Test multiplication on the left by a non-constant.\n \"\"\"\n c = numpy.array([[1, 2]]).T\n p = Problem(cp.Minimize(c.T @ self.A @ c), [self.A >= 2])\n result = p.solve()\n self.assertAlmostEqual(result, 18)\n\n p = Problem(cp.Minimize(self.a*2), [self.a >= 2])\n result = p.solve()\n self.assertAlmostEqual(result, 4)\n\n p = Problem(cp.Minimize(self.x.T @ c), [self.x >= 2])\n result = p.solve()\n self.assertAlmostEqual(result, 6)\n\n p = Problem(cp.Minimize((self.x.T + self.z.T) @ c),\n [self.x >= 2, self.z >= 1])\n result = p.solve()\n self.assertAlmostEqual(result, 9)\n\n # TODO segfaults in Python 3\n A = numpy.ones((5, 10))\n x = Variable(5)\n p = cp.Problem(cp.Minimize(cp.sum(x @ A)), [x >= 0])\n result = p.solve()\n self.assertAlmostEqual(result, 0)\n\n # Test redundant constraints in cpopt.\n def test_redundant_constraints(self) -> None:\n obj = cp.Minimize(cp.sum(self.x))\n constraints = [self.x == 2, self.x == 2, self.x.T == 2, self.x[0] == 2]\n p = Problem(obj, constraints)\n result = p.solve(solver=s.SCS)\n self.assertAlmostEqual(result, 4)\n\n obj = cp.Minimize(cp.sum(cp.square(self.x)))\n constraints = [self.x == self.x]\n p = Problem(obj, constraints)\n result = p.solve(solver=s.SCS)\n self.assertAlmostEqual(result, 0)\n\n with self.assertRaises(ValueError) as cm:\n obj = cp.Minimize(cp.sum(cp.square(self.x)))\n constraints = [self.x == self.x]\n problem = Problem(obj, constraints)\n problem.solve(solver=s.ECOS)\n self.assertEqual(\n str(cm.exception),\n \"ECOS cannot handle sparse data with nnz == 0; \"\n \"this is a bug in ECOS, and it indicates that your problem \"\n \"might have redundant constraints.\")\n\n # Test that symmetry is enforced.\n def test_sdp_symmetry(self) -> None:\n p = Problem(cp.Minimize(cp.lambda_max(self.A)), [self.A >= 2])\n p.solve()\n self.assertItemsAlmostEqual(self.A.value, self.A.value.T, places=3)\n\n p = Problem(cp.Minimize(cp.lambda_max(self.A)), [self.A == [[1, 2], [3, 4]]])\n p.solve()\n self.assertEqual(p.status, s.INFEASIBLE)\n\n # Test PSD\n def test_sdp(self) -> None:\n # Ensure sdp constraints enforce transpose.\n obj = cp.Maximize(self.A[1, 0] - self.A[0, 1])\n p = Problem(obj, [cp.lambda_max(self.A) <= 100,\n self.A[0, 0] == 2,\n self.A[1, 1] == 2,\n self.A[1, 0] == 2])\n result = p.solve()\n self.assertAlmostEqual(result, 0, places=3)\n\n # Test getting values for expressions.\n def test_expression_values(self) -> None:\n diff_exp = self.x - self.z\n inf_exp = cp.norm_inf(diff_exp)\n sum_exp = 5 + cp.norm1(self.z) + cp.norm1(self.x) + inf_exp\n constr_exp = cp.pnorm(self.x + self.z, p=2)\n obj = cp.pnorm(sum_exp, p=2)\n p = Problem(cp.Minimize(obj),\n [self.x >= [2, 3], self.z <= [-1, -4], constr_exp <= 2])\n result = p.solve()\n self.assertAlmostEqual(result, 22)\n self.assertItemsAlmostEqual(self.x.value, [2, 3])\n self.assertItemsAlmostEqual(self.z.value, [-1, -4])\n # Expression values.\n self.assertItemsAlmostEqual(diff_exp.value, self.x.value - self.z.value)\n self.assertAlmostEqual(inf_exp.value,\n LA.norm(self.x.value - self.z.value, numpy.inf))\n self.assertAlmostEqual(sum_exp.value,\n 5 + LA.norm(self.z.value, 1) + LA.norm(self.x.value, 1) +\n LA.norm(self.x.value - self.z.value, numpy.inf))\n self.assertAlmostEqual(constr_exp.value,\n LA.norm(self.x.value + self.z.value, 2))\n self.assertAlmostEqual(obj.value, result)\n\n def test_mult_by_zero(self) -> None:\n \"\"\"Test multiplication by zero.\n \"\"\"\n self.a.value = 1\n exp = 0*self.a\n self.assertEqual(exp.value, 0)\n obj = cp.Minimize(exp)\n p = Problem(obj)\n result = p.solve()\n self.assertAlmostEqual(result, 0)\n assert self.a.value is not None\n\n def test_div(self) -> None:\n \"\"\"Tests a problem with division.\n \"\"\"\n obj = cp.Minimize(cp.norm_inf(self.A/5))\n p = Problem(obj, [self.A >= 5])\n result = p.solve()\n self.assertAlmostEqual(result, 1)\n\n c = cp.Constant([[1., -1], [2, -2]])\n expr = self.A/(1./c)\n obj = cp.Minimize(cp.norm_inf(expr))\n p = Problem(obj, [self.A == 5])\n result = p.solve()\n self.assertAlmostEqual(result, 10)\n self.assertItemsAlmostEqual(expr.value, [5, -5] + [10, -10])\n\n # Test with a sparse matrix.\n import scipy.sparse as sp\n interface = intf.get_matrix_interface(sp.csc_matrix)\n c = interface.const_to_matrix([1, 2])\n c = cp.Constant(c)\n expr = self.x[:, None]/(1/c)\n obj = cp.Minimize(cp.norm_inf(expr))\n p = Problem(obj, [self.x == 5])\n result = p.solve()\n self.assertAlmostEqual(result, 10)\n self.assertItemsAlmostEqual(expr.value, [5, 10])\n\n # Test promotion.\n c = [[1, -1], [2, -2]]\n c = cp.Constant(c)\n expr = self.a/(1/c)\n obj = cp.Minimize(cp.norm_inf(expr))\n p = Problem(obj, [self.a == 5])\n result = p.solve()\n self.assertAlmostEqual(result, 10)\n self.assertItemsAlmostEqual(expr.value, [5, -5] + [10, -10])\n\n def test_multiply(self) -> None:\n \"\"\"Tests problems with multiply.\n \"\"\"\n c = [[1, -1], [2, -2]]\n expr = cp.multiply(c, self.A)\n obj = cp.Minimize(cp.norm_inf(expr))\n p = Problem(obj, [self.A == 5])\n result = p.solve()\n self.assertAlmostEqual(result, 10)\n self.assertItemsAlmostEqual(expr.value, [5, -5] + [10, -10])\n\n # Test with a sparse matrix.\n import scipy.sparse as sp\n interface = intf.get_matrix_interface(sp.csc_matrix)\n c = interface.const_to_matrix([1, 2])\n expr = cp.multiply(c, self.x[:, None])\n obj = cp.Minimize(cp.norm_inf(expr))\n p = Problem(obj, [self.x == 5])\n result = p.solve()\n self.assertAlmostEqual(result, 10)\n self.assertItemsAlmostEqual(expr.value.toarray(), [5, 10])\n\n # Test promotion.\n c = [[1, -1], [2, -2]]\n expr = cp.multiply(c, self.a)\n obj = cp.Minimize(cp.norm_inf(expr))\n p = Problem(obj, [self.a == 5])\n result = p.solve()\n self.assertAlmostEqual(result, 10)\n self.assertItemsAlmostEqual(expr.value, [5, -5] + [10, -10])\n\n def test_invalid_solvers(self) -> None:\n \"\"\"Tests that errors occur when you use an invalid solver.\n \"\"\"\n with self.assertRaises(SolverError):\n Problem(cp.Minimize(Variable(boolean=True))).solve(solver=s.ECOS)\n\n with self.assertRaises(SolverError):\n Problem(cp.Minimize(cp.lambda_max(self.A))).solve(solver=s.ECOS)\n\n with self.assertRaises(SolverError):\n Problem(cp.Minimize(self.a)).solve(solver=s.SCS)\n\n def test_solver_error_raised_on_failure(self) -> None:\n \"\"\"Tests that a SolverError is raised when a solver fails.\n \"\"\"\n A = numpy.random.randn(40, 40)\n b = cp.matmul(A, numpy.random.randn(40))\n\n with self.assertRaises(SolverError):\n Problem(cp.Minimize(\n cp.sum_squares(cp.matmul(A, cp.Variable(40)) - b))).solve(\n solver=s.OSQP, max_iter=1)\n\n def test_reshape(self) -> None:\n \"\"\"Tests problems with reshape.\n \"\"\"\n # Test on scalars.\n self.assertEqual(cp.reshape(1, (1, 1)).value, 1)\n\n # Test vector to matrix.\n x = Variable(4)\n mat = numpy.array([[1, -1], [2, -2]]).T\n vec = numpy.array([[1, 2, 3, 4]]).T\n vec_mat = numpy.array([[1, 2], [3, 4]]).T\n expr = cp.reshape(x, (2, 2))\n obj = cp.Minimize(cp.sum(mat @ expr))\n prob = Problem(obj, [x[:, None] == vec])\n result = prob.solve()\n self.assertAlmostEqual(result, numpy.sum(mat.dot(vec_mat)))\n\n # Test on matrix to vector.\n c = [1, 2, 3, 4]\n expr = cp.reshape(self.A, (4, 1))\n obj = cp.Minimize(expr.T @ c)\n constraints = [self.A == [[-1, -2], [3, 4]]]\n prob = Problem(obj, constraints)\n result = prob.solve()\n self.assertAlmostEqual(result, 20)\n self.assertItemsAlmostEqual(expr.value, [-1, -2, 3, 4])\n self.assertItemsAlmostEqual(cp.reshape(expr, (2, 2)).value, [-1, -2, 3, 4])\n\n # Test matrix to matrix.\n expr = cp.reshape(self.C, (2, 3))\n mat = numpy.array([[1, -1], [2, -2]])\n C_mat = numpy.array([[1, 4], [2, 5], [3, 6]])\n obj = cp.Minimize(cp.sum(mat @ expr))\n prob = Problem(obj, [self.C == C_mat])\n result = prob.solve()\n reshaped = numpy.reshape(C_mat, (2, 3), 'F')\n self.assertAlmostEqual(result, (mat.dot(reshaped)).sum())\n self.assertItemsAlmostEqual(expr.value, C_mat)\n\n # Test promoted expressions.\n c = numpy.array([[1, -1], [2, -2]]).T\n expr = cp.reshape(c * self.a, (1, 4))\n obj = cp.Minimize(expr @ [1, 2, 3, 4])\n prob = Problem(obj, [self.a == 2])\n result = prob.solve()\n self.assertAlmostEqual(result, -6)\n self.assertItemsAlmostEqual(expr.value, 2*c)\n\n expr = cp.reshape(c * self.a, (4, 1))\n obj = cp.Minimize(expr.T @ [1, 2, 3, 4])\n prob = Problem(obj, [self.a == 2])\n result = prob.solve()\n self.assertAlmostEqual(result, -6)\n self.assertItemsAlmostEqual(expr.value, 2*c)\n\n def test_cumsum(self) -> None:\n \"\"\"Test problems with cumsum.\n \"\"\"\n tt = cp.Variable(5)\n prob = cp.Problem(cp.Minimize(cp.sum(tt)),\n [cp.cumsum(tt, 0) >= -0.0001])\n result = prob.solve()\n self.assertAlmostEqual(result, -0.0001)\n\n def test_cummax(self) -> None:\n \"\"\"Test problems with cummax.\n \"\"\"\n tt = cp.Variable(5)\n prob = cp.Problem(cp.Maximize(cp.sum(tt)),\n [cp.cummax(tt, 0) <= numpy.array([1, 2, 3, 4, 5])])\n result = prob.solve()\n self.assertAlmostEqual(result, 15)\n\n def test_vec(self) -> None:\n \"\"\"Tests problems with vec.\n \"\"\"\n c = [1, 2, 3, 4]\n expr = cp.vec(self.A)\n obj = cp.Minimize(expr.T @ c)\n constraints = [self.A == [[-1, -2], [3, 4]]]\n prob = Problem(obj, constraints)\n result = prob.solve()\n self.assertAlmostEqual(result, 20)\n self.assertItemsAlmostEqual(expr.value, [-1, -2, 3, 4])\n\n def test_diag_prob(self) -> None:\n \"\"\"Test a problem with diag.\n \"\"\"\n C = Variable((3, 3))\n obj = cp.Maximize(C[0, 2])\n constraints = [cp.diag(C) == 1,\n C[0, 1] == 0.6,\n C[1, 2] == -0.3,\n C == Variable((3, 3), PSD=True)]\n prob = Problem(obj, constraints)\n result = prob.solve()\n self.assertAlmostEqual(result, 0.583151, places=2)\n\n def test_presolve_parameters(self) -> None:\n \"\"\"Test presolve with parameters.\n \"\"\"\n # Test with parameters.\n gamma = Parameter(nonneg=True)\n x = Variable()\n obj = cp.Minimize(x)\n prob = Problem(obj, [gamma == 1, x >= 0])\n gamma.value = 0\n prob.solve(solver=s.SCS)\n self.assertEqual(prob.status, s.INFEASIBLE)\n\n gamma.value = 1\n prob.solve(solver=s.SCS)\n self.assertEqual(prob.status, s.OPTIMAL)\n\n def test_parameter_expressions(self) -> None:\n \"\"\"Test that expressions with parameters are updated properly.\n \"\"\"\n x = Variable()\n y = Variable()\n x0 = Parameter()\n xSquared = x0*x0 + 2*x0*(x - x0)\n\n # initial guess for x\n x0.value = 2\n\n # make the constraint x**2 - y == 0\n g = xSquared - y\n\n # set up the problem\n obj = cp.abs(x - 1)\n prob = Problem(cp.Minimize(obj), [g == 0])\n self.assertFalse(prob.is_dpp())\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n prob.solve(cp.SCS)\n x0.value = 1\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n prob.solve()\n self.assertAlmostEqual(g.value, 0)\n\n # Test multiplication.\n prob = Problem(cp.Minimize(x0*x), [x == 1])\n x0.value = 2\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n prob.solve()\n x0.value = 1\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n prob.solve()\n self.assertAlmostEqual(prob.value, 1, places=2)\n\n def test_psd_constraints(self) -> None:\n \"\"\"Test positive definite constraints.\n \"\"\"\n C = Variable((3, 3))\n obj = cp.Maximize(C[0, 2])\n constraints = [cp.diag(C) == 1,\n C[0, 1] == 0.6,\n C[1, 2] == -0.3,\n C == C.T,\n C >> 0]\n prob = Problem(obj, constraints)\n result = prob.solve()\n self.assertAlmostEqual(result, 0.583151, places=2)\n\n C = Variable((2, 2))\n obj = cp.Maximize(C[0, 1])\n constraints = [C == 1, C >> [[2, 0], [0, 2]]]\n prob = Problem(obj, constraints)\n result = prob.solve()\n self.assertEqual(prob.status, s.INFEASIBLE)\n\n C = Variable((2, 2), symmetric=True)\n obj = cp.Minimize(C[0, 0])\n constraints = [C << [[2, 0], [0, 2]]]\n prob = Problem(obj, constraints)\n result = prob.solve()\n self.assertEqual(prob.status, s.UNBOUNDED)\n\n def test_psd_duals(self) -> None:\n \"\"\"Test the duals of PSD constraints.\n \"\"\"\n if s.CVXOPT in INSTALLED_SOLVERS:\n # Test the dual values with cpopt.\n C = Variable((2, 2), symmetric=True, name='C')\n obj = cp.Maximize(C[0, 0])\n constraints = [C << [[2, 0], [0, 2]]]\n prob = Problem(obj, constraints)\n result = prob.solve(solver=s.CVXOPT)\n self.assertAlmostEqual(result, 2)\n\n psd_constr_dual = constraints[0].dual_value.copy()\n C = Variable((2, 2), symmetric=True, name='C')\n X = Variable((2, 2), PSD=True)\n obj = cp.Maximize(C[0, 0])\n constraints = [X == [[2, 0], [0, 2]] - C]\n prob = Problem(obj, constraints)\n result = prob.solve(solver=s.CVXOPT)\n self.assertItemsAlmostEqual(constraints[0].dual_value, psd_constr_dual)\n\n # Test the dual values with SCS.\n C = Variable((2, 2), symmetric=True)\n obj = cp.Maximize(C[0, 0])\n constraints = [C << [[2, 0], [0, 2]]]\n prob = Problem(obj, constraints)\n result = prob.solve(solver=s.SCS)\n self.assertAlmostEqual(result, 2, places=4)\n\n psd_constr_dual = constraints[0].dual_value\n C = Variable((2, 2), symmetric=True)\n X = Variable((2, 2), PSD=True)\n obj = cp.Maximize(C[0, 0])\n constraints = [X == [[2, 0], [0, 2]] - C]\n prob = Problem(obj, constraints)\n result = prob.solve(solver=s.SCS)\n self.assertItemsAlmostEqual(constraints[0].dual_value, psd_constr_dual)\n\n # Test dual values with SCS that have off-diagonal entries.\n C = Variable((2, 2), symmetric=True)\n obj = cp.Maximize(C[0, 1] + C[1, 0])\n constraints = [C << [[2, 0], [0, 2]], C >= 0]\n prob = Problem(obj, constraints)\n result = prob.solve(solver=s.SCS)\n self.assertAlmostEqual(result, 4, places=3)\n\n psd_constr_dual = constraints[0].dual_value\n C = Variable((2, 2), symmetric=True)\n X = Variable((2, 2), PSD=True)\n obj = cp.Maximize(C[0, 1] + C[1, 0])\n constraints = [X == [[2, 0], [0, 2]] - C, C >= 0]\n prob = Problem(obj, constraints)\n result = prob.solve(solver=s.SCS)\n self.assertItemsAlmostEqual(constraints[0].dual_value, psd_constr_dual,\n places=3)\n\n def test_geo_mean(self) -> None:\n import numpy as np\n\n x = Variable(2)\n cost = cp.geo_mean(x)\n prob = Problem(cp.Maximize(cost), [x <= 1])\n prob.solve()\n self.assertAlmostEqual(prob.value, 1)\n\n prob = Problem(cp.Maximize(cost), [cp.sum(x) <= 1])\n prob.solve()\n self.assertItemsAlmostEqual(x.value, [.5, .5])\n\n x = Variable((3, 3))\n self.assertRaises(ValueError, cp.geo_mean, x)\n\n x = Variable((3, 1))\n g = cp.geo_mean(x)\n self.assertSequenceEqual(g.w, [Fraction(1, 3)]*3)\n\n x = Variable((1, 5))\n g = cp.geo_mean(x)\n self.assertSequenceEqual(g.w, [Fraction(1, 5)]*5)\n\n # check that we get the right answer for\n # max geo_mean(x) s.t. sum(x) <= 1\n p = np.array([.07, .12, .23, .19, .39])\n\n def short_geo_mean(x, p):\n p = np.array(p)/sum(p)\n x = np.array(x)\n return np.prod(x**p)\n\n x = Variable(5)\n prob = Problem(cp.Maximize(cp.geo_mean(x, p)), [cp.sum(x) <= 1])\n prob.solve()\n x = np.array(x.value).flatten()\n x_true = p/sum(p)\n\n self.assertTrue(np.allclose(prob.value, cp.geo_mean(list(x), p).value))\n self.assertTrue(np.allclose(prob.value, short_geo_mean(x, p)))\n self.assertTrue(np.allclose(x, x_true, 1e-3))\n\n # check that we get the right answer for\n # max geo_mean(x) s.t. norm(x) <= 1\n x = Variable(5)\n prob = Problem(cp.Maximize(cp.geo_mean(x, p)), [cp.norm(x) <= 1])\n prob.solve()\n x = np.array(x.value).flatten()\n x_true = np.sqrt(p/sum(p))\n\n self.assertTrue(np.allclose(prob.value, cp.geo_mean(list(x), p).value))\n self.assertTrue(np.allclose(prob.value, short_geo_mean(x, p)))\n self.assertTrue(np.allclose(x, x_true, 1e-3))\n\n # the following 3 tests check vstack and hstack input to geo_mean\n # the following 3 formulations should be equivalent\n n = 5\n x_true = np.ones(n)\n x = Variable(n)\n\n Problem(cp.Maximize(cp.geo_mean(x)), [x <= 1]).solve()\n xval = np.array(x.value).flatten()\n self.assertTrue(np.allclose(xval, x_true, 1e-3))\n\n y = cp.vstack([x[i] for i in range(n)])\n Problem(cp.Maximize(cp.geo_mean(y)), [x <= 1]).solve()\n xval = np.array(x.value).flatten()\n self.assertTrue(np.allclose(xval, x_true, 1e-3))\n\n y = cp.hstack([x[i] for i in range(n)])\n Problem(cp.Maximize(cp.geo_mean(y)), [x <= 1]).solve()\n xval = np.array(x.value).flatten()\n self.assertTrue(np.allclose(xval, x_true, 1e-3))\n\n def test_pnorm(self) -> None:\n import numpy as np\n\n x = Variable(3, name='x')\n\n a = np.array([1.0, 2, 3])\n\n # todo: add -1, .5, .3, -2.3 and testing positivity constraints\n\n for p in (1, 1.6, 1.3, 2, 1.99, 3, 3.7, np.inf):\n prob = Problem(cp.Minimize(cp.pnorm(x, p=p)), [x.T @ a >= 1])\n prob.solve(verbose=True)\n\n # formula is true for any a >= 0 with p > 1\n if p == np.inf:\n x_true = np.ones_like(a)/sum(a)\n elif p == 1:\n # only works for the particular a = [1,2,3]\n x_true = np.array([0, 0, 1.0/3])\n else:\n x_true = a**(1.0/(p-1))/a.dot(a**(1.0/(p-1)))\n\n x_alg = np.array(x.value).flatten()\n self.assertTrue(np.allclose(x_alg, x_true, 1e-2), 'p = {}'.format(p))\n self.assertTrue(np.allclose(prob.value, np.linalg.norm(x_alg, p)))\n self.assertTrue(np.allclose(np.linalg.norm(x_alg, p), cp.pnorm(x_alg, p).value))\n\n def test_pnorm_concave(self) -> None:\n import numpy as np\n\n x = Variable(3, name='x')\n\n # test positivity constraints\n a = np.array([-1.0, 2, 3])\n for p in (-1, .5, .3, -2.3):\n prob = Problem(cp.Minimize(cp.sum(cp.abs(x-a))), [cp.pnorm(x, p) >= 0])\n prob.solve()\n\n self.assertTrue(np.allclose(prob.value, 1))\n\n a = np.array([1.0, 2, 3])\n for p in (-1, .5, .3, -2.3):\n prob = Problem(cp.Minimize(cp.sum(cp.abs(x-a))), [cp.pnorm(x, p) >= 0])\n prob.solve()\n\n self.assertAlmostEqual(prob.value, 0, places=6)\n\n def test_power(self) -> None:\n x = Variable()\n prob = Problem(cp.Minimize(cp.power(x, 1.7) + cp.power(x, -2.3) - cp.power(x, .45)))\n prob.solve()\n x = x.value\n self.assertTrue(builtins.abs(1.7*x**.7 - 2.3*x**-3.3 - .45*x**-.55) <= 1e-3)\n\n def test_multiply_by_scalar(self) -> None:\n \"\"\"Test a problem with multiply by a scalar.\n \"\"\"\n import numpy as np\n T = 10\n J = 20\n rvec = np.random.randn(T, J)\n dy = np.random.randn(2*T)\n theta = Variable(J)\n\n delta = 1e-3\n loglambda = rvec @ theta # rvec: TxJ regressor matrix, theta: (Jx1) cp variable\n a = cp.multiply(dy[0:T], loglambda) # size(Tx1)\n b1 = cp.exp(loglambda)\n b2 = cp.multiply(delta, b1)\n cost = -a + b1\n\n cost = -a + b2 # size (Tx1)\n prob = Problem(cp.Minimize(cp.sum(cost)))\n prob.solve(solver=s.SCS)\n\n obj = cp.Minimize(cp.sum(cp.multiply(2, self.x)))\n prob = Problem(obj, [self.x == 2])\n result = prob.solve()\n self.assertAlmostEqual(result, 8)\n\n def test_int64(self) -> None:\n \"\"\"Test bug with 64 bit integers.\n \"\"\"\n q = cp.Variable(numpy.int64(2))\n objective = cp.Minimize(cp.norm(q, 1))\n problem = cp.Problem(objective)\n problem.solve()\n print(q.value)\n\n def test_neg_slice(self) -> None:\n \"\"\"Test bug with negative slice.\n \"\"\"\n x = cp.Variable(2)\n objective = cp.Minimize(x[0] + x[1])\n constraints = [x[-2:] >= 1]\n problem = cp.Problem(objective, constraints)\n problem.solve()\n self.assertItemsAlmostEqual(x.value, [1, 1])\n\n def test_pnorm_axis(self) -> None:\n \"\"\"Test pnorm with axis != 0.\n \"\"\"\n b = numpy.arange(2)\n X = cp.Variable(shape=(2, 10))\n expr = cp.pnorm(X, p=2, axis=1) - b\n con = [expr <= 0]\n obj = cp.Maximize(cp.sum(X))\n prob = cp.Problem(obj, con)\n prob.solve(solver='ECOS')\n self.assertItemsAlmostEqual(expr.value, numpy.zeros(2))\n\n b = numpy.arange(10)\n X = cp.Variable(shape=(10, 2))\n expr = cp.pnorm(X, p=2, axis=1) - b\n con = [expr <= 0]\n obj = cp.Maximize(cp.sum(X))\n prob = cp.Problem(obj, con)\n prob.solve(solver='ECOS')\n self.assertItemsAlmostEqual(expr.value, numpy.zeros(10))\n\n def test_bool_constr(self) -> None:\n \"\"\"Test constraints that evaluate to booleans.\n \"\"\"\n x = cp.Variable(pos=True)\n prob = cp.Problem(cp.Minimize(x), [True])\n prob.solve()\n self.assertAlmostEqual(x.value, 0)\n\n x = cp.Variable(pos=True)\n prob = cp.Problem(cp.Minimize(x), [True]*10)\n prob.solve()\n self.assertAlmostEqual(x.value, 0)\n\n prob = cp.Problem(cp.Minimize(x), [42 <= x] + [True]*10)\n prob.solve()\n self.assertAlmostEqual(x.value, 42)\n\n prob = cp.Problem(cp.Minimize(x), [True] + [42 <= x] + [True] * 10)\n prob.solve()\n self.assertAlmostEqual(x.value, 42)\n\n prob = cp.Problem(cp.Minimize(x), [False])\n prob.solve()\n self.assertEqual(prob.status, s.INFEASIBLE)\n\n prob = cp.Problem(cp.Minimize(x), [False]*10)\n prob.solve()\n self.assertEqual(prob.status, s.INFEASIBLE)\n\n prob = cp.Problem(cp.Minimize(x), [True]*10 + [False] + [True]*10)\n prob.solve()\n self.assertEqual(prob.status, s.INFEASIBLE)\n\n prob = cp.Problem(cp.Minimize(x), [42 <= x] + [True]*10 + [False])\n prob.solve()\n self.assertEqual(prob.status, s.INFEASIBLE)\n\n # only Trues, but infeasible solution since x must be non-negative.\n prob = cp.Problem(cp.Minimize(x), [True] + [x <= -42] + [True]*10)\n prob.solve()\n self.assertEqual(prob.status, s.INFEASIBLE)\n\n def test_pos(self) -> None:\n \"\"\"Test the pos and neg attributes.\n \"\"\"\n x = cp.Variable(pos=True)\n prob = cp.Problem(cp.Minimize(x))\n prob.solve()\n self.assertAlmostEqual(x.value, 0)\n\n x = cp.Variable(neg=True)\n prob = cp.Problem(cp.Maximize(x))\n prob.solve()\n self.assertAlmostEqual(x.value, 0)\n\n def test_pickle(self) -> None:\n \"\"\"Test pickling and unpickling problems.\n \"\"\"\n prob = cp.Problem(cp.Minimize(2*self.a + 3),\n [self.a >= 1])\n prob_str = pickle.dumps(prob)\n new_prob = pickle.loads(prob_str)\n result = new_prob.solve()\n self.assertAlmostEqual(result, 5.0)\n self.assertAlmostEqual(new_prob.variables()[0].value, 1.0)\n\n def test_spare_int8_matrix(self) -> None:\n \"\"\"Test problem with sparse int8 matrix.\n issue #809.\n \"\"\"\n\n a = Variable(shape=(3, 1))\n q = np.array([1.88922129, 0.06938685, 0.91948919])\n P = np.array([[280.64, -49.84, -80.],\n [-49.84, 196.04, 139.],\n [-80., 139., 106.]])\n D_dense = np.array([[-1, 1, 0, 0, 0, 0],\n [0, -1, 1, 0, 0, 0],\n [0, 0, 0, -1, 1, 0]], dtype=np.int8)\n D_sparse = sp.coo_matrix(D_dense)\n\n def make_problem(D):\n obj = cp.Minimize(0.5 * cp.quad_form(a, P) - a.T @ q)\n assert obj.is_dcp()\n\n alpha = cp.Parameter(nonneg=True, value=2)\n constraints = [a >= 0., -alpha <= D.T @ a, D.T @ a <= alpha]\n\n prob = cp.Problem(obj, constraints)\n prob.solve(solver=cp.settings.ECOS)\n assert prob.status == 'optimal'\n return prob\n\n expected_coef = np.array([\n [-0.011728003147, 0.011728002895, 0.000000000252,\n -0.017524801335, 0.017524801335, 0.]])\n\n make_problem(D_dense)\n coef_dense = a.value.T.dot(D_dense)\n np.testing.assert_almost_equal(expected_coef, coef_dense)\n\n make_problem(D_sparse)\n coef_sparse = a.value.T @ D_sparse\n np.testing.assert_almost_equal(expected_coef, coef_sparse)\n\n def test_special_index(self) -> None:\n \"\"\"Test QP code path with special indexing.\n \"\"\"\n x = cp.Variable((1, 3))\n y = cp.sum(x[:, 0:2], axis=1)\n cost = cp.QuadForm(y, np.diag([1]))\n prob = cp.Problem(cp.Minimize(cost))\n result1 = prob.solve()\n\n x = cp.Variable((1, 3))\n y = cp.sum(x[:, [0, 1]], axis=1)\n cost = cp.QuadForm(y, np.diag([1]))\n prob = cp.Problem(cp.Minimize(cost))\n result2 = prob.solve()\n self.assertAlmostEqual(result1, result2)\n\n def test_indicator(self) -> None:\n \"\"\"Test a problem with indicators.\n \"\"\"\n n = 5\n m = 2\n q = np.arange(n)\n a = np.ones((m, n))\n b = np.ones((m, 1))\n x = cp.Variable((n, 1), name='x')\n constraints = [a @ x == b]\n objective = cp.Minimize((1/2) * cp.square(q.T @ x) + cp.transforms.indicator(constraints))\n problem = cp.Problem(objective)\n solution1 = problem.solve()\n\n # Without indicators.\n objective = cp.Minimize((1/2) * cp.square(q.T @ x))\n problem = cp.Problem(objective, constraints)\n solution2 = problem.solve()\n self.assertAlmostEqual(solution1, solution2)\n\n def test_rmul_scalar_mats(self) -> None:\n \"\"\"Test that rmul works with 1x1 matrices.\n \"\"\"\n x = [[4144.30127531]]\n y = [[7202.52114311]]\n z = cp.Variable(shape=(1, 1))\n objective = cp.Minimize(cp.quad_form(z, x) - 2 * z.T @ y)\n\n prob = cp.Problem(objective)\n prob.solve('OSQP', verbose=True)\n result1 = prob.value\n\n x = 4144.30127531\n y = 7202.52114311\n z = cp.Variable()\n objective = cp.Minimize(x*z**2 - 2 * z * y)\n\n prob = cp.Problem(objective)\n prob.solve('OSQP', verbose=True)\n self.assertAlmostEqual(prob.value, result1)\n\n def test_min_with_axis(self) -> None:\n \"\"\"Test reshape of a min with axis=0.\n \"\"\"\n x = cp.Variable((5, 2))\n y = cp.Variable((5, 2))\n\n stacked_flattened = cp.vstack([cp.vec(x), cp.vec(y)]) # (2, 10)\n minimum = cp.min(stacked_flattened, axis=0) # (10,)\n reshaped_minimum = cp.reshape(minimum, (5, 2)) # (5, 2)\n\n obj = cp.sum(reshaped_minimum)\n problem = cp.Problem(cp.Maximize(obj), [x == 1, y == 2])\n result = problem.solve()\n self.assertAlmostEqual(result, 10)\n"
] | [
[
"numpy.dot",
"numpy.maximum",
"numpy.sqrt",
"numpy.random.seed",
"numpy.power",
"numpy.linalg.inv",
"scipy.sparse.rand",
"scipy.linalg.lstsq",
"numpy.ones",
"numpy.atleast_2d",
"scipy.sparse.random",
"numpy.random.randn",
"numpy.random.rand",
"numpy.array"
],
[
"numpy.diag",
"scipy.sparse.coo_matrix",
"numpy.ones_like",
"numpy.allclose",
"numpy.reshape",
"numpy.arange",
"numpy.linalg.norm",
"numpy.ones",
"numpy.testing.assert_almost_equal",
"numpy.int64",
"numpy.random.randn",
"numpy.prod",
"numpy.array",
"numpy.zeros",
"numpy.isinf"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
Christian8491/tpcx-bb | [
"936b5343c61880fac31c52ad795f81255f5aaa93"
] | [
"tpcx_bb/queries/q16/tpcx_bb_query_16.py"
] | [
"#\n# Copyright (c) 2019-2020, NVIDIA CORPORATION.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport sys\n\n\nfrom xbb_tools.utils import (\n benchmark,\n tpcxbb_argparser,\n run_dask_cudf_query,\n)\nfrom xbb_tools.merge_util import hash_merge\nfrom xbb_tools.readers import build_reader\nfrom dask.distributed import wait\n\nimport numpy as np\n\ncli_args = tpcxbb_argparser()\n\n### conf\nq16_date = \"2001-03-16\"\n\nwebsale_cols = [\n \"ws_order_number\",\n \"ws_item_sk\",\n \"ws_warehouse_sk\",\n \"ws_sold_date_sk\",\n \"ws_sales_price\",\n]\nweb_returns_cols = [\"wr_order_number\", \"wr_item_sk\", \"wr_refunded_cash\"]\ndate_cols = [\"d_date\", \"d_date_sk\"]\nitem_cols = [\"i_item_sk\", \"i_item_id\"]\nwarehouse_cols = [\"w_warehouse_sk\", \"w_state\"]\n\n### util function\ndef convert_datestring_to_datetime(df, date_col=\"d_date\", date_format=\"%Y-%m-%d\"):\n datetime_array = cudf.core.column.column_empty(len(df), dtype=np.int64)\n df[date_col].str.timestamp2int(\n format=date_format, units=\"D\", devptr=datetime_array.data_ptr\n )\n df[date_col] = datetime_array\n return df\n\n\n# INSERT INTO TABLE ${hiveconf:RESULT_TABLE}\n# SELECT w_state, i_item_id,\n# SUM(\n# CASE WHEN (unix_timestamp(d_date,'yyyy-MM-dd') < unix_timestamp('${hiveconf:q16_date}','yyyy-MM-dd'))\n# THEN ws_sales_price - COALESCE(wr_refunded_cash,0)\n# ELSE 0.0 END\n# ) AS sales_before,\n# SUM(\n# CASE WHEN (unix_timestamp(d_date,'yyyy-MM-dd') >= unix_timestamp('${hiveconf:q16_date}','yyyy-MM-dd'))\n# THEN ws_sales_price - COALESCE(wr_refunded_cash,0)\n# ELSE 0.0 END\n# ) AS sales_after\n\n\ndef get_before_after_sales(df, q16_timestamp):\n before_flag = df[\"d_date\"] < q16_timestamp\n after_flag = df[\"d_date\"] >= q16_timestamp\n\n df[\"sales_before\"] = df[\"sales\"].copy()\n df.loc[~before_flag, \"sales_before\"] = 0.00\n\n df[\"sales_after\"] = df[\"sales\"].copy()\n df.loc[~after_flag, \"sales_after\"] = 0.00\n return df\n\n\n@benchmark(dask_profile=cli_args[\"dask_profile\"])\ndef read_tables():\n table_reader = build_reader(basepath=cli_args[\"data_dir\"])\n\n web_sales_df = table_reader.read(\"web_sales\", relevant_cols=websale_cols)\n web_returns_df = table_reader.read(\"web_returns\", relevant_cols=web_returns_cols)\n date_dim_df = table_reader.read(\"date_dim\", relevant_cols=date_cols)\n item_df = table_reader.read(\"item\", relevant_cols=item_cols)\n warehouse_df = table_reader.read(\"warehouse\", relevant_cols=warehouse_cols)\n return web_sales_df, web_returns_df, date_dim_df, item_df, warehouse_df\n\n\n@benchmark(dask_profile=cli_args[\"dask_profile\"])\ndef main(client):\n\n web_sales_df, web_returns_df, date_dim_df, item_df, warehouse_df = read_tables()\n\n warehouse_df[\"w_state_code\"] = warehouse_df[[\"w_state\"]].categorize()[\"w_state\"]\n\n item_df[\"i_item_id_code\"] = item_df[[\"i_item_id\"]].categorize()[\"i_item_id\"]\n\n ## persisting as you need it for length calculation and to prevent duplicate reading\n ## downstream\n warehouse_df = warehouse_df.persist()\n\n item_df = item_df.persist()\n ## casting down because of dtype incosistieny in cudf/dask due to cat columns\n ### https://github.com/rapidsai/cudf/issues/4093\n wh_df_codes_min_signed_type = cudf.utils.dtypes.min_signed_type(\n len(warehouse_df[\"w_state_code\"].compute().cat.categories)\n )\n warehouse_df[\"w_state_code\"] = warehouse_df[\"w_state_code\"].cat.codes.astype(\n wh_df_codes_min_signed_type\n )\n unique_states = warehouse_df[[\"w_state_code\", \"w_state\"]].drop_duplicates()\n\n warehouse_df = warehouse_df[[\"w_state_code\", \"w_warehouse_sk\"]]\n\n ## casting down because of dtype incosistieny in cudf/dask due to cat columns\n ### https://github.com/rapidsai/cudf/issues/4093\n item_df_codes_min_signed_type = cudf.utils.dtypes.min_signed_type(\n len(item_df[\"i_item_id_code\"].compute().cat.categories)\n )\n item_df[\"i_item_id_code\"] = item_df[\"i_item_id_code\"].cat.codes.astype(\n item_df_codes_min_signed_type\n )\n unique_items = item_df[[\"i_item_id_code\", \"i_item_id\"]].drop_duplicates()\n item_df = item_df[[\"i_item_id_code\", \"i_item_sk\"]]\n\n # JOIN date_dim d ON a1.ws_sold_date_sk = d.d_date_sk\n # AND unix_timestamp(d.d_date, 'yyyy-MM-dd') >= unix_timestamp('${hiveconf:q16_date}', 'yyyy-MM-dd') - 30*24*60*60 --subtract 30 days in seconds\n # AND unix_timestamp(d.d_date, 'yyyy-MM-dd') <= unix_timestamp('${hiveconf:q16_date}', 'yyyy-MM-dd') + 30*24*60*60 --add 30 days in seconds\n\n ##todo: remove below\n date_dim_cov_df = date_dim_df.map_partitions(convert_datestring_to_datetime)\n q16_timestamp = np.datetime64(q16_date, \"D\").astype(int)\n filtered_date_df = date_dim_cov_df.query(\n f\"d_date >={q16_timestamp- 30} and d_date <= {q16_timestamp+30}\",\n meta=date_dim_cov_df._meta,\n ).reset_index(drop=True)\n\n web_sales_df = web_sales_df.merge(\n filtered_date_df,\n left_on=[\"ws_sold_date_sk\"],\n right_on=[\"d_date_sk\"],\n how=\"inner\",\n )\n\n cols_2_keep = [\n \"ws_order_number\",\n \"ws_item_sk\",\n \"ws_warehouse_sk\",\n \"ws_sales_price\",\n \"d_date\",\n ]\n\n web_sales_df = web_sales_df[cols_2_keep]\n web_sales_df = web_sales_df.persist()\n wait(web_sales_df)\n\n # SELECT *\n # FROM web_sales ws\n # LEFT OUTER JOIN web_returns wr ON (ws.ws_order_number = wr.wr_order_number\n # AND ws.ws_item_sk = wr.wr_item_sk)\n # ) a1\n\n web_sales_web_returns_join = hash_merge(\n lhs=web_sales_df,\n rhs=web_returns_df,\n left_on=[\"ws_order_number\", \"ws_item_sk\"],\n right_on=[\"wr_order_number\", \"wr_item_sk\"],\n how=\"left\",\n )\n cols_2_keep = [\n \"ws_item_sk\",\n \"ws_warehouse_sk\",\n \"ws_sales_price\",\n \"wr_refunded_cash\",\n \"d_date\",\n ]\n\n web_sales_web_returns_join = web_sales_web_returns_join[cols_2_keep]\n web_sales_web_returns_join = web_sales_web_returns_join.persist()\n\n wait(web_sales_web_returns_join)\n del web_sales_df\n\n # JOIN item i ON a1.ws_item_sk = i.i_item_sk\n web_sales_web_returns_item_join = web_sales_web_returns_join.merge(\n item_df, left_on=[\"ws_item_sk\"], right_on=[\"i_item_sk\"], how=\"inner\"\n )\n\n cols_2_keep = [\n \"ws_warehouse_sk\",\n \"ws_sales_price\",\n \"wr_refunded_cash\",\n \"i_item_id_code\",\n \"d_date\",\n ]\n\n web_sales_web_returns_item_join = web_sales_web_returns_item_join[cols_2_keep]\n\n # JOIN warehouse w ON a1.ws_warehouse_sk = w.w_warehouse_sk\n web_sales_web_returns_item_warehouse_join = web_sales_web_returns_item_join.merge(\n warehouse_df,\n left_on=[\"ws_warehouse_sk\"],\n right_on=[\"w_warehouse_sk\"],\n how=\"inner\",\n )\n\n merged_df = web_sales_web_returns_item_warehouse_join[\n [\n \"ws_sales_price\",\n \"wr_refunded_cash\",\n \"i_item_id_code\",\n \"w_state_code\",\n \"d_date\",\n ]\n ]\n\n merged_df[\"sales\"] = web_sales_web_returns_item_warehouse_join[\n \"ws_sales_price\"\n ].fillna(0) - web_sales_web_returns_item_warehouse_join[\"wr_refunded_cash\"].fillna(\n 0\n )\n sales_df = merged_df[[\"i_item_id_code\", \"w_state_code\", \"d_date\", \"sales\"]]\n\n sales_before_after_df = sales_df.map_partitions(\n get_before_after_sales, q16_timestamp\n )\n cols_2_keep = [\"i_item_id_code\", \"w_state_code\", \"sales_before\", \"sales_after\"]\n sales_before_after_df = sales_before_after_df[cols_2_keep]\n\n ## group by logic\n group_cols = [\"w_state_code\", \"i_item_id_code\"]\n\n agg_df = sales_before_after_df.groupby(group_cols).agg(\n {\"sales_before\": \"sum\", \"sales_after\": \"sum\"}\n )\n agg_df = agg_df.reset_index(drop=False)\n\n agg_df = agg_df.loc[:99].persist()\n\n agg_df = agg_df.reset_index(drop=False)\n agg_df.columns = [\n \"sorted_grp_index\",\n \"w_state_code\",\n \"i_item_id_code\",\n \"sales_before\",\n \"sales_after\",\n ]\n agg_df = agg_df.merge(unique_states, how=\"left\", on=\"w_state_code\")[\n [\"sorted_grp_index\", \"w_state\", \"i_item_id_code\", \"sales_before\", \"sales_after\"]\n ]\n agg_df = agg_df.merge(unique_items, how=\"left\", on=\"i_item_id_code\")[\n [\"sorted_grp_index\", \"w_state\", \"i_item_id\", \"sales_before\", \"sales_after\"]\n ]\n agg_df = agg_df.sort_values(by=[\"sorted_grp_index\"])\n ## only 100 rows so computing is fine\n return agg_df[[\"w_state\", \"i_item_id\", \"sales_before\", \"sales_after\"]].compute()\n\n\nif __name__ == \"__main__\":\n from xbb_tools.cluster_startup import attach_to_cluster\n import cudf\n import dask_cudf\n\n client = attach_to_cluster(cli_args)\n\n run_dask_cudf_query(cli_args=cli_args, client=client, query_func=main)\n"
] | [
[
"numpy.datetime64"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Erfi/stable-baselines3 | [
"a31863e1db4fe58ad06ed45fb6e0169b0db56a9c"
] | [
"stable_baselines3/petssac/petssac.py"
] | [
"from typing import List, Dict, Tuple, Any\n\nimport numpy as np\nimport torch as th\nfrom torch.nn import functional as F\n\nfrom gym.envs.mujoco.mujoco_env import MujocoEnv\nfrom stable_baselines3.sac import SAC\nfrom stable_baselines3.common import logger\nfrom stable_baselines3.common.vec_env import DummyVecEnv\nfrom stable_baselines3.common.utils import polyak_update\nfrom stable_baselines3.common.monitor import Monitor\n\n\nfrom PETS.env.cartpole import CartpoleEnv\nfrom PETS.defaults import get_cartpole_defaults\nfrom PETS.MPC import MPC\n\n\nclass PETSSAC(SAC):\n def __init__(self, petssac_coef: float = 1.0, mbctrl_retrain_period: int = 5000, *args, **kwargs):\n self.petssac_coef = petssac_coef\n self.mbctrl_retrain_period = mbctrl_retrain_period\n self.env = self._get_from_args_kwargs(\n args, kwargs, argidx=1, argname=\"env\", argisinstance=(MujocoEnv, DummyVecEnv, Monitor)\n )\n self.mbctrl = self._get_mbctrl()\n super().__init__(*args, **kwargs)\n\n def train(self, gradient_steps: int, batch_size: int) -> None:\n # train / retrain the PETS' dynamic model\n self.train_mbctrl()\n # Update optimizers learning rate\n optimizers = [self.actor.optimizer, self.critic.optimizer]\n if self.ent_coef_optimizer is not None:\n optimizers += [self.ent_coef_optimizer]\n\n # Update learning rate according to lr schedule\n self._update_learning_rate(optimizers)\n\n ent_coef_losses, ent_coefs = [], []\n actor_losses, critic_losses, petssac_losses = [], [], []\n\n for gradient_step in range(gradient_steps):\n # Sample replay buffer\n replay_data = self.replay_buffer.sample(batch_size, env=self._vec_normalize_env)\n\n # We need to sample because `log_std` may have changed between two gradient steps\n if self.use_sde:\n self.actor.reset_noise()\n\n # PETS' suggested actions for observations\n actions_mb = self.mbctrl.act(replay_data.observations)\n actions_mb = th.from_numpy(self.policy.scale_action(actions_mb)).float()\n\n # Action by the current actor for the sampled state\n actions_pi, log_prob = self.actor.action_log_prob(replay_data.observations)\n log_prob = log_prob.reshape(-1, 1)\n\n ent_coef_loss = None\n if self.ent_coef_optimizer is not None:\n # Important: detach the variable from the graph\n # so we don't change it with other losses\n # see https://github.com/rail-berkeley/softlearning/issues/60\n ent_coef = th.exp(self.log_ent_coef.detach())\n ent_coef_loss = -(self.log_ent_coef * (log_prob + self.target_entropy).detach()).mean()\n ent_coef_losses.append(ent_coef_loss.item())\n else:\n ent_coef = self.ent_coef_tensor\n\n ent_coefs.append(ent_coef.item())\n\n # Optimize entropy coefficient, also called\n # entropy temperature or alpha in the paper\n if ent_coef_loss is not None:\n self.ent_coef_optimizer.zero_grad()\n ent_coef_loss.backward()\n self.ent_coef_optimizer.step()\n\n with th.no_grad():\n # Select action according to policy\n next_actions, next_log_prob = self.actor.action_log_prob(replay_data.next_observations)\n # Compute the target Q value: min over all critics targets\n targets = th.cat(self.critic_target(replay_data.next_observations, next_actions), dim=1)\n target_q, _ = th.min(targets, dim=1, keepdim=True)\n # add entropy term\n target_q = target_q - ent_coef * next_log_prob.reshape(-1, 1)\n # td error + entropy term\n q_backup = replay_data.rewards + (1 - replay_data.dones) * self.gamma * target_q\n\n # q(s, PETS_action)\n actions_mb_qs = th.cat(self.critic_target(replay_data.observations, actions_mb), dim=1)\n actions_mb_q, _ = th.min(actions_mb_qs, dim=1, keepdim=True)\n\n # Get current Q estimates for each critic network\n # using action from the replay buffer\n current_q_estimates = self.critic(replay_data.observations, replay_data.actions)\n\n # Compute critic loss\n critic_loss = 0.5 * sum([F.mse_loss(current_q, q_backup) for current_q in current_q_estimates])\n critic_losses.append(critic_loss.item())\n\n # Optimize the critic\n self.critic.optimizer.zero_grad()\n critic_loss.backward()\n self.critic.optimizer.step()\n\n # Compute actor loss\n # Alternative: actor_loss = th.mean(log_prob - qf1_pi)\n # Mean over all critic networks\n q_values_pi = th.cat(self.critic.forward(replay_data.observations, actions_pi), dim=1)\n min_qf_pi, _ = th.min(q_values_pi, dim=1, keepdim=True)\n petssac_loss = F.mse_loss(min_qf_pi, actions_mb_q, reduction=\"none\").mean()\n sac_actor_loss = (ent_coef * log_prob - min_qf_pi).mean()\n actor_loss = sac_actor_loss + self.petssac_coef * petssac_loss\n\n actor_losses.append(actor_loss.item())\n petssac_losses.append(petssac_loss.item())\n\n # Optimize the actor\n self.actor.optimizer.zero_grad()\n actor_loss.backward()\n self.actor.optimizer.step()\n\n # Update target networks\n if gradient_step % self.target_update_interval == 0:\n polyak_update(self.critic.parameters(), self.critic_target.parameters(), self.tau)\n\n self._n_updates += gradient_steps\n\n logger.record(\"train/n_updates\", self._n_updates, exclude=\"tensorboard\")\n logger.record(\"train/ent_coef\", np.mean(ent_coefs))\n logger.record(\"train/actor_loss\", np.mean(actor_losses))\n logger.record(\"train/critic_loss\", np.mean(critic_losses))\n logger.record(\"train/petssac_loss\", np.mean(petssac_losses))\n if len(ent_coef_losses) > 0:\n logger.record(\"train/ent_coef_loss\", np.mean(ent_coef_losses))\n\n def _get_from_args_kwargs(\n self,\n args: List,\n kwargs: Dict,\n argidx: int = None,\n argname: str = None,\n argisinstance: Any = None,\n pop: bool = False,\n ) -> Any:\n \"\"\"\n Returns the desired argument from args (using argidx) and kwargs (using argname).\n Priority is with args if not found kwargs.\n \"\"\"\n arg = None\n if argidx and len(args) > argidx:\n arg = args.pop(argidx) if pop else args[argidx]\n else:\n arg = kwargs.pop(argname, None) if pop else kwargs.get(argname, None)\n if argisinstance:\n assert isinstance(arg, argisinstance), f\"Need an instance of {argisinstance}\"\n return arg\n\n def _get_mbctrl(self) -> MPC:\n \"\"\"\n We want to pass to the MPC the original env without the wrappers\n \"\"\"\n mbctrl = None\n env = self.env\n if isinstance(self.env, Monitor):\n env = self.env.env\n elif isinstance(self.env, DummyVecEnv):\n env = self.env.envs[0].env\n if isinstance(env, Monitor):\n env = env.env\n else:\n env = self.env\n if isinstance(env, CartpoleEnv):\n mbctrl_params = get_cartpole_defaults()\n mbctrl = MPC(mbctrl_params)\n return mbctrl\n\n def train_mbctrl(self):\n if self.num_timesteps == self.learning_starts + 1: # first training call\n batch_size = self.learning_starts\n elif self.num_timesteps % self.mbctrl_retrain_period == 0: # periodic update of the dynamics model\n self.mbctrl.model_train_cfg[\"epochs\"] = 1\n batch_size = self.batch_size\n else:\n return\n samples = self.replay_buffer.sample(batch_size)\n self.mbctrl.train(obs=samples.observations, next_obs=samples.next_observations, actions=samples.actions)\n\n def _excluded_save_params(self) -> List[str]:\n \"\"\"\n Returns the names of the parameters that should be excluded from being\n saved by pickling. E.g. replay buffers are skipped by default\n as they take up a lot of space. PyTorch variables should be excluded\n with this so they can be stored with ``th.save``.\n\n :return: List of parameters that should be excluded from being saved with pickle.\n \"\"\"\n return super(SAC, self)._excluded_save_params() + [\n \"actor\",\n \"critic\",\n \"critic_target\",\n \"mbctrl\",\n ]\n\n def _get_torch_save_params(self) -> Tuple[List[str], List[str]]:\n \"\"\"\n Get the name of the torch variables that will be saved with\n PyTorch ``th.save``, ``th.load`` and ``state_dicts`` instead of the default\n pickling strategy. This is to handle device placement correctly.\n\n Names can point to specific variables under classes, e.g.\n \"policy.optimizer\" would point to ``optimizer`` object of ``self.policy``\n if this object.\n\n :return:\n List of Torch variables whose state dicts to save (e.g. th.nn.Modules),\n and list of other Torch variables to store with ``th.save``.\n \"\"\"\n state_dicts = [\n \"policy\",\n \"actor.optimizer\",\n \"critic.optimizer\",\n \"mbctrl.model\",\n \"mbctrl.model.optim\",\n ]\n saved_pytorch_variables = [\"log_ent_coef\", \"mbctrl.has_been_trained\", \"petssac_coef\"]\n if self.ent_coef_optimizer is not None:\n state_dicts.append(\"ent_coef_optimizer\")\n else:\n saved_pytorch_variables.append(\"ent_coef_tensor\")\n return state_dicts, saved_pytorch_variables\n"
] | [
[
"torch.nn.functional.mse_loss",
"torch.no_grad",
"torch.min",
"numpy.mean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ofazzito/yolov4-deepsort | [
"bac1e8f800f3074e89bb6980a7787be636e5cd58"
] | [
"alpr/ocr.py"
] | [
"import tensorflow as tf\nimport numpy as np\nimport cv2\nimport string\n\nMODELOS = {\n 1: 'alpr/models/ocr/m1_2.0M_GPU',\n 2: 'alpr/models/ocr/m2_1.5M_GPU',\n 3: 'alpr/models/ocr/m3_1.3M_CPU',\n 4: 'alpr/models/ocr/m4_1.1M_CPU',\n}\n\n\nclass PlateOCR:\n '''\n Modulo encargado del reconocimiento\n de caracteres de las patentes (ya recortadas)\n '''\n\n def __init__(self,\n ocr_model_num: int = 3,\n confianza_avg: float = 0.5,\n none_low_thresh: float = 0.35):\n '''\n Parametros:\n ocr_model_num Numero del modelo a usar (1-4)\n '''\n if ocr_model_num not in MODELOS:\n raise KeyError('Modelo inexistente, valores posibles: (1-4)')\n\n ocr_model_path = MODELOS[ocr_model_num]\n self.imported = tf.saved_model.load(ocr_model_path)\n self.cnn_ocr_model = self.imported.signatures[\"serving_default\"]\n self.alphabet = string.digits + string.ascii_uppercase + '_'\n self.confianza_avg = confianza_avg\n self.none_low_thresh = none_low_thresh\n\n def predict(self, iter_coords, frame: np.ndarray) -> list:\n '''\n Reconoce a partir de un frame todas\n las patentes en formato de texto\n\n Parametros:\n iter_coords: generator object que yieldea las patentes\n frame: sub-frame conteniendo la patente candidato\n Returns:\n Lista de patentes (en formato de texto)\n '''\n patentes = []\n for yolo_prediction in iter_coords:\n # x1, y1, x2, y2, score = yolo_prediction\n x1, y1, x2, y2, _ = yolo_prediction\n plate, probs = self.predict_ocr(x1, y1, x2, y2, frame)\n # Ignorar si tiene baja confianza el OCR\n avg = np.mean(probs)\n if avg > self.confianza_avg and self.none_low(probs, thresh=self.none_low_thresh):\n plate = (''.join(plate)).replace('_', '')\n patentes.append(plate)\n return patentes\n\n def none_low(self, probs, thresh=.5):\n '''\n Devuelve False si hay algun caracter\n con probabilidad por debajo de thresh\n '''\n for prob in probs:\n if prob < thresh:\n return False\n return True\n\n def print_plates(self):\n print(', '.join(self.unique_plates))\n\n def predict_ocr(self,\n x1: int,\n y1: int,\n x2: int,\n y2: int,\n frame: np.ndarray):\n '''\n Hace OCR en un sub-frame del frame\n\n Parametros:\n x1: Valor de x de la esquina superior izquierda del rectangulo\n y1: \" y \" \" \"\n x2: Valor de x de la esquina inferior derecha del rectangulo\n y2: \" y \" \" \"\n frame: array conteniendo la imagen original\n '''\n cropped_plate = frame[y1:y2, x1:x2]\n prediction_ocr = self.__predict_from_array(cropped_plate)\n plate, probs = self.__probs_to_plate(prediction_ocr)\n return plate, probs\n\n def __probs_to_plate(self, prediction):\n prediction = prediction.reshape((7, 37))\n probs = np.max(prediction, axis=-1)\n prediction = np.argmax(prediction, axis=-1)\n plate = list(map(lambda x: self.alphabet[x], prediction))\n return plate, probs\n\n def __predict_from_array(self, patente_recortada: np.ndarray):\n '''\n Hace el preprocessing (normaliza, agrega batch_dimension)\n y hace la inferencia\n\n Parametros:\n patente_recortada: array conteniendo la imagen recortada (solo la patente)\n Returns:\n np.array de (1,259) que contiene las predicciones para cada\n caracter de la patente (37 posibles caracteres * 7 lugares)\n '''\n patente_recortada = cv2.cvtColor(patente_recortada, cv2.COLOR_RGB2GRAY)\n patente_recortada = cv2.resize(patente_recortada, (140, 70))\n patente_recortada = patente_recortada[np.newaxis, ..., np.newaxis]\n patente_recortada = tf.constant(\n patente_recortada, dtype=tf.float32) / 255.\n # Hacer prediction\n pred = self.cnn_ocr_model(patente_recortada)\n return pred[next(iter(pred))].numpy()\n"
] | [
[
"tensorflow.constant",
"tensorflow.saved_model.load",
"numpy.max",
"numpy.argmax",
"numpy.mean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
anonymousUpdatar/fse22_prompt | [
"68a0ce66e2965dd9456a6834e202725f0d8a3117"
] | [
"defect/prompt/run.py"
] | [
"from __future__ import absolute_import, division, print_function\n\nimport argparse\nimport glob\nimport logging\nimport os\nimport pickle\nimport random\nimport re\nimport shutil\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import DataLoader, Dataset, SequentialSampler, RandomSampler,TensorDataset\nfrom torch.utils.data.distributed import DistributedSampler\nimport json\n# try:\n# from torch.utils.tensorboard import SummaryWriter\n# except:\n# from tensorboardX import SummaryWriter\n\nfrom tqdm import tqdm, trange\n# import multiprocessing\nfrom model import Model\n# cpu_cont = multiprocessing.cpu_count()\nfrom transformers import (WEIGHTS_NAME, AdamW, get_linear_schedule_with_warmup,\n BertConfig, BertForMaskedLM, BertTokenizer,\n GPT2Config, GPT2LMHeadModel, GPT2Tokenizer,\n OpenAIGPTConfig, OpenAIGPTLMHeadModel, OpenAIGPTTokenizer,\n RobertaConfig, RobertaForSequenceClassification, RobertaTokenizer,\n DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer)\n\nlogger = logging.getLogger(__name__)\n\nMODEL_CLASSES = {\n 'gpt2': (GPT2Config, GPT2LMHeadModel, GPT2Tokenizer),\n 'openai-gpt': (OpenAIGPTConfig, OpenAIGPTLMHeadModel, OpenAIGPTTokenizer),\n 'bert': (BertConfig, BertForMaskedLM, BertTokenizer),\n 'roberta': (RobertaConfig, RobertaForSequenceClassification, RobertaTokenizer),\n 'distilbert': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer)\n}\n\n\nclass InputFeatures(object):\n \"\"\"A single training/test features for a example.\"\"\"\n def __init__(self,\n input_tokens,\n input_ids,\n idx,\n label,\n\n ):\n self.input_tokens = input_tokens\n self.input_ids = input_ids\n self.idx=str(idx)\n self.label=label\n\n \ndef convert_examples_to_features(js,tokenizer,args):\n #source\n code=' '.join(js['func'].split())\n code_tokens=tokenizer.tokenize(code)[:args.block_size-2]\n source_tokens =[tokenizer.cls_token]+code_tokens+[tokenizer.sep_token]\n source_ids = tokenizer.convert_tokens_to_ids(source_tokens)\n padding_length = args.block_size - len(source_ids)\n source_ids+=[tokenizer.pad_token_id]*padding_length\n return InputFeatures(source_tokens,source_ids,js['idx'],js['target'])\n\nclass TextDataset(Dataset):\n def __init__(self, tokenizer, args, file_path=None):\n self.examples = []\n with open(file_path) as f:\n for line in f:\n js=json.loads(line.strip())\n self.examples.append(convert_examples_to_features(js,tokenizer,args))\n if 'train' in file_path:\n for idx, example in enumerate(self.examples[:3]):\n logger.info(\"*** Example ***\")\n logger.info(\"idx: {}\".format(idx))\n logger.info(\"label: {}\".format(example.label))\n logger.info(\"input_tokens: {}\".format([x.replace('\\u0120','_') for x in example.input_tokens]))\n logger.info(\"input_ids: {}\".format(' '.join(map(str, example.input_ids))))\n\n def __len__(self):\n return len(self.examples)\n\n def __getitem__(self, i): \n return torch.tensor(self.examples[i].input_ids),torch.tensor(self.examples[i].label)\n \n\ndef set_seed(seed=42):\n random.seed(seed)\n os.environ['PYHTONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n\n\n"
] | [
[
"torch.manual_seed",
"torch.cuda.manual_seed",
"numpy.random.seed",
"torch.tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bobiblazeski/navigation | [
"bb863b4475a90ff26bede20af647ae4882a0f6fb"
] | [
"agent.py"
] | [
"import numpy as np\nimport random\nfrom collections import namedtuple, deque\n\n\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n\nfrom lib.network import QNetwork, DuelingQNetwork\nfrom lib.replay_buffer import ReplayBuffer\nfrom lib.priority_buffer import PriorityBuffer\n\n\nBUFFER_SIZE = int(1e5) # replay buffer size\nBATCH_SIZE = 64 # minibatch size\nGAMMA = 0.99 # discount factor\nTAU = 1e-3 # for soft update of target parameters\nLR = 5e-4 # learning rate \nUPDATE_EVERY = 4 # how often to update the network\n\n\nclass Agent():\n \"\"\"Interacts with and learns from the environment.\"\"\"\n\n def __init__(self, state_size, action_size, seed,\n double=True, dueling=True, priority=False):\n \"\"\"Initialize an Agent object.\n \n Params\n ======\n state_size (int): dimension of each state\n action_size (int): dimension of each action\n seed (int): random seed\n \"\"\"\n self.state_size = state_size\n self.action_size = action_size\n self.seed = random.seed(seed)\n self.double = double\n self.dueling = dueling\n self.priority = priority\n self.gpu = torch.cuda.is_available() \n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n # Q-Network\n if self.dueling:\n self.qnetwork_local = DuelingQNetwork(state_size, action_size, seed).to(self.device)\n self.qnetwork_target = DuelingQNetwork(state_size, action_size, seed).to(self.device)\n else:\n self.qnetwork_local = QNetwork(state_size, action_size, seed).to(self.device)\n self.qnetwork_target = QNetwork(state_size, action_size, seed).to(self.device)\n \n self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=LR)\n\n # Replay memory\n if self.priority:\n self.memory = PriorityBuffer(BUFFER_SIZE, BATCH_SIZE, self.device)\n else:\n self.memory = ReplayBuffer(BUFFER_SIZE, BATCH_SIZE, seed, self.device)\n # Initialize time step (for updating every UPDATE_EVERY steps)\n self.t_step = 0\n \n def step(self, state, action, reward, next_state, done):\n # Save experience in replay memory\n self.memory.add(state, action, reward, next_state, done)\n \n # Learn every UPDATE_EVERY time steps.\n self.t_step = (self.t_step + 1) % UPDATE_EVERY\n if self.t_step == 0:\n # If enough samples are available in memory, get random subset and learn\n if len(self.memory) > BATCH_SIZE:\n if self.priority:\n experiences, idx_batch = self.memory.sample()\n errors = self.learn(experiences, GAMMA)\n self.memory.update(idx_batch, errors)\n else:\n experiences = self.memory.sample()\n self.learn(experiences, GAMMA)\n \n\n def act(self, state, eps=0.):\n \"\"\"Returns actions for given state as per current policy.\n \n Params\n ======\n state (array_like): current state\n eps (float): epsilon, for epsilon-greedy action selection\n \"\"\"\n state = torch.from_numpy(state).float().unsqueeze(0).to(self.device)\n self.qnetwork_local.eval()\n with torch.no_grad():\n action_values = self.qnetwork_local(state)\n self.qnetwork_local.train()\n\n # Epsilon-greedy action selection\n if random.random() > eps:\n return np.argmax(action_values.cpu().data.numpy())\n else:\n return random.choice(np.arange(self.action_size))\n\n def learn(self, experiences, gamma):\n \"\"\"Update value parameters using given batch of experience tuples.\n\n Params\n ======\n experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples \n gamma (float): discount factor\n \"\"\"\n states, actions, rewards, next_states, dones = experiences\n\n # Get max predicted Q values (for next states) from target model\n if self.double: \n Q_targets_local_next = self.qnetwork_local(next_states).detach().max(1)[0].unsqueeze(1) \n Q_targets_target_next = self.qnetwork_target(next_states).detach().max(1)[0].unsqueeze(1) \n Q_targets_next = Q_targets_target_next.gather(1, torch.max(Q_targets_local_next, 1)[1].unsqueeze(1))\n else:\n Q_targets_next = self.qnetwork_target(next_states).detach().max(1)[0].unsqueeze(1)\n # Compute Q targets for current states \n Q_targets = rewards + (gamma * Q_targets_next * (1 - dones))\n\n # Get expected Q values from local model\n Q_expected = self.qnetwork_local(states).gather(1, actions)\n\n # Compute loss\n loss = F.mse_loss(Q_expected, Q_targets)\n # Minimize the loss\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n # ------------------- update target network ------------------- #\n self.soft_update(self.qnetwork_local, self.qnetwork_target, TAU) \n abs_error = torch.abs(torch.squeeze(Q_expected - Q_targets))\n if self.gpu: \n abs_error = abs_error.cpu() \n return abs_error.data.numpy()\n\n def soft_update(self, local_model, target_model, tau):\n \"\"\"Soft update model parameters.\n θ_target = τ*θ_local + (1 - τ)*θ_target\n\n Params\n ======\n local_model (PyTorch model): weights will be copied from\n target_model (PyTorch model): weights will be copied to\n tau (float): interpolation parameter \n \"\"\"\n for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):\n target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)\n \n def load(self, checkpoint):\n self.qnetwork_local.load_state_dict(torch.load(checkpoint))\n self.qnetwork_target.load_state_dict(torch.load(checkpoint))"
] | [
[
"torch.max",
"torch.load",
"numpy.arange",
"torch.from_numpy",
"torch.nn.functional.mse_loss",
"torch.no_grad",
"torch.cuda.is_available",
"torch.squeeze"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kchen92/graphnav | [
"7c2159b876ac377e6ff075ae6c7201036144f4f2"
] | [
"src/semnav/lib/navigation_plan.py"
] | [
"from __future__ import print_function\n\nimport numpy as np\n\nfrom collections import namedtuple, OrderedDict\n\nfrom semnav_ros.msg import NavCommandGoal\nfrom semnav.lib.categories import NavPlanDifficulty\n\n\nNavigationGoal = namedtuple('NavigationGoal', ['start_node', 'end_node'])\n\n\nclass NavigationPlan(object):\n \"\"\"Navigation plan as a sequence of nodes/behaviors.\n \"\"\"\n\n def __init__(self, node_list):\n assert len(node_list) > 0\n\n # Build edge list\n edge_list = []\n node2edge = OrderedDict()\n for idx, cur_node in enumerate(node_list):\n if (idx + 1) < len(node_list):\n next_node = node_list[idx + 1]\n for edge in cur_node.outgoing_edges:\n if edge.end_node is next_node:\n edge_list.append(edge)\n node2edge[cur_node] = edge\n break\n assert len(edge_list) == (len(node_list) - 1)\n\n self._node_list = tuple(node_list)\n self._edge_list = tuple(edge_list)\n self._node2edge = node2edge\n self._nav_goal = NavigationGoal(self.node_list[0], self.node_list[-1])\n assert self.is_valid_nav_plan() is True\n self._estimated_distance = self.compute_estimated_distance() # Map coord units (meters)\n if len(node_list) < 10:\n self._difficulty = NavPlanDifficulty.easy\n elif len(node_list) < 20:\n self._difficulty = NavPlanDifficulty.moderate\n else:\n self._difficulty = NavPlanDifficulty.hard\n\n def compute_estimated_distance(self):\n total_dist = 0.\n for edge in self.edge_list:\n cur_dist = np.linalg.norm(edge.end_node.map_coord - edge.start_node.map_coord)\n total_dist += cur_dist\n return total_dist\n\n def percentage_plan_completed(self, last_valid_node):\n cur_node_step = 0\n for node in self.node_list:\n cur_node_step += 1\n if node is last_valid_node:\n break\n return float(cur_node_step) / len(self.node_list)\n\n def to_ros_msg(self, episode_idx):\n nav_plan_string = ' '.join([node.name for node in self.node_list])\n nav_command_goal = NavCommandGoal(episode_idx=episode_idx, nav_plan=nav_plan_string)\n return nav_command_goal\n\n @staticmethod\n def from_msg(sem_graph, ros_msg):\n \"\"\"Decode a nav_plan_msg (ROS msg) to a NavigationPlan.\n \"\"\"\n node_names = ros_msg.nav_plan.split(' ')\n node_list = [sem_graph.nodes[node_name] for node_name in node_names]\n nav_plan = NavigationPlan(node_list)\n return int(ros_msg.episode_idx), nav_plan\n\n def is_valid_nav_plan(self):\n \"\"\"Performs the following checks to make sure the navigation plan is valid:\n - Navigation plan has length greater than 0\n - Navigation plan starts in room\n - Navigation plan ends in room\n\n We should never visit the same node twice for any given navigation plan.\n \"\"\"\n return len(self.node_list) > 0\n\n @property\n def node_list(self):\n return self._node_list\n\n @property\n def edge_list(self):\n return self._edge_list\n\n @property\n def node2edge(self):\n return self._node2edge\n\n @property\n def nav_goal(self):\n return self._nav_goal\n\n @property\n def estimated_distance(self):\n return self._estimated_distance\n\n @property\n def difficulty(self):\n return self._difficulty\n"
] | [
[
"numpy.linalg.norm"
]
] | [
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.24",
"1.13",
"1.16",
"1.9",
"1.18",
"1.23",
"1.21",
"1.22",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
condereis/kaggle-mnist | [
"51c6935fccb1545dcbf3160e9041f3dc89f1a304"
] | [
"src/models/predict.py"
] | [
"import click\nimport json\nimport numpy as np\nimport os\nimport pandas as pd\nimport sys\nimport tensorflow as tf\n\nimport logreg\nimport convnn\n\n\[email protected]()\[email protected]('--model', type=click.Choice(['logreg', 'convnn']), default='convnn')\ndef main(model):\n # Load data\n project_dir = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)\n settings = json.loads(\n open(os.path.join(project_dir, 'SETTINGS.json')).read()\n )\n\n test_path = os.path.join(project_dir, settings['TEST_DATA_PATH'])\n test_data = pd.read_csv(test_path)\n\n # Run training\n if model == 'logreg':\n logreg.run(None, test_data, False, True)\n else:\n convnn.run(None, test_data, False, True)\n\n\nif __name__ == '__main__':\n main()"
] | [
[
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
EmeseThamo/rl-attack | [
"2bb72aed3c684d2f88eec84df9b82b0099de8b25"
] | [
"enjoy-adv.py"
] | [
"\"\"\" DQN - Test-time attacks\n\n============ Sample usage ============ \n\nNo attack, testing a DQN model of Breakout trained without parameter noise:\n$> python3 enjoy-adv.py --env Breakout --model-dir ./data/Breakout/model-173000 --video ./Breakout.mp4\n\nNo attack, testing a DQN model of Breakout trained with parameter noise (NoisyNet implementation):\n$> python3 enjoy-adv.py --env Breakout --noisy --model-dir ./data/Breakout/model-173000 --video ./Breakout.mp4\n\nWhitebox FGSM attack, testing a DQN model of Breakout trained without parameter noise:\n$> python3 enjoy-adv.py --env Breakout --model-dir ./data/Breakout/model-173000 --attack fgsm --video ./Breakout.mp4\n\nWhitebox FGSM attack, testing a DQN model of Breakout trained with parameter noise (NoisyNet implementation):\n$> python3 enjoy-adv.py --env Breakout --noisy --model-dir ./data/Breakout/model-173000 --attack fgsm --video ./Breakout.mp4\n\nBlackbox FGSM attack, testing a DQN model of Breakout trained without parameter noise:\n$> python3 enjoy-adv.py --env Breakout --model-dir ./data/Breakout/model-173000 --attack fgsm --blackbox --model-dir2 ./data/Breakout/model-173000-2 --video ./Breakout.mp4\n\nBlackbox FGSM attack, testing a DQN model of Breakout trained with parameter noise (NoisyNet implementation), replica model trained without parameter noise:\n$> python3 enjoy-adv.py --env Breakout --noisy --model-dir ./data/Breakout/model-173000 --attack fgsm --blackbox --model-dir2 ./data/Breakout/model-173000-2 --video ./Breakout.mp4\n\nBlackbox FGSM attack, testing a DQN model of Breakout trained with parameter noise (NoisyNet implementation), replica model trained with parameter noise:\n$> python3 enjoy-adv.py --env Breakout --noisy --model-dir ./data/Breakout/model-173000 --attack fgsm --blackbox --model-dir2 ./data/Breakout/model-173000-2 --noisy2 --video ./Breakout.mp4\n\n\"\"\"\n\nimport argparse\nimport gym\nimport os\nimport numpy as np\n\n#from gym.monitoring import VideoRecorder\nfrom gym import wrappers\nfrom time import time\nimport rlattack.common.tf_util as U\n\nfrom rlattack import deepq\nfrom rlattack.common.misc_util import (\n\tboolean_flag,\n\tSimpleMonitor,\n)\nfrom rlattack.common.atari_wrappers_deprecated import wrap_dqn\n#from rlattack.deepq.experiments.atari.model import model, dueling_model\n\n#V: imports#\nimport tensorflow as tf\nimport cv2\nfrom collections import deque\nfrom model import model, dueling_model\nfrom statistics import statistics\n\nclass DQNModel:\n\t\"\"\"\n\tCreating Q-graph, FGSM graph\n\tSupports loading multiple graphs - needed for blackbox attacks\n\t\"\"\"\n\n\tdef __init__(self, env, dueling, noisy, fname):\n\t\tself.g = tf.Graph()\n\t\tself.noisy = noisy\n\t\tself.dueling = dueling \n\t\tself.env = env\n\t\twith self.g.as_default():\n\t\t\tself.act = deepq.build_act_enjoy(\n\t\t\t\tmake_obs_ph=lambda name: U.Uint8Input(env.observation_space.shape, name=name),\n\t\t\t\tq_func=dueling_model if dueling else model,\n\t\t\t\tnum_actions=env.action_space.n,\n\t\t\t\tnoisy=noisy\n\t\t\t\t)\n\t\t\tself.saver = tf.train.Saver()\n\t\tself.sess = tf.Session(graph=self.g)\t\n\t\t\n\t\tif fname is not None:\n\t\t\tprint ('Loading Model...')\n\t\t\tself.saver.restore(self.sess, fname)\n\t\n\tdef get_act(self):\n\t\treturn self.act\n\t\t\n\tdef get_session(self):\n\t\treturn self.sess \n\t\n\tdef craft_adv(self):\n\t\twith self.sess.as_default():\n\t\t\twith self.g.as_default():\n\t\t\t\tcraft_adv_obs = deepq.build_adv(\n\t\t\t\t\t\t\t\tmake_obs_tf=lambda name: U.Uint8Input(self.env.observation_space.shape, name=name),\n\t\t\t\t\t\t\t\tq_func=dueling_model if self.dueling else model,\n\t\t\t\t\t\t\t\tnum_actions=self.env.action_space.n,\n\t\t\t\t\t\t\t\tepsilon = 1.0/255.0,\n\t\t\t\t\t\t\t\tnoisy=self.noisy,\n\t\t\t\t\t\t\t\t)\n\t\treturn craft_adv_obs\n\t\t\n\t\t\t\n\t\ndef parse_args():\n\tparser = argparse.ArgumentParser(\"Run an already learned DQN model.\")\n\t# Environment\n\tparser.add_argument(\"--env\", type=str, required=True, help=\"name of the game\")\n\tparser.add_argument(\"--model-dir\", type=str, default=None, help=\"load model from this directory. \")\n\tparser.add_argument(\"--video\", type=str, default=None, help=\"Path to mp4 file where the video of first episode will be recorded.\")\n\tboolean_flag(parser, \"stochastic\", default=True, help=\"whether or not to use stochastic actions according to models eps value\")\n\tboolean_flag(parser, \"dueling\", default=False, help=\"whether or not to use dueling model\")\n\t#V: Attack Arguments#\n\tparser.add_argument(\"--model-dir2\", type=str, default=None, help=\"load adversarial model from this directory (blackbox attacks). \")\n\tparser.add_argument(\"--attack\", type=str, default=None, help=\"Method to attack the model.\")\n\tboolean_flag(parser, \"noisy\", default=False, help=\"whether or not to NoisyNetwork\")\n\tboolean_flag(parser, \"noisy2\", default=False, help=\"whether or not to NoisyNetwork\")\n\tboolean_flag(parser, \"blackbox\", default=False, help=\"whether or not to NoisyNetwork\")\n\n\treturn parser.parse_args()\n\n\ndef make_env(game_name):\n\tenv = gym.make(game_name + \"NoFrameskip-v4\")\n\t#env = SimpleMonitor(env)\n\tenv = wrappers.Monitor(env, './videos/' + str(time()) + '/')\n\tenv = wrap_dqn(env)\n\treturn env\n\n\ndef play(env, act, craft_adv_obs, craft_adv_obs2, stochastic, video_path, attack, m_target, m_adv):\n\tnum_episodes = 0\n\tnum_moves = 0\n\tnum_transfer = 0\n\tepisode_rewards = [0.0]\n\t#video_recorder = None\n\t#video_recorder = VideoRecorder(\n\t#\tenv, video_path, enabled=video_path is not None)\n\tobs = env.reset()\n\twhile True:\n\t\tenv.unwrapped.render()\n\t\t#video_recorder.capture_frame()\n\n\t#V: Attack #\n\t\tif attack != None:\n\t\t\t# Craft adv. examples\n\t\t\twith m_adv.get_session().as_default():\n\t\t\t\tadv_obs = craft_adv_obs(np.array(obs)[None], stochastic_adv=stochastic)[0]\n\t\t\twith m_target.get_session().as_default():\n\t\t\t\taction = act(np.array(adv_obs)[None], stochastic=stochastic)[0]\n\t\t\t\taction2 = act(np.array(obs)[None], stochastic=stochastic)[0]\n\t\t\t\tnum_moves += 1\n\t\t\t\tif (action != action2):\n\t\t\t\t\tnum_transfer += 1\n\t\telse:\n\t\t\t# Normal\n\t\t\taction = act(np.array(obs)[None], stochastic=stochastic)[0]\n\t\t\n\t\tobs, rew, done, _ = env.step(action)\n\t\tepisode_rewards[-1] += rew\n\t\tif done:\n\t\t\tobs = env.reset()\n\t\t\tepisode_rewards.append(0.0)\n\n\n\t\tif done:\n\t\t\t#if len(info[\"rewards\"]) == 1: #and video_recorder.enabled:\n\t\t\t\t# save video of first episode\n\t\t\t\t#print(\"Saved video.\")\n\t\t\t\t#video_recorder.close()\n\t\t\t\t#video_recorder.enabled = False\n\t\t\t#mean_100ep_reward = round(np.mean(episode_rewards[-101:-1]), 1)\n\t\t\tprint('Reward: ' + str(episode_rewards[-2]))\n\t\t\tnum_episodes = len(episode_rewards)\n\t\t\tprint ('Episode: ' + str(num_episodes))\n\t\t\tsuccess = float((num_transfer)/num_moves) * 100.0\n\t\t\tprint(\"Percentage of successful attacks: \"+str(success))\n\t\t\tnum_moves = 0\n\t\t\tnum_transfer = 0\n\n\n\nif __name__ == '__main__':\n\targs = parse_args()\n\tenv = make_env(args.env)\n\tg1 = tf.Graph()\n\tg2 = tf.Graph()\n\twith g1.as_default():\n\t\tm1 = DQNModel(env, args.dueling, args.noisy, os.path.join(args.model_dir, \"saved\"))\n\tif args.blackbox == True:\n\t\twith g2.as_default():\n\t\t\tm2 = DQNModel(env, args.dueling, args.noisy2, os.path.join(args.model_dir2, \"saved\"))\n\t\t\twith m2.get_session().as_default():\n\t\t\t\tcraft_adv_obs = m2.craft_adv()\n\t\t\twith m1.get_session().as_default():\n\t\t\t\tcraft_adv_obs2 = m1.craft_adv()\n\t\t\t\tplay(env, m1.get_act(), craft_adv_obs, craft_adv_obs2, args.stochastic, args.video, args.attack, m1, m2)\n\telse:\n\t\twith m1.get_session().as_default():\n\t\t\tcraft_adv_obs = m1.craft_adv()\n\t\t\tplay(env, m1.get_act(), craft_adv_obs, None, args.stochastic, args.video, args.attack, m1, m1)\n"
] | [
[
"tensorflow.train.Saver",
"tensorflow.Graph",
"numpy.array",
"tensorflow.Session"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
julianyulu/SyncNetCN | [
"cdd378aa3a2ac5a3a3edef5edc0478ae66da041d"
] | [
"SyncNet/runner.py"
] | [
"import os\nimport glob \nimport torch\nimport argparse\nfrom tqdm import tqdm \nfrom .dataset import Dataset\nfrom .model import SyncNet\nfrom omegaconf import OmegaConf \nfrom torch.utils import data as data_utils\nfrom utils import wandb_utils\nfrom utils.batch_sampler import RandomEntryBatchSampler\nimport pdb \n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nclass Runner:\n def __init__(self, config):\n self.cfg = config \n # set model \n self.model = SyncNet(1024)\n if torch.cuda.device_count() > 1:\n self.model = torch.nn.DataParallel(self.model)\n self.model = self.model.to(device)\n self.optimizer = torch.optim.Adam([p for p in self.model.parameters() if p.requires_grad], lr = self.cfg.runtime.init_learning_rate)\n \n if self.cfg.model.resume_ckpt:\n self.resume_from_ckpt(self.cfg.model.resume_ckpt)\n else:\n os.makedirs(self.cfg.runtime.checkpoint_dir, exist_ok = True)\n OmegaConf.save(self.cfg, os.path.join(self.cfg.runtime.checkpoint_dir, 'config.yaml'))\n\n if self.cfg.wandb.enable:\n wandb_utils.init(self.cfg)\n\n def resume_from_ckpt(self, resume_ckpt):\n # overwrite curr config from ckpt dir \n if self.cfg.model.resume_ckpt_config: \n self.cfg = OmegaConf.load(os.path.join(os.path.dirname(resume_ckpt), 'config.yaml'))\n \n print(\"Loading checkpoint from: {}\".format(resume_ckpt))\n\n if torch.cuda.is_available():\n checkpoint = torch.load(resume_ckpt, map_location = lambda storage, loc: storage)\n else:\n checkpoint = torch.load(resume_ckpt)\n\n self.model.load_state_dict(checkpoint[\"state_dict\"])\n\n if not self.cfg.runtime.reset_optimizer:\n optimizer_state = checkpoint[\"optimizer\"]\n if optimizer_state is not None:\n print(\"Loading optimizer state from {}\".format(resume_ckpt))\n self.optimizer.load_state_dict(checkpoint[\"optimizer\"])\n \n self.global_step = checkpoint[\"global_step\"]\n self.global_epoch = checkpoint[\"global_epoch\"]\n\n def save_checkpoint(self):\n os.makedirs(self.cfg.runtime.checkpoint_dir, exist_ok = True)\n ckpt_path = os.path.join(self.cfg.runtime.checkpoint_dir,\n f\"checkpoint_step{int(self.global_step)}.pth\")\n opt_state = self.optimizer.state_dict() if self.cfg.runtime.save_optimizer_state else None\n model_state = self.model.state_dict()\n\n torch.save({\n \"state_dict\": model_state,\n \"optimizer\": opt_state,\n \"global_step\": self.global_step,\n \"global_epoch\": self.global_epoch\n }, ckpt_path)\n print(f\"Saved checkpoint: {ckpt_path}\")\n \n def get_dataloader(self, split):\n dataset = Dataset(self.cfg, split)\n if split == 'train':\n batch_sampler = RandomEntryBatchSampler(len(dataset),\n batch_size = self.cfg.runtime.batch_size,\n steps_per_epoch = self.cfg.runtime.steps_per_epoch)\n data_loader = data_utils.DataLoader(dataset,\n pin_memory = True,\n batch_sampler = batch_sampler)\n else:\n \n data_loader = data_utils.DataLoader(dataset,\n batch_size = self.cfg.runtime.batch_size,\n pin_memory = False,\n shuffle = False,\n num_workers = self.cfg.runtime.num_workers)\n return data_loader\n \n def loss_fn(self, a, v, y):\n if not hasattr(self, '_bce_loss'):\n self._bce_loss = torch.nn.BCELoss()\n d = torch.nn.functional.cosine_similarity(a, v)\n loss = self._bce_loss((d.unsqueeze(1) + 1) / 2., y)\n return loss \n\n def log(self, log_dict):\n if self.cfg.wandb.enable:\n wandb_utils.log(log_dict)\n \n def eval(self):\n if not hasattr(self, '_test_data_loader'):\n self._test_data_loader = self.get_dataloader('val')\n losses = []\n step = 0 \n while True:\n for x, mel, y in self._test_data_loader:\n self.model.eval()\n x = x.to(device)\n mel = mel.to(device)\n a, v = self.model(mel, x)\n y = y.to(device)\n loss = self.loss_fn(a, v, y)\n losses.append(loss.item())\n step += 1\n if step >= self.cfg.runtime.eval_forward_steps:\n break\n if step >= self.cfg.runtime.eval_forward_steps:\n break\n \n averaged_loss = sum(losses) / len(losses)\n \n return {\"eval_loss\": averaged_loss,\n \"step\": self.global_step,\n \"epoch\": self.global_epoch}\n\n def train(self):\n if not hasattr(self, 'global_step'): self.global_step = 0\n if not hasattr(self, 'global_epoch'): self.global_epoch = 0\n\n train_data_loader = self.get_dataloader('train')\n\n while self.global_epoch < self.cfg.runtime.nepochs:\n running_loss = 0.\n prog_bar = tqdm(enumerate(train_data_loader), total = self.cfg.runtime.steps_per_epoch)\n \n for step, (x, mel, y) in prog_bar:\n # x: (B, 3, 5, 240, 240)\n # mel: (B, 1, 13, 20)\n self.model.train()\n self.optimizer.zero_grad()\n x = x.to(device)\n mel = mel.to(device)\n a, v = self.model(mel, x) #(B, 1024)\n y = y.to(device)\n loss = self.loss_fn(a, v, y)\n loss.backward()\n self.optimizer.step()\n self.global_step += 1\n running_loss += loss.item()\n\n prog_bar.set_description(f\"Epoch: {self.global_epoch} | Step: {self.global_step} | Train Loss: {running_loss / (step + 1):.6f}\")\n \n if self.global_step >0 and self.global_step % self.cfg.runtime.checkpoint_interval == 0:\n self.save_checkpoint()\n\n if self.global_step % self.cfg.runtime.eval_interval == 0:\n with torch.no_grad():\n eval_res = self.eval()\n self.log(eval_res)\n print(f\"\\nEval Loss @ step {self.global_step} | epoch {self.global_epoch}: {eval_res['eval_loss']:.6f}\") \n \n self.global_epoch += 1 \n self.log({\"step\": self.global_step,\n \"epoch\": self.global_epoch,\n \"train_loss\": running_loss / (step + 1)})\n"
] | [
[
"torch.load",
"torch.utils.data.DataLoader",
"torch.nn.BCELoss",
"torch.nn.DataParallel",
"torch.nn.functional.cosine_similarity",
"torch.no_grad",
"torch.cuda.is_available",
"torch.cuda.device_count",
"torch.save"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
statmlben/CUHK-STAT3009 | [
"6cf8f70a8533ba15abbfb5f50db17cb01fc56410"
] | [
"TF-Ranking/examples/keras/tfrbert_antique_train.py"
] | [
"# Copyright 2021 The TensorFlow Ranking 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\nr\"\"\"A training driver which fine-tunes a TFR-BERT model.\n\nPlease download a BERT checkpoint from tensorflow models\nwebsite:\nhttps://github.com/tensorflow/models/blob/master/official/nlp/docs/pretrained_models.md.\nNote that those checkpoints are TF 2.x compatible, which are different from the\ncheckpoints downloaded here: https://github.com/google-research/bert. You may\nconvert a TF 1.x checkpoint to TF 2.x using `tf2_encoder_checkpoint_converter`\nunder https://github.com/tensorflow/models/tree/master/official/nlp/bert.\nThe following command downloads an uncased BERT-base model checkpoint for you:\n\n```\nmkdir -p /tmp/tfrbert && \\\nwget https://storage.googleapis.com/cloud-tpu-checkpoints/bert/v3/\\\nuncased_L-12_H-768_A-12.tar.gz -P /tmp/tfrbert && \\\nmkdir -p /tmp/tfrbert/uncased_L-12_H-768_A-12 && \\\ntar -xvf /tmp/tfrbert/uncased_L-12_H-768_A-12.tar.gz \\\n--strip-components 3 -C /tmp/tfrbert/uncased_L-12_H-768_A-12/\n```\n\nYou can also download from here the Antique data set which has been converted\ninto BERT-compatible format:\nhttps://ciir.cs.umass.edu/downloads/Antique/tfr-bert/ELWC/. The following\ncommand downloads the data set to \"/tmp/tfrbert/data/\" directory.\n\n```\nmkdir -p /tmp/tfrbert/data && \\\nwget https://ciir.cs.umass.edu/downloads/Antique/tf-ranking/\\\nantique_train_seq_64_elwc.tfrecords -P /tmp/tfrbert/data && \\\nwget https://ciir.cs.umass.edu/downloads/Antique/tf-ranking/\\\nantique_test_seq_64_elwc.tfrecords -P /tmp/tfrbert/data\n```\n\nThen, use the following command to run training and evaluation locally with CPU\nor GPU. For GPU, please add `CUDA_VISIBLE_DEVICES=0` and `--config=cuda`. The\nexample toy data contains 3 lists in train and test respectively. Due to the\nlarge number of BERT parameters, if running into the `out-of-memory` issue,\nplese see: https://github.com/google-research/bert#out-of-memory-issues.\n\nMODEL_DIR=\"/tmp/tfrbert/model\" && \\\nbazel build -c opt \\\ntensorflow_ranking/examples/keras:tfrbert_antique_train && \\\n./bazel-bin/tensorflow_ranking/examples/keras/tfrbert_antique_train \\\n --experiment=\"tfr_bert\" \\\n --mode=\"train_and_eval\" \\\n --model_dir=\"${MODEL_DIR}\" \\\n --config_file=\\\ntensorflow_ranking/examples/keras/tfrbert_antique_train_config.yaml\n\nChange the paramters in the .yaml `config_file` if you want to change the BERT\ncheckpoint, the data set and the training configurations. Change the `mode` to\n\"eval\" and modify the `output_preds` in the .yaml config file to true to obtain\nprediction of a trained model.\n\"\"\"\n\nfrom absl import app\nfrom absl import flags\nimport gin\nimport tensorflow as tf\n\nfrom official.common import distribute_utils\nfrom official.common import flags as tfm_flags\nfrom official.core import task_factory\nfrom official.core import train_lib\nfrom official.core import train_utils\nfrom official.modeling import performance\n# pylint: disable=unused-import\nfrom tensorflow_ranking.examples.keras import tfrbert_task_experiments\n# pylint: enable=unused-import\n\nFLAGS = flags.FLAGS\n\n\ndef main(_):\n gin.parse_config_files_and_bindings(FLAGS.gin_file, FLAGS.gin_params)\n params = train_utils.parse_configuration(FLAGS)\n model_dir = FLAGS.model_dir\n if 'train' in FLAGS.mode:\n # Pure eval modes do not output yaml files. Otherwise continuous eval job\n # may race against the train job for writing the same file.\n train_utils.serialize_config(params, model_dir)\n\n # Sets mixed_precision policy. Using 'mixed_float16' or 'mixed_bfloat16'\n # can have significant impact on model speeds by utilizing float16 in case of\n # GPUs, and bfloat16 in the case of TPUs. loss_scale takes effect only when\n # dtype is float16\n if params.runtime.mixed_precision_dtype:\n performance.set_mixed_precision_policy(params.runtime.mixed_precision_dtype)\n distribution_strategy = distribute_utils.get_distribution_strategy(\n distribution_strategy=params.runtime.distribution_strategy,\n all_reduce_alg=params.runtime.all_reduce_alg,\n num_gpus=params.runtime.num_gpus,\n tpu_address=params.runtime.tpu,\n **params.runtime.model_parallelism())\n with distribution_strategy.scope():\n task = task_factory.get_task(\n params.task,\n label_spec=('relevance', tf.io.FixedLenFeature(\n shape=[1,], dtype=tf.int64, default_value=-1)),\n logging_dir=model_dir)\n\n train_lib.run_experiment(\n distribution_strategy=distribution_strategy,\n task=task,\n mode=FLAGS.mode,\n params=params,\n model_dir=model_dir)\n\nif __name__ == '__main__':\n tfm_flags.define_flags()\n app.run(main)\n"
] | [
[
"tensorflow.io.FixedLenFeature"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AlexMuresan/single_person_tracker | [
"17bbdf48e1ef6618cbe8ce0f31a5febc02adc22d"
] | [
"demo_script_video_parallel.py"
] | [
"import os\nimport cv2\nimport copy\nimport torch\nimport warnings\nimport numpy as np\n\nfrom threading import Thread\nfrom datetime import datetime\n\nfrom tqdm import tqdm\nfrom utils import get_gt\nfrom utils import get_pred\nfrom utils import load_model\nfrom utils import xywh2xyxy\n\nfrom utils import draw_border, get_optimal_font_scale\n\nfrom human_separation import HumanSeparator\nfrom feature_extraction import FeatureExtractor\nfrom feature_comparison import Comparator\n\nwarnings.filterwarnings('ignore')\n\n\ndef process_video_part(thread_idx, start_frame, end_frame, model, ref_features):\n device = 'cuda:0'\n cap = cv2.VideoCapture('./data/video/AVSS_AB_Hard.mp4')\n curr_frame = start_frame\n cap.set(cv2.CAP_PROP_POS_FRAMES, curr_frame)\n\n refs, refs_torch, refs_hist, refs_nn_feats, refs_limbs_hist = ref_features\n\n while curr_frame != end_frame:\n ret, frame = cap.read()\n curr_frame = cap.get(cv2.CAP_PROP_POS_FRAMES)\n\n if curr_frame % 50 == 0:\n print(f'Thread {thread_idx}: Processing frame {curr_frame}')\n\n if (ret is True) or (frame is not None):\n frame_raw = copy.deepcopy(frame)\n dets_scores_classes = get_gt(curr_frame, gt_dict)\n\n if (len(dets_scores_classes) == 3) and (None not in dets_scores_classes):\n detections = dets_scores_classes[0]\n out_scores = dets_scores_classes[1]\n classes = dets_scores_classes[2]\n\n # Creating a mask based on our segmentation model\n # We apply person segmentation on the whole frame\n labels = get_pred(frame, model, device)\n mask = labels == 15\n mask = np.array(mask, dtype=np.uint8) * 255\n frame = cv2.bitwise_or(frame, frame, mask=mask)\n\n for det, _, obj_cls in zip(detections, out_scores, classes):\n # For each frame we're only using the 'person' detections (0)\n if int(obj_cls) == 0:\n # Yolo detections need to be scaled back to the dimensions of the video\n det = det * scaler\n bbox = xywh2xyxy(det)\n xmin, ymin, xmax, ymax = bbox.astype(int)\n # We extract each human from the segmentated frame\n human = frame[ymin:ymax, xmin:xmax]\n # We also keep the detection without any segmentation\n human_no_seg = frame_raw[ymin:ymax, xmin:xmax]\n\n if np.mean(human) <= 21:\n continue\n\n human_original = copy.deepcopy(human_no_seg)\n human = cv2.resize(human, dims, interpolation=cv2.INTER_CUBIC)\n\n # Here we're extracting the same features we extracted for the refference images\n # for each 'person' detection we have in the current frame\n human_hist = feat_ext.color_histogram(human)\n human_nn_feats = feat_ext.nnet_features(human, cpu_output=False)\n human_logits = feat_ext.get_human_parsing_logits(human)\n human_limbs = feat_ext.get_masked_limbs(human, human_logits, idx_list=[5, 7, 13])\n human_limbs_hist = feat_ext.color_histogram(human_limbs)\n\n scores = []\n\n # Here we're comparing the refference features to the current detection's features\n # We have two types of comparisons:\n # - cosine similarity\n # - histogram comparison\n for ref, ref_torch, ref_hist, ref_nn_feats, ref_limbs_hist in zip(\n refs, refs_torch, refs_hist, refs_nn_feats, refs_limbs_hist):\n\n hist_score = comp.compare_histograms(human_hist, ref_hist)\n cos_score = comp.cosine_similarity(torch.Tensor(human).to(device), ref_torch,\n use_torch=True)\n nn_feats_score = comp.cosine_similarity(human_nn_feats, ref_nn_feats,\n use_torch=True)\n limbs_hist_score = comp.compare_histograms(human_limbs_hist, ref_limbs_hist)\n\n # Sometimes the limbs separation doesn't work well, in which case we don't include that\n # in the final score of the detection\n\n if np.mean(human_limbs) < 15:\n score = hist_score + cos_score.cpu() + nn_feats_score.cpu()\n else:\n score = hist_score + cos_score.cpu() + nn_feats_score.cpu() + limbs_hist_score\n scores.append(score)\n\n human_mask = mask[ymin:ymax, xmin:xmax]\n\n zeros = np.zeros_like(human_mask)\n ones = np.ones_like(human_mask)\n\n # In case we have a high score (meaning the detection is close to the refference images)\n # We draw the outline of the detected person with red.\n # If the score is low the outline will be green\n if np.mean(scores) >= 2.2:\n color = np.stack([zeros, zeros, ones * 100], axis=2)\n color_mask = cv2.bitwise_and(color, color, mask=human_mask)\n masked_human = cv2.bitwise_or(human_original, color_mask)\n frame_raw[ymin:ymax, xmin:xmax] = masked_human\n\n optimal_font_scale = get_optimal_font_scale('Suspect', ((xmax - xmin) + 25))\n\n xPos = xmin - 5\n yPos = ymin - 10\n while yPos < 10:\n yPos += 10\n\n draw_border(frame_raw, (xmin, ymin), (xmax, ymax), (0, 0, 255), thickness=2,\n r=5, d=5)\n cv2.putText(frame_raw, 'Suspect', (xmin, yPos), cv2.FONT_HERSHEY_SIMPLEX,\n optimal_font_scale, (0, 0, 255), 1)\n else:\n color = np.stack([zeros, ones * 100, zeros], axis=2)\n color_mask = cv2.bitwise_and(color, color, mask=human_mask)\n masked_human = cv2.bitwise_or(human_original, color_mask)\n frame_raw[ymin:ymax, xmin:xmax] = masked_human\n\n draw_border(frame_raw, (xmin, ymin), (xmax, ymax), (0, 255, 0), thickness=2,\n r=5, d=5)\n\n cv2.imwrite(f'video_images/{int(curr_frame)}.jpg', frame_raw)\n\n else:\n print(f'Thread {thread_idx}: No detections found at frame {curr_frame}')\n continue\n\n print(f'Thread {thread_idx} done!')\n\n\ndef get_ref_features(device):\n # Scanning the reference image folder and extracting features from each image present\n # The extracted features are:\n # - color histogram\n # - neural net extracted features\n # - color histogram extracted from torso, hands, legs and face\n\n refs = []\n refs_torch = []\n refs_hist = []\n refs_nn_feats = []\n refs_limbs_hist = []\n\n for i in tqdm(range(4)):\n ref = cv2.resize(cv2.imread(f'ref_images/{i}.png'), dims, interpolation=cv2.INTER_CUBIC)\n torch_ref = torch.Tensor(ref).to(device)\n\n refs.append(ref)\n refs_torch.append(torch_ref)\n\n refs_hist.append(feat_ext.color_histogram(ref))\n refs_nn_feats.append(feat_ext.nnet_features(ref, cpu_output=False))\n ref_logits = feat_ext.get_human_parsing_logits(ref, use_gpu=True)\n ref_limbs = feat_ext.get_masked_limbs(ref, ref_logits, idx_list=[5, 7, 13])\n refs_limbs_hist.append(feat_ext.color_histogram(ref_limbs))\n\n return (refs, refs_torch, refs_hist, refs_nn_feats, refs_limbs_hist)\n\n\ndef get_splits(start, end, num_threads):\n # Splitting video frames based on number of threads\n # Each thread is gettting is getting basically the same number of frames to process\n\n splits = [start]\n total_frames = end - start\n for i in range(1, num_threads):\n splits.append(start + i * int(total_frames/num_threads))\n\n splits.append(end)\n\n return splits\n\nif __name__ == '__main__':\n start_time = datetime.now()\n print(f\"Start time: {start_time}\")\n device = 'cuda:0'\n\n # Instantiation of the human separator (we use this for segmentation and to parse detections from Yolo)\n sep = HumanSeparator('./data/video/AVSS_AB_Hard.mp4',\n './data/detections/AVSS_AB_Hard.txt',\n load_segmentation=True, device=device)\n\n scaler = sep.scaler\n cap = sep.get_cap()\n gt_dict = sep.get_gt_dict()\n meta = sep.get_meta_info()\n\n # Instantiation of the feature extractor\n feat_ext = FeatureExtractor(load_human_segmentation_model=True, load_human_parsing_model=True,\n device=device)\n\n # Instantiation of the feature comparator\n comp = Comparator()\n\n model = load_model(device)\n\n # The dimensions at which we reshape each detection since this is what the neural network uses\n dims = (473, 473)\n\n # refs, refs_torch, refs_hist, refs_nn_feats, refs_limbs, refs_limbs_hist, refs_clothing_colors, ref_orb_descriptors = get_ref_features(device)\n ref_features = get_ref_features(device)\n\n # We're using 20 threads and starting at frame number 250 since the video is empty before that\n num_threads = 20\n start = 250\n finish = meta['total_frame_nr']\n\n splits = get_splits(start, finish, num_threads)\n\n threads = []\n\n # Starting each thread and giving it it's respective frame-range to process\n for i in range(num_threads):\n worker = Thread(target=process_video_part, args=(i, splits[i], splits[i+1], model, ref_features))\n worker.setDaemon(True)\n print(f'Starting thread {i}')\n worker.start()\n threads.append(worker)\n\n # Joining threads so we can keep monitoring them and so that the script won't finish\n # before the threads finish their work\n for t in threads:\n t.join()\n\n end_time = datetime.now()\n print(f\"Start time: {start_time}\")\n print(f\"End time: {end_time}\")\n print(f\"Run time: {end_time - start_time}\")\n\n print(\"Running ffmpeg command to stitch images\")\n ffmpeg_comand = f\"ffmpeg -framerate 25 -pattern_type glob -i './video_images/*.jpg' -c:v mpeg4 ./output/AVSS_AB_Hard_Out.mp4 -b 5000k\"\n os.system(ffmpeg_comand)"
] | [
[
"numpy.ones_like",
"torch.Tensor",
"numpy.stack",
"numpy.zeros_like",
"numpy.mean",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
neolixcn/LaneATT | [
"146b72de909ff0561b84d51f63f7cfb51e18f7aa"
] | [
"lib/experiment.py"
] | [
"import os\nimport re\nimport json\nimport logging\nimport subprocess\n\nimport torch\nfrom torch.utils.tensorboard import SummaryWriter\n\n\nclass Experiment:\n def __init__(self, exp_name, args=None, mode='train', exps_basedir='experiments', tensorboard_dir='tensorboard'):\n self.name = exp_name\n self.exp_dirpath = os.path.join(exps_basedir, exp_name)\n self.models_dirpath = os.path.join(self.exp_dirpath, 'models')\n self.results_dirpath = os.path.join(self.exp_dirpath, 'results')\n self.cfg_path = os.path.join(self.exp_dirpath, 'config.yaml')\n self.code_state_path = os.path.join(self.exp_dirpath, 'code_state.txt')\n self.log_path = os.path.join(self.exp_dirpath, 'log_{}.txt'.format(mode))\n self.tensorboard_writer = SummaryWriter(os.path.join(tensorboard_dir, exp_name))\n self.cfg = None\n self.setup_exp_dir()\n self.setup_logging()\n\n if args is not None:\n self.log_args(args)\n\n def setup_exp_dir(self):\n os.makedirs(self.exp_dirpath, mode=0o777,exist_ok=True)\n os.makedirs(self.models_dirpath, mode=0o777,exist_ok=True)\n os.makedirs(self.results_dirpath, mode=0o777,exist_ok=True)\n self.save_code_state()\n\n def save_code_state(self):\n state = \"Git hash: {}\".format(\n subprocess.run(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE, check=False).stdout.decode('utf-8'))\n state += '\\n*************\\nGit diff:\\n*************\\n'\n state += subprocess.run(['git', 'diff'], stdout=subprocess.PIPE, check=False).stdout.decode('utf-8')\n with open(self.code_state_path, 'w') as code_state_file:\n code_state_file.write(state)\n\n def setup_logging(self):\n formatter = logging.Formatter(\"[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s\")\n file_handler = logging.FileHandler(self.log_path)\n file_handler.setLevel(logging.DEBUG)\n file_handler.setFormatter(formatter)\n stream_handler = logging.StreamHandler()\n stream_handler.setLevel(logging.INFO)\n stream_handler.setFormatter(formatter)\n logging.basicConfig(level=logging.DEBUG, handlers=[file_handler, stream_handler])\n self.logger = logging.getLogger(__name__)\n\n def log_args(self, args):\n self.logger.debug('CLI Args:\\n %s', str(args))\n\n def set_cfg(self, cfg, override=False):\n assert 'model_checkpoint_interval' in cfg\n self.cfg = cfg\n if not os.path.exists(self.cfg_path) or override:\n with open(self.cfg_path, 'w') as cfg_file:\n cfg_file.write(str(cfg))\n\n def get_last_checkpoint_epoch(self):\n pattern = re.compile('model_(\\\\d+).pt')\n last_epoch = -1\n for ckpt_file in os.listdir(self.models_dirpath):\n result = pattern.match(ckpt_file)\n if result is not None:\n epoch = int(result.groups()[0])\n if epoch > last_epoch:\n last_epoch = epoch\n\n return last_epoch\n\n def get_checkpoint_path(self, epoch):\n return os.path.join(self.models_dirpath, 'model_{:04d}.pt'.format(epoch))\n\n def get_epoch_model(self, epoch):\n return torch.load(self.get_checkpoint_path(epoch))['model']\n\n def load_last_train_state(self, model, optimizer, scheduler):\n epoch = self.get_last_checkpoint_epoch()\n train_state_path = self.get_checkpoint_path(epoch)\n train_state = torch.load(train_state_path)\n model.load_state_dict(train_state['model'])\n optimizer.load_state_dict(train_state['optimizer'])\n scheduler.load_state_dict(train_state['scheduler'])\n\n return epoch, model, optimizer, scheduler\n\n def save_train_state(self, epoch, model, optimizer, scheduler):\n train_state_path = self.get_checkpoint_path(epoch)\n torch.save(\n {\n 'epoch': epoch,\n 'model': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'scheduler': scheduler.state_dict()\n }, train_state_path)\n\n def iter_end_callback(self, epoch, max_epochs, iter_nb, max_iter, loss, loss_components):\n line = 'Epoch [{}/{}] - Iter [{}/{}] - Loss: {:.5f} - '.format(epoch, max_epochs, iter_nb, max_iter, loss)\n line += ' - '.join(\n ['{}: {:.5f}'.format(component, loss_components[component]) for component in loss_components])\n self.logger.debug(line)\n overall_iter = (epoch * max_iter) + iter_nb\n self.tensorboard_writer.add_scalar('loss/total_loss', loss, overall_iter)\n for key in loss_components:\n self.tensorboard_writer.add_scalar('loss/{}'.format(key), loss_components[key], overall_iter)\n\n def epoch_start_callback(self, epoch, max_epochs):\n self.logger.debug('Epoch [%d/%d] starting.', epoch, max_epochs)\n\n def epoch_end_callback(self, epoch, max_epochs, model, optimizer, scheduler):\n self.logger.debug('Epoch [%d/%d] finished.', epoch, max_epochs)\n if epoch % self.cfg['model_checkpoint_interval'] == 0:\n self.save_train_state(epoch, model, optimizer, scheduler)\n\n def train_start_callback(self, cfg):\n self.logger.debug('Beginning training session. CFG used:\\n%s', str(cfg))\n\n def train_end_callback(self):\n self.logger.debug('Training session finished.')\n\n def eval_start_callback(self, cfg):\n self.logger.debug('Beginning testing session. CFG used:\\n%s', str(cfg))\n\n def eval_end_callback(self, dataset, predictions, epoch_evaluated):\n metrics = self.save_epoch_results(dataset, predictions, epoch_evaluated)\n self.logger.debug('Testing session finished on model after epoch %d.', epoch_evaluated)\n self.logger.info('Results:\\n %s', str(metrics))\n\n def save_epoch_results(self, dataset, predictions, epoch):\n # setup dirs\n epoch_results_path = os.path.join(self.results_dirpath, 'epoch_{:04d}'.format(epoch))\n predictions_dir = os.path.join(epoch_results_path, '{}_predictions'.format(dataset.split))\n os.makedirs(predictions_dir, exist_ok=True)\n # eval metrics\n metrics = dataset.eval_predictions(predictions, output_basedir=predictions_dir)\n # log tensorboard metrics\n for key in metrics:\n self.tensorboard_writer.add_scalar('{}_metrics/{}'.format(dataset.split, key), metrics[key], epoch)\n # save metrics\n metrics_path = os.path.join(epoch_results_path, '{}_metrics.json'.format(dataset.split))\n with open(metrics_path, 'w') as results_file:\n json.dump(metrics, results_file)\n # save the cfg used\n with open(os.path.join(epoch_results_path, 'config.yaml'), 'w') as cfg_file:\n cfg_file.write(str(self.cfg))\n\n return metrics\n"
] | [
[
"torch.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
fossabot/unifacisa-visao-computacional | [
"14aef22a3e7fe10ee820d31ce12ad21a3cad7b0b"
] | [
"modulo2/5-publicacao/5.2-servidor/servidor/models.py"
] | [
"import torch.nn.functional as F\n\nfrom utils.google_utils import *\nfrom utils.parse_config import *\nfrom utils.utils import *\n\nONNX_EXPORT = False\n\n\ndef create_modules(module_defs, img_size, arc):\n # Constructs module list of layer blocks from module configuration in module_defs\n\n hyperparams = module_defs.pop(0)\n output_filters = [int(hyperparams['channels'])]\n module_list = nn.ModuleList()\n routs = [] # list of layers which rout to deeper layes\n yolo_index = -1\n\n for i, mdef in enumerate(module_defs):\n modules = nn.Sequential()\n\n if mdef['type'] == 'convolutional':\n bn = int(mdef['batch_normalize'])\n filters = int(mdef['filters'])\n kernel_size = int(mdef['size'])\n pad = (kernel_size - 1) // 2 if int(mdef['pad']) else 0\n modules.add_module('Conv2d', nn.Conv2d(in_channels=output_filters[-1],\n out_channels=filters,\n kernel_size=kernel_size,\n stride=int(mdef['stride']),\n padding=pad,\n bias=not bn))\n if bn:\n modules.add_module('BatchNorm2d', nn.BatchNorm2d(filters, momentum=0.1))\n if mdef['activation'] == 'leaky': # TODO: activation study https://github.com/ultralytics/yolov3/issues/441\n modules.add_module('activation', nn.LeakyReLU(0.1, inplace=True))\n # modules.add_module('activation', nn.PReLU(num_parameters=1, init=0.10))\n # modules.add_module('activation', Swish())\n\n elif mdef['type'] == 'maxpool':\n kernel_size = int(mdef['size'])\n stride = int(mdef['stride'])\n maxpool = nn.MaxPool2d(kernel_size=kernel_size, stride=stride, padding=int((kernel_size - 1) // 2))\n if kernel_size == 2 and stride == 1: # yolov3-tiny\n modules.add_module('ZeroPad2d', nn.ZeroPad2d((0, 1, 0, 1)))\n modules.add_module('MaxPool2d', maxpool)\n else:\n modules = maxpool\n\n elif mdef['type'] == 'upsample':\n modules = nn.Upsample(scale_factor=int(mdef['stride']), mode='nearest')\n\n elif mdef['type'] == 'route': # nn.Sequential() placeholder for 'route' layer\n layers = [int(x) for x in mdef['layers'].split(',')]\n filters = sum([output_filters[i + 1 if i > 0 else i] for i in layers])\n routs.extend([l if l > 0 else l + i for l in layers])\n # if mdef[i+1]['type'] == 'reorg3d':\n # modules = nn.Upsample(scale_factor=1/float(mdef[i+1]['stride']), mode='nearest') # reorg3d\n\n elif mdef['type'] == 'shortcut': # nn.Sequential() placeholder for 'shortcut' layer\n filters = output_filters[int(mdef['from'])]\n layer = int(mdef['from'])\n routs.extend([i + layer if layer < 0 else layer])\n\n elif mdef['type'] == 'reorg3d': # yolov3-spp-pan-scale\n # torch.Size([16, 128, 104, 104])\n # torch.Size([16, 64, 208, 208]) <-- # stride 2 interpolate dimensions 2 and 3 to cat with prior layer\n pass\n\n elif mdef['type'] == 'yolo':\n yolo_index += 1\n mask = [int(x) for x in mdef['mask'].split(',')] # anchor mask\n modules = YOLOLayer(anchors=mdef['anchors'][mask], # anchor list\n nc=int(mdef['classes']), # number of classes\n img_size=img_size, # (416, 416)\n yolo_index=yolo_index, # 0, 1 or 2\n arc=arc) # yolo architecture\n\n # Initialize preceding Conv2d() bias (https://arxiv.org/pdf/1708.02002.pdf section 3.3)\n try:\n if arc == 'defaultpw' or arc == 'Fdefaultpw': # default with positive weights\n b = [-4, -3.6] # obj, cls\n elif arc == 'default': # default no pw (40 cls, 80 obj)\n b = [-5.5, -4.0]\n elif arc == 'uBCE': # unified BCE (80 classes)\n b = [0, -8.5]\n elif arc == 'uCE': # unified CE (1 background + 80 classes)\n b = [10, -0.1]\n elif arc == 'Fdefault': # Focal default no pw (28 cls, 21 obj, no pw)\n b = [-2.1, -1.8]\n elif arc == 'uFBCE' or arc == 'uFBCEpw': # unified FocalBCE (5120 obj, 80 classes)\n b = [0, -6.5]\n elif arc == 'uFCE': # unified FocalCE (64 cls, 1 background + 80 classes)\n b = [7.7, -1.1]\n\n bias = module_list[-1][0].bias.view(len(mask), -1) # 255 to 3x85\n bias[:, 4] += b[0] - bias[:, 4].mean() # obj\n bias[:, 5:] += b[1] - bias[:, 5:].mean() # cls\n # bias = torch.load('weights/yolov3-spp.bias.pt')[yolo_index] # list of tensors [3x85, 3x85, 3x85]\n module_list[-1][0].bias = torch.nn.Parameter(bias.view(-1))\n # utils.print_model_biases(model)\n except:\n print('WARNING: smart bias initialization failure.')\n\n else:\n print('Warning: Unrecognized Layer Type: ' + mdef['type'])\n\n # Register module list and number of output filters\n module_list.append(modules)\n output_filters.append(filters)\n\n return module_list, routs\n\n\nclass Swish(nn.Module):\n def __init__(self):\n super(Swish, self).__init__()\n\n def forward(self, x):\n return x * torch.sigmoid(x)\n\n\nclass YOLOLayer(nn.Module):\n def __init__(self, anchors, nc, img_size, yolo_index, arc):\n super(YOLOLayer, self).__init__()\n\n self.anchors = torch.Tensor(anchors)\n self.na = len(anchors) # number of anchors (3)\n self.nc = nc # number of classes (80)\n self.nx = 0 # initialize number of x gridpoints\n self.ny = 0 # initialize number of y gridpoints\n self.arc = arc\n\n if ONNX_EXPORT: # grids must be computed in __init__\n stride = [32, 16, 8][yolo_index] # stride of this layer\n nx = int(img_size[1] / stride) # number x grid points\n ny = int(img_size[0] / stride) # number y grid points\n create_grids(self, img_size, (nx, ny))\n\n def forward(self, p, img_size, var=None):\n if ONNX_EXPORT:\n bs = 1 # batch size\n else:\n bs, ny, nx = p.shape[0], p.shape[-2], p.shape[-1]\n if (self.nx, self.ny) != (nx, ny):\n create_grids(self, img_size, (nx, ny), p.device, p.dtype)\n\n # p.view(bs, 255, 13, 13) -- > (bs, 3, 13, 13, 85) # (bs, anchors, grid, grid, classes + xywh)\n p = p.view(bs, self.na, self.nc + 5, self.ny, self.nx).permute(0, 1, 3, 4, 2).contiguous() # prediction\n\n if self.training:\n return p\n\n elif ONNX_EXPORT:\n # Constants CAN NOT BE BROADCAST, ensure correct shape!\n ngu = self.ng.repeat((1, self.na * self.nx * self.ny, 1))\n grid_xy = self.grid_xy.repeat((1, self.na, 1, 1, 1)).view((1, -1, 2))\n anchor_wh = self.anchor_wh.repeat((1, 1, self.nx, self.ny, 1)).view((1, -1, 2)) / ngu\n\n p = p.view(-1, 5 + self.nc)\n xy = torch.sigmoid(p[..., 0:2]) + grid_xy[0] # x, y\n wh = torch.exp(p[..., 2:4]) * anchor_wh[0] # width, height\n p_conf = torch.sigmoid(p[:, 4:5]) # Conf\n p_cls = F.softmax(p[:, 5:85], 1) * p_conf # SSD-like conf\n return torch.cat((xy / ngu[0], wh, p_conf, p_cls), 1).t()\n\n # p = p.view(1, -1, 5 + self.nc)\n # xy = torch.sigmoid(p[..., 0:2]) + grid_xy # x, y\n # wh = torch.exp(p[..., 2:4]) * anchor_wh # width, height\n # p_conf = torch.sigmoid(p[..., 4:5]) # Conf\n # p_cls = p[..., 5:5 + self.nc]\n # # Broadcasting only supported on first dimension in CoreML. See onnx-coreml/_operators.py\n # # p_cls = F.softmax(p_cls, 2) * p_conf # SSD-like conf\n # p_cls = torch.exp(p_cls).permute((2, 1, 0))\n # p_cls = p_cls / p_cls.sum(0).unsqueeze(0) * p_conf.permute((2, 1, 0)) # F.softmax() equivalent\n # p_cls = p_cls.permute(2, 1, 0)\n # return torch.cat((xy / ngu, wh, p_conf, p_cls), 2).squeeze().t()\n\n else: # inference\n # s = 1.5 # scale_xy (pxy = pxy * s - (s - 1) / 2)\n io = p.clone() # inference output\n io[..., 0:2] = torch.sigmoid(io[..., 0:2]) + self.grid_xy # xy\n io[..., 2:4] = torch.exp(io[..., 2:4]) * self.anchor_wh # wh yolo method\n # io[..., 2:4] = ((torch.sigmoid(io[..., 2:4]) * 2) ** 3) * self.anchor_wh # wh power method\n io[..., :4] *= self.stride\n\n if 'default' in self.arc: # seperate obj and cls\n torch.sigmoid_(io[..., 4:])\n elif 'BCE' in self.arc: # unified BCE (80 classes)\n torch.sigmoid_(io[..., 5:])\n io[..., 4] = 1\n elif 'CE' in self.arc: # unified CE (1 background + 80 classes)\n io[..., 4:] = F.softmax(io[..., 4:], dim=4)\n io[..., 4] = 1\n\n if self.nc == 1:\n io[..., 5] = 1 # single-class model https://github.com/ultralytics/yolov3/issues/235\n\n # reshape from [1, 3, 13, 13, 85] to [1, 507, 85]\n return io.view(bs, -1, 5 + self.nc), p\n\n\nclass Darknet(nn.Module):\n # YOLOv3 object detection model\n\n def __init__(self, cfg, img_size=(416, 416), arc='default'):\n super(Darknet, self).__init__()\n\n self.module_defs = parse_model_cfg(cfg)\n self.module_list, self.routs = create_modules(self.module_defs, img_size, arc)\n self.yolo_layers = get_yolo_layers(self)\n\n # Darknet Header https://github.com/AlexeyAB/darknet/issues/2914#issuecomment-496675346\n self.version = np.array([0, 2, 5], dtype=np.int32) # (int32) version info: major, minor, revision\n self.seen = np.array([0], dtype=np.int64) # (int64) number of images seen during training\n\n def forward(self, x, var=None):\n img_size = x.shape[-2:]\n layer_outputs = []\n output = []\n\n for i, (mdef, module) in enumerate(zip(self.module_defs, self.module_list)):\n mtype = mdef['type']\n if mtype in ['convolutional', 'upsample', 'maxpool']:\n x = module(x)\n elif mtype == 'route':\n layers = [int(x) for x in mdef['layers'].split(',')]\n if len(layers) == 1:\n x = layer_outputs[layers[0]]\n else:\n try:\n x = torch.cat([layer_outputs[i] for i in layers], 1)\n except: # apply stride 2 for darknet reorg layer\n layer_outputs[layers[1]] = F.interpolate(layer_outputs[layers[1]], scale_factor=[0.5, 0.5])\n x = torch.cat([layer_outputs[i] for i in layers], 1)\n # print(''), [print(layer_outputs[i].shape) for i in layers], print(x.shape)\n elif mtype == 'shortcut':\n x = x + layer_outputs[int(mdef['from'])]\n elif mtype == 'yolo':\n x = module(x, img_size)\n output.append(x)\n layer_outputs.append(x if i in self.routs else [])\n\n if self.training:\n return output\n elif ONNX_EXPORT:\n output = torch.cat(output, 1) # cat 3 layers 85 x (507, 2028, 8112) to 85 x 10647\n nc = self.module_list[self.yolo_layers[0]].nc # number of classes\n return output[5:5 + nc].t(), output[:4].t() # ONNX scores, boxes\n else:\n io, p = list(zip(*output)) # inference output, training output\n return torch.cat(io, 1), p\n\n def fuse(self):\n # Fuse Conv2d + BatchNorm2d layers throughout model\n fused_list = nn.ModuleList()\n for a in list(self.children())[0]:\n if isinstance(a, nn.Sequential):\n for i, b in enumerate(a):\n if isinstance(b, nn.modules.batchnorm.BatchNorm2d):\n # fuse this bn layer with the previous conv2d layer\n conv = a[i - 1]\n fused = torch_utils.fuse_conv_and_bn(conv, b)\n a = nn.Sequential(fused, *list(a.children())[i + 1:])\n break\n fused_list.append(a)\n self.module_list = fused_list\n # model_info(self) # yolov3-spp reduced from 225 to 152 layers\n\n\ndef get_yolo_layers(model):\n return [i for i, x in enumerate(model.module_defs) if x['type'] == 'yolo'] # [82, 94, 106] for yolov3\n\n\ndef create_grids(self, img_size=416, ng=(13, 13), device='cpu', type=torch.float32):\n nx, ny = ng # x and y grid size\n self.img_size = max(img_size)\n self.stride = self.img_size / max(ng)\n\n # build xy offsets\n yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])\n self.grid_xy = torch.stack((xv, yv), 2).to(device).type(type).view((1, 1, ny, nx, 2))\n\n # build wh gains\n self.anchor_vec = self.anchors.to(device) / self.stride\n self.anchor_wh = self.anchor_vec.view(1, self.na, 1, 1, 2).to(device).type(type)\n self.ng = torch.Tensor(ng).to(device)\n self.nx = nx\n self.ny = ny\n\n\ndef load_darknet_weights(self, weights, cutoff=-1):\n # Parses and loads the weights stored in 'weights'\n\n # Establish cutoffs (load layers between 0 and cutoff. if cutoff = -1 all are loaded)\n file = Path(weights).name\n if file == 'darknet53.conv.74':\n cutoff = 75\n elif file == 'yolov3-tiny.conv.15':\n cutoff = 15\n\n # Read weights file\n with open(weights, 'rb') as f:\n # Read Header https://github.com/AlexeyAB/darknet/issues/2914#issuecomment-496675346\n self.version = np.fromfile(f, dtype=np.int32, count=3) # (int32) version info: major, minor, revision\n self.seen = np.fromfile(f, dtype=np.int64, count=1) # (int64) number of images seen during training\n\n weights = np.fromfile(f, dtype=np.float32) # The rest are weights\n\n ptr = 0\n for i, (mdef, module) in enumerate(zip(self.module_defs[:cutoff], self.module_list[:cutoff])):\n if mdef['type'] == 'convolutional':\n conv_layer = module[0]\n if mdef['batch_normalize']:\n # Load BN bias, weights, running mean and running variance\n bn_layer = module[1]\n num_b = bn_layer.bias.numel() # Number of biases\n # Bias\n bn_b = torch.from_numpy(weights[ptr:ptr + num_b]).view_as(bn_layer.bias)\n bn_layer.bias.data.copy_(bn_b)\n ptr += num_b\n # Weight\n bn_w = torch.from_numpy(weights[ptr:ptr + num_b]).view_as(bn_layer.weight)\n bn_layer.weight.data.copy_(bn_w)\n ptr += num_b\n # Running Mean\n bn_rm = torch.from_numpy(weights[ptr:ptr + num_b]).view_as(bn_layer.running_mean)\n bn_layer.running_mean.data.copy_(bn_rm)\n ptr += num_b\n # Running Var\n bn_rv = torch.from_numpy(weights[ptr:ptr + num_b]).view_as(bn_layer.running_var)\n bn_layer.running_var.data.copy_(bn_rv)\n ptr += num_b\n else:\n # Load conv. bias\n num_b = conv_layer.bias.numel()\n conv_b = torch.from_numpy(weights[ptr:ptr + num_b]).view_as(conv_layer.bias)\n conv_layer.bias.data.copy_(conv_b)\n ptr += num_b\n # Load conv. weights\n num_w = conv_layer.weight.numel()\n conv_w = torch.from_numpy(weights[ptr:ptr + num_w]).view_as(conv_layer.weight)\n conv_layer.weight.data.copy_(conv_w)\n ptr += num_w\n\n return cutoff\n\n\ndef save_weights(self, path='model.weights', cutoff=-1):\n # Converts a PyTorch model to Darket format (*.pt to *.weights)\n # Note: Does not work if model.fuse() is applied\n with open(path, 'wb') as f:\n # Write Header https://github.com/AlexeyAB/darknet/issues/2914#issuecomment-496675346\n self.version.tofile(f) # (int32) version info: major, minor, revision\n self.seen.tofile(f) # (int64) number of images seen during training\n\n # Iterate through layers\n for i, (mdef, module) in enumerate(zip(self.module_defs[:cutoff], self.module_list[:cutoff])):\n if mdef['type'] == 'convolutional':\n conv_layer = module[0]\n # If batch norm, load bn first\n if mdef['batch_normalize']:\n bn_layer = module[1]\n bn_layer.bias.data.cpu().numpy().tofile(f)\n bn_layer.weight.data.cpu().numpy().tofile(f)\n bn_layer.running_mean.data.cpu().numpy().tofile(f)\n bn_layer.running_var.data.cpu().numpy().tofile(f)\n # Load conv bias\n else:\n conv_layer.bias.data.cpu().numpy().tofile(f)\n # Load conv weights\n conv_layer.weight.data.cpu().numpy().tofile(f)\n\n\ndef convert(cfg='cfg/yolov3-spp.cfg', weights='weights/yolov3-spp.weights'):\n # Converts between PyTorch and Darknet format per extension (i.e. *.weights convert to *.pt and vice versa)\n # from models import *; convert('cfg/yolov3-spp.cfg', 'weights/yolov3-spp.weights')\n\n # Initialize model\n model = Darknet(cfg)\n\n # Load weights and save\n if weights.endswith('.pt'): # if PyTorch format\n model.load_state_dict(torch.load(weights, map_location='cpu')['model'])\n save_weights(model, path='converted.weights', cutoff=-1)\n print(\"Success: converted '%s' to 'converted.weights'\" % weights)\n\n elif weights.endswith('.weights'): # darknet format\n _ = load_darknet_weights(model, weights)\n\n chkpt = {'epoch': -1,\n 'best_fitness': None,\n 'training_results': None,\n 'model': model.state_dict(),\n 'optimizer': None}\n\n torch.save(chkpt, 'converted.pt')\n print(\"Success: converted '%s' to 'converted.pt'\" % weights)\n\n else:\n print('Error: extension not supported.')\n\n\ndef attempt_download(weights):\n # Attempt to download pretrained weights if not found locally\n\n msg = weights + ' missing, download from https://drive.google.com/drive/folders/1uxgUBemJVw9wZsdpboYbzUN4bcRhsuAI'\n if weights and not os.path.isfile(weights):\n file = Path(weights).name\n\n if file == 'yolov3-spp.weights':\n gdrive_download(id='1oPCHKsM2JpM-zgyepQciGli9X0MTsJCO', name=weights)\n elif file == 'yolov3-spp.pt':\n gdrive_download(id='1vFlbJ_dXPvtwaLLOu-twnjK4exdFiQ73', name=weights)\n elif file == 'yolov3.pt':\n gdrive_download(id='11uy0ybbOXA2hc-NJkJbbbkDwNX1QZDlz', name=weights)\n elif file == 'yolov3-tiny.pt':\n gdrive_download(id='1qKSgejNeNczgNNiCn9ZF_o55GFk1DjY_', name=weights)\n elif file == 'darknet53.conv.74':\n gdrive_download(id='18xqvs_uwAqfTXp-LJCYLYNHBOcrwbrp0', name=weights)\n elif file == 'yolov3-tiny.conv.15':\n gdrive_download(id='140PnSedCsGGgu3rOD6Ez4oI6cdDzerLC', name=weights)\n\n else:\n try: # download from pjreddie.com\n url = 'https://pjreddie.com/media/files/' + file\n print('Downloading ' + url)\n os.system('curl -f ' + url + ' -o ' + weights)\n except IOError:\n print(msg)\n os.system('rm ' + weights) # remove partial downloads\n\n assert os.path.exists(weights), msg # download missing weights from Google Drive\n"
] | [
[
"torch.nn.functional.softmax",
"torch.nn.functional.interpolate"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ykanebako/AI-Feynman | [
"1f937533a7e510e31c704ec8ac343c770630f17a"
] | [
"aifeynman/S_NN_get_gradients.py"
] | [
"# SAve a file with 2*(n-1) columns contaning the (n-1) independent variables and the (n-1) gradients of the trained NN with respect these variables\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport copy\nimport os\nimport sys\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nis_cuda = torch.cuda.is_available()\n\ndef evaluate_derivatives(pathdir, filename, model, device):\n try:\n data = np.loadtxt(pathdir+filename)[:,0:-1]\n pts = np.loadtxt(pathdir+filename)[:,0:-1]\n pts = torch.tensor(pts)\n pts = pts.clone().detach()\n is_cuda = torch.cuda.is_available()\n grad_weights = torch.ones(pts.shape[0], 1)\n\n pts = pts.float().to(device)\n model = model.to(device)\n grad_weights = grad_weights.to(device)\n\n pts.requires_grad_(True)\n outs = model(pts)\n grad = torch.autograd.grad(outs, pts, grad_outputs=grad_weights, create_graph=True)[0]\n save_grads = grad.detach().data.cpu().numpy()\n save_data = np.column_stack((data,save_grads))\n np.savetxt(\"results/gradients_comp_%s.txt\" %filename,save_data)\n return 1\n except:\n return 0\n"
] | [
[
"torch.ones",
"torch.tensor",
"torch.cuda.is_available",
"numpy.column_stack",
"numpy.savetxt",
"torch.autograd.grad",
"numpy.loadtxt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Saphron-Asia/nan.ai-ml-ocr | [
"bcae3eaed21f61a1c4478a1bc7510197e99b3979"
] | [
"data extraction/word_detector_nn/src/dataloader.py"
] | [
"from collections import namedtuple\n\nimport cv2\nimport numpy as np\nimport torch\n\nfrom aabb import AABB\nfrom coding import encode\nfrom utils import compute_scale_down, prob_true\n\nDataLoaderItem = namedtuple('DataLoaderItem', 'batch_imgs,batch_gt_maps,batch_aabbs')\n\n\nclass DataLoaderIAM:\n \"\"\"loader for IAM dataset\"\"\"\n\n def __init__(self, dataset, batch_size, input_size, output_size):\n self.dataset = dataset\n self.batch_size = batch_size\n self.input_size = input_size\n self.output_size = output_size\n self.scale_down = compute_scale_down(input_size, output_size)\n self.shuffled_indices = np.arange(len(self.dataset))\n self.curr_idx = 0\n self.is_random = False\n\n def __getitem__(self, item):\n batch_imgs = []\n batch_gt_maps = []\n batch_aabbs = []\n for b in range(self.batch_size):\n if self.is_random:\n shuffled_idx = self.shuffled_indices[item * self.batch_size + b]\n else:\n shuffled_idx = item * self.batch_size + b\n\n img, aabbs = self.dataset[shuffled_idx]\n\n if self.is_random:\n # geometric data augmentation (image [0..255] and gt)\n if prob_true(0.75):\n # random scale\n fx = np.random.uniform(0.5, 1.5)\n fy = np.random.uniform(0.5, 1.5)\n\n # random position around center\n txc = self.input_size[1] * (1 - fx) / 2\n tyc = self.input_size[0] * (1 - fy) / 2\n freedom_x = self.input_size[1] // 10\n freedom_y = self.input_size[0] // 10\n tx = txc + np.random.randint(-freedom_x, freedom_x)\n ty = tyc + np.random.randint(-freedom_y, freedom_y)\n\n # map image into target image\n M = np.float32([[fx, 0, tx], [0, fy, ty]])\n white_bg = np.ones(self.input_size, np.uint8) * 255\n img = cv2.warpAffine(img, M, dsize=self.input_size[::-1], dst=white_bg,\n borderMode=cv2.BORDER_TRANSPARENT)\n\n # apply the same transformations to gt, and clip/remove aabbs outside of target image\n aabb_clip = AABB(0, img.shape[1], 0, img.shape[0])\n aabbs = [aabb.scale(fx, fy).translate(tx, ty).clip(aabb_clip) for aabb in aabbs]\n aabbs = [aabb for aabb in aabbs if aabb.area() > 0]\n\n # photometric data augmentation (image [-0.5..0.5] only)\n img = (img / 255 - 0.5)\n if prob_true(0.25): # random distractors (lines)\n num_lines = np.random.randint(1, 20)\n for _ in range(num_lines):\n rand_pt = lambda: (np.random.randint(0, img.shape[1]), np.random.randint(0, img.shape[0]))\n color = np.random.triangular(-0.5, 0, 0.5)\n thickness = np.random.randint(1, 3)\n cv2.line(img, rand_pt(), rand_pt(), color, thickness)\n if prob_true(0.75): # random contrast\n img = (img - img.min()) / (img.max() - img.min()) - 0.5 # stretch\n img = img * np.random.triangular(0.1, 0.9, 1) # reduce contrast\n if prob_true(0.25): # random noise\n img = img + np.random.uniform(-0.1, 0.1, size=img.shape)\n if prob_true(0.25): # change thickness of text\n img = cv2.erode(img, np.ones((3, 3)))\n if prob_true(0.25): # change thickness of text\n img = cv2.dilate(img, np.ones((3, 3)))\n if prob_true(0.25): # invert image\n img = 0.5 - img\n\n else:\n img = (img / 255 - 0.5)\n\n gt_map = encode(self.output_size, aabbs, self.scale_down)\n\n batch_imgs.append(img[None, ...].astype(np.float32))\n batch_gt_maps.append(gt_map)\n batch_aabbs.append(aabbs)\n\n batch_imgs = np.stack(batch_imgs, axis=0)\n batch_gt_maps = np.stack(batch_gt_maps, axis=0)\n\n # batch_imgs = torch.from_numpy(batch_imgs).to('cuda')\n # batch_gt_maps = torch.from_numpy(batch_gt_maps.astype(np.float32)).to('cuda')\n batch_imgs = torch.from_numpy(batch_imgs).to('cpu')\n batch_gt_maps = torch.from_numpy(batch_gt_maps.astype(np.float32)).to('cpu')\n\n return DataLoaderItem(batch_imgs, batch_gt_maps, batch_aabbs)\n\n def reset(self):\n self.curr_idx = 0\n\n def random(self, enable=True):\n np.random.shuffle(self.shuffled_indices)\n self.is_random = enable\n\n def __len__(self):\n return len(self.dataset) // self.batch_size\n\n\nclass DataLoaderImgFile:\n \"\"\"loader which simply goes through all jpg files of a directory\"\"\"\n\n def __init__(self, root_dir, input_size, device, max_side_len=1024):\n self.fn_imgs = root_dir.files('*.jpg')\n self.input_size = input_size\n self.device = device\n self.max_side_len = max_side_len\n\n def ceil32(self, val):\n if val % 32 == 0:\n return val\n val = (val // 32 + 1) * 32\n return val\n\n def __getitem__(self, item):\n # Load all .jpg images\n orig = cv2.imread(self.fn_imgs[item], cv2.IMREAD_GRAYSCALE)\n\n f = min(self.max_side_len / orig.shape[0], self.max_side_len / orig.shape[0])\n if f < 1:\n orig = cv2.resize(orig, dsize=None, fx=f, fy=f)\n img = np.ones((self.ceil32(orig.shape[0]), self.ceil32(orig.shape[1])), np.uint8) * 255\n img[:orig.shape[0], :orig.shape[1]] = orig\n\n img = (img / 255 - 0.5).astype(np.float32)\n imgs = img[None, None, ...]\n imgs = torch.from_numpy(imgs).to(self.device)\n return DataLoaderItem(imgs, None, None)\n\n def get_scale_factor(self, item):\n img = cv2.imread(self.fn_imgs[item], cv2.IMREAD_GRAYSCALE)\n f = min(self.max_side_len / img.shape[0], self.max_side_len / img.shape[0])\n return f if f < 1 else 1\n\n def get_original_img(self, item):\n img = cv2.imread(self.fn_imgs[item], cv2.IMREAD_GRAYSCALE)\n img = (img / 255 - 0.5).astype(np.float32)\n return img\n\n def __len__(self):\n return len(self.fn_imgs)\n"
] | [
[
"torch.from_numpy",
"numpy.random.shuffle",
"numpy.stack",
"numpy.ones",
"numpy.float32",
"numpy.random.triangular",
"numpy.random.uniform",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
xufuzhi/crnn_pytorch | [
"0e07d1269339101f147a0d83bb41a006cd0406d9"
] | [
"train.py"
] | [
"import argparse\nimport time\n\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\nfrom torch.nn import CTCLoss\nimport os\nfrom utils import utils, dataset\n\nimport models.crnn as crnn\nimport verify\n\ncudnn.benchmark = True\n\n\n# custom weights initialization called on net_crnn\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n m.weight.data.normal_(0.0, 0.02)\n elif classname.find('BatchNorm') != -1:\n m.weight.data.normal_(1.0, 0.02)\n m.bias.data.fill_(0)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--trainroot', required=True, help='path to dataset')\n parser.add_argument('--valroot', required=True, help='path to dataset')\n parser.add_argument('--workers', type=int, help='number of data loading workers', default=0)\n parser.add_argument('--batchSize', type=int, default=128, help='input batch size')\n parser.add_argument('--imgH', type=int, default=32, help='the height of the input image to network')\n parser.add_argument('--imgW', type=int, default=100, help='the width of the input image to network')\n parser.add_argument('--nh', type=int, default=256, help='size of the lstm hidden state')\n parser.add_argument('--nepoch', type=int, default=100, help='number of epochs to train for')\n # TODO(meijieru): epoch -> iter\n parser.add_argument('--cuda', action='store_true', help='enables cuda')\n parser.add_argument('--ngpu', type=int, default=1, help='number of GPUs to use')\n # parser.add_argument('--pretrained', default='weights/lol_/netCRNN_CRNN_1c_lastest.pth', help=\"path to pretrained model (to continue training)\")\n parser.add_argument('--pretrained', default='', help=\"path to pretrained model (to continue training)\")\n parser.add_argument('--alphabet', type=str, default='./data/lol.alphabet')\n parser.add_argument('--expr_dir', default='weights/lol', help='Where to store samples and models')\n parser.add_argument('--displayInterval', type=int, default=20, help='Interval to be displayed')\n parser.add_argument('--n_test_disp', type=int, default=10, help='Number of samples to display when test')\n parser.add_argument('--valInterval', type=int, default=200, help='Interval to be verifyed')\n parser.add_argument('--saveInterval', type=int, default=100000, help='Interval to be saved')\n parser.add_argument('--lr', type=float, default=0.001, help='learning rate for Critic, not used by adadealta')\n parser.add_argument('--beta1', type=float, default=0.9, help='beta1 for adam. default=0.9')\n parser.add_argument('--adam', action='store_true', help='Whether to use adam (default is rmsprop)')\n parser.add_argument('--adadelta', action='store_true', help='Whether to use adadelta (default is rmsprop)')\n parser.add_argument('--keep_ratio', action='store_true', help='whether to keep ratio for image resize')\n parser.add_argument('--manualSeed', type=int, default=1234, help='reproduce experiemnt')\n parser.add_argument('--random_sample', action='store_true',\n help='whether to sample the dataset with random sampler')\n\n\n parser.add_argument('--backbone', type=str, default='ocr7')\n parser.add_argument('--prtnet', action='store_true')\n parser.add_argument('--lr_sch', type=str, default='R')\n parser.add_argument('--in_channels', type=int, default=3)\n parser.add_argument('--imgaug', action='store_true')\n opt = parser.parse_args()\n print(opt)\n\n # random.seed(opt.manualSeed)\n # np.random.seed(opt.manualSeed)\n # torch.manual_seed(opt.manualSeed)\n\n if not os.path.exists(opt.expr_dir):\n os.makedirs(opt.expr_dir)\n\n # 创建日志文件\n logfile = os.path.join(opt.expr_dir, 'train.log')\n with open(logfile, 'w', encoding='utf-8') as f:\n f.write('')\n\n if torch.cuda.is_available() and not opt.cuda:\n print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\n\n # ### 读取字母表\n with open(opt.alphabet, encoding='utf-8') as f:\n alphabet = f.read().strip()\n\n # ### 构建数据集对象\n dataset_train = dataset.Dataset_lmdb(root=opt.trainroot, in_channels=opt.in_channels)\n assert dataset_train\n if not opt.random_sample:\n sampler = dataset.RandomSequentialSampler(dataset_train, opt.batchSize)\n else:\n sampler = None\n train_loader = torch.utils.data.DataLoader(\n dataset_train, batch_size=opt.batchSize,\n shuffle=True, sampler=sampler,\n num_workers=int(opt.workers),\n collate_fn=dataset.AlignCollate(imgH=opt.imgH, imgW=opt.imgW, keep_ratio=opt.keep_ratio, augment=opt.imgaug))\n dataset_val = dataset.Dataset_lmdb(root=opt.valroot, in_channels=opt.in_channels)\n val_loader = torch.utils.data.DataLoader(\n dataset_val, batch_size=opt.batchSize,\n shuffle=True, num_workers=int(opt.workers),\n collate_fn=dataset.AlignCollate(imgH=opt.imgH, imgW=opt.imgW, keep_ratio=opt.keep_ratio))\n\n # 构建网络\n net_crnn = crnn.CRNN(opt.imgH, opt.in_channels, len(alphabet) + 1, opt.nh, cnn_layer=opt.backbone)\n # net_crnn.apply(weights_init)\n if opt.pretrained != '':\n print('loading pretrained model from %s' % opt.pretrained)\n net_crnn.load_state_dict(torch.load(opt.pretrained))\n if opt.prtnet:\n print(net_crnn)\n\n str2label = utils.StrLabelConverter(alphabet)\n ctc_loss = CTCLoss(zero_infinity=True)\n # setup optimizer\n if opt.adam:\n optimizer = optim.Adam(net_crnn.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999), weight_decay=0)\n elif opt.adadelta:\n optimizer = optim.Adadelta(net_crnn.parameters())\n else:\n optimizer = optim.RMSprop(net_crnn.parameters(), lr=opt.lr)\n\n\n # 学习率衰减器\n class scheduler():\n if opt.lr_sch == 'R':\n r_adj = optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.7, patience=500, min_lr=0.00005)\n elif opt.lr_sch == 'C':\n r_adj = optim.lr_scheduler.CosineAnnealingLR(optimizer, len(train_loader) * opt.nepoch)\n elif opt.lr_sch == 'N':\n r_adj = lambda x: None\n else:\n raise ValueError\n\n def __init__(self):\n pass\n\n @classmethod\n def step(cls, x):\n if opt.lr_sch == 'R':\n cls.r_adj.step(x)\n elif opt.lr_sch == 'C':\n cls.r_adj.step()\n elif opt.lr_sch == 'N':\n pass\n else:\n raise ValueError\n\n\n image = torch.empty((opt.batchSize, 3, opt.imgH, opt.imgH), dtype=torch.float32)\n text = torch.empty(opt.batchSize * 5, dtype=torch.int32)\n length = torch.empty(opt.batchSize, dtype=torch.int32)\n\n if opt.cuda:\n net_crnn.cuda()\n # net_crnn = torch.nn.DataParallel(net_crnn, device_ids=range(opt.ngpu))\n image = image.cuda()\n ctc_loss = ctc_loss.cuda()\n\n # loss Averager\n loss_avg = utils.Averager()\n # ### begin training\n iteration, total_iter = 0, len(train_loader) * opt.nepoch\n best_precision = 0\n for epoch in range(opt.nepoch):\n for i, data in enumerate(train_loader, start=1):\n iteration += 1\n for p in net_crnn.parameters():\n p.requires_grad = True\n net_crnn.train()\n\n # ### train one batch ################################\n cpu_images, cpu_texts = data\n batch_size = cpu_images.size(0)\n utils.loadData(image, cpu_images)\n t, l = str2label.encode(cpu_texts)\n utils.loadData(text, t)\n utils.loadData(length, l)\n\n preds = net_crnn(image)\n preds_size = torch.LongTensor([preds.size(0)] * batch_size)\n preds = preds.to(torch.float32)\n cost = ctc_loss(preds, text, preds_size, length)\n optimizer.zero_grad()\n cost.backward()\n optimizer.step()\n scheduler.step(cost)\n ###########################################\n loss_avg.add(cost)\n\n # ### 计算这个批次精度\n if iteration % opt.displayInterval == 0:\n # aa = torch.ones(1).detach\n preds_v = preds.detach()\n preds_size_v = preds_size.detach()\n\n _, preds_v = preds_v.max(2)\n # preds = preds.squeeze(2)\n preds_v = preds_v.transpose(1, 0).contiguous().view(-1)\n sim_preds = str2label.decode(preds_v.data, preds_size_v.data, raw=False)\n n_correct = 0\n for pred, target in zip(sim_preds, cpu_texts):\n if pred == target.lower():\n n_correct += 1\n precision = n_correct / float(batch_size)\n print(f'precision: {precision}')\n\n # ### 打印信息\n if iteration % opt.displayInterval == 0:\n lr = optimizer.state_dict()['param_groups'][0]['lr']\n prt_msg = f'[{time.strftime(\"%H:%M:%S\", time.localtime())}] ' \\\n f'epoch: [{epoch}/{opt.nepoch}] | iter: {iteration} | Loss: {loss_avg.val()} | lr: {lr:>.6f}'\n print(prt_msg)\n loss_avg.reset()\n with open(logfile, 'a', encoding='utf-8') as f:\n f.writelines(prt_msg + '\\n')\n\n # ### 验证精度\n if iteration % opt.valInterval == 0:\n vals, prt_msg = verify.val(net_crnn, val_loader, ctc_loss, str2label, batchSize=opt.batchSize,\n max_iter=0, n_display=opt.n_test_disp)\n if vals['precision'] > best_precision:\n best_precision = vals['precision']\n torch.save(net_crnn.state_dict(),\n os.path.join(opt.expr_dir, f'netCRNN_{opt.backbone}_{opt.in_channels}c_best.pth'))\n prt_msg += f' best_precision:{best_precision:.3f}'\n print(prt_msg)\n with open(logfile, 'a', encoding='utf-8') as f:\n f.writelines(prt_msg + '\\n')\n\n # ### 保存权重\n if iteration % opt.saveInterval == 0:\n torch.save(net_crnn.state_dict(), f'{opt.expr_dir}/netCRNN_{opt.backbone}_{epoch}_{iteration}.pth')\n # 每2000次保存一次 lastest.pth\n if iteration % 2000 == 0:\n torch.save(net_crnn.state_dict(),\n os.path.join(opt.expr_dir, f'netCRNN_{opt.backbone}_{opt.in_channels}c_lastest.pth'))\n\n torch.save(net_crnn.state_dict(), os.path.join(opt.expr_dir, f'netCRNN_{opt.backbone}_{opt.in_channels}c_lastest.pth'))\n\n\n"
] | [
[
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.empty",
"torch.load",
"torch.nn.CTCLoss",
"torch.cuda.is_available"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
parkjan4/DSIP | [
"9a1fabd1b87f70d5f94a14b6c5adc0c6895cfbf0"
] | [
"ProblemSet3/Churn prediction.py"
] | [
"#!/usr/bin/env python\n# coding: utf-8\n\n# In[16]:\n\n\nget_ipython().run_line_magic('pylab', 'inline --no-import-all')\n\nfrom scipy import interp\n\nimport pandas as pd\nfrom pandas.api.types import CategoricalDtype\n\nimport sklearn\nfrom sklearn import ensemble, model_selection, metrics\nimport xgboost\nfrom xgboost import XGBClassifier\n\nplt.rcParams['figure.figsize'] = (12, 8)\n\n\n# First we define some functions to convert data from the csv to Python types.\n\n# ## Data loading and preprocessing\n\n# In[6]:\n\n\ndef convert_bool(col, true_str=\"Yes\", false_str=\"No\"):\n \"\"\"\n Convert string to boolean values.\n \"\"\"\n if col == true_str: #check for nan\n return 1\n elif col == false_str:\n return 0\n else:\n raise ValueError(col)\n\n\ndef convert_float(col):\n \"\"\"\n Convert floating point values. If it is not possible, it returns 0.\n \n This is useful for the TotalCharges columns, since it contains\n empty cells when it should be 0.\n \"\"\"\n try:\n return float(col)\n except ValueError:\n return 0\n\n\n# In[111]:\n\n\ncategorical_no_internet = CategoricalDtype(categories=[\"No internet service\", \"No\", \"Yes\"])\n\ndf = pd.read_csv(\n \"Telco-Customer-Churn.csv\", \n dtype={\n \"MultipleLines\": CategoricalDtype(categories=[\"No phone service\", \"No\", \"Yes\"]),\n 'InternetService': 'category',\n 'OnlineSecurity': categorical_no_internet,\n 'OnlineBackup': categorical_no_internet,\n 'DeviceProtection': categorical_no_internet,\n 'TechSupport': categorical_no_internet,\n 'StreamingTV': categorical_no_internet,\n 'StreamingMovies': categorical_no_internet,\n 'Contract': 'category',\n # 'PaperlessBilling': 'category',\n 'PaymentMethod': 'category',\n },\n converters={\n 'gender': lambda x: convert_bool(x, 'Male', \"Female\"),\n 'Partner': convert_bool,\n 'Dependents': convert_bool,\n 'PhoneService': convert_bool,\n 'PaperlessBilling': convert_bool,\n 'TotalCharges': convert_float,\n 'Churn': convert_bool\n })\n\n# TotalCharges is related to tenure and MonthlyCharges (TotalCharges is approx = to tenure*MonthlyCharges)\n# Instead of storing TotalCharges, we just store the deviation between TotalCharges and tenure*MonthlyCharges.\ndf[\"discount\"] = (df[\"tenure\"] * df[\"MonthlyCharges\"] - df[\"TotalCharges\"])/(np.maximum(df[\"tenure\"], 1))\n\ny = df[\"Churn\"].values\ndf = df.drop(labels=[\"customerID\", \"Churn\", \"TotalCharges\"], axis=1)\n\n\n# In[112]:\n\n\ndf.dtypes\n\n\n# We convert categorical fields to multiple binary fields\n\n# In[113]:\n\n\ndf_nocat = pd.get_dummies(df, drop_first=True)\ndf_nocat.dtypes\n\n\n# Get values in NumPy's array format\n\n# In[114]:\n\n\nx = df_nocat.values\n\n\n# Variables x and y contain the features and the class to predict, respectively.\n\n# ## Classification\n# \n# Since y is a boolean array, we will use classifiers to predict y given x.\n# \n# We will use two different classifiers: RandomForestClassifier from sklearn and the boosting classifier from XGBoost.\n\n# In[162]:\n\n\n# We use 1000 estimators (trees)\nclsf_forest = ensemble.RandomForestClassifier(n_estimators=1000)\nclsf_boost = XGBClassifier(n_estimators=1000)\n\n\n# ### Cross-validation\n\n# In[135]:\n\n\ndef cv_roc(clsf, x, y, n_splits=4):\n \n results = {'tpr': [], 'fpr': [], 'average_precision': [], \"roc_auc\": [], \"accuracy\": []}\n \n mean_tpr = 0.0\n mean_fpr = np.linspace(0, 1, 100)\n \n cv = model_selection.StratifiedKFold(n_splits=n_splits)\n for train_idx, test_idx in cv.split(x, y):\n train_x, train_y = x[train_idx], y[train_idx]\n test_x, test_y = x[test_idx], y[test_idx]\n\n clsf.fit(train_x, train_y)\n \n y_pred = clsf.predict_proba(test_x)[:, 1]\n \n fpr, tpr, _ = metrics.roc_curve(test_y, y_pred)\n mean_tpr += interp(mean_fpr, fpr, tpr)\n mean_tpr[0] = 0.0\n \n results['fpr'].append(fpr)\n results['tpr'].append(tpr)\n results['average_precision'].append(metrics.average_precision_score(test_y, y_pred))\n results['roc_auc'].append(metrics.roc_auc_score(test_y, y_pred))\n \n results['accuracy'].append(metrics.accuracy_score(test_y, y_pred>0.5))\n \n mean_tpr /= n_splits\n mean_tpr[-1] = 1.0\n \n return {\n 'mean_fpr': mean_fpr,\n 'mean_tpr': mean_tpr,\n **{k: np.array(v) for k, v in results.items()}\n }\n\n\n# In[136]:\n\n\nresults_forest = cv_roc(clsf_forest, x, y)\n\n\n# In[137]:\n\n\nplt.figure(figsize=(9, 9))\nplt.plot(results_forest['mean_fpr'], results_forest['mean_tpr'],\n color='black', linewidth=4, label=\"Mean ROC curve\")\n\nfor i, (fpr, tpr) in enumerate(zip(results_forest['fpr'], results_forest['tpr'])):\n plt.plot(fpr, tpr, linewidth=2, linestyle='--', label=\"ROC curve of fold {}\".format(i))\n\nplt.legend(loc='lower right', fontsize=14)\nplt.xlabel(\"False positive rate\", fontsize=16)\nplt.ylabel(\"True positive rate\", fontsize=16)\nplt.grid()\n\nplt.title(\"Random Forest\", fontsize=18)\n\n\n# In[138]:\n\n\nresults_boost = cv_roc(clsf_boost, x, y)\n\n\n# In[139]:\n\n\nplt.figure(figsize=(9, 9))\nplt.plot(results_boost['mean_fpr'], results_boost['mean_tpr'],\n color='black', linewidth=4, label=\"Mean ROC curve\")\n\nfor i, (fpr, tpr) in enumerate(zip(results_boost['fpr'], results_boost['tpr'])):\n plt.plot(fpr, tpr, linewidth=2, linestyle='--', label=\"ROC curve of fold {}\".format(i))\n\nplt.legend(loc='lower right', fontsize=14)\nplt.xlabel(\"False positive rate\", fontsize=16)\nplt.ylabel(\"True positive rate\", fontsize=16)\nplt.grid()\n\nplt.title(\"XGBoost\", fontsize=18)\n\n\n# In[140]:\n\n\nplt.figure(figsize=(9, 9))\n\nauc_forest = metrics.auc(results_forest['mean_fpr'], results_forest['mean_tpr'])\nauc_boost = metrics.auc(results_boost['mean_fpr'], results_boost['mean_tpr'])\n\nplt.plot(results_forest['mean_fpr'], results_forest['mean_tpr'],\n color='C1', linewidth=4, label=\"Random forest (AUC={:.2g})\".format(auc_forest))\nplt.plot(results_boost['mean_fpr'], results_boost['mean_tpr'],\n color='C2', linewidth=4, label=\"XGBoost (AUC={:.2g})\".format(auc_boost))\nplt.grid()\n\nplt.legend(loc='lower right', fontsize=14)\nplt.xlabel(\"False positive rate\", fontsize=16)\nplt.ylabel(\"True positive rate\", fontsize=16)\n\nplt.title(\"Random forest vs. XGBoost\", fontsize=18)\n\n\n# The average accuracy of both models is:\n\n# In[158]:\n\n\nacc = results_boost[\"accuracy\"]\nprint(\"XGBoost accuracy: {:.2f}%(stddev {:.2f})\".format(acc.mean() * 100, acc.std()))\n\n\n# In[159]:\n\n\nacc = results_forest[\"accuracy\"]\nprint(\"Forest accuracy: {:.2f}%(stddev {:.2f})\".format(acc.mean() * 100, acc.std()))\n\n\n# There are two interesting conclusions from these results:\n# 1. The performance of different folds is very similar. This suggests that the dataset is large enough and that we can work with a single training/testing split instead of using cross-validation.\n# 2. The difference in performance of the random forest and XGBoost is negligible. \n# \n# In the following discussion, we will evaluate the feature importance estimated by the random forest for the following split:\n\n# In[153]:\n\n\ntrain_x, test_x, train_y, test_y = model_selection.train_test_split(x, y, stratify=y)\n\n\n# We look at the feature importances computed by the random forest to understand which factors are more relevant for churn prediction.\n\n# In[154]:\n\n\nclsf_forest.fit(train_x, train_y)\n\n\n# In[155]:\n\n\nplt.figure(figsize=(12, 8))\nplt.stem(clsf_forest.feature_importances_)\nplt.xlabel(\"Feature index\", fontsize=16)\nplt.ylabel(\"Importance\", fontsize=16)\nplt.grid()\n\n\n# We sort the columns of the dataset by the importance according to the random forest:\n\n# In[156]:\n\n\nindices = np.argsort(clsf_forest.feature_importances_)[::-1]\ndf_nocat.columns.values[indices]\n\n\n# The most important factor for churn prediction is 'tenure', followed by MonthlyCharges.\n# \n# We plot the histogram of tenure for customers with churn=\"no\" and churn=\"yes\" separately:\n\n# In[157]:\n\n\n_ = plt.hist([x[y==0, 4], x[y==1, 4]], 50, density=True)\nplt.xlabel(\"Tenure\", fontsize=18)\nplt.grid()\n\n\n# As the histogram shows, customers with smaller tenure are more likely to churn than long-term customers.\n\n# In[167]:\n\n\n_ = plt.hist([x[y==0, 7], x[y==1, 7]], 50, density=True)\nplt.xlabel(\"Monthly charges\", fontsize=18)\nplt.grid()\n\n\n# As expected, customers with higher monthly charges are more likely to churn.\n"
] | [
[
"sklearn.metrics.roc_auc_score",
"pandas.api.types.CategoricalDtype",
"sklearn.ensemble.RandomForestClassifier",
"sklearn.metrics.accuracy_score",
"sklearn.model_selection.train_test_split",
"sklearn.model_selection.StratifiedKFold",
"sklearn.metrics.roc_curve",
"sklearn.metrics.average_precision_score",
"scipy.interp",
"sklearn.metrics.auc",
"pandas.get_dummies"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
Nordant/plantstat | [
"50f43f55b2b9895132fe840b426a7d58b41a76c0"
] | [
"plantstat/vision/stomata_vision.py"
] | [
"import numpy as np\r\nimport pandas as pd\r\nimport random, os, cv2, glob\r\nimport matplotlib.pyplot as plt\r\nfrom tqdm import tqdm\r\nimport torch\r\nimport torchvision\r\nfrom torchvision import transforms\r\nfrom torch.utils.data import DataLoader\r\nfrom google_drive_downloader import GoogleDriveDownloader as gdd\r\n\r\n\r\ndef set_seed(seed=0):\r\n '''\r\n Set seed for data reproducibility.\r\n Args:\r\n seed - int argument (default - 0)\r\n '''\r\n random.seed(seed)\r\n os.environ['PYTHONASSEED'] = str(seed)\r\n np.random.seed(seed)\r\n torch.manual_seed(seed)\r\n torch.cuda.manual_seed(seed)\r\n torch.backends.cudnn.deterministic = True\r\n torch.backends.cudnn.benchmark = True\r\n print('--- Seed: \"%i\" ---' %seed)\r\n\r\n\r\nclass ImageFolderWithPaths(torchvision.datasets.ImageFolder):\r\n '''\r\n Class that returns image tensors, fake labels \r\n and image paths for the dataloader.\r\n '''\r\n def __getitem__(self, index):\r\n original_tuple = super(ImageFolderWithPaths, self).__getitem__(index)\r\n path = self.imgs[index][0]\r\n tuple_with_path = (original_tuple + (path,))\r\n return tuple_with_path\r\n\r\n\r\ndef dataloader(path, batch_size):\r\n '''\r\n Make PyTorch DataLoader object for images in the custom directory.\r\n Args:\r\n path - path to the directory (str)\r\n batch_size - the size of batches (int)\r\n '''\r\n num_images = len(glob.glob(path+'/*/*'))\r\n if batch_size > num_images:\r\n raise ValueError('Batch size greater than the number of images')\r\n else:\r\n transformer = transforms.Compose([transforms.Resize((224, 224)),\r\n transforms.ToTensor(),\r\n transforms.Normalize([0.485, 0.456, 0.406], \r\n [0.229, 0.224, 0.225])])\r\n dataset = ImageFolderWithPaths(path, transformer)\r\n dataloader = DataLoader(dataset, batch_size=batch_size, \r\n shuffle=False)\r\n return dataloader\r\n \r\n\r\nclass OpenStomataPredictor:\r\n '''\r\n The main class for stomata open/close classes prediction.\r\n '''\r\n def __init__(self, path, batch_size):\r\n self.path = path\r\n self.batch_size = batch_size\r\n self.classes = ['close', 'open']\r\n\r\n def predict(self, save=False, f_format='excel'):\r\n '''\r\n Main function for stomata open/close classification.\r\n Args:\r\n save - save prediction in a local directory or not\r\n f_format - format of data saving (if save = True): 'csv' or 'excel' (default)\r\n '''\r\n assert f_format in {'excel', 'csv'}\r\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n data_loader = dataloader(self.path, self.batch_size)\r\n \r\n gdd.download_file_from_google_drive(file_id='1qNpC2fhEtzeZAS3zXk1bx5RlQOwTkkEB',\r\n dest_path='./stomata_model_resnet50.pkl')\r\n print('\\n')\r\n model = torch.load('stomata_model_resnet50.pkl', map_location=torch.device(device))\r\n model.eval()\r\n \r\n test_img_paths = []\r\n test_preds = []\r\n \r\n for inputs, _, paths in tqdm(data_loader, position = 0, leave = True):\r\n inputs = inputs.to(device)\r\n with torch.set_grad_enabled(False):\r\n preds = model(inputs)\r\n test_preds.append(torch.sigmoid(preds)[:, 1].data.cpu().numpy())\r\n test_img_paths.extend(paths)\r\n test_preds = np.concatenate(test_preds)\r\n \r\n self.test_img_paths_ = test_img_paths\r\n self.test_preds_ = test_preds\r\n self.test_classes_ = [self.classes[int(round(i))] for i in self.test_preds_]\r\n \r\n self.report_ = pd.DataFrame({'image': pd.Series(self.test_img_paths_).apply(lambda x: x.split('\\\\')[-1]),\r\n 'probability': self.test_preds_,\r\n 'class': self.test_classes_,\r\n 'path': self.test_img_paths_})\r\n \r\n if save == True and f_format == 'csv':\r\n self.report_.to_csv('OpenStomata_report.csv')\r\n elif save == True and f_format == 'excel':\r\n self.report_.to_excel('OpenStomata_report.xlsx', sheet_name = 'preds')\r\n else:\r\n pass\r\n \r\n OpenStomata = self.test_preds_.round().sum() / len(self.test_preds_) * 100\r\n print('\\nDone!')\r\n print('Open: {:.1f}%'.format(OpenStomata))\r\n print('Close: {:.1f}%'.format(100 - OpenStomata))\r\n\r\n def visualize(self, n_imgs=16, save=False):\r\n '''\r\n Visualize some random stomata open/close classification results.\r\n Args:\r\n n_imgs - images to visualize (int, default = 16)\r\n save = whether to save the output plot in local directory or not\r\n '''\r\n if n_imgs > len(self.test_preds_):\r\n raise ValueError('n_imgs arg greater than the number of images')\r\n else:\r\n plt.figure(figsize=(15, 15))\r\n for idx, i in enumerate(random.sample(range(len(self.test_preds_)), n_imgs)):\r\n path = self.test_img_paths_[i]\r\n plt.subplot(int(np.ceil(n_imgs / 4)), 4, idx+1)\r\n image = cv2.imread(path)\r\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\r\n plt.imshow(image)\r\n plt.axis('off')\r\n plt.title('Predicted class: {} ({:.4f})'.format(self.classes[int(round(self.test_preds_[i]))], self.test_preds_[i]))\r\n \r\n if save == True:\r\n plt.savefig('OpenStomata_report.png', dpi = 200)\r\n plt.show()\r\n"
] | [
[
"matplotlib.pyplot.imshow",
"torch.sigmoid",
"pandas.Series",
"torch.cuda.manual_seed",
"numpy.random.seed",
"torch.manual_seed",
"torch.utils.data.DataLoader",
"matplotlib.pyplot.savefig",
"numpy.concatenate",
"numpy.ceil",
"torch.set_grad_enabled",
"torch.cuda.is_available",
"matplotlib.pyplot.axis",
"torch.device",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
schlegelflegel/manim | [
"3e7bc9cc242e6d2da1c5346ad93fc9c964221bcb"
] | [
"manim/scene/scene.py"
] | [
"\"\"\"A Scene is the canvas of the animation.\"\"\"\n\n\n__all__ = [\"Scene\", \"EndSceneEarlyException\"]\n\n\nimport inspect\nimport random\nimport warnings\nimport platform\nimport copy\n\nfrom tqdm import tqdm as ProgressDisplay\nimport numpy as np\n\nfrom .. import camera_config, file_writer_config, logger\nfrom ..animation.animation import Animation\nfrom ..animation.transform import MoveToTarget, ApplyMethod\nfrom ..camera.camera import Camera\nfrom ..constants import *\nfrom ..container import Container\nfrom ..mobject.mobject import Mobject\nfrom ..scene.scene_file_writer import SceneFileWriter\nfrom ..utils.iterables import list_update\nfrom ..utils.hashing import get_hash_from_play_call, get_hash_from_wait_call\n\n\nclass Scene(Container):\n \"\"\"A Scene is the canvas of your animation.\n\n All of your own named Scenes will be subclasses of Scene, or other named\n scenes.\n\n Examples\n --------\n Override the construct() method to tell Manim what should go on in the\n Scene.\n\n .. code-block:: python\n\n class MyScene(Scene):\n def construct(self):\n self.play(\n Write(Text(\"Hello World!\"))\n )\n\n Some important variables to note are:\n camera: The camera object to be used for the scene.\n file_writer : The object that writes the animations in the scene to a video file.\n mobjects : The list of mobjects present in the scene.\n foreground_mobjects : List of mobjects explicitly in the foreground.\n num_plays : Number of play() functions in the scene.\n time: time elapsed since initialisation of scene.\n random_seed: The seed with which all random operations are done.\n\n \"\"\"\n\n CONFIG = {\n \"camera_class\": Camera,\n \"skip_animations\": False,\n \"always_update_mobjects\": False,\n \"random_seed\": 0,\n }\n\n def __init__(self, **kwargs):\n Container.__init__(self, **kwargs)\n self.camera = self.camera_class(**camera_config)\n self.file_writer = SceneFileWriter(self, **file_writer_config,)\n self.play_hashes_list = []\n self.mobjects = []\n # TODO, remove need for foreground mobjects\n self.foreground_mobjects = []\n self.num_plays = 0\n self.time = 0\n self.original_skipping_status = file_writer_config[\"skip_animations\"]\n if self.random_seed is not None:\n random.seed(self.random_seed)\n np.random.seed(self.random_seed)\n\n self.setup()\n try:\n self.construct()\n except EndSceneEarlyException:\n pass\n self.tear_down()\n # We have to reset these settings in case of multiple renders.\n file_writer_config[\"skip_animations\"] = False\n self.original_skipping_status = file_writer_config[\"skip_animations\"]\n self.file_writer.finish()\n self.print_end_message()\n\n def setup(self):\n \"\"\"\n This is meant to be implemented by any scenes which\n are comonly subclassed, and have some common setup\n involved before the construct method is called.\n \"\"\"\n pass\n\n def tear_down(self):\n \"\"\"\n This is meant to be implemented by any scenes which\n are comonly subclassed, and have some common method\n to be invoked before the scene ends.\n \"\"\"\n pass\n\n def construct(self):\n \"\"\"\n The primary method for constructing (i.e adding content to)\n the Scene.\n \"\"\"\n pass # To be implemented in subclasses\n\n def __str__(self):\n return self.__class__.__name__\n\n def print_end_message(self):\n \"\"\"\n Used internally to print the number of\n animations played after the scene ends,\n as well as the name of the scene rendered\n (useful when using the `-a` option).\n \"\"\"\n logger.info(f\"Rendered {str(self)}\\nPlayed {self.num_plays} animations\")\n\n def set_variables_as_attrs(self, *objects, **newly_named_objects):\n \"\"\"\n This method is slightly hacky, making it a little easier\n for certain methods (typically subroutines of construct)\n to share local variables.\n \"\"\"\n caller_locals = inspect.currentframe().f_back.f_locals\n for key, value in list(caller_locals.items()):\n for o in objects:\n if value is o:\n setattr(self, key, value)\n for key, value in list(newly_named_objects.items()):\n setattr(self, key, value)\n return self\n\n def get_attrs(self, *keys):\n \"\"\"\n Gets attributes of a scene given the attribute's identifier/name.\n\n Parameters\n ----------\n *keys : str\n Name(s) of the argument(s) to return the attribute of.\n\n Returns\n -------\n list\n List of attributes of the passed identifiers.\n \"\"\"\n return [getattr(self, key) for key in keys]\n\n def get_frame(self):\n \"\"\"\n Gets the current frame as NumPy array.\n\n Returns\n -------\n np.array\n NumPy array of pixel values of each pixel in screen.\n The shape of the array is height x width x 3\n \"\"\"\n return np.array(self.camera.pixel_array)\n\n def update_frame( # TODO Description in Docstring\n self,\n mobjects=None,\n background=None,\n include_submobjects=True,\n ignore_skipping=True,\n **kwargs,\n ):\n \"\"\"Update the frame.\n\n Parameters\n ----------\n mobjects: list, optional\n list of mobjects\n\n background: np.ndarray, optional\n Pixel Array for Background.\n\n include_submobjects: bool, optional\n\n ignore_skipping : bool, optional\n\n **kwargs\n\n \"\"\"\n if file_writer_config[\"skip_animations\"] and not ignore_skipping:\n return\n if mobjects is None:\n mobjects = list_update(self.mobjects, self.foreground_mobjects,)\n if background is not None:\n self.camera.set_pixel_array(background)\n else:\n self.camera.reset()\n\n kwargs[\"include_submobjects\"] = include_submobjects\n self.camera.capture_mobjects(mobjects, **kwargs)\n\n def freeze_background(self):\n self.update_frame()\n self.camera = Camera(self.get_frame())\n self.clear()\n\n ###\n\n def update_mobjects(self, dt):\n \"\"\"\n Begins updating all mobjects in the Scene.\n\n Parameters\n ----------\n dt: int or float\n Change in time between updates. Defaults (mostly) to 1/frames_per_second\n \"\"\"\n for mobject in self.mobjects:\n mobject.update(dt)\n\n def should_update_mobjects(self):\n \"\"\"\n Returns True if any mobject in Scene is being updated\n or if the scene has always_update_mobjects set to true.\n\n Returns\n -------\n bool\n \"\"\"\n return self.always_update_mobjects or any(\n [mob.has_time_based_updater() for mob in self.get_mobject_family_members()]\n )\n\n ###\n\n def increment_time(self, d_time):\n \"\"\"\n Increments the time elapsed after intialisation of scene by\n passed \"d_time\".\n\n Parameters\n ----------\n d_time : int or float\n Time in seconds to increment by.\n \"\"\"\n self.time += d_time\n\n ###\n\n def get_top_level_mobjects(self):\n \"\"\"\n Returns all mobjects which are not submobjects.\n\n Returns\n -------\n list\n List of top level mobjects.\n \"\"\"\n # Return only those which are not in the family\n # of another mobject from the scene\n mobjects = self.get_mobjects()\n families = [m.get_family() for m in mobjects]\n\n def is_top_level(mobject):\n num_families = sum([(mobject in family) for family in families])\n return num_families == 1\n\n return list(filter(is_top_level, mobjects))\n\n def get_mobject_family_members(self):\n \"\"\"\n Returns list of family-members of all mobjects in scene.\n If a Circle() and a VGroup(Rectangle(),Triangle()) were added,\n it returns not only the Circle(), Rectangle() and Triangle(), but\n also the VGroup() object.\n\n Returns\n -------\n list\n List of mobject family members.\n \"\"\"\n return self.camera.extract_mobject_family_members(self.mobjects)\n\n def add(self, *mobjects):\n \"\"\"\n Mobjects will be displayed, from background to\n foreground in the order with which they are added.\n\n Parameters\n ---------\n *mobjects : Mobject\n Mobjects to add.\n\n Returns\n -------\n Scene\n The same scene after adding the Mobjects in.\n\n \"\"\"\n mobjects = [*mobjects, *self.foreground_mobjects]\n self.restructure_mobjects(to_remove=mobjects)\n self.mobjects += mobjects\n return self\n\n def add_mobjects_among(self, values):\n \"\"\"\n This is meant mostly for quick prototyping,\n e.g. to add all mobjects defined up to a point,\n call self.add_mobjects_among(locals().values())\n \"\"\"\n self.add(*filter(lambda m: isinstance(m, Mobject), values))\n return self\n\n def add_mobjects_from_animations(self, animations):\n\n curr_mobjects = self.get_mobject_family_members()\n for animation in animations:\n # Anything animated that's not already in the\n # scene gets added to the scene\n mob = animation.mobject\n if mob not in curr_mobjects:\n self.add(mob)\n curr_mobjects += mob.get_family()\n\n def remove(self, *mobjects):\n \"\"\"\n Removes mobjects in the passed list of mobjects\n from the scene and the foreground, by removing them\n from \"mobjects\" and \"foreground_mobjects\"\n\n Parameters\n ----------\n *mobjects : Mobject\n The mobjects to remove.\n \"\"\"\n for list_name in \"mobjects\", \"foreground_mobjects\":\n self.restructure_mobjects(mobjects, list_name, False)\n return self\n\n def restructure_mobjects(\n self, to_remove, mobject_list_name=\"mobjects\", extract_families=True\n ):\n \"\"\"\n tl:wr\n If your scene has a Group(), and you removed a mobject from the Group,\n this dissolves the group and puts the rest of the mobjects directly\n in self.mobjects or self.foreground_mobjects.\n\n In cases where the scene contains a group, e.g. Group(m1, m2, m3), but one\n of its submobjects is removed, e.g. scene.remove(m1), the list of mobjects\n will be edited to contain other submobjects, but not m1, e.g. it will now\n insert m2 and m3 to where the group once was.\n\n Parameters\n ----------\n to_remove : Mobject\n The Mobject to remove.\n\n mobject_list_name : str, optional\n The list of mobjects (\"mobjects\", \"foreground_mobjects\" etc) to remove from.\n\n extract_families : bool, optional\n Whether the mobject's families should be recursively extracted.\n\n Returns\n -------\n Scene\n The Scene mobject with restructured Mobjects.\n \"\"\"\n if extract_families:\n to_remove = self.camera.extract_mobject_family_members(to_remove)\n _list = getattr(self, mobject_list_name)\n new_list = self.get_restructured_mobject_list(_list, to_remove)\n setattr(self, mobject_list_name, new_list)\n return self\n\n def get_restructured_mobject_list(self, mobjects, to_remove):\n \"\"\"\n Given a list of mobjects and a list of mobjects to be removed, this\n filters out the removable mobjects from the list of mobjects.\n\n Parameters\n ----------\n\n mobjects : list\n The Mobjects to check.\n\n to_remove : list\n The list of mobjects to remove.\n\n Returns\n -------\n list\n The list of mobjects with the mobjects to remove removed.\n \"\"\"\n\n new_mobjects = []\n\n def add_safe_mobjects_from_list(list_to_examine, set_to_remove):\n for mob in list_to_examine:\n if mob in set_to_remove:\n continue\n intersect = set_to_remove.intersection(mob.get_family())\n if intersect:\n add_safe_mobjects_from_list(mob.submobjects, intersect)\n else:\n new_mobjects.append(mob)\n\n add_safe_mobjects_from_list(mobjects, set(to_remove))\n return new_mobjects\n\n # TODO, remove this, and calls to this\n def add_foreground_mobjects(self, *mobjects):\n \"\"\"\n Adds mobjects to the foreground, and internally to the list\n foreground_mobjects, and mobjects.\n\n Parameters\n ----------\n *mobjects : Mobject\n The Mobjects to add to the foreground.\n\n Returns\n ------\n Scene\n The Scene, with the foreground mobjects added.\n \"\"\"\n self.foreground_mobjects = list_update(self.foreground_mobjects, mobjects)\n self.add(*mobjects)\n return self\n\n def add_foreground_mobject(self, mobject):\n \"\"\"\n Adds a single mobject to the foreground, and internally to the list\n foreground_mobjects, and mobjects.\n\n Parameters\n ----------\n mobject : Mobject\n The Mobject to add to the foreground.\n\n Returns\n ------\n Scene\n The Scene, with the foreground mobject added.\n \"\"\"\n return self.add_foreground_mobjects(mobject)\n\n def remove_foreground_mobjects(self, *to_remove):\n \"\"\"\n Removes mobjects from the foreground, and internally from the list\n foreground_mobjects.\n\n Parameters\n ----------\n *to_remove : Mobject\n The mobject(s) to remove from the foreground.\n\n Returns\n ------\n Scene\n The Scene, with the foreground mobjects removed.\n \"\"\"\n self.restructure_mobjects(to_remove, \"foreground_mobjects\")\n return self\n\n def remove_foreground_mobject(self, mobject):\n \"\"\"\n Removes a single mobject from the foreground, and internally from the list\n foreground_mobjects.\n\n Parameters\n ----------\n mobject : Mobject\n The mobject to remove from the foreground.\n\n Returns\n ------\n Scene\n The Scene, with the foreground mobject removed.\n \"\"\"\n return self.remove_foreground_mobjects(mobject)\n\n def bring_to_front(self, *mobjects):\n \"\"\"\n Adds the passed mobjects to the scene again,\n pushing them to he front of the scene.\n\n Parameters\n ----------\n *mobjects : Mobject\n The mobject(s) to bring to the front of the scene.\n\n Returns\n ------\n Scene\n The Scene, with the mobjects brought to the front\n of the scene.\n \"\"\"\n self.add(*mobjects)\n return self\n\n def bring_to_back(self, *mobjects):\n \"\"\"\n Removes the mobject from the scene and\n adds them to the back of the scene.\n\n Parameters\n ----------\n *mobjects : Mobject\n The mobject(s) to push to the back of the scene.\n\n Returns\n ------\n Scene\n The Scene, with the mobjects pushed to the back\n of the scene.\n \"\"\"\n self.remove(*mobjects)\n self.mobjects = list(mobjects) + self.mobjects\n return self\n\n def clear(self):\n \"\"\"\n Removes all mobjects present in self.mobjects\n and self.foreground_mobjects from the scene.\n\n Returns\n ------\n Scene\n The Scene, with all of its mobjects in\n self.mobjects and self.foreground_mobjects\n removed.\n \"\"\"\n self.mobjects = []\n self.foreground_mobjects = []\n return self\n\n def get_mobjects(self):\n \"\"\"\n Returns all the mobjects in self.mobjects\n\n Returns\n ------\n list\n The list of self.mobjects .\n \"\"\"\n return list(self.mobjects)\n\n def get_mobject_copies(self):\n \"\"\"\n Returns a copy of all mobjects present in\n self.mobjects .\n\n Returns\n ------\n list\n A list of the copies of all the mobjects\n in self.mobjects\n \"\"\"\n return [m.copy() for m in self.mobjects]\n\n def get_moving_mobjects(self, *animations):\n \"\"\"\n Gets all moving mobjects in the passed animation(s).\n\n Parameters\n ----------\n *animations : Animation\n The animations to check for moving mobjects.\n\n Returns\n ------\n list\n The list of mobjects that could be moving in\n the Animation(s)\n \"\"\"\n # Go through mobjects from start to end, and\n # as soon as there's one that needs updating of\n # some kind per frame, return the list from that\n # point forward.\n animation_mobjects = [anim.mobject for anim in animations]\n mobjects = self.get_mobject_family_members()\n for i, mob in enumerate(mobjects):\n update_possibilities = [\n mob in animation_mobjects,\n len(mob.get_family_updaters()) > 0,\n mob in self.foreground_mobjects,\n ]\n if any(update_possibilities):\n return mobjects[i:]\n return []\n\n def get_time_progression(\n self, run_time, n_iterations=None, override_skip_animations=False\n ):\n \"\"\"\n You will hardly use this when making your own animations.\n This method is for Manim's internal use.\n\n Returns a CommandLine ProgressBar whose fill_time\n is dependent on the run_time of an animation,\n the iterations to perform in that animation\n and a bool saying whether or not to consider\n the skipped animations.\n\n Parameters\n ----------\n run_time: float\n The run_time of the animation.\n\n n_iterations: int, optional\n The number of iterations in the animation.\n\n override_skip_animations: bool, optional\n Whether or not to show skipped animations in the progress bar.\n\n Returns\n ------\n ProgressDisplay\n The CommandLine Progress Bar.\n \"\"\"\n if file_writer_config[\"skip_animations\"] and not override_skip_animations:\n times = [run_time]\n else:\n step = 1 / self.camera.frame_rate\n times = np.arange(0, run_time, step)\n time_progression = ProgressDisplay(\n times,\n total=n_iterations,\n leave=file_writer_config[\"leave_progress_bars\"],\n ascii=True if platform.system() == \"Windows\" else None,\n disable=not file_writer_config[\"progress_bar\"],\n )\n return time_progression\n\n def get_run_time(self, animations):\n \"\"\"\n Gets the total run time for a list of animations.\n\n Parameters\n ----------\n animations: list of Animation\n A list of the animations whose total\n run_time is to be calculated.\n\n Returns\n ------\n float\n The total run_time of all of the animations in the list.\n \"\"\"\n\n return np.max([animation.run_time for animation in animations])\n\n def get_animation_time_progression(self, animations):\n \"\"\"\n You will hardly use this when making your own animations.\n This method is for Manim's internal use.\n\n Uses get_time_progression to obtaina\n CommandLine ProgressBar whose fill_time is\n dependent on the qualities of the passed Animation,\n\n Parameters\n ----------\n animations : list of Animation\n The list of animations to get\n the time progression for.\n\n Returns\n ------\n ProgressDisplay\n The CommandLine Progress Bar.\n \"\"\"\n run_time = self.get_run_time(animations)\n time_progression = self.get_time_progression(run_time)\n time_progression.set_description(\n \"\".join(\n [\n \"Animation {}: \".format(self.num_plays),\n str(animations[0]),\n (\", etc.\" if len(animations) > 1 else \"\"),\n ]\n )\n )\n return time_progression\n\n def compile_play_args_to_animation_list(self, *args, **kwargs):\n \"\"\"\n Each arg can either be an animation, or a mobject method\n followed by that methods arguments (and potentially follow\n by a dict of kwargs for that method).\n This animation list is built by going through the args list,\n and each animation is simply added, but when a mobject method\n s hit, a MoveToTarget animation is built using the args that\n follow up until either another animation is hit, another method\n is hit, or the args list runs out.\n\n Parameters\n ----------\n *args : Animation or method of a mobject, which is followed by that method's arguments\n\n **kwargs : any named arguments like run_time or lag_ratio.\n\n Returns\n -------\n list : list of animations with the parameters applied to them.\n \"\"\"\n animations = []\n state = {\n \"curr_method\": None,\n \"last_method\": None,\n \"method_args\": [],\n }\n\n def compile_method(state):\n if state[\"curr_method\"] is None:\n return\n mobject = state[\"curr_method\"].__self__\n if state[\"last_method\"] and state[\"last_method\"].__self__ is mobject:\n animations.pop()\n # method should already have target then.\n else:\n mobject.generate_target()\n #\n if len(state[\"method_args\"]) > 0 and isinstance(\n state[\"method_args\"][-1], dict\n ):\n method_kwargs = state[\"method_args\"].pop()\n else:\n method_kwargs = {}\n state[\"curr_method\"].__func__(\n mobject.target, *state[\"method_args\"], **method_kwargs\n )\n animations.append(MoveToTarget(mobject))\n state[\"last_method\"] = state[\"curr_method\"]\n state[\"curr_method\"] = None\n state[\"method_args\"] = []\n\n for arg in args:\n if isinstance(arg, Animation):\n compile_method(state)\n animations.append(arg)\n elif inspect.ismethod(arg):\n compile_method(state)\n state[\"curr_method\"] = arg\n elif state[\"curr_method\"] is not None:\n state[\"method_args\"].append(arg)\n elif isinstance(arg, Mobject):\n raise Exception(\n \"\"\"\n I think you may have invoked a method\n you meant to pass in as a Scene.play argument\n \"\"\"\n )\n else:\n raise Exception(\"Invalid play arguments\")\n compile_method(state)\n\n for animation in animations:\n # This is where kwargs to play like run_time and rate_func\n # get applied to all animations\n animation.update_config(**kwargs)\n\n return animations\n\n def update_skipping_status(self):\n \"\"\"\n This method is used internally to check if the current\n animation needs to be skipped or not. It also checks if\n the number of animations that were played correspond to\n the number of animations that need to be played, and\n raises an EndSceneEarlyException if they don't correspond.\n \"\"\"\n\n if file_writer_config[\"from_animation_number\"]:\n if self.num_plays == file_writer_config[\"from_animation_number\"]:\n file_writer_config[\"skip_animations\"] = False\n if file_writer_config[\"upto_animation_number\"]:\n if self.num_plays >= file_writer_config[\"upto_animation_number\"]:\n file_writer_config[\"skip_animations\"] = True\n raise EndSceneEarlyException()\n\n def handle_caching_play(func):\n \"\"\"\n Decorator that returns a wrapped version of func that will compute the hash of the play invocation.\n\n The returned function will act according to the computed hash: either skip the animation because it's already cached, or let the invoked function play normally.\n\n Parameters\n ----------\n func : Callable[[...], None]\n The play like function that has to be written to the video file stream. Take the same parameters as `scene.play`.\n \"\"\"\n\n def wrapper(self, *args, **kwargs):\n self.revert_to_original_skipping_status()\n animations = self.compile_play_args_to_animation_list(*args, **kwargs)\n self.add_mobjects_from_animations(animations)\n if not file_writer_config[\"disable_caching\"]:\n mobjects_on_scene = self.get_mobjects()\n hash_play = get_hash_from_play_call(\n self.camera, animations, mobjects_on_scene\n )\n self.play_hashes_list.append(hash_play)\n if self.file_writer.is_already_cached(hash_play):\n logger.info(\n f\"Animation {self.num_plays} : Using cached data (hash : {hash_play})\"\n )\n file_writer_config[\"skip_animations\"] = True\n else:\n hash_play = \"uncached_{:05}\".format(self.num_plays)\n self.play_hashes_list.append(hash_play)\n func(self, *args, **kwargs)\n\n return wrapper\n\n def handle_caching_wait(func):\n \"\"\"\n Decorator that returns a wrapped version of func that will compute the hash of the wait invocation.\n\n The returned function will act according to the computed hash: either skip the animation because it's already cached, or let the invoked function play normally.\n\n Parameters\n ----------\n func : Callable[[...], None]\n The wait like function that has to be written to the video file stream. Take the same parameters as `scene.wait`.\n \"\"\"\n\n def wrapper(self, duration=DEFAULT_WAIT_TIME, stop_condition=None):\n self.revert_to_original_skipping_status()\n if not file_writer_config[\"disable_caching\"]:\n hash_wait = get_hash_from_wait_call(\n self.camera, duration, stop_condition, self.get_mobjects()\n )\n self.play_hashes_list.append(hash_wait)\n if self.file_writer.is_already_cached(hash_wait):\n logger.info(\n f\"Wait {self.num_plays} : Using cached data (hash : {hash_wait})\"\n )\n file_writer_config[\"skip_animations\"] = True\n else:\n hash_wait = \"uncached_{:05}\".format(self.num_plays)\n self.play_hashes_list.append(hash_wait)\n func(self, duration, stop_condition)\n\n return wrapper\n\n def handle_play_like_call(func):\n \"\"\"\n This method is used internally to wrap the\n passed function, into a function that\n actually writes to the video stream.\n Simultaneously, it also adds to the number\n of animations played.\n\n Parameters\n ----------\n func : function\n The play() like function that has to be\n written to the video file stream.\n\n Returns\n -------\n function\n The play() like function that can now write\n to the video file stream.\n \"\"\"\n\n def wrapper(self, *args, **kwargs):\n self.update_skipping_status()\n allow_write = not file_writer_config[\"skip_animations\"]\n self.file_writer.begin_animation(allow_write)\n func(self, *args, **kwargs)\n self.file_writer.end_animation(allow_write)\n self.num_plays += 1\n\n return wrapper\n\n def begin_animations(self, animations):\n \"\"\"\n This method begins the list of animations that is passed,\n and adds any mobjects involved (if not already present)\n to the scene again.\n\n Parameters\n ----------\n animations : list\n List of involved animations.\n\n \"\"\"\n for animation in animations:\n # Begin animation\n animation.begin()\n\n def progress_through_animations(self, animations):\n \"\"\"\n This method progresses through each animation\n in the list passed and and updates the frames as required.\n\n Parameters\n ----------\n animations : list\n List of involved animations.\n \"\"\"\n # Paint all non-moving objects onto the screen, so they don't\n # have to be rendered every frame\n moving_mobjects = self.get_moving_mobjects(*animations)\n self.update_frame(excluded_mobjects=moving_mobjects)\n static_image = self.get_frame()\n last_t = 0\n for t in self.get_animation_time_progression(animations):\n dt = t - last_t\n last_t = t\n for animation in animations:\n animation.update_mobjects(dt)\n alpha = t / animation.run_time\n animation.interpolate(alpha)\n self.update_mobjects(dt)\n self.update_frame(moving_mobjects, static_image)\n self.add_frames(self.get_frame())\n\n def finish_animations(self, animations):\n \"\"\"\n This function cleans up after the end\n of each animation in the passed list.\n\n Parameters\n ----------\n animations : list\n list of animations to finish.\n \"\"\"\n for animation in animations:\n animation.finish()\n animation.clean_up_from_scene(self)\n self.mobjects_from_last_animation = [anim.mobject for anim in animations]\n if file_writer_config[\"skip_animations\"]:\n # TODO, run this call in for each animation?\n self.update_mobjects(self.get_run_time(animations))\n else:\n self.update_mobjects(0)\n\n @handle_caching_play\n @handle_play_like_call\n def play(self, *args, **kwargs):\n \"\"\"\n This method is used to prep the animations for rendering,\n apply the arguments and parameters required to them,\n render them, and write them to the video file.\n\n Parameters\n ----------\n *args : Animation or mobject with mobject method and params\n **kwargs : named parameters affecting what was passed in *args e.g run_time, lag_ratio etc.\n \"\"\"\n if len(args) == 0:\n warnings.warn(\"Called Scene.play with no animations\")\n return\n animations = self.compile_play_args_to_animation_list(*args, **kwargs)\n self.begin_animations(animations)\n self.progress_through_animations(animations)\n self.finish_animations(animations)\n\n def clean_up_animations(self, *animations):\n \"\"\"\n This method cleans up and removes from the\n scene all the animations that were passed\n\n Parameters\n ----------\n *animations : Animation\n Animation to clean up.\n\n Returns\n -------\n Scene\n The scene with the animations\n cleaned up.\n\n \"\"\"\n for animation in animations:\n animation.clean_up_from_scene(self)\n return self\n\n def get_mobjects_from_last_animation(self):\n \"\"\"\n This method returns the mobjects from the previous\n played animation, if any exist, and returns an empty\n list if not.\n\n Returns\n --------\n list\n The list of mobjects from the previous animation.\n\n \"\"\"\n if hasattr(self, \"mobjects_from_last_animation\"):\n return self.mobjects_from_last_animation\n return []\n\n def get_wait_time_progression(self, duration, stop_condition):\n \"\"\"\n This method is used internally to obtain the CommandLine\n Progressbar for when self.wait() is called in a scene.\n\n Parameters\n ----------\n duration: int or float\n duration of wait time\n\n stop_condition : function\n The function which determines whether to continue waiting.\n\n Returns\n -------\n ProgressBar\n The CommandLine ProgressBar of the wait time\n\n \"\"\"\n if stop_condition is not None:\n time_progression = self.get_time_progression(\n duration,\n n_iterations=-1, # So it doesn't show % progress\n override_skip_animations=True,\n )\n time_progression.set_description(\n \"Waiting for {}\".format(stop_condition.__name__)\n )\n else:\n time_progression = self.get_time_progression(duration)\n time_progression.set_description(\"Waiting {}\".format(self.num_plays))\n return time_progression\n\n @handle_caching_wait\n @handle_play_like_call\n def wait(self, duration=DEFAULT_WAIT_TIME, stop_condition=None):\n \"\"\"\n This method is used to wait, and do nothing to the scene, for some\n duration.\n Updaters stop updating, nothing happens.\n\n Parameters\n ----------\n duration : float or int, optional\n The duration of wait time.\n stop_condition :\n A function that determines whether to stop waiting or not.\n\n Returns\n -------\n Scene\n The scene, after waiting.\n \"\"\"\n self.update_mobjects(dt=0) # Any problems with this?\n if self.should_update_mobjects():\n time_progression = self.get_wait_time_progression(duration, stop_condition)\n # TODO, be smart about setting a static image\n # the same way Scene.play does\n last_t = 0\n for t in time_progression:\n dt = t - last_t\n last_t = t\n self.update_mobjects(dt)\n self.update_frame()\n self.add_frames(self.get_frame())\n if stop_condition is not None and stop_condition():\n time_progression.close()\n break\n elif file_writer_config[\"skip_animations\"]:\n # Do nothing\n return self\n else:\n self.update_frame()\n dt = 1 / self.camera.frame_rate\n n_frames = int(duration / dt)\n frame = self.get_frame()\n self.add_frames(*[frame] * n_frames)\n return self\n\n def wait_until(self, stop_condition, max_time=60):\n \"\"\"\n Like a wrapper for wait().\n You pass a function that determines whether to continue waiting,\n and a max wait time if that is never fulfilled.\n\n Parameters\n ----------\n stop_condition : function\n The function whose boolean return value determines whether to continue waiting\n\n max_time : int or float, optional\n The maximum wait time in seconds, if the stop_condition is never fulfilled.\n \"\"\"\n self.wait(max_time, stop_condition=stop_condition)\n\n def force_skipping(self):\n \"\"\"\n This forces the skipping of animations,\n by setting original_skipping_status to\n whatever skip_animations was, and setting\n skip_animations to True.\n\n Returns\n -------\n Scene\n The Scene, with skipping turned on.\n \"\"\"\n self.original_skipping_status = file_writer_config[\"skip_animations\"]\n file_writer_config[\"skip_animations\"] = True\n return self\n\n def revert_to_original_skipping_status(self):\n \"\"\"\n Forces the scene to go back to its original skipping status,\n by setting skip_animations to whatever it reads\n from original_skipping_status.\n\n Returns\n -------\n Scene\n The Scene, with the original skipping status.\n \"\"\"\n if hasattr(self, \"original_skipping_status\"):\n file_writer_config[\"skip_animations\"] = self.original_skipping_status\n return self\n\n def add_frames(self, *frames):\n \"\"\"\n Adds a frame to the video_file_stream\n\n Parameters\n ----------\n *frames : numpy.ndarray\n The frames to add, as pixel arrays.\n \"\"\"\n dt = 1 / self.camera.frame_rate\n self.increment_time(len(frames) * dt)\n if file_writer_config[\"skip_animations\"]:\n return\n for frame in frames:\n self.file_writer.write_frame(frame)\n\n def add_sound(self, sound_file, time_offset=0, gain=None, **kwargs):\n \"\"\"\n This method is used to add a sound to the animation.\n\n Parameters\n ----------\n sound_file : str\n The path to the sound file.\n\n time_offset : int,float, optional\n The offset in the sound file after which\n the sound can be played.\n\n gain :\n\n \"\"\"\n if file_writer_config[\"skip_animations\"]:\n return\n time = self.time + time_offset\n self.file_writer.add_sound(sound_file, time, gain, **kwargs)\n\n def show_frame(self):\n \"\"\"\n Opens the current frame in the Default Image Viewer\n of your system.\n \"\"\"\n self.update_frame(ignore_skipping=True)\n self.camera.get_image().show()\n\n\nclass EndSceneEarlyException(Exception):\n pass\n"
] | [
[
"numpy.arange",
"numpy.max",
"numpy.array",
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
muntumdwara/TopGun | [
"fc253faa8ac0a7c9b7d000c2ea018bba9c584d27"
] | [
"topgun/charting/overplot.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\" Overplot\n\nSeries of functions designed to help with charting in Plotly\n\n\"\"\"\n\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objs as go\nimport plotly.io as pio\n\n# %% PLOTLY EXPRESS STANLIB TEMPLATE\n\n# Approximatation of STANLIB colour theme\nCOLOUR_MAP = {0:'purple',\n 1:'turquoise',\n 2:'grey',\n 3:'black',\n 4:'green',\n 5:'blue',\n 6:'crimson',\n 7:'orange',\n 8:'mediumvioletred'}\n\n# Hack together basic template\nfig = go.Figure(layout=dict(\n font={'family':'Courier New', 'size':12},\n plot_bgcolor= 'white',\n colorway=['grey','turquoise', 'purple', 'lime', 'blue', 'black', 'brown', 'red', 'orange'],\n showlegend=False,\n legend={'orientation':'v'},\n margin = {'l':75, 'r':50, 'b':50, 't':50},\n xaxis= {'anchor': 'y1', 'title': '',\n 'showline':True, 'linecolor': 'gray',\n 'zeroline':True, 'zerolinewidth':1 , 'zerolinecolor':'whitesmoke',\n 'showgrid': True, 'gridcolor': 'whitesmoke',\n },\n yaxis= {'anchor': 'x1', 'title': '', 'hoverformat':'.1f', 'tickformat':'.1f',\n 'showline':True, 'linecolor':'gray',\n 'zeroline':True, 'zerolinewidth':1 , 'zerolinecolor':'whitesmoke',\n 'showgrid': True, 'gridcolor': 'whitesmoke'},\n updatemenus= [dict(type='buttons',\n active=-1, showactive = True,\n direction='down',\n y=0.5, x=1.1,\n pad = {'l':0, 'r':0, 't':0, 'b':0},\n buttons=[])],\n annotations=[],))\n\n# save it\ntemplated_fig = pio.to_templated(fig)\npio.templates['multi_strat'] = templated_fig.layout.template\n\n# %%\n\ndef line_stacker(df, template='multi_strat',\n yaxis_title= '', source='', source_posn=[0.85, 0.08],\n **kwargs):\n \"\"\" Line plot with columns as lines\n \n Plotly express does a cool thing called 'colours' where it loads multiple\n traces which can be clicked on and off on the chart. It does however require\n a f*cking stupid format where all data is in one long vector with repeated \n dates AND a column of 'colours'... why they don't just let you use the\n varname and have a logical df is beyond me'\n \n INPUT:\n df - dataframe with dates as index; column headers as legend titles\n kwargs - ONLY use arguments you could normally pass to plotly express\n \"\"\"\n \n # set up the 3 columns we need\n vn = ['date', 'value', 'index']\n z = pd.DataFrame(columns = vn)\n \n # itserate through df concatinating to silly long vector\n for ticker in df:\n i = df[ticker].reset_index()\n i['value'] = ticker\n i.columns = vn\n z = pd.concat([z, i])\n \n # initial figure\n fig = px.line(z, x=\"date\", y=\"value\", color=\"index\", template=template, **kwargs)\n \n # updates not in kwargs\n fig.update_layout(yaxis_title=yaxis_title)\n fig.update_layout(showlegend=True)\n \n # Add source as annotation (may need some re-jigging ex-post)\n fig.add_annotation(text=source, xref='paper', yref='paper',\n align='right', ax=0, ay=0,\n x=source_posn[0], y=source_posn[1])\n \n return fig\n\n# %%\n \n"
] | [
[
"pandas.concat",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
ea42gh/holoviews_functions | [
"e450617ac99656cd080a52437efb5bfc4bb49bc0"
] | [
"holoviews_functions/vectorfield.py"
] | [
"import numpy as np\nimport holoviews as hv\n\ndef vector_field_with_background(x,y, slopes, length=1, subsample=3):\n \"\"\"\n Given vectors x, y and an array of slopes(x,y)\n return a grayscale image of the slopes y' together with\n a vector field representation of the slopes\n \"\"\"\n\n # compute the data\n theta = np.arctan2( slopes, 1) # angle of the slope y' at x,y\n\n # Obtain the vector field (subsample the grid)\n decim_x = x[::subsample]\n decim_y = y[::subsample]\n decim_theta = theta[::subsample,::subsample]\n \n if isinstance( length, (int,float)):\n decim_len = np.full_like( decim_theta, length)\n else:\n decim_len = length[::subsample, ::subsample]\n vf_opts = dict(size_index=3, alpha=0.3, muted_alpha=0.05)\n vec_field = hv.VectorField((decim_x,decim_y,decim_theta,decim_len) ).opts(**vf_opts)\n\n # Normalize the given array so that it can be used with the RGB element's alpha channel \n def norm(arr):\n arr = (arr-arr.min())\n return arr/arr.max()\n\n normXY = norm(np.copy(slopes))\n img_field = hv.RGB( (x, y, normXY, normXY, normXY, np.full_like(theta, 0.1)),\n vdims=['R','G','B','A'] )\\\n .opts(shared_axes=False)\n\n return img_field*vec_field\n\n"
] | [
[
"numpy.arctan2",
"numpy.copy",
"numpy.full_like"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Shinetism/MEE | [
"6ce38b4c930cdd50f69fd9f79e6dec441aa2d220"
] | [
"src/utils/grad_ckpt.py"
] | [
"import torch\nimport warnings\n\n\ndef detach_variable(inputs):\n if isinstance(inputs, tuple):\n out = []\n for inp in inputs:\n x = inp.detach()\n x.requires_grad = inp.requires_grad\n out.append(x)\n return tuple(out)\n else:\n raise RuntimeError(\n \"Only tuple of tensors is supported. Got Unsupported input type: \", type(inputs).__name__)\n\n\ndef check_backward_validity(inputs):\n if not any(inp.requires_grad for inp in inputs):\n warnings.warn(\"None of the inputs have requires_grad=True. Gradients will be None\")\n\n\nclass CheckpointFunction(torch.autograd.Function):\n @staticmethod\n def forward(ctx, run_function, length, *args):\n ctx.run_function = run_function\n ctx.input_tensors = list(args[:length])\n ctx.input_params = list(args[length:])\n with torch.no_grad():\n output_tensors = ctx.run_function(*ctx.input_tensors)\n return output_tensors\n\n @staticmethod\n def backward(ctx, *output_grads):\n for i in range(len(ctx.input_tensors)):\n temp = ctx.input_tensors[i]\n ctx.input_tensors[i] = temp.detach()\n ctx.input_tensors[i].requires_grad = temp.requires_grad\n with torch.enable_grad():\n output_tensors = ctx.run_function(*ctx.input_tensors)\n input_grads = torch.autograd.grad(output_tensors, ctx.input_tensors + ctx.input_params, output_grads, allow_unused=True)\n return (None, None) + input_grads"
] | [
[
"torch.no_grad",
"torch.autograd.grad",
"torch.enable_grad"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kaywenith/TorchMPS | [
"abd2dca54f3eb35b931cfb8c43ba09a6fa94ae49"
] | [
"torchmps/torchmps.py"
] | [
"\"\"\"\nTODO:\n (1) Update master to include all the new features in dynamic_capacity\n\"\"\"\nimport torch\nimport torch.nn as nn\n\nfrom .utils import init_tensor, svd_flex\nfrom .contractables import (\n SingleMat,\n MatRegion,\n OutputCore,\n ContractableList,\n EdgeVec,\n OutputMat,\n)\n\n\nclass TI_MPS(nn.Module):\n \"\"\"\n Sequence MPS which converts input of arbitrary length to a single output vector\n \"\"\"\n\n def __init__(\n self,\n output_dim,\n bond_dim,\n feature_dim=2,\n parallel_eval=False,\n fixed_ends=False,\n init_std=1e-9,\n use_bias=True,\n fixed_bias=True,\n ):\n super().__init__()\n\n # Initialize the core tensor defining our model near the identity\n # This tensor holds all of the trainable parameters of our model\n tensor = init_tensor(\n bond_str=\"lri\",\n shape=[bond_dim, bond_dim, feature_dim],\n init_method=(\"random_zero\", init_std),\n )\n self.register_parameter(name=\"core_tensor\", param=nn.Parameter(tensor))\n\n # Define our initial vector and terminal matrix, which are both\n # functional modules, i.e. unchanged during training\n assert isinstance(fixed_ends, bool)\n self.init_vector = InitialVector(bond_dim, fixed_vec=fixed_ends)\n self.terminal_mat = TerminalOutput(bond_dim, output_dim, fixed_mat=fixed_ends)\n\n # Set the bias matrix\n if use_bias:\n # bias_mat is identity when fixed_bias=True, near-identity otherwise\n if fixed_bias:\n bias_mat = torch.eye(bond_dim)\n self.register_buffer(name=\"bias_mat\", tensor=bias_mat)\n else:\n bias_mat = init_tensor(\n bond_str=\"lr\",\n shape=[bond_dim, bond_dim],\n init_method=(\"random_eye\", init_std),\n )\n self.register_parameter(name=\"bias_mat\", param=nn.Parameter(bias_mat))\n else:\n self.bias_mat = None\n\n # Set the rest of our TI_MPS attributes\n self.feature_dim = feature_dim\n self.output_dim = output_dim\n self.bond_dim = bond_dim\n self.parallel_eval = parallel_eval\n self.use_bias = use_bias\n self.fixed_bias = fixed_bias\n self.feature_map = None\n\n def forward(self, input_data):\n \"\"\"\n Converts batch input tensor into a batch output tensor\n\n Args:\n input_data: A tensor of shape [batch_size, length, feature_dim].\n \"\"\"\n\n # Reformat our input to a batch format, padding with zeros as needed\n batch_input = self.format_input(input_data)\n batch_size = batch_input.size(0)\n seq_len = batch_input.size(1)\n\n # Build up a contractable_list as EdgeVec + MatRegion + OutputMat\n expanded_core = self.core_tensor.expand(\n [seq_len, self.bond_dim, self.bond_dim, self.feature_dim]\n )\n input_region = InputRegion(\n expanded_core,\n use_bias=self.use_bias,\n fixed_bias=self.fixed_bias,\n bias_mat=self.bias_mat,\n ephemeral=True,\n )\n contractable_list = [input_region(batch_input)]\n\n # Prepend an EdgeVec and append an OutputMat\n contractable_list = [self.init_vector()] + contractable_list\n contractable_list.append(self.terminal_mat())\n\n # Wrap contractable_list as a ContractableList instance\n contractable_list = ContractableList(contractable_list)\n\n # Contract everything in contractable_list\n output = contractable_list.reduce(parallel_eval=self.parallel_eval)\n batch_output = output.tensor\n\n # Check shape before returning output values\n assert output.bond_str == \"bo\"\n assert batch_output.size(0) == batch_size\n assert batch_output.size(1) == self.output_dim\n\n return batch_output\n\n def format_input(self, input_data):\n \"\"\"\n Converts input list of sequences into a single batch sequence tensor.\n\n If input is already a batch tensor, it is returned unchanged. Otherwise,\n convert input list into a batch sequence with shape [batch_size, length,\n feature_dim].\n\n If self.use_bias = self.fixed_bias = True, then sequences of different\n lengths can be used, in which case shorter sequences are padded with\n zeros at the end, making the batch tensor length equal to the length\n of the longest input sequence.\n\n Args:\n input_data: A tensor of shape [batch_size, length] or\n [batch_size, length, feature_dim], or a list of length batch_size,\n whose i'th item is a tensor of shape [length_i, feature_dim] or\n [length_i]. If self.use_bias or self.fixed_bias are False, then\n length_i must be the same for all i.\n \"\"\"\n feature_dim = self.feature_dim\n\n # If we get a batch tensor, just embed it and/or return it unchanged\n if isinstance(input_data, torch.Tensor):\n if len(input_data.shape) == 2:\n input_data = self.embed_input(input_data)\n\n # Check to make sure shape is alright\n shape = input_data.shape\n assert len(shape) == 3\n assert shape[2] == feature_dim\n\n return input_data\n\n # Collate the input list into a single batch tensor\n elif isinstance(input_data, list):\n # Check formatting, require that input sequences are either all\n # unembedded or all pre-embedded\n num_modes = len(input_data[0].shape)\n assert num_modes in [1, 2]\n assert all(\n [\n isinstance(s, torch.Tensor) and len(s.shape) == num_modes\n for s in input_data\n ]\n )\n assert num_modes == 1 or all([s.size(1) == feature_dim for s in input_data])\n\n # Check that all the sequences are the same length or can be padded\n max_len = max([s.size(0) for s in input_data])\n can_pad = self.use_bias and self.fixed_bias\n if not can_pad and any([s.size(0) != max_len for s in input_data]):\n raise ValueError(\n \"To process input_data as list of sequences \"\n \"with different lengths, must have self.use_bias=\"\n \"self.fixed_bias=True (currently self.use_bias=\"\n f\"{self.use_bias}, self.fixed_bias={self.fixed_bias})\"\n )\n\n # Pad the sequences with zeros (if needed), return as batch tensor\n if can_pad:\n batch_size = len(input_data)\n full_size = [batch_size, max_len, feature_dim]\n batch_input = torch.zeros(full_size[: num_modes + 1])\n\n # Copy each sequence into batch_input\n for i, seq in enumerate(input_data):\n batch_input[i, : seq.size(0)] = seq\n else:\n batch_input = torch.stack(input_data)\n\n # Embed everything (if needed) and return the batch tensor\n if len(batch_input.shape) == 2:\n batch_input = self.embed_input(batch_input)\n\n return batch_input\n\n else:\n raise ValueError(\n \"input_data must either be Tensor with shape\"\n \"[batch_size, length] or [batch_size, length, feature_dim], \"\n \"or list of Tensors with shapes [length_i, feature_dim] or \"\n \"[length_i]\"\n )\n\n def embed_input(self, input_data):\n \"\"\"\n Embed pixels of input_data into separate local feature spaces\n\n Args:\n input_data (Tensor): Input with shape [batch_size, length].\n\n Returns:\n embedded_data (Tensor): Input embedded into a tensor with shape\n [batch_size, input_dim, feature_dim]\n \"\"\"\n assert len(input_data.shape) == 2\n\n # Get relevant dimensions\n batch_dim, length = input_data.shape\n feature_dim = self.feature_dim\n embedded_shape = [batch_dim, length, feature_dim]\n\n # Apply a custom embedding map if it has been defined by the user\n if self.feature_map is not None:\n f_map = self.feature_map\n embedded_data = torch.stack(\n [torch.stack([f_map(x) for x in batch]) for batch in input_data]\n )\n\n # Make sure our embedded input has the desired size\n assert list(embedded_data.shape) == embedded_shape\n\n # Otherwise, use a simple linear embedding map with feature_dim = 2\n else:\n if self.feature_dim != 2:\n raise RuntimeError(\n f\"self.feature_dim = {feature_dim}, but \"\n \"default feature_map requires self.feature_dim = 2\"\n )\n embedded_data = torch.empty(embedded_shape)\n\n embedded_data[:, :, 0] = input_data\n embedded_data[:, :, 1] = 1 - input_data\n\n return embedded_data\n\n def register_feature_map(self, feature_map):\n \"\"\"\n Register a custom feature map to be used for embedding input data\n\n Args:\n feature_map (function): Takes a single scalar input datum and\n returns an embedded representation of the\n image. The output size of the function must\n match self.feature_dim. If feature_map=None,\n then the feature map will be reset to a\n simple default linear embedding\n \"\"\"\n if feature_map is not None:\n # Test to make sure feature_map outputs vector of proper size\n test_out = feature_map(torch.tensor(0))\n assert isinstance(test_out, torch.Tensor)\n\n out_shape, needed_shape = list(test_out.shape), [self.feature_dim]\n if out_shape != needed_shape:\n raise ValueError(\n \"Given feature_map returns values with shape \"\n f\"{list(out_shape)}, but should return \"\n f\"values of size {list(needed_shape)}\"\n )\n\n self.feature_map = feature_map\n\n\nclass MPS(nn.Module):\n \"\"\"\n Tunable MPS model giving mapping from fixed-size data to output vector\n\n Model works by first converting each 'pixel' (local data) to feature\n vector via a simple embedding, then contracting embeddings with inputs\n to each MPS cores. The resulting transition matrices are contracted\n together along bond dimensions (i.e. hidden state spaces), with output\n produced via an uncontracted edge of an additional output core.\n\n MPS model permits many customizable behaviors, including custom\n 'routing' of MPS through the input, choice of boundary conditions\n (meaning the model can act as a tensor train or a tensor ring),\n GPU-friendly parallel evaluation, and an experimental mode to support\n adaptive choice of bond dimensions based on singular value spectrum.\n\n Args:\n input_dim: Number of 'pixels' in the input to the MPS\n output_dim: Size of the vectors output by MPS via output core\n bond_dim: Dimension of the 'bonds' connecting adjacent MPS\n cores, which act as hidden state spaces of the\n model. In adaptive mode, bond_dim instead\n specifies the maximum allowed bond dimension\n feature_dim: Size of the local feature spaces each pixel is\n embedded into (default: 2)\n periodic_bc: Whether MPS has periodic boundary conditions (i.e.\n is a tensor ring) or open boundary conditions\n (i.e. is a tensor train) (default: False)\n parallel_eval: Whether contraction of tensors is performed in a\n serial or parallel fashion. The former is less\n expensive for open boundary conditions, but\n parallelizes more poorly (default: False)\n label_site: Location in the MPS chain where output is placed\n (default: input_dim // 2)\n path: List specifying a path through the input data\n which MPS is 'routed' along. For example, choosing\n path=[0, 1, ..., input_dim-1] gives a standard\n in-order traversal (behavior when path=None), while\n path=[0, 2, ..., input_dim-1] specifies an MPS\n accepting input only from even-valued input pixels\n (default: None)\n init_std: Size of the Gaussian noise used in default\n near-identity initialization (default: 1e-9)\n initializer: Pytorch initializer for custom initialization of\n MPS cores, with None specifying default\n near-identity initialization (default: None)\n use_bias: Whether to use trainable bias matrices in MPS\n cores, which are initialized near the zero matrix\n (default: False)\n adaptive_mode: Whether MPS is trained with experimental adaptive\n bond dimensions selection (default: False)\n cutoff: Singular value cutoff controlling bond dimension\n adaptive selection (default: 1e-9)\n merge_threshold: Number of inputs before adaptive MPS shifts its\n merge state once, with two shifts leading to the\n update of all bond dimensions (default: 2000)\n \"\"\"\n\n # TODO: Support arbitrary initializers\n # TODO: Clean up the current treatment of initialization\n # TODO: Resolve weirdness with fixed bias and initialization choice\n # TODO: Add function to convert to canonical form\n # TODO: Fix issue of no training when use_bias=False\n\n def __init__(\n self,\n input_dim,\n output_dim,\n bond_dim,\n feature_dim=2,\n periodic_bc=False,\n parallel_eval=False,\n label_site=None,\n path=None,\n init_std=1e-9,\n initializer=None,\n use_bias=True,\n adaptive_mode=False,\n cutoff=1e-10,\n merge_threshold=2000,\n ):\n super().__init__()\n\n if label_site is None:\n label_site = input_dim // 2\n assert label_site >= 0 and label_site <= input_dim\n\n # Using bias matrices in adaptive_mode is too complicated, so I'm\n # disabling it here\n if adaptive_mode:\n use_bias = False\n\n # Our MPS is made of two InputRegions separated by an OutputSite.\n module_list = []\n if adaptive_mode or (not use_bias):\n input_region_init_method = \"random_eye2\"\n else:\n input_region_init_method = \"random_zero\"\n init_args = {\n \"bond_str\": \"slri\",\n \"shape\": [label_site, bond_dim, bond_dim, feature_dim],\n \"init_method\": (\n input_region_init_method,\n init_std,\n output_dim,\n ),\n }\n\n # The first input region\n if label_site > 0:\n tensor = init_tensor(**init_args)\n\n module_list.append(InputRegion(tensor, use_bias=use_bias, fixed_bias=False))\n\n # The output site\n tensor = init_tensor(\n shape=[output_dim, bond_dim, bond_dim],\n bond_str=\"olr\",\n init_method=(\n \"min_random_eye\" if adaptive_mode else \"random_eye\",\n init_std,\n output_dim,\n ),\n )\n module_list.append(OutputSite(tensor))\n\n # The other input region\n if label_site < input_dim:\n init_args[\"shape\"] = [\n input_dim - label_site,\n bond_dim,\n bond_dim,\n feature_dim,\n ]\n tensor = init_tensor(**init_args)\n module_list.append(InputRegion(tensor, use_bias=use_bias, fixed_bias=False))\n\n # Initialize linear_region according to our adaptive_mode specification\n if adaptive_mode:\n self.linear_region = MergedLinearRegion(\n module_list=module_list,\n periodic_bc=periodic_bc,\n parallel_eval=parallel_eval,\n cutoff=cutoff,\n merge_threshold=merge_threshold,\n )\n\n # Initialize the list of bond dimensions, which starts out constant\n self.bond_list = bond_dim * torch.ones(input_dim + 2, dtype=torch.long)\n if not periodic_bc:\n self.bond_list[0], self.bond_list[-1] = 1, 1\n\n # Initialize the list of singular values, which start out at -1\n self.sv_list = -1.0 * torch.ones([input_dim + 2, bond_dim])\n\n else:\n self.linear_region = LinearRegion(\n module_list=module_list,\n periodic_bc=periodic_bc,\n parallel_eval=parallel_eval,\n )\n assert len(self.linear_region) == input_dim\n\n if path:\n assert isinstance(path, (list, torch.Tensor))\n assert len(path) == input_dim\n\n # Set the rest of our MPS attributes\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.bond_dim = bond_dim\n self.feature_dim = feature_dim\n self.periodic_bc = periodic_bc\n self.adaptive_mode = adaptive_mode\n self.label_site = label_site\n self.path = path\n self.use_bias = use_bias\n self.cutoff = cutoff\n self.merge_threshold = merge_threshold\n self.feature_map = None\n\n def forward(self, input_data):\n \"\"\"\n Embed our data and pass it to an MPS with a single output site\n\n Args:\n input_data (Tensor): Input with shape [batch_size, input_dim] or\n [batch_size, input_dim, feature_dim]. In the\n former case, the data points are turned into\n 2D vectors using a default linear feature map.\n\n When using a user-specified path, the size of\n the second tensor mode need not exactly equal\n input_dim, since the path variable is used to\n slice a certain subregion of input_data. This\n can be used to define multiple MPS 'strings',\n which act on different parts of the input.\n \"\"\"\n # For custom paths, rearrange our input into the desired order\n if self.path:\n path_inputs = []\n for site_num in self.path:\n path_inputs.append(input_data[:, site_num])\n input_data = torch.stack(path_inputs, dim=1)\n \n # When MPS itself is used as a trainable embedding of another MPS\n as_trainable_embedding = False\n if len(input_data.shape) == 1:\n as_trainable_embedding = True\n input_data = input_data.view((1, -1))\n\n # Embed our input data before feeding it into our linear region\n input_data = self.embed_input(input_data)\n output = self.linear_region(input_data)\n\n # If we got a tuple as output, then use the last two entries to\n # update our bond dimensions and singular values\n if isinstance(output, tuple):\n output, new_bonds, new_svs = output\n\n assert len(new_bonds) == len(self.bond_list)\n assert len(new_bonds) == len(new_svs)\n for i, bond_dim in enumerate(new_bonds):\n if bond_dim is not None:\n assert new_svs[i] is not None\n self.bond_list[i] = bond_dim\n self.sv_list[i] = new_svs[i]\n\n # When MPS itself is used as a trainable embedding of another MPS\n if as_trainable_embedding:\n output = output.view(-1)\n return output\n\n def embed_input(self, input_data):\n \"\"\"\n Embed pixels of input_data into separate local feature spaces\n\n Args:\n input_data (Tensor): Input with shape [batch_size, input_dim], or\n [batch_size, input_dim, feature_dim]. In the\n latter case, the data is assumed to already\n be embedded, and is returned unchanged.\n\n Returns:\n embedded_data (Tensor): Input embedded into a tensor with shape\n [batch_size, input_dim, feature_dim]\n \"\"\"\n assert len(input_data.shape) in [2, 3]\n assert input_data.size(1) == self.input_dim\n\n # If input already has a 3rd dimension and no feature map is defined, assume that the 3rd dimesion is feature map and return it as is\n if len(input_data.shape) == 3 and self.feature_map is None:\n if input_data.size(2) != self.feature_dim:\n raise ValueError(\n f\"input_data has wrong shape to be unembedded \"\n \"or pre-embedded data (input_data.shape = \"\n f\"{list(input_data.shape)}, feature_dim = {self.feature_dim})\"\n )\n return input_data\n\n # Apply a custom embedding map if it has been defined by the user\n if self.feature_map is not None:\n f_map = self.feature_map\n embedded_data = torch.stack(\n [torch.stack([f_map(x) for x in batch]) for batch in input_data]\n )\n\n # Make sure our embedded input has the desired size\n assert embedded_data.shape == torch.Size(\n [input_data.size(0), self.input_dim, self.feature_dim]\n )\n\n # Otherwise, use a simple linear embedding map with feature_dim = 2\n else:\n if self.feature_dim != 2:\n raise RuntimeError(\n f\"self.feature_dim = {self.feature_dim}, \"\n \"but default feature_map requires self.feature_dim = 2\"\n )\n\n embedded_data = torch.stack([input_data, 1 - input_data], dim=2)\n\n return embedded_data\n\n def register_feature_map(self, feature_map):\n \"\"\"\n Register a custom feature map to be used for embedding input data\n\n Args:\n feature_map (function): Takes a single scalar input datum and\n returns an embedded representation of the\n image. The output size of the function must\n match self.feature_dim. If feature_map=None,\n then the feature map will be reset to a\n simple default linear embedding\n \"\"\"\n # TODO: diabling the test for now. Should come back to this\n \"\"\"\n if feature_map is not None:\n # Test to make sure feature_map outputs vector of proper size\n out_shape = feature_map(torch.tensor(0)).shape\n needed_shape = torch.Size([self.feature_dim])\n if out_shape != needed_shape:\n raise ValueError(\n \"Given feature_map returns values of size \"\n f\"{list(out_shape)}, but should return \"\n f\"values of size {list(needed_shape)}\"\n )\n \"\"\"\n\n self.feature_map = feature_map\n\n def core_len(self):\n \"\"\"\n Returns the number of cores, which is at least the required input size\n \"\"\"\n return self.linear_region.core_len()\n\n def __len__(self):\n \"\"\"\n Returns the number of input sites, which equals the input size\n \"\"\"\n return self.input_dim\n\n\nclass LinearRegion(nn.Module):\n \"\"\"\n List of modules which feeds input to each module and returns reduced output\n \"\"\"\n\n def __init__(\n self, module_list, periodic_bc=False, parallel_eval=False, module_states=None\n ):\n # Check that module_list is a list whose entries are Pytorch modules\n if not isinstance(module_list, list) or module_list is []:\n raise ValueError(\"Input to LinearRegion must be nonempty list\")\n for i, item in enumerate(module_list):\n if not isinstance(item, nn.Module):\n raise ValueError(\n \"Input items to LinearRegion must be PyTorch \"\n f\"Module instances, but item {i} is not\"\n )\n super().__init__()\n\n # Wrap as a ModuleList for proper parameter registration\n self.module_list = nn.ModuleList(module_list)\n self.periodic_bc = periodic_bc\n self.parallel_eval = parallel_eval\n\n def forward(self, input_data):\n \"\"\"\n Contract input with list of MPS cores and return result as contractable\n\n Args:\n input_data (Tensor): Input with shape [batch_size, input_dim,\n feature_dim]\n \"\"\"\n # Check that input_data has the correct shape\n assert len(input_data.shape) == 3\n assert input_data.size(1) == len(self)\n periodic_bc = self.periodic_bc\n parallel_eval = self.parallel_eval\n lin_bonds = [\"l\", \"r\"]\n\n # Whether to move intermediate vectors to a GPU (fixes Issue #8)\n to_cuda = input_data.is_cuda\n device = f\"cuda:{input_data.get_device()}\" if to_cuda else \"cpu\"\n\n # For each module, pull out the number of pixels needed and call that\n # module's forward() method, putting the result in contractable_list\n ind = 0\n contractable_list = []\n for module in self.module_list:\n mod_len = len(module)\n if mod_len == 1:\n mod_input = input_data[:, ind]\n else:\n mod_input = input_data[:, ind : (ind + mod_len)]\n ind += mod_len\n\n contractable_list.append(module(mod_input))\n\n # For periodic boundary conditions, reduce contractable_list and\n # trace over the left and right indices to get our output\n if periodic_bc:\n contractable_list = ContractableList(contractable_list)\n contractable = contractable_list.reduce(parallel_eval=True)\n\n # Unpack the output (atomic) contractable\n tensor, bond_str = contractable.tensor, contractable.bond_str\n assert all(c in bond_str for c in lin_bonds)\n\n # Build einsum string for the trace of tensor\n in_str, out_str = \"\", \"\"\n for c in bond_str:\n if c in lin_bonds:\n in_str += \"l\"\n else:\n in_str += c\n out_str += c\n ein_str = in_str + \"->\" + out_str\n\n # Return the trace over left and right indices\n return torch.einsum(ein_str, [tensor])\n\n # For open boundary conditions, add dummy edge vectors to\n # contractable_list and reduce everything to get our output\n else:\n # Get the dimension of left and right bond indices\n end_items = [contractable_list[i] for i in [0, -1]]\n bond_strs = [item.bond_str for item in end_items]\n bond_inds = [bs.index(c) for (bs, c) in zip(bond_strs, lin_bonds)]\n bond_dims = [\n item.tensor.size(ind) for (item, ind) in zip(end_items, bond_inds)\n ]\n\n # Build dummy end vectors and insert them at the ends of our list\n end_vecs = [torch.zeros(dim).to(device) for dim in bond_dims]\n\n for vec in end_vecs:\n vec[0] = 1\n contractable_list.insert(0, EdgeVec(end_vecs[0], is_left_vec=True))\n contractable_list.append(EdgeVec(end_vecs[1], is_left_vec=False))\n\n # Multiply together everything in contractable_list\n contractable_list = ContractableList(contractable_list)\n output = contractable_list.reduce(parallel_eval=parallel_eval)\n\n return output.tensor\n\n def core_len(self):\n \"\"\"\n Returns the number of cores, which is at least the required input size\n \"\"\"\n return sum([module.core_len() for module in self.module_list])\n\n def __len__(self):\n \"\"\"\n Returns the number of input sites, which is the required input size\n \"\"\"\n return sum([len(module) for module in self.module_list])\n\n\nclass MergedLinearRegion(LinearRegion):\n \"\"\"\n Dynamic variant of LinearRegion that periodically rearranges its submodules\n \"\"\"\n\n def __init__(\n self,\n module_list,\n periodic_bc=False,\n parallel_eval=False,\n cutoff=1e-10,\n merge_threshold=2000,\n ):\n # Initialize a LinearRegion with our given module_list\n super().__init__(module_list, periodic_bc, parallel_eval)\n\n # Initialize attributes self.module_list_0 and self.module_list_1\n # using the unmerged self.module_list, then redefine the latter in\n # terms of one of the former lists\n self.offset = 0\n self._merge(offset=self.offset)\n self._merge(offset=(self.offset + 1) % 2)\n self.module_list = getattr(self, f\"module_list_{self.offset}\")\n\n # Initialize variables used during switching\n self.input_counter = 0\n self.merge_threshold = merge_threshold\n self.cutoff = cutoff\n\n def forward(self, input_data):\n \"\"\"\n Contract input with list of MPS cores and return result as contractable\n\n MergedLinearRegion keeps an input counter of the number of inputs, and\n when this exceeds its merge threshold, triggers an unmerging and\n remerging of its parameter tensors.\n\n Args:\n input_data (Tensor): Input with shape [batch_size, input_dim,\n feature_dim]\n \"\"\"\n # If we've hit our threshold, flip the merge state of our tensors\n if self.input_counter >= self.merge_threshold:\n bond_list, sv_list = self._unmerge(cutoff=self.cutoff)\n self.offset = (self.offset + 1) % 2\n self._merge(offset=self.offset)\n self.input_counter -= self.merge_threshold\n\n # Point self.module_list to the appropriate merged module\n self.module_list = getattr(self, f\"module_list_{self.offset}\")\n else:\n bond_list, sv_list = None, None\n\n # Increment our counter and call the LinearRegion's forward method\n self.input_counter += input_data.size(0)\n output = super().forward(input_data)\n\n # If we flipped our merge state, then return the bond_list and output\n if bond_list:\n return output, bond_list, sv_list\n else:\n return output\n\n @torch.no_grad()\n def _merge(self, offset):\n \"\"\"\n Convert unmerged modules in self.module_list to merged counterparts\n\n Calling _merge (or _unmerge) directly can cause undefined behavior,\n but see MergedLinearRegion.forward for intended use\n\n This proceeds by first merging all unmerged cores internally, then\n merging lone cores when possible during a second sweep\n \"\"\"\n assert offset in [0, 1]\n\n unmerged_list = self.module_list\n\n # Merge each core internally and add the results to midway_list\n site_num = offset\n merged_list = []\n for core in unmerged_list:\n assert not isinstance(core, MergedInput)\n assert not isinstance(core, MergedOutput)\n\n # Apply internal merging routine if our core supports it\n if hasattr(core, \"_merge\"):\n merged_list.extend(core._merge(offset=site_num % 2))\n else:\n merged_list.append(core)\n\n site_num += core.core_len()\n\n # Merge pairs of cores when possible (currently only with\n # InputSites), making sure to respect the offset for merging.\n while True:\n mod_num, site_num = 0, 0\n combined_list = []\n\n while mod_num < len(merged_list) - 1:\n left_core, right_core = merged_list[mod_num : mod_num + 2]\n new_core = self.combine(left_core, right_core, merging=True)\n\n # If cores aren't combinable, move our sliding window by 1\n if new_core is None or offset != site_num % 2:\n combined_list.append(left_core)\n mod_num += 1\n site_num += left_core.core_len()\n\n # If we get something new, move to the next distinct pair\n else:\n assert (\n new_core.core_len()\n == left_core.core_len() + right_core.core_len()\n )\n combined_list.append(new_core)\n mod_num += 2\n site_num += new_core.core_len()\n\n # Add the last core if there's nothing to merge it with\n if mod_num == len(merged_list) - 1:\n combined_list.append(merged_list[mod_num])\n mod_num += 1\n\n # We're finished when unmerged_list remains unchanged\n if len(combined_list) == len(merged_list):\n break\n else:\n merged_list = combined_list\n\n # Finally, update the appropriate merged module list\n list_name = f\"module_list_{offset}\"\n # If the merged module list hasn't been set yet, initialize it\n if not hasattr(self, list_name):\n setattr(self, list_name, nn.ModuleList(merged_list))\n\n # Otherwise, do an in-place update so that all tensors remain\n # properly registered with whatever optimizer we use\n else:\n module_list = getattr(self, list_name)\n assert len(module_list) == len(merged_list)\n for i in range(len(module_list)):\n assert module_list[i].tensor.shape == merged_list[i].tensor.shape\n module_list[i].tensor[:] = merged_list[i].tensor\n\n @torch.no_grad()\n def _unmerge(self, cutoff=1e-10):\n \"\"\"\n Convert merged modules to unmerged counterparts\n\n Calling _unmerge (or _merge) directly can cause undefined behavior,\n but see MergedLinearRegion.forward for intended use\n\n This proceeds by first unmerging all merged cores internally, then\n combining lone cores where possible\n \"\"\"\n list_name = f\"module_list_{self.offset}\"\n merged_list = getattr(self, list_name)\n\n # Unmerge each core internally and add results to unmerged_list\n unmerged_list, bond_list, sv_list = [], [None], [None]\n for core in merged_list:\n\n # Apply internal unmerging routine if our core supports it\n if hasattr(core, \"_unmerge\"):\n new_cores, new_bonds, new_svs = core._unmerge(cutoff)\n unmerged_list.extend(new_cores)\n bond_list.extend(new_bonds[1:])\n sv_list.extend(new_svs[1:])\n else:\n assert not isinstance(core, InputRegion)\n unmerged_list.append(core)\n bond_list.append(None)\n sv_list.append(None)\n\n # Combine all combinable pairs of cores. This occurs in several\n # passes, and for now acts nontrivially only on InputSite instances\n while True:\n mod_num = 0\n combined_list = []\n\n while mod_num < len(unmerged_list) - 1:\n left_core, right_core = unmerged_list[mod_num : mod_num + 2]\n new_core = self.combine(left_core, right_core, merging=False)\n\n # If cores aren't combinable, move our sliding window by 1\n if new_core is None:\n combined_list.append(left_core)\n mod_num += 1\n\n # If we get something new, move to the next distinct pair\n else:\n combined_list.append(new_core)\n mod_num += 2\n\n # Add the last core if there's nothing to combine it with\n if mod_num == len(unmerged_list) - 1:\n combined_list.append(unmerged_list[mod_num])\n mod_num += 1\n\n # We're finished when unmerged_list remains unchanged\n if len(combined_list) == len(unmerged_list):\n break\n else:\n unmerged_list = combined_list\n\n # Find the average (log) norm of all of our cores\n log_norms = []\n for core in unmerged_list:\n log_norms.append([torch.log(norm) for norm in core.get_norm()])\n log_scale = sum([sum(ns) for ns in log_norms])\n log_scale /= sum([len(ns) for ns in log_norms])\n\n # Now rescale all cores so that their norms are roughly equal\n scales = [[torch.exp(log_scale - n) for n in ns] for ns in log_norms]\n for core, these_scales in zip(unmerged_list, scales):\n core.rescale_norm(these_scales)\n\n # Add our unmerged module list as a new attribute and return\n # the updated bond dimensions\n self.module_list = nn.ModuleList(unmerged_list)\n return bond_list, sv_list\n\n def combine(self, left_core, right_core, merging):\n \"\"\"\n Combine a pair of cores into a new core using context-dependent rules\n\n Depending on the types of left_core and right_core, along with whether\n we're currently merging (merging=True) or unmerging (merging=False),\n either return a new core, or None if no rule exists for this context\n \"\"\"\n\n # Combine an OutputSite with a stray InputSite, return a MergedOutput\n if merging and (\n (isinstance(left_core, OutputSite) and isinstance(right_core, InputSite))\n or (isinstance(left_core, InputSite) and isinstance(right_core, OutputSite))\n ):\n\n left_site = isinstance(left_core, InputSite)\n if left_site:\n new_tensor = torch.einsum(\n \"lui,our->olri\", [left_core.tensor, right_core.tensor]\n )\n else:\n new_tensor = torch.einsum(\n \"olu,uri->olri\", [left_core.tensor, right_core.tensor]\n )\n return MergedOutput(new_tensor, left_output=(not left_site))\n\n # Combine an InputRegion with a stray InputSite, return an InputRegion\n elif not merging and (\n (isinstance(left_core, InputRegion) and isinstance(right_core, InputSite))\n or (\n isinstance(left_core, InputSite) and isinstance(right_core, InputRegion)\n )\n ):\n\n left_site = isinstance(left_core, InputSite)\n if left_site:\n left_tensor = left_core.tensor.unsqueeze(0)\n right_tensor = right_core.tensor\n else:\n left_tensor = left_core.tensor\n right_tensor = right_core.tensor.unsqueeze(0)\n\n assert left_tensor.shape[1:] == right_tensor.shape[1:]\n new_tensor = torch.cat([left_tensor, right_tensor])\n\n return InputRegion(new_tensor)\n\n # If this situation doesn't belong to the above cases, return None\n else:\n return None\n\n def core_len(self):\n \"\"\"\n Returns the number of cores, which is at least the required input size\n \"\"\"\n return sum([module.core_len() for module in self.module_list])\n\n def __len__(self):\n \"\"\"\n Returns the number of input sites, which is the required input size\n \"\"\"\n return sum([len(module) for module in self.module_list])\n\n\nclass InputRegion(nn.Module):\n \"\"\"\n Contiguous region of MPS input cores, associated with bond_str = 'slri'\n \"\"\"\n\n def __init__(\n self, tensor, use_bias=True, fixed_bias=True, bias_mat=None, ephemeral=False\n ):\n super().__init__()\n\n # Make sure tensor has correct size and the component mats are square\n assert len(tensor.shape) == 4\n assert tensor.size(1) == tensor.size(2)\n bond_dim = tensor.size(1)\n\n # If we are using bias matrices, set those up here\n if use_bias:\n assert bias_mat is None or isinstance(bias_mat, torch.Tensor)\n bias_mat = (\n torch.eye(bond_dim).unsqueeze(0) if bias_mat is None else bias_mat\n )\n\n bias_modes = len(list(bias_mat.shape))\n assert bias_modes in [2, 3]\n if bias_modes == 2:\n bias_mat = bias_mat.unsqueeze(0)\n\n # Register our tensors as a Pytorch Parameter or Tensor\n if ephemeral:\n self.register_buffer(name=\"tensor\", tensor=tensor.contiguous())\n self.register_buffer(name=\"bias_mat\", tensor=bias_mat)\n else:\n self.register_parameter(\n name=\"tensor\", param=nn.Parameter(tensor.contiguous())\n )\n if fixed_bias:\n self.register_buffer(name=\"bias_mat\", tensor=bias_mat)\n else:\n self.register_parameter(name=\"bias_mat\", param=nn.Parameter(bias_mat))\n\n self.use_bias = use_bias\n self.fixed_bias = fixed_bias\n\n def forward(self, input_data):\n \"\"\"\n Contract input with MPS cores and return result as a MatRegion\n\n Args:\n input_data (Tensor): Input with shape [batch_size, input_dim,\n feature_dim]\n \"\"\"\n # Check that input_data has the correct shape\n tensor = self.tensor\n assert len(input_data.shape) == 3\n assert input_data.size(1) == len(self)\n assert input_data.size(2) == tensor.size(3)\n\n # Contract the input with our core tensor\n mats = torch.einsum(\"slri,bsi->bslr\", [tensor, input_data])\n\n # If we're using bias matrices, add those here\n if self.use_bias:\n bias_mat = self.bias_mat.unsqueeze(0)\n mats = mats + bias_mat.expand_as(mats)\n\n return MatRegion(mats)\n\n def _merge(self, offset):\n \"\"\"\n Merge all pairs of neighboring cores and return a new list of cores\n\n offset is either 0 or 1, which gives the first core at which we start\n our merging. Depending on the length of our InputRegion, the output of\n merge may have 1, 2, or 3 entries, with the majority of sites ending in\n a MergedInput instance\n \"\"\"\n assert offset in [0, 1]\n num_sites = self.core_len()\n parity = num_sites % 2\n\n # Cases with empty tensors might arise in recursion below\n if num_sites == 0:\n return [None]\n\n # Simplify the problem into one where offset=0 and num_sites is even\n if (offset, parity) == (1, 1):\n out_list = [self[0], self[1:]._merge(offset=0)[0]]\n elif (offset, parity) == (1, 0):\n out_list = [self[0], self[1:-1]._merge(offset=0)[0], self[-1]]\n elif (offset, parity) == (0, 1):\n out_list = [self[:-1]._merge(offset=0)[0], self[-1]]\n\n # The main case of interest, with no offset and an even number of sites\n else:\n tensor = self.tensor\n even_cores, odd_cores = tensor[0::2], tensor[1::2]\n assert len(even_cores) == len(odd_cores)\n\n # Multiply all pairs of cores, keeping inputs separate\n merged_cores = torch.einsum(\"slui,surj->slrij\", [even_cores, odd_cores])\n out_list = [MergedInput(merged_cores)]\n\n # Remove empty MergedInputs, which appear in very small InputRegions\n return [x for x in out_list if x is not None]\n\n def __getitem__(self, key):\n \"\"\"\n Returns an InputRegion instance sliced along the site index\n \"\"\"\n assert isinstance(key, int) or isinstance(key, slice)\n\n if isinstance(key, slice):\n return InputRegion(self.tensor[key])\n else:\n return InputSite(self.tensor[key])\n\n def get_norm(self):\n \"\"\"\n Returns list of the norms of each core in InputRegion\n \"\"\"\n return [torch.norm(core) for core in self.tensor]\n\n @torch.no_grad()\n def rescale_norm(self, scale_list):\n \"\"\"\n Rescales the norm of each core by an amount specified in scale_list\n\n For the i'th tensor defining a core in InputRegion, we rescale as\n tensor_i <- scale_i * tensor_i, where scale_i = scale_list[i]\n \"\"\"\n assert len(scale_list) == len(self.tensor)\n\n for core, scale in zip(self.tensor, scale_list):\n core *= scale\n\n def core_len(self):\n return len(self)\n\n def __len__(self):\n return self.tensor.size(0)\n\n\nclass MergedInput(nn.Module):\n \"\"\"\n Contiguous region of merged MPS cores, each taking in a pair of input data\n\n Since MergedInput arises after contracting together existing input cores,\n a merged input tensor is required for initialization\n \"\"\"\n\n def __init__(self, tensor):\n # Check that our input tensor has the correct shape\n # bond_str = \"slrij\"\n shape = tensor.shape\n assert len(shape) == 5\n assert shape[1] == shape[2]\n assert shape[3] == shape[4]\n\n super().__init__()\n\n # Register our tensor as a Pytorch Parameter\n self.register_parameter(name=\"tensor\", param=nn.Parameter(tensor.contiguous()))\n\n def forward(self, input_data):\n \"\"\"\n Contract input with merged MPS cores and return result as a MatRegion\n\n Args:\n input_data (Tensor): Input with shape [batch_size, input_dim,\n feature_dim], where input_dim must be even\n (each merged core takes 2 inputs)\n \"\"\"\n # Check that input_data has the correct shape\n tensor = self.tensor\n assert len(input_data.shape) == 3\n assert input_data.size(1) == len(self)\n assert input_data.size(2) == tensor.size(3)\n assert input_data.size(1) % 2 == 0\n\n # Divide input_data into inputs living on even and on odd sites\n inputs = [input_data[:, 0::2], input_data[:, 1::2]]\n\n # Contract the odd (right-most) and even inputs with merged cores\n tensor = torch.einsum(\"slrij,bsj->bslri\", [tensor, inputs[1]])\n mats = torch.einsum(\"bslri,bsi->bslr\", [tensor, inputs[0]])\n\n return MatRegion(mats)\n\n def _unmerge(self, cutoff=1e-10):\n \"\"\"\n Separate the cores in our MergedInput and return an InputRegion\n\n The length of the resultant InputRegion will be identical to our\n original MergedInput (same number of inputs), but its core_len will\n be doubled (twice as many individual cores)\n \"\"\"\n # bond_str = \"slrij\"\n tensor = self.tensor\n svd_string = \"lrij->lui,urj\"\n max_D = tensor.size(1)\n\n # Split every one of the cores into two and add them both to core_list\n core_list, bond_list, sv_list = [], [None], [None]\n for merged_core in tensor:\n sv_vec = torch.empty(max_D)\n left_core, right_core, bond_dim = svd_flex(\n merged_core, svd_string, max_D, cutoff, sv_vec=sv_vec\n )\n\n core_list += [left_core, right_core]\n bond_list += [bond_dim, None]\n sv_list += [sv_vec, None]\n\n # Collate the split cores into one tensor and return as an InputRegion\n tensor = torch.stack(core_list)\n return [InputRegion(tensor)], bond_list, sv_list\n\n def get_norm(self):\n \"\"\"\n Returns list of the norm of each core in MergedInput\n \"\"\"\n return [torch.norm(core) for core in self.tensor]\n\n @torch.no_grad()\n def rescale_norm(self, scale_list):\n \"\"\"\n Rescales the norm of each core by an amount specified in scale_list\n\n For the i'th tensor defining a core in MergedInput, we rescale as\n tensor_i <- scale_i * tensor_i, where scale_i = scale_list[i]\n \"\"\"\n assert len(scale_list) == len(self.tensor)\n\n for core, scale in zip(self.tensor, scale_list):\n core *= scale\n\n def core_len(self):\n return len(self)\n\n def __len__(self):\n \"\"\"\n Returns the number of input sites, which is twice the number of cores\n \"\"\"\n return 2 * self.tensor.size(0)\n\n\nclass InputSite(nn.Module):\n \"\"\"\n A single MPS core which takes in a single input datum, bond_str = 'lri'\n \"\"\"\n\n def __init__(self, tensor):\n super().__init__()\n # Register our tensor as a Pytorch Parameter\n self.register_parameter(name=\"tensor\", param=nn.Parameter(tensor.contiguous()))\n\n def forward(self, input_data):\n \"\"\"\n Contract input with MPS core and return result as a SingleMat\n\n Args:\n input_data (Tensor): Input with shape [batch_size, feature_dim]\n \"\"\"\n # Check that input_data has the correct shape\n tensor = self.tensor\n assert len(input_data.shape) == 2\n assert input_data.size(1) == tensor.size(2)\n\n # Contract the input with our core tensor\n mat = torch.einsum(\"lri,bi->blr\", [tensor, input_data])\n\n return SingleMat(mat)\n\n def get_norm(self):\n \"\"\"\n Returns the norm of our core tensor, wrapped as a singleton list\n \"\"\"\n return [torch.norm(self.tensor)]\n\n @torch.no_grad()\n def rescale_norm(self, scale):\n \"\"\"\n Rescales the norm of our core by a factor of input `scale`\n \"\"\"\n if isinstance(scale, list):\n assert len(scale) == 1\n scale = scale[0]\n\n self.tensor *= scale\n\n def core_len(self):\n return 1\n\n def __len__(self):\n return 1\n\n\nclass OutputSite(nn.Module):\n \"\"\"\n A single MPS core with no input and a single output index, bond_str = 'olr'\n \"\"\"\n\n def __init__(self, tensor):\n super().__init__()\n # Register our tensor as a Pytorch Parameter\n self.register_parameter(name=\"tensor\", param=nn.Parameter(tensor.contiguous()))\n\n def forward(self, input_data):\n \"\"\"\n Return the OutputSite wrapped as an OutputCore contractable\n \"\"\"\n return OutputCore(self.tensor)\n\n def get_norm(self):\n \"\"\"\n Returns the norm of our core tensor, wrapped as a singleton list\n \"\"\"\n return [torch.norm(self.tensor)]\n\n @torch.no_grad()\n def rescale_norm(self, scale):\n \"\"\"\n Rescales the norm of our core by a factor of input `scale`\n \"\"\"\n if isinstance(scale, list):\n assert len(scale) == 1\n scale = scale[0]\n\n self.tensor *= scale\n\n def core_len(self):\n return 1\n\n def __len__(self):\n return 0\n\n\nclass MergedOutput(nn.Module):\n \"\"\"\n Merged MPS core taking in one input datum and returning an output vector\n\n Since MergedOutput arises after contracting together an existing input and\n output core, an already-merged tensor is required for initialization\n\n Args:\n tensor (Tensor): Value that our merged core is initialized to\n left_output (bool): Specifies if the output core is on the left side of\n the input core (True), or on the right (False)\n \"\"\"\n\n def __init__(self, tensor, left_output):\n # Check that our input tensor has the correct shape\n # bond_str = \"olri\"\n assert len(tensor.shape) == 4\n super().__init__()\n\n # Register our tensor as a Pytorch Parameter\n self.register_parameter(name=\"tensor\", param=nn.Parameter(tensor.contiguous()))\n self.left_output = left_output\n\n def forward(self, input_data):\n \"\"\"\n Contract input with input index of core and return an OutputCore\n\n Args:\n input_data (Tensor): Input with shape [batch_size, feature_dim]\n \"\"\"\n # Check that input_data has the correct shape\n tensor = self.tensor\n assert len(input_data.shape) == 2\n assert input_data.size(1) == tensor.size(3)\n\n # Contract the input with our core tensor\n tensor = torch.einsum(\"olri,bi->bolr\", [tensor, input_data])\n\n return OutputCore(tensor)\n\n def _unmerge(self, cutoff=1e-10):\n \"\"\"\n Split our MergedOutput into an OutputSite and an InputSite\n\n The non-zero entries of our tensors are dynamically sized according to\n the SVD cutoff, but will generally be padded with zeros to give the\n new index a regular size.\n \"\"\"\n # bond_str = \"olri\"\n tensor = self.tensor\n left_output = self.left_output\n if left_output:\n svd_string = \"olri->olu,uri\"\n max_D = tensor.size(2)\n sv_vec = torch.empty(max_D)\n\n output_core, input_core, bond_dim = svd_flex(\n tensor, svd_string, max_D, cutoff, sv_vec=sv_vec\n )\n return (\n [OutputSite(output_core), InputSite(input_core)],\n [None, bond_dim, None],\n [None, sv_vec, None],\n )\n\n else:\n svd_string = \"olri->our,lui\"\n max_D = tensor.size(1)\n sv_vec = torch.empty(max_D)\n\n output_core, input_core, bond_dim = svd_flex(\n tensor, svd_string, max_D, cutoff, sv_vec=sv_vec\n )\n return (\n [InputSite(input_core), OutputSite(output_core)],\n [None, bond_dim, None],\n [None, sv_vec, None],\n )\n\n def get_norm(self):\n \"\"\"\n Returns the norm of our core tensor, wrapped as a singleton list\n \"\"\"\n return [torch.norm(self.tensor)]\n\n @torch.no_grad()\n def rescale_norm(self, scale):\n \"\"\"\n Rescales the norm of our core by a factor of input `scale`\n \"\"\"\n if isinstance(scale, list):\n assert len(scale) == 1\n scale = scale[0]\n\n self.tensor *= scale\n\n def core_len(self):\n return 2\n\n def __len__(self):\n return 1\n\n\nclass InitialVector(nn.Module):\n \"\"\"\n Vector of ones and zeros to act as initial vector within the MPS\n\n By default the initial vector is chosen to be all ones, but if fill_dim is\n specified then only the first fill_dim entries are set to one, with the\n rest zero.\n\n If fixed_vec is False, then the initial vector will be registered as a\n trainable model parameter.\n \"\"\"\n\n def __init__(self, bond_dim, fill_dim=None, fixed_vec=True, is_left_vec=True):\n super().__init__()\n\n vec = torch.ones(bond_dim)\n if fill_dim is not None:\n assert fill_dim >= 0 and fill_dim <= bond_dim\n vec[fill_dim:] = 0\n\n if fixed_vec:\n vec.requires_grad = False\n self.register_buffer(name=\"vec\", tensor=vec)\n else:\n vec.requires_grad = True\n self.register_parameter(name=\"vec\", param=nn.Parameter(vec))\n\n assert isinstance(is_left_vec, bool)\n self.is_left_vec = is_left_vec\n\n def forward(self):\n \"\"\"\n Return our initial vector wrapped as an EdgeVec contractable\n \"\"\"\n return EdgeVec(self.vec, self.is_left_vec)\n\n def core_len(self):\n return 1\n\n def __len__(self):\n return 0\n\n\nclass TerminalOutput(nn.Module):\n \"\"\"\n Output matrix at end of chain to transmute virtual state into output vector\n\n By default, a fixed rectangular identity matrix with shape\n [bond_dim, output_dim] will be used as a state transducer. If fixed_mat is\n False, then the matrix will be registered as a trainable model parameter.\n \"\"\"\n\n def __init__(self, bond_dim, output_dim, fixed_mat=False, is_left_mat=False):\n super().__init__()\n\n # I don't have a nice initialization scheme for a non-injective fixed\n # state transducer, so just throw an error if that's needed\n if fixed_mat and output_dim > bond_dim:\n raise ValueError(\n \"With fixed_mat=True, TerminalOutput currently \"\n \"only supports initialization for bond_dim >= \"\n \"output_dim, but here bond_dim=\"\n f\"{bond_dim} and output_dim={output_dim}\"\n )\n\n # Initialize the matrix and register it appropriately\n mat = torch.eye(bond_dim, output_dim)\n if fixed_mat:\n mat.requires_grad = False\n self.register_buffer(name=\"mat\", tensor=mat)\n else:\n # Add some noise to help with training\n mat = mat + torch.randn_like(mat) / bond_dim\n\n mat.requires_grad = True\n self.register_parameter(name=\"mat\", param=nn.Parameter(mat))\n\n assert isinstance(is_left_mat, bool)\n self.is_left_mat = is_left_mat\n\n def forward(self):\n \"\"\"\n Return our terminal matrix wrapped as an OutputMat contractable\n \"\"\"\n return OutputMat(self.mat, self.is_left_mat)\n\n def core_len(self):\n return 1\n\n def __len__(self):\n return 0\n"
] | [
[
"torch.randn_like",
"torch.norm",
"torch.ones",
"torch.empty",
"torch.nn.Parameter",
"torch.cat",
"torch.zeros",
"torch.einsum",
"torch.nn.ModuleList",
"torch.eye",
"torch.tensor",
"torch.exp",
"torch.no_grad",
"torch.log",
"torch.stack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
atultherajput/machine-learning | [
"7bb6de78f8bc482bf74a115c3db009011c38c454"
] | [
"naive_bayes/nb_author_id.py"
] | [
"#!/usr/bin/env python3\n\n\"\"\"\n\n Use a Naive Bayes Classifier to identify emails by their authors\n\n authors and labels:\n Sara has label 0\n Chris has label 1\n\"\"\"\n\nimport sys\nfrom time import time\nsys.path.append(\"../libraries/tools\")\nfrom email_preprocess import preprocess\n\n\n### features_train and features_test are the features for the training\n### and testing datasets, respectively\n### labels_train and labels_test are the corresponding item labels\nfeatures_train, features_test, labels_train, labels_test = preprocess()\n\n\n\n\n#########################################################\n### code goes here ###\n\nfrom sklearn.naive_bayes import GaussianNB\nclf = GaussianNB()\n\nt0 = time()\nclf.fit(features_train, labels_train)\nprint (\"Training time:\", round(time()-t0, 3), \"sec\")\n\nt0 = time()\npred = clf.predict(features_test)\nprint (\"Prediction time:\", round(time()-t0, 3), \"sec\")\n\nfrom sklearn.metrics import accuracy_score\nprint (\"Accuracy:\", accuracy_score(pred, labels_test))\n\n#########################################################\n\n\n"
] | [
[
"sklearn.naive_bayes.GaussianNB",
"sklearn.metrics.accuracy_score"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
amckenna41/pySAR | [
"f5f5dea252c04bcf40ed102e1353af9cedbd75a0"
] | [
"tests/test_proDSP.py"
] | [
"################################################################################\n################# ProDSP Module Tests #################\n################################################################################\n\nimport os\nimport sys\nimport pandas as pd\nimport numpy as np\nimport pySAR.aaindex as aaindex\nimport pySAR.proDSP as proDSP_\nimport pySAR.pySAR as pysar\nimport pySAR\nimport unittest\nimport requests\nimport urllib.request\n\nclass ProDSPTests(unittest.TestCase):\n\n def setUp(self):\n \"\"\" Import the 4 test datasets used for testing the proDSP methods. \"\"\"\n\n try:\n self.test_dataset1 = pd.read_csv(os.path.join('tests','test_data','test_thermostability.txt'),sep=\",\", header=0)\n except:\n raise IOError('Error reading in test_dataset1.')\n try:\n self.test_dataset2 = pd.read_csv(os.path.join('tests','test_data','test_enantioselectivity.txt'),sep=\",\", header=0)\n except:\n raise IOError('Error reading in test_dataset2')\n try:\n self.test_dataset3 = pd.read_csv(os.path.join('tests','test_data','test_localization.txt'),sep=\",\", header=0)\n except:\n raise IOError('Error reading in test_dataset3')\n try:\n self.test_dataset4 = pd.read_csv(os.path.join('tests','test_data','test_absorption.txt'),sep=\",\", header=0)\n except:\n raise IOError('Error reading in test_dataset4')\n\n self.aaindex = aaindex.AAIndex()\n\n self.pySAR = pysar.PySAR(algorithm=\"PLSReg\",dataset=os.path.join('tests','test_data','test_enantioselectivity.txt'), activity=\"e-value\")\n\n def test_proDSP(self):\n #test general stuff like the input parameters etc\n\n test_aaindices1 = \"BURA740101\"\n test_aaindices2 = \"COHE430101\"\n test_aaindices3 = [\"FAUJ880108\",\"NAKH900102\",\"YUTK870103\"]\n#1.)\n encoded_seq1 = self.pySAR.get_aai_enoding(test_aaindices1)\n proDsp = proDSP_.ProDSP(encoded_seq1)\n self.assertEqual(proDsp.spectrum, \"power\")\n self.assertEqual(proDsp.window_type, \"hamming\")\n self.assertIsInstance(proDsp.window, np.ndarray)\n self.assertIsNone(proDsp.filter_)\n self.assertEqual(proDsp.encoded_sequences.shape, (self.pySAR.num_seqs,self.pySAR.seq_len))\n self.assertEqual(proDsp.num_seqs, self.pySAR.num_seqs)\n self.assertEqual(proDsp.signal_len, self.pySAR.seq_len)\n self.assertEqual(proDsp.fft_power.shape, encoded_seq1.shape)\n self.assertTrue(proDsp.fft_power.dtype, 'float64')\n self.assertEqual(proDsp.fft_real.shape, encoded_seq1.shape)\n self.assertEqual(proDsp.fft_real.dtype, 'float64')\n self.assertEqual(proDsp.fft_abs.shape, encoded_seq1.shape)\n self.assertEqual(proDsp.fft_abs.dtype, 'float64')\n self.assertEqual(proDsp.fft_imag.shape, encoded_seq1.shape)\n self.assertEqual(proDsp.fft_imag.dtype, 'float64')\n self.assertTrue(proDsp.spectrum_encoding.any() == proDsp.fft_power.any())\n self.assertEqual(proDsp.fft_freqs.shape,encoded_seq1.shape)\n#2.)\n proDsp = proDSP_.ProDSP(encoded_seq1, window=\"notawindow\")\n self.assertEqual(proDsp.window, 1)\n#3.)\n with(self.assertRaises(ValueError)):\n proDsp = proDSP_.ProDSP(encoded_seq1, spectrum=\"blahblahblah\")\n\n with(self.assertRaises(ValueError)):\n proDsp = proDSP_.ProDSP(encoded_seq1, spectrum=None)\n#4.)\n proDsp = proDSP_.ProDSP(encoded_seq1, filter_=\"blahblahblah\")\n self.assertEqual(proDsp.filter_, \"\")\n#5.)\n #test window closeness function\n proDsp = proDSP_.ProDSP(encoded_seq1, window = \"hamm\")\n self.assertEqual(proDsp.window_type, \"hamming\")\n proDsp = proDSP_.ProDSP(encoded_seq1, window = \"bart\")\n self.assertEqual(proDsp.window_type, \"bartlett\")\n proDsp = proDSP_.ProDSP(encoded_seq1, window = \"gausi\")\n self.assertEqual(proDsp.window_type, \"gaussian\")\n#6.)\n proDSP = proDSP_.ProDSP(encoded_seq1, spectrum = \"absolute\")\n self.assertEqual(proDSP.spectrum, \"absolute\")\n proDSP = proDSP_.ProDSP(encoded_seq1, spectrum = \"imaginary\")\n self.assertEqual(proDSP.spectrum, \"imaginary\")\n\n self.assertEqual(proDsp.window_type, \"gaussian\")\n#7.)\n proDSP = proDSP_.ProDSP(encoded_seq1, filter_ = \"savgol\")\n self.assertEqual(proDSP.filter_, \"savgol\")\n\n def test_preprocessing(self):\n \"\"\" Testing preprocessing functionality of proDSP class. \"\"\"\n\n test_aaindices1 = \"COHE430101\"\n#1.)\n encoded_seq1 = self.pySAR.get_aai_enoding(test_aaindices1)\n proDsp = proDSP_.ProDSP(encoded_seq1)\n proDsp.pre_processing()\n self.assertTrue(np.all((proDsp.fft_power==0)))\n self.assertTrue(np.all((proDsp.fft_real==0)))\n self.assertTrue(np.all((proDsp.fft_imag==0)))\n self.assertTrue(np.all((proDsp.fft_abs==0)))\n self.assertFalse(np.isnan(proDsp.encoded_sequences).any(),\n 'Sequences contain null values.')\n#2.)\n\n def test_protein_spectra(self):\n \"\"\" Testing getting protein spectra from encoded protein sequences. \"\"\"\n\n test_aaindices1 = \"COHE430101\"\n#1.)\n encoded_seq1 = self.pySAR.get_aai_enoding(test_aaindices1)\n proDsp = proDSP_.ProDSP(encoded_seq1)\n self.assertTrue(proDsp.fft_power.dtype, \"complex128\")\n self.assertTrue(proDsp.fft_real.dtype, \"complex128\")\n self.assertTrue(proDsp.fft_imag.dtype, \"complex128\")\n self.assertTrue(proDsp.fft_abs.dtype, \"complex128\")\n\n def test_max_freq(self):\n \"\"\" Testing max frequency functionality. \"\"\"\n#1.)\n test_aaindices1 = \"COHE430101\"\n encoded_seq1 = self.pySAR.get_aai_enoding(test_aaindices1)\n proDsp = proDSP_.ProDSP(encoded_seq1)\n"
] | [
[
"numpy.all",
"numpy.isnan"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
manjitullal/spatiotemporal | [
"00d731b2c437ba2356fc1ccf4b3a73cf9ce76acc"
] | [
"src/Transformer/Batch.py"
] | [
"import torch\nfrom torchtext import data\nimport numpy as np\nfrom torch.autograd import Variable\n\n\ndef nopeak_mask(size, opt):\n np_mask = np.triu(np.ones((1, size, size)),\n k=1).astype('uint8')\n np_mask = Variable(torch.from_numpy(np_mask) == 0)\n# if opt.device == 0:\n# np_mask = np_mask.cuda()\n return np_mask\n\ndef create_masks(src, trg, opt):\n \n src_mask = (src != opt.src_pad).unsqueeze(-2)\n src_mask = src_mask.view(1, 1, 10, 7)\n\n if trg is not None:\n trg_mask = (trg != opt.trg_pad).unsqueeze(-2)\n trg_mask = trg_mask.view(1, 1, 1, 3)\n #comment the line 22 to 26 because our target is single line and we want to see everything\n '''size = trg.size(1) # get seq_len for matrix\n np_mask = nopeak_mask(size, opt)\n if trg.is_cuda:\n np_mask.cuda()\n trg_mask = trg_mask & np_mask'''\n \n else:\n trg_mask = None\n return src_mask, trg_mask\n\n# patch on Torchtext's batching process that makes it more efficient\n# from http://nlp.seas.harvard.edu/2018/04/03/attention.html#position-wise-feed-forward-networks\n\nclass MyIterator(data.Iterator):\n def create_batches(self):\n if self.train:\n def pool(d, random_shuffler):\n for p in data.batch(d, self.batch_size * 100):\n p_batch = data.batch(\n sorted(p, key=self.sort_key),\n self.batch_size, self.batch_size_fn)\n for b in random_shuffler(list(p_batch)):\n yield b\n self.batches = pool(self.data(), self.random_shuffler)\n \n else:\n self.batches = []\n for b in data.batch(self.data(), self.batch_size,\n self.batch_size_fn):\n self.batches.append(sorted(b, key=self.sort_key))\n\nglobal max_src_in_batch, max_tgt_in_batch\n\ndef batch_size_fn(new, count, sofar):\n \"Keep augmenting batch and calculate total number of tokens + padding.\"\n global max_src_in_batch, max_tgt_in_batch\n if count == 1:\n max_src_in_batch = 0\n max_tgt_in_batch = 0\n max_src_in_batch = max(max_src_in_batch, len(new.src))\n max_tgt_in_batch = max(max_tgt_in_batch, len(new.trg) + 2)\n src_elements = count * max_src_in_batch\n tgt_elements = count * max_tgt_in_batch\n return max(src_elements, tgt_elements)\n"
] | [
[
"torch.from_numpy",
"numpy.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
RomainBrault/addons | [
"f5337ad39d12c7bc381006b86dffbf1c17e722a4"
] | [
"tensorflow_addons/image/tests/resampler_ops_test.py"
] | [
"# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Tests for resampler.\"\"\"\n\nfrom absl.testing import parameterized\n\nimport numpy as np\nimport pytest\n\nimport tensorflow as tf\nfrom tensorflow_addons.image import resampler_ops\nfrom tensorflow_addons.utils import test_utils\n\n\ndef _bilinearly_interpolate(data, x, y):\n \"\"\"Performs bilinenar interpolation of grid data at user defined\n coordinates.\n\n This interpolation function:\n a) implicitly pads the input data with 0s.\n b) returns 0 when sampling outside the (padded) image.\n The effect is that the sampled signal smoothly goes to 0 outside the\n original input domain, rather than producing a jump discontinuity at\n the image boundaries.\n Args:\n data: numpy array of shape `[data_height, data_width]` containing data\n samples assumed to be defined at the corresponding pixel coordinates.\n x: numpy array of shape `[warp_height, warp_width]` containing\n x coordinates at which interpolation will be performed.\n y: numpy array of shape `[warp_height, warp_width]` containing\n y coordinates at which interpolation will be performed.\n Returns:\n Numpy array of shape `[warp_height, warp_width]` containing interpolated\n values.\n \"\"\"\n shape = x.shape\n x = np.asarray(x) + 1\n y = np.asarray(y) + 1\n data = np.pad(data, 1, \"constant\", constant_values=0)\n\n x_0 = np.floor(x).astype(int)\n x_1 = x_0 + 1\n y_0 = np.floor(y).astype(int)\n y_1 = y_0 + 1\n\n x_0 = np.clip(x_0, 0, data.shape[1] - 1)\n x_1 = np.clip(x_1, 0, data.shape[1] - 1)\n y_0 = np.clip(y_0, 0, data.shape[0] - 1)\n y_1 = np.clip(y_1, 0, data.shape[0] - 1)\n\n i_a = data[y_0, x_0]\n i_b = data[y_1, x_0]\n i_c = data[y_0, x_1]\n i_d = data[y_1, x_1]\n\n w_a = (x_1 - x) * (y_1 - y)\n w_b = (x_1 - x) * (y - y_0)\n w_c = (x - x_0) * (y_1 - y)\n w_d = (x - x_0) * (y - y_0)\n\n samples = w_a * i_a + w_b * i_b + w_c * i_c + w_d * i_d\n samples = samples.reshape(shape)\n\n return samples\n\n\ndef _make_warp(batch_size, warp_height, warp_width, dtype):\n \"\"\"Creates batch of warping coordinates.\"\"\"\n x, y = np.meshgrid(\n np.linspace(0, warp_width - 1, warp_width),\n np.linspace(0, warp_height - 1, warp_height),\n )\n warp = np.concatenate(\n (\n x.reshape([warp_height, warp_width, 1]),\n y.reshape([warp_height, warp_width, 1]),\n ),\n 2,\n )\n warp = np.tile(warp.reshape([1, warp_height, warp_width, 2]), [batch_size, 1, 1, 1])\n warp += np.random.randn(*warp.shape)\n return warp.astype(dtype)\n\n\n@test_utils.run_all_in_graph_and_eager_modes\nclass ResamplerTest(tf.test.TestCase, parameterized.TestCase):\n @parameterized.named_parameters((\"float32\", np.float32), (\"float64\", np.float64))\n def test_op_forward_pass_gpu(self, dtype):\n if not tf.test.is_gpu_available():\n self.skipTest(\"gpu is not available.\")\n self._test_op_forward_pass(True, dtype)\n\n @parameterized.named_parameters(\n (\"float16\", np.float16), (\"float32\", np.float32), (\"float64\", np.float64)\n )\n def test_op_forward_pass_cpu(self, dtype):\n self._test_op_forward_pass(False, dtype)\n\n def _test_op_forward_pass(self, on_gpu, dtype):\n np.random.seed(0)\n data_width = 7\n data_height = 9\n data_channels = 5\n warp_width = 4\n warp_height = 8\n batch_size = 10\n\n warp = _make_warp(batch_size, warp_height, warp_width, dtype)\n data_shape = (batch_size, data_height, data_width, data_channels)\n data = np.random.rand(*data_shape).astype(dtype)\n use_gpu = on_gpu and tf.test.is_gpu_available()\n with test_utils.device(use_gpu):\n data_ph = tf.constant(data)\n warp_ph = tf.constant(warp)\n outputs = self.evaluate(resampler_ops.resampler(data=data_ph, warp=warp_ph))\n self.assertEqual(\n outputs.shape, (10, warp_height, warp_width, data_channels)\n )\n\n # Generate reference output via bilinear interpolation in numpy\n reference_output = np.zeros_like(outputs)\n for batch in range(batch_size):\n for c in range(data_channels):\n reference_output[batch, :, :, c] = _bilinearly_interpolate(\n data[batch, :, :, c], warp[batch, :, :, 0], warp[batch, :, :, 1]\n )\n\n self.assertAllCloseAccordingToType(\n outputs, reference_output, half_rtol=5e-3, half_atol=5e-3\n )\n\n def test_op_errors(self):\n batch_size = 10\n data_height = 9\n data_width = 7\n data_depth = 3\n data_channels = 5\n warp_width = 4\n warp_height = 8\n\n # Input data shape is not defined over a 2D grid, i.e. its shape is not like\n # (batch_size, data_height, data_width, data_channels).\n data_shape = (batch_size, data_height, data_width, data_depth, data_channels)\n data = np.zeros(data_shape)\n warp_shape = (batch_size, warp_height, warp_width, 2)\n warp = np.zeros(warp_shape)\n\n with self.assertRaisesRegexp(\n tf.errors.UnimplementedError,\n \"Only bilinear interpolation is currently supported.\",\n ):\n self.evaluate(resampler_ops.resampler(data, warp))\n\n # Warp tensor must be at least a matrix, with shape [batch_size, 2].\n data_shape = (batch_size, data_height, data_width, data_channels)\n data = np.zeros(data_shape)\n warp_shape = (batch_size,)\n warp = np.zeros(warp_shape)\n\n with self.assertRaisesRegexp(\n tf.errors.InvalidArgumentError, \"warp should be at least a matrix\"\n ):\n self.evaluate(resampler_ops.resampler(data, warp))\n\n # The batch size of the data and warp tensors must be the same.\n data_shape = (batch_size, data_height, data_width, data_channels)\n data = np.zeros(data_shape)\n warp_shape = (batch_size + 1, warp_height, warp_width, 2)\n warp = np.zeros(warp_shape)\n\n with self.assertRaisesRegexp(\n tf.errors.InvalidArgumentError, \"Batch size of data and warp tensor\"\n ):\n self.evaluate(resampler_ops.resampler(data, warp))\n\n # The warp tensor must contain 2D coordinates, i.e. its shape last dimension\n # must be 2.\n data_shape = (batch_size, data_height, data_width, data_channels)\n data = np.zeros(data_shape)\n warp_shape = (batch_size, warp_height, warp_width, 3)\n warp = np.zeros(warp_shape)\n\n with self.assertRaisesRegexp(\n tf.errors.UnimplementedError,\n \"Only bilinear interpolation is supported, warping\",\n ):\n self.evaluate(resampler_ops.resampler(data, warp))\n\n\[email protected](\"cpu_and_gpu\")\[email protected](\"dtype\", [np.float16, np.float32, np.float64])\ndef test_op_backward_pass(dtype):\n np.random.seed(13)\n data_width = 5\n data_height = 4\n data_channels = 3\n warp_width = 2\n warp_height = 6\n batch_size = 3\n\n warp = _make_warp(batch_size, warp_height, warp_width, dtype)\n data_shape = (batch_size, data_height, data_width, data_channels)\n data = np.random.rand(*data_shape).astype(dtype)\n data_tensor = tf.constant(data)\n warp_tensor = tf.constant(warp)\n theoretical, _ = tf.test.compute_gradient(\n resampler_ops.resampler, [data_tensor, warp_tensor]\n )\n data_tensor_64 = tf.constant(data, dtype=tf.float64)\n warp_tensor_64 = tf.constant(warp, dtype=tf.float64)\n _, numerical_64 = tf.test.compute_gradient(\n resampler_ops.resampler, [data_tensor_64, warp_tensor_64]\n )\n\n for t, n in zip(theoretical, numerical_64):\n test_utils.assert_allclose_according_to_type(\n t, n, float_rtol=5e-5, float_atol=5e-5\n )\n"
] | [
[
"tensorflow.constant",
"numpy.pad",
"numpy.random.seed",
"numpy.clip",
"numpy.asarray",
"numpy.linspace",
"numpy.random.randn",
"tensorflow.test.compute_gradient",
"numpy.zeros_like",
"numpy.floor",
"numpy.random.rand",
"tensorflow.test.is_gpu_available",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
NeurIPS21-3353/CodeRepo | [
"514dce311daf5d075fa266c473aaa76885e078ad"
] | [
"loggers/plotting/basics.py"
] | [
"import os\n\nimport matplotlib\nimport numpy as np\nimport torch\n\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom matplotlib import cm\n\n\nclass TwoDimPlotter():\n def __init__(self, target, location, rotation=None, interval=1, range=5.5, steps=200):\n self.steps = steps\n self.target = target\n self.location = location\n self.rotation = rotation\n self.interval = interval\n self.range = range\n\n self.image_list = []\n\n if not os.path.exists(location):\n os.makedirs(location, exist_ok=True)\n\n def execute(self, samples, true_samples, epoch, prefix=\"\"):\n if epoch % self.interval != 0:\n return\n\n rot = torch.FloatTensor([[0, 1], [-1, 0]])\n\n r = self.range\n x_range =[-r, r]\n y_range =[-r, r]\n\n # Filter samples outof range\n id = samples[(torch.abs(samples) <= r).all(dim=1)]\n\n x = torch.linspace(x_range[0], x_range[1], self.steps)\n y = torch.linspace(y_range[0], y_range[1], self.steps)\n\n x, y = np.meshgrid(x, y)\n pos = np.empty(x.shape + (2,))\n pos[:, :, 0] = x\n pos[:, :, 1] = y\n\n inp = torch.tensor(pos.astype('float32')).view((-1, 2))\n z = self.target.log_prob(inp).exp().detach()\n z = z.view(self.steps, self.steps)\n # z = self.target.get_z_probabilities(x, y)\n\n clev = torch.arange(-0.02, float(z.max()+0.001), .001)\n plt.clf()\n fig = plt.gcf()\n fig.set_size_inches((5, 5))\n plt.contourf(x, y, z, clev, cmap='magma')\n\n if id.size(1) > 0:\n if self.rotation is not None and self.rotation == \"rotate\":\n rot1 = id @ rot\n rot2 = id @ rot @ rot\n rot3 = id @ rot @ rot @ rot\n plt.scatter(id[:, 0], id[:, 1], color='firebrick', edgecolors='white', linewidths=1)\n plt.scatter(rot1[:, 0], rot1[:, 1], color='cornflowerblue', edgecolors='white', linewidths=1)\n plt.scatter(rot2[:, 0], rot2[:, 1], color='lightgreen', edgecolors='white', linewidths=1)\n plt.scatter(rot3[:, 0], rot3[:, 1], color='khaki', edgecolors='white', linewidths=1)\n elif self.rotation is not None and self.rotation == \"mode\":\n for idx, sample in enumerate(id):\n x = sample[0]\n y = sample[1]\n while sample[0] < 0 or torch.abs(sample[1]) > sample[0]:\n sample = sample @ rot\n id[idx, :] = sample\n plt.scatter(id[:, 0], id[:, 1], color='firebrick', edgecolors='white', linewidths=1)\n elif self.rotation is not None and self.rotation == \"line\":\n norms = torch.norm(id, dim=1)\n id = torch.zeros_like(id)\n id[:, 0] = norms\n id = id[norms <= r]\n plt.scatter(id[:, 0], id[:, 1], color='firebrick', edgecolors='white', linewidths=1)\n else:\n plt.scatter(id[:, 0], id[:, 1], color='firebrick', edgecolors='white', linewidths=1)\n plt.axis('off')\n plt.tight_layout(True)\n # plt.show()\n\n path = f\"{self.location}/{prefix}epoch_{epoch}.png\"\n plt.savefig(path)\n self.image_list.append(Image.open(path).convert(\"RGB\"))\n\n def convert_to_gif(self):\n self.image_list[0].save(f'{self.location}/loop.gif',\n save_all=True, append_images=self.image_list[1:], optimize=False, duration=40, loop=0)\n\n def reset(self):\n self.image_list = []\n\n\nclass ThreeDimPlotter():\n def __init__(self, target, location, show_rotation, interval=1, range=5.5):\n self.target = target\n self.location = location\n self.show_rotation = show_rotation\n self.interval = interval\n self.range = range\n\n self.plotting_samples = self.target.sample(5000)\n\n self.image_list = []\n\n if not os.path.exists(location):\n os.makedirs(location, exist_ok=True)\n\n def execute(self, samples, true_samples, epoch):\n if epoch % self.interval != 0:\n return\n\n r = self.range\n cmap = cm.get_cmap('magma')\n dist_color = cmap(0.99)\n back_color = cmap(0.1)\n\n plt.clf()\n fig = plt.gcf()\n fig.set_size_inches((5, 5))\n matplotlib.rc('axes', edgecolor=(1, 1, 1, 0))\n ax = fig.add_subplot(111, projection='3d')\n ax.scatter(self.plotting_samples[:, 0], self.plotting_samples[:, 1], self.plotting_samples[:, 2], color=dist_color, edgecolors=dist_color, s=10, alpha=0.1)\n if not self.show_rotation:\n ax.scatter(samples[:, 0], samples[:, 1], samples[:, 2], color='firebrick', edgecolors='white', linewidths=1, s=30)\n else:\n norms = samples.norm(dim=1)\n normed = torch.zeros_like(samples)\n normed[:, 0] = norms\n ax.scatter(normed[:, 0], normed[:, 1], normed[:, 2], color='firebrick', edgecolors='white', linewidths=1, s=30)\n\n ax.xaxis.set_pane_color((1, 1, 1, 0))\n ax.yaxis.set_pane_color((1, 1, 1, 0))\n ax.zaxis.set_pane_color((1, 1, 1, 0))\n\n # make the grid lines transparent\n ax.xaxis._axinfo[\"grid\"]['color'] = (1, 1, 1, 0.)\n ax.yaxis._axinfo[\"grid\"]['color'] = (1, 1, 1, 0.)\n ax.zaxis._axinfo[\"grid\"]['color'] = (1, 1, 1, 0.)\n ax.set_facecolor(back_color)\n\n ax.tick_params(axis='x', labelsize=0, color=(1, 1, 1, 0))\n ax.tick_params(axis='y', labelsize=0, color=(1, 1, 1, 0))\n ax.tick_params(axis='z', labelsize=0, color=(1, 1, 1, 0))\n ax.set_xlim([-9., 9.])\n ax.set_ylim([-9., 9.])\n ax.set_zlim([-9., 9.])\n ax.dist = 7\n plt.tight_layout()\n # plt.show()\n\n path = f\"{self.location}/epoch_{epoch}.png\"\n plt.savefig(path, dpi=300)\n self.image_list.append(Image.open(path).convert(\"RGB\"))\n\n def convert_to_gif(self):\n self.image_list[0].save(f'{self.location}/loop.gif',\n save_all=True, append_images=self.image_list[1:], optimize=False, duration=40, loop=0)"
] | [
[
"torch.abs",
"torch.linspace",
"matplotlib.pyplot.contourf",
"matplotlib.pyplot.tight_layout",
"torch.norm",
"matplotlib.pyplot.scatter",
"torch.zeros_like",
"matplotlib.rc",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.clf",
"torch.FloatTensor",
"matplotlib.pyplot.axis",
"matplotlib.cm.get_cmap",
"numpy.meshgrid",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tobias17/CodeNamesOld | [
"10fdccc35b5a23eb68ed5d7e7257e9fe83977278"
] | [
"engine.py"
] | [
"from __future__ import print_function, division\n\nimport itertools\nimport re\nimport sys\nimport os\nimport platform\n\nimport numpy as np\nfrom datetime import datetime\n\nimport model\nfrom config import config\nfrom tqdm import tqdm\n\nCLUE_PATTERN = r\"^([a-zA-Z]+) ({0})$\"\nUNLIMITED = \"unlimited\"\n\ndisplay_to_console = True\n\n# noinspection PyAttributeOutsideInit\nclass GameEngine(object):\n def __init__(self, seed=None, expert=False, display=True):\n\n # Load our word list if necessary.\n # TODO: Max length of 11 is hardcoded here and in print_board()\n with open(config.word_list) as f:\n _words = [line.rstrip().lower().replace(\" \", \"_\") for line in f.readlines()]\n self.words = np.array(_words, dtype=\"S11\")\n\n # Initialize our word embedding model if necessary.\n self.model = model.WordEmbedding(config.embedding)\n self.logs_filename = '{}/{}.log'.format(config.logs_folder, str(datetime.now()).replace(' ', '_').replace(':', '-').replace('.', '-'))\n\n # Initialize random numbers.\n self.generator = np.random.RandomState(seed=seed)\n\n # Register expert mode\n self.expert = expert\n self.unfound_words = (set(), set())\n\n # If we want to display to console\n self.display = display\n global display_to_console\n display_to_console = display\n\n # Useful regular expressions.\n if self.expert:\n self.valid_clue = re.compile(CLUE_PATTERN.format(\"[0-9]|\" + UNLIMITED))\n else:\n self.valid_clue = re.compile(CLUE_PATTERN.format(\"[0-9]\"))\n\n def initialize_random_game(self, size=5):\n\n self.size = size\n\n # Shuffle the wordlist.\n shuffle = self.generator.choice(len(self.words), size * size, replace=False)\n self.board = self.words[shuffle]\n\n # Specify the layout for this game.\n assignments = self.generator.permutation(size * size)\n self.owner = np.empty(size * size, int)\n self.owner[assignments[0]] = 0 # assassin\n self.owner[assignments[1:10]] = 1 # first player: 9 words\n self.owner[assignments[10:18]] = 2 # second player: 8 words\n self.owner[assignments[18:]] = 3 # bystander: 7 words\n\n self.assassin_word = self.board[self.owner == 0]\n self.given_clues = []\n\n # All cards are initially visible.\n self.visible = np.ones_like(self.owner, dtype=bool)\n\n self.num_turns = -1\n\n def initialize_from_words(self, initial_words, size=5):\n \"\"\"\n The initial_words parameter should be in the format:\n\n ASSASSIN;TEAM1;TEAM2;NEUTRAL\n\n where each group consists of comma-separated words from the word list.\n\n The total number of words must be <= size * size. Any missing words\n are considered to be already covered and neutral.\n \"\"\"\n self.size = size\n\n word_groups = initial_words.split(\";\")\n if len(word_groups) != 4:\n raise ValueError(\"Expected 4 groups separated by semicolon.\")\n\n board, owner, visible = [], [], []\n for group_index, word_group in enumerate(word_groups):\n words = word_group.split(\",\")\n for word in words:\n word = word.lower().replace(\" \", \"_\")\n if word not in self.words:\n raise ValueError('Invalid word \"{0}\".'.format(word))\n if word in board:\n raise ValueError('Duplicate word \"{0}\".'.format(word))\n board.append(word)\n owner.append(group_index)\n visible.append(True)\n if len(board) > size * size:\n raise ValueError(\"Too many words. Expected <= {0}.\".format(size * size))\n # Add dummy hidden words if necessary.\n while len(board) < size * size:\n board.append(\"---\")\n owner.append(3)\n visible.append(False)\n\n self.board = np.array(board)\n self.owner = np.array(owner)\n self.visible = np.array(visible)\n\n # Perform a random shuffle of the board.\n shuffle = self.generator.permutation(size * size)\n self.board = self.board[shuffle]\n self.owner = self.owner[shuffle]\n self.visible = self.visible[shuffle]\n\n self.assassin_word = self.board[self.owner == 0]\n self.num_turns = -1\n\n def print_board(self, spymaster=False, clear_screen=True, override=False):\n\n # Check to see if we want to display, if not return\n if not self.display and not override:\n return\n\n if clear_screen:\n if platform.system() == \"Windows\":\n os.system(\"cls\")\n else:\n sys.stdout.write(chr(27) + \"[2J\")\n\n board = self.board.reshape(self.size, self.size)\n owner = self.owner.reshape(self.size, self.size)\n visible = self.visible.reshape(self.size, self.size)\n\n sys.stdout.write(\n \"Words left: {}, Opponent: {}\\n\".format(\n len(self.player_words), len(self.opponent_words)\n )\n )\n\n for row in range(self.size):\n for col in range(self.size):\n word = board[row, col]\n tag = \"#<>-\"[owner[row, col]]\n if not visible[row, col]:\n word = tag * 11\n elif not spymaster:\n tag = \" \"\n if not spymaster or owner[row, col] in (0, 1, 2):\n word = word.upper()\n sys.stdout.write(\"{0}{1:11s} \".format(\" \", str(word)[2:-1]))\n sys.stdout.write(\"\\n\")\n\n def play_computer_spymaster(self, gamma=1.0, verbose=True, give_words=False):\n\n say(\"Thinking...\")\n sys.stdout.flush()\n\n saved_clues, best_score = self.get_clue_list_pair_stretch(gamma, verbose)\n\n num_clues = len(saved_clues)\n order = sorted(range(num_clues), key=lambda k: best_score[k], reverse=True)\n\n if not os.path.exists(config.logs_folder):\n os.makedirs(config.logs_folder)\n with open(self.logs_filename, 'a+') as f:\n for i in order[:10]:\n clue, words = saved_clues[i]\n f.write(\n u\"{0:.3f} {2} {3} = {1}\\n\".format(\n best_score[i],\n \" + \".join([str(w).upper()[2:-1] for w in words]),\n str(clue)[2:-1],\n len(words),\n )\n )\n f.write(\"\\n\")\n\n if verbose or True:\n self.print_board(spymaster=True)\n for i in order[:10]:\n clue, words = saved_clues[i]\n say(\n u\"{0:.3f} {1} = {2}\".format(\n best_score[i], \" + \".join([str(w).upper() for w in words]), clue\n )\n )\n\n clue, words = saved_clues[order[0]]\n self.unfound_words[self.player].update(words)\n self.given_clues.append(clue)\n if give_words:\n return clue, words\n if self.expert and self._should_say_unlimited(nb_clue_words=len(words)):\n return clue, UNLIMITED\n else:\n return clue, len(words)\n\n\n def get_clue_list_pair_stretch(self, gamma, verbose, max_group=2, does_stretch=[2]):\n # Loop over all permutations of words.\n num_words = len(self.player_words)\n best_score, saved_clues = [], []\n counts = range(min(num_words, max_group), 0, -1)\n groups_and_count = []\n for count in counts:\n for group in itertools.combinations(range(num_words), count):\n groups_and_count.append((group, count,))\n if self.display or True:\n groups_and_count = tqdm(groups_and_count)\n for group, count in groups_and_count:\n # Multiply similarity scores by this factor for any clue\n # corresponding to this many words.\n bonus_factor = count ** gamma\n words = self.player_words[list(group)]\n clue, score, stretch = self.model.get_clue_stretch(\n clue_words=words,\n pos_words=self.player_words,\n neg_words=self.opponent_words,\n neut_words=self.neutral_words,\n veto_words=self.assassin_word,\n given_clues=self.given_clues,\n give_stretch=(count in does_stretch),\n )\n if clue:\n best_score.append(score * bonus_factor)\n clue_words = words\n if stretch:\n clue_words = np.concatenate((words, np.asarray(stretch)))\n saved_clues.append((clue, clue_words))\n return saved_clues, best_score\n\n\n def get_clue_list_dkirkby(self, gamma, verbose):\n # Loop over all permutations of words.\n num_words = len(self.player_words)\n best_score, saved_clues = [], []\n counts = range(num_words, 0, -1)\n groups_and_count = []\n for count in counts:\n for group in itertools.combinations(range(num_words), count):\n groups_and_count.append((group, count,))\n if self.display or True:\n groups_and_count = tqdm(groups_and_count)\n for group, count in groups_and_count:\n # Multiply similarity scores by this factor for any clue\n # corresponding to this many words.\n bonus_factor = count ** gamma\n words = self.player_words[list(group)]\n clue, score = self.model.get_clue(\n clue_words=words,\n pos_words=self.player_words,\n neg_words=np.concatenate((self.opponent_words, self.neutral_words)),\n veto_words=self.assassin_word,\n given_clues=self.given_clues,\n )\n if clue:\n best_score.append(score * bonus_factor)\n saved_clues.append((clue, words))\n return saved_clues\n\n\n def _should_say_unlimited(self, nb_clue_words, threshold_opponent=2):\n \"\"\"\n Announce \"unlimited\" if :\n (1) the opposing team risks winning with their next clue,\n (2) and our +1 guess isn't enough to catch up during this clue,\n (3) but all the words hinted by the current and previous clues\n are enough to catch up and win\n \"\"\"\n return (\n len(self.opponent_words) <= threshold_opponent # (1)\n and nb_clue_words + 1 < len(self.player_words) # (2)\n and self.unfound_words[self.player] == set(self.player_words)\n ) # (3)\n\n def play_human_spymaster(self):\n\n self.print_board(spymaster=True)\n\n while True:\n clue = ask(\"{0} Enter your clue: \".format(self.player_label))\n matched = self.valid_clue.match(clue)\n if matched:\n word, count = matched.groups()\n if count != UNLIMITED:\n count = int(count)\n return word, count\n say(\"Invalid clue, should be WORD COUNT.\")\n\n def play_human_team(self, word, count):\n\n num_guesses = 0\n while (self.expert and count == UNLIMITED) or num_guesses < count + 1:\n self.print_board(clear_screen=(num_guesses == 0))\n say(\n u\"{0} your clue is: {1} {2}\".format(\n self.player_label, str(word)[2:-1], count\n )\n )\n\n num_guesses += 1\n while True:\n guess = ask(\n \"{0} enter your guess #{1}: \".format(self.player_label, num_guesses)\n )\n guess = guess.strip().lower().replace(\" \", \"_\")\n if guess == \"\":\n # Team does not want to make any more guesses.\n return True\n guess = guess.encode(\"utf8\")\n if guess in self.board[self.visible]:\n break\n say(\"Invalid guess, should be a visible word.\")\n\n loc = np.where(self.board == guess)[0]\n self.visible[loc] = False\n\n if guess == self.assassin_word:\n say(\n \"{0} You guessed the assasin - game over!\".format(self.player_label)\n )\n return False\n\n if guess in self.player_words:\n self.unfound_words[self.player].discard(guess)\n if num_guesses == len(self.player_words):\n say(\"{0} You won!!!\".format(self.player_label))\n return False\n else:\n ask(\n \"{0} Congratulations, keep going! (hit ENTER)\\n\".format(\n self.player_label\n )\n )\n else:\n if guess in self.opponent_words:\n ask(\n \"{0} Sorry, word from opposing team! (hit ENTER)\\n\".format(\n self.player_label\n )\n )\n else:\n ask(\"{0} Sorry, bystander! (hit ENTER)\\n\".format(self.player_label))\n break\n\n return True\n\n def next_turn(self):\n self.num_turns += 1\n\n self.player = self.num_turns % 2\n self.opponent = (self.player + 1) % 2\n\n self.player_label = \"<>\"[self.player] * 3\n self.player_words = self.board[(self.owner == self.player + 1) & self.visible]\n self.opponent_words = self.board[\n (self.owner == self.opponent + 1) & self.visible\n ]\n self.neutral_words = self.board[(self.owner == 3) & self.visible]\n\n def play_turn(self, spymaster=\"human\", team=\"human\"):\n\n self.next_turn()\n\n if spymaster == \"human\":\n word, count = self.play_human_spymaster()\n else:\n word, count = self.play_computer_spymaster()\n\n if team == \"human\":\n ongoing = self.play_human_team(word, count)\n else:\n raise NotImplementedError()\n\n return ongoing\n\n def play_game(\n self,\n spymaster1=\"human\",\n team1=\"human\",\n spymaster2=\"human\",\n team2=\"human\",\n init=None,\n ):\n\n if init is None:\n self.initialize_random_game()\n else:\n self.initialize_from_words(init)\n\n while True:\n if not self.play_turn(spymaster1, team1):\n break\n if not self.play_turn(spymaster2, team2):\n break\n\n\ndef say(message):\n if display_to_console:\n sys.stdout.write(message + \"\\n\")\n\n\ndef ask(message):\n try:\n return input(message)\n except KeyboardInterrupt:\n say(\"\\nBye.\")\n sys.exit(0)\n"
] | [
[
"numpy.ones_like",
"numpy.random.RandomState",
"numpy.asarray",
"numpy.concatenate",
"numpy.array",
"numpy.where",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
flurinus/IntTripAssignment | [
"9e6ce4c7ba21bb989537b6492b8f05b7cbb5a14e"
] | [
"src/area.py"
] | [
"import simpy\nimport math\nimport numpy as np\nfrom parameter import Parameter\n\nclass Area:\n \n def __init__(self, simEnv, surfaceArea, areaType):\n assert(surfaceArea > 0)\n assert(areaType in Parameter.maxFacilityDensity)\n \n self.streamList = list()\n \n #area type\n self.areaType = areaType\n \n #capacity\n self.maxDensity = Parameter.maxFacilityDensity[areaType]['maxDensity']\n maxNumPed = math.floor( surfaceArea * self.maxDensity )\n \n self.resource = AreaResource(simEnv,maxNumPed,surfaceArea,areaType)\n \n def addStream(self, linkID):\n self.streamList.append(linkID)\n \n #returns resource request event\n def getResReqEvent(self):\n return self.resource.request()\n \n def getRelease(self,resReqEvent):\n self.resource.release(resReqEvent)\n \n def getAreaDensity(self):\n return self.resource.count/self.resource.areaSize\n \n def getWalkingCost(self,timeIn, timeOut):\n if timeIn not in self.resource.cumWalkCost or timeOut not in self.resource.cumWalkCost:\n print(\"self.resource.cumWalkCost\", self.resource.cumWalkCost)\n print(\"timeIn: %.3f, timeOut: %.3f\" % (timeIn, timeOut))\n \n assert (timeIn in self.resource.cumWalkCost)\n assert (timeOut in self.resource.cumWalkCost)\n return self.resource.cumWalkCost[timeOut] - self.resource.cumWalkCost[timeIn]\n \n def getWaitingCost(self,timeIn, timeOut):\n assert (timeIn in self.resource.cumWaitCost and timeOut in self.resource.cumWaitCost)\n return self.resource.cumWaitCost[timeOut] - self.resource.cumWaitCost[timeIn] \n \n#patch resource class to keep information on travel cost\nclass AreaResource(simpy.Resource):\n def __init__(self, simEnv,capacity,areaSize,areaType):\n super().__init__(simEnv,capacity)\n \n self.areaSize = areaSize\n self.areaType = areaType\n \n #cumulative walking cost\n self.cumWalkCost = {0:0}\n \n #on platform areas, people may also wait\n if self.areaType == \"horizontal\":\n self.cumWaitCost = {0:0}\n \n #density\n self.densityLog = {0:0}\n \n self.lastTime = 0\n\n def request(self, *args, **kwargs):\n self.updateCost()\n return super().request(*args, **kwargs)\n\n def release(self, *args, **kwargs):\n self.updateCost()\n return super().release(*args, **kwargs)\n \n def updateCost(self):\n \n curTime = self._env.now\n \n #add time stamp only if different from previous\n if curTime != self.lastTime:\n curDensity = self.count/self.areaSize\n self.densityLog[curTime] = curDensity\n \n lastWalkCost = self.cumWalkCost[self.lastTime]\n curWalkCost = lastWalkCost + self.walkingVOT(curDensity)*(curTime - self.lastTime)\n self.cumWalkCost[curTime] = curWalkCost\n \n #compute waiting cost if needed\n if self.areaType == \"horizontal\":\n lastWaitCost = self.cumWaitCost[self.lastTime]\n curWaitCost = lastWaitCost + self.waitingVOT(curDensity)*(curTime - self.lastTime)\n self.cumWaitCost[curTime] = curWaitCost\n \n self.lastTime = curTime\n \n def walkingVOT(self,density):\n if self.areaType == \"horizontal\":\n activity = \"walkingHorizontal\"\n else:\n #for escalators and stairways, activity pre-determined by facility type\n activity = self.areaType\n \n assert(activity in Parameter.timeMultiplierRailAccess), \\\n \"activity '%s' not in Parameter.timeMultiplierRailAccess\" % activity\n \n return self.getRailAccessTimeMultiplier(activity, density)*Parameter.betaIVTZero\n \n def waitingVOT(self,density):\n assert(self.areaType == \"horizontal\"), \"Pedestrian erroneously waiting on %s\" % self.areaType\n activity = \"waitingPlatform\"\n assert(activity in Parameter.timeMultiplierRailAccess)\n \n return self.getRailAccessTimeMultiplier(activity, density)*Parameter.betaIVTZero\n \n def getRailAccessTimeMultiplier(self, activity, density):\n assert( activity in Parameter.timeMultiplierRailAccess ), \\\n \"activity '%s' not in Parameter.timeMultiplierRailAccess\" % activity\n \n #retrieve crowding multiplier\n densCrowdMultTupleList = Parameter.timeMultiplierRailAccess[activity]\n densList, crowdMultList = zip(*densCrowdMultTupleList)\n \n assert( min(densList) <= density and density <= max(densList) )\n return np.interp(density, densList, crowdMultList)\n \n #def getWalkingLOSMultiplier(self,density):\n # for index,losThreshold in enumerate(Parameter.losWalkingFruin):\n # if density <= losThreshold:\n # losLevel = Parameter.losLevels[index]\n # break\n # \n # #get multiplier corresponding to current walking LOS \n # return Parameter.crowdingMultiplierLOS[losLevel]\n \n #def getWaitingLOSMultiplier(self,density):\n # for index,losThreshold in enumerate(Parameter.losWaitingFruin):\n # if density <= losThreshold:\n # losLevel = Parameter.losLevels[index]\n # break\n # \n # #get multiplier corresponding to current walking LOS \n # return Parameter.crowdingMultiplierLOS[losLevel]\n \n \n \n "
] | [
[
"numpy.interp"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ishine/phonetic_mlm | [
"91ae25fa3f3508a50d26f86029dbfde145686ecf"
] | [
"src/test_phonetic_mlm.py"
] | [
"import os\nimport argparse\nfrom pprint import pprint\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom transformers import BertTokenizer, BertForTokenClassification, BertForMaskedLM\nfrom tqdm import tqdm\n\nfrom dataset import prepare_data, TypoDataset\nfrom utils import load_config, RunningAverage\nfrom dimsim import prepare_dimsim\nfrom module import PhoneticMLM\nfrom evaluation_func import calculate_cer, get_csc_metric\n\n\ndef replace_correction(texts, correct_positions):\n corrected_texts = []\n for text, correct_position in zip(texts, correct_positions):\n for position, correct_char in correct_position:\n text = text[:position] + correct_char + text[position+1:]\n corrected_texts.append(text)\n return corrected_texts\n\n\ndef evaluate(texts, gt_texts, subsitute_gt_positions, pred_positions):\n cer_averger = RunningAverage()\n origin_cer_averager = RunningAverage()\n\n corrected_texts = replace_correction(texts, pred_positions)\n\n for text, gt_text, corrected_text in zip(texts, gt_texts, corrected_texts):\n cer = calculate_cer(gt_text, corrected_text, exec_detail=False)\n cer_averger.add(cer)\n\n origin_cer = calculate_cer(gt_text, text, exec_detail=False)\n origin_cer_averager.add(origin_cer)\n\n evaluation = {\n 'avg_cer': cer_averger.get(),\n 'avg_origin_cer': origin_cer_averager.get(),\n 'csc_metric': get_csc_metric(subsitute_gt_positions, pred_positions)\n }\n return evaluation\n\n\ndef predict(texts, model, dataloader, tokenizer, device):\n model.eval()\n\n correct_positions = []\n\n with torch.no_grad():\n for data in tqdm(dataloader, desc='predict'):\n input_ids, token_type_ids, attention_mask, bopomofo_ids = [d.to(device) for d in data[:4]]\n infos = data[-1]\n\n logits = model(\n input_ids=input_ids,\n token_type_ids=token_type_ids,\n attention_mask=attention_mask,\n bopomofo_ids=bopomofo_ids\n )\n output_ids = logits.argmax(dim=-1)\n is_diffs = input_ids != output_ids\n\n output_ids = output_ids.cpu().tolist()\n is_diffs = is_diffs.cpu().tolist()\n\n for is_diff_seq, output_id_seq, info in zip(is_diffs, output_ids, infos):\n token2text = info['token2text']\n correct_position = []\n for i, (is_diff, output_id) in enumerate(zip(is_diff_seq, output_id_seq)):\n if is_diff:\n start, end = token2text[i - 1] # remove [CLS]\n assert start + 1 == end\n position = start\n correct_char = tokenizer.convert_ids_to_tokens(output_id)\n correct_position.append((position, correct_char))\n correct_positions.append(correct_position)\n\n return correct_positions\n\n\ndef main(config, detector_config, test_json):\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n tokenizer = BertTokenizer.from_pretrained(config.model_source)\n\n bopomofo_dict, bopomofo_to_dist = prepare_dimsim(tokenizer.vocab)\n\n texts, typos, _, true_texts = prepare_data(test_json, obtain_true_text=True)\n\n dataset = TypoDataset(tokenizer, texts, typos, bopomofos=None, bopomofo_dict=bopomofo_dict, max_length=detector_config.max_len,\n for_train=True, for_detect=False)\n\n dataloader = DataLoader(\n dataset=dataset,\n batch_size=config.batch_size,\n collate_fn=dataset.create_mini_batch,\n num_workers=config.num_workers\n )\n\n detector = BertForTokenClassification.from_pretrained(detector_config.model_source, return_dict=True, num_labels=2)\n detector.load_state_dict(torch.load(config.detector_checkpoint_path, map_location=device))\n detector.to(device)\n\n mlm = BertForMaskedLM.from_pretrained(config.model_source)\n mlm.to(device)\n\n unknown_bopomofo_id = bopomofo_dict['UNK']\n model = PhoneticMLM(detector, mlm, tokenizer, bopomofo_to_dist, unknown_bopomofo_id, alpha=config.alpha, detector_threshold=config.detector_threshold)\n\n pred_positions = predict(texts, model, dataloader, tokenizer, device)\n\n subsitute_gt_positions = [[(i, char) for _, char, i, _ in typo_list] for typo_list in typos]\n evaluation = evaluate(texts, true_texts, subsitute_gt_positions, pred_positions)\n pprint(evaluation)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--config', required=True, help='config path')\n parser.add_argument('--json', required=True, help='json path')\n\n opt = parser.parse_args()\n\n config = load_config(opt.config)\n detector_config = load_config(config.detector_config_path)\n\n main(config, detector_config, opt.json)\n"
] | [
[
"torch.no_grad",
"torch.utils.data.DataLoader",
"torch.cuda.is_available",
"torch.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
birds-on-mars/birdsonearth | [
"62921423b787ad8b81b8e60e8de42a3f6e113d88"
] | [
"train.py"
] | [
"import sys, getopt\nimport imp\nimport params as p\nimport VGGish_model as m\nimport torch\nimport pickle\nimport os\n\nfrom utils import Dataset as d\nfrom utils import trainer as t\nfrom utils import preprocessing as pre\n\nimp.reload(p)\nimp.reload(d)\nimp.reload(m)\nimp.reload(t)\nimp.reload(pre)\n\n\ndef prepare(params):\n '''\n reads in a terminal command in the format:\n\n $ python train.py -d <data dir> -n <# training epochs> -b <batch size>\n\n options in this command override those in params.py.\n Takes care of handling the terminal input and preprocessing the data\n '''\n\n #reading in options from terminal command\n print('working out options')\n try:\n opts, args = getopt.getopt(sys.argv[1:], 'd:n:b:f:e:', \\\n ['data=', 'nepochs=', 'batchsize=', 'format=', 'epochs='])\n except getopt.GetoptError as err:\n print(err)\n sys.exit()\n\n for o, a in opts:\n if o in ('-d', '--data'):\n params.data_root = a\n if o in ('-e', '--epochs'):\n params.n_epochs = int(a)\n if o in ('-b', '--batchsize'):\n params.batch_size = int(a)\n if o in ('-f', '--format'):\n params.data_format = a\n if o in ('-n', '--name'):\n params.name = a\n\n\n # preprocessing\n if os.path.exists(params.mel_spec_root):\n print('skipping preprocessing and using spectograms in ', params.mel_spec_root)\n else:\n print('preprocessing: generating spectrograms from ', params.data_root)\n if params.data_format == 'mp3':\n pre.process_mp3s_for_training(params)\n if params.data_format == 'wav':\n pre.process_wavs_for_training(params)\n\n return params\n\n\ndef start_training_with(params):\n '''\n takes a params object and expects ready to be used spectrograms\n in params.mel_spec_root.\n Sets up all requirements for training, runs the training and returns the\n trained model\n '''\n # setup\n device = torch.device(params.device)\n n_classes = len(os.listdir(params.mel_spec_root))\n params.n_classes = n_classes\n print('setting up training for {} classes'.format(n_classes))\n dataset = d.MelSpecDataset(params)\n net = m.VGGish(params)\n net.init_weights()\n net.freeze_bottom()\n new_top = torch.nn.Linear(net.out_dims*512, net.n_classes)\n net.classifier = new_top\n net.to(device)\n criterion = torch.nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(net.parameters())\n trainer = t.Trainer(net, dataset, criterion, optimizer, params, device)\n\n # starting training\n print('start training on {} for {} epochs'.format(device, params.n_epochs))\n trainer.run_training()\n\n # saving model weights and class labels\n if params.save_model:\n print('saving weights and class labels')\n net.save_weights()\n print(dataset.labels)\n with open(os.path.join(params.model_zoo, params.name+'.pkl'), 'wb') as f:\n pickle.dump(dataset.labels, f)\n\n return net, dataset.labels\n\n\nif __name__ == '__main__':\n\n params = p.Params()\n params = prepare(params)\n _, _ = start_training_with(params)\n print('done')\n"
] | [
[
"torch.device",
"torch.nn.Linear",
"torch.nn.CrossEntropyLoss"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dennis199441/Audio-Captcha-Recognition | [
"cd8a30a95daefb24cad7a9abe37604417f893484"
] | [
"src/utils.py"
] | [
"# -*- coding: utf-8 -*-\n#\n# This file is part of SIDEKIT.\n#\n# SIDEKIT is a python package for speaker verification.\n# Home page: http://www-lium.univ-lemans.fr/sidekit/\n#\n# SIDEKIT is a python package for speaker verification.\n# Home page: http://www-lium.univ-lemans.fr/sidekit/\n# \n# SIDEKIT is free software: you can redistribute it and/or modify\n# it under the terms of the GNU LLesser General Public License as \n# published by the Free Software Foundation, either version 3 of the License, \n# or (at your option) any later version.\n#\n# SIDEKIT is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with SIDEKIT. If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\nCopyright 2014-2017 Anthony Larcher and Sylvain Meignier\n\n:mod:`frontend` provides methods to process an audio signal in order to extract\nuseful parameters for speaker verification.\n\"\"\"\n\nimport numpy\nimport numpy.matlib\nimport scipy\nfrom scipy.fftpack.realtransforms import dct\n#from sidekit.frontend.vad import pre_emphasis\n#from sidekit.frontend.io import *\n#from sidekit.frontend.normfeat import *\n#from sidekit.frontend.features import *\nimport numpy.matlib\n\nPARAM_TYPE = numpy.float32\n\n__author__ = \"Anthony Larcher and Sylvain Meignier\"\n__copyright__ = \"Copyright 2014-2017 Anthony Larcher and Sylvain Meignier\"\n__license__ = \"LGPL\"\n__maintainer__ = \"Anthony Larcher\"\n__email__ = \"[email protected]\"\n__status__ = \"Production\"\n__docformat__ = 'reStructuredText'\n\ndef pre_emphasis(input_sig, pre):\n \"\"\"Pre-emphasis of an audio signal.\n :param input_sig: the input vector of signal to pre emphasize\n :param pre: value that defines the pre-emphasis filter. \n \"\"\"\n if input_sig.ndim == 1:\n return (input_sig - numpy.c_[input_sig[numpy.newaxis, :][..., :1],\n input_sig[numpy.newaxis, :][..., :-1]].squeeze() * pre)\n else:\n return input_sig - numpy.c_[input_sig[..., :1], input_sig[..., :-1]] * pre\n\ndef hz2mel(f, htk=True):\n \"\"\"Convert an array of frequency in Hz into mel.\n \n :param f: frequency to convert\n \n :return: the equivalence on the mel scale.\n \"\"\"\n if htk:\n return 2595 * numpy.log10(1 + f / 700.)\n else:\n f = numpy.array(f)\n\n # Mel fn to match Slaney's Auditory Toolbox mfcc.m\n # Mel fn to match Slaney's Auditory Toolbox mfcc.m\n f_0 = 0.\n f_sp = 200. / 3.\n brkfrq = 1000.\n brkpt = (brkfrq - f_0) / f_sp\n logstep = numpy.exp(numpy.log(6.4) / 27)\n\n linpts = f < brkfrq\n\n z = numpy.zeros_like(f)\n # fill in parts separately\n z[linpts] = (f[linpts] - f_0) / f_sp\n z[~linpts] = brkpt + (numpy.log(f[~linpts] / brkfrq)) / numpy.log(logstep)\n\n if z.shape == (1,):\n return z[0]\n else:\n return z\n\n\n\ndef mel2hz(z, htk=True):\n \"\"\"Convert an array of mel values in Hz.\n \n :param m: ndarray of frequencies to convert in Hz.\n \n :return: the equivalent values in Hertz.\n \"\"\"\n if htk:\n return 700. * (10**(z / 2595.) - 1)\n else:\n z = numpy.array(z, dtype=float)\n f_0 = 0\n f_sp = 200. / 3.\n brkfrq = 1000.\n brkpt = (brkfrq - f_0) / f_sp\n logstep = numpy.exp(numpy.log(6.4) / 27)\n\n linpts = (z < brkpt)\n\n f = numpy.zeros_like(z)\n\n # fill in parts separately\n f[linpts] = f_0 + f_sp * z[linpts]\n f[~linpts] = brkfrq * numpy.exp(numpy.log(logstep) * (z[~linpts] - brkpt))\n\n if f.shape == (1,):\n return f[0]\n else:\n return f\n\n\n\ndef hz2bark(f):\n \"\"\"\n Convert frequencies (Hertz) to Bark frequencies\n\n :param f: the input frequency\n :return:\n \"\"\"\n return 6. * numpy.arcsinh(f / 600.)\n\n\n\ndef bark2hz(z):\n \"\"\"\n Converts frequencies Bark to Hertz (Hz)\n\n :param z:\n :return:\n \"\"\"\n return 600. * numpy.sinh(z / 6.)\n\n\n\ndef compute_delta(features,\n win=3,\n method='filter',\n filt=numpy.array([.25, .5, .25, 0, -.25, -.5, -.25])):\n \"\"\"features is a 2D-ndarray each row of features is a a frame\n \n :param features: the feature frames to compute the delta coefficients\n :param win: parameter that set the length of the computation window.\n The size of the window is (win x 2) + 1\n :param method: method used to compute the delta coefficients\n can be diff or filter\n :param filt: definition of the filter to use in \"filter\" mode, default one\n is similar to SPRO4: filt=numpy.array([.2, .1, 0, -.1, -.2])\n \n :return: the delta coefficients computed on the original features.\n \"\"\"\n # First and last features are appended to the begining and the end of the \n # stream to avoid border effect\n x = numpy.zeros((features.shape[0] + 2 * win, features.shape[1]), dtype=PARAM_TYPE)\n x[:win, :] = features[0, :]\n x[win:-win, :] = features\n x[-win:, :] = features[-1, :]\n\n delta = numpy.zeros(x.shape, dtype=PARAM_TYPE)\n\n if method == 'diff':\n filt = numpy.zeros(2 * win + 1, dtype=PARAM_TYPE)\n filt[0] = -1\n filt[-1] = 1\n\n for i in range(features.shape[1]):\n delta[:, i] = numpy.convolve(features[:, i], filt)\n\n return delta[win:-win, :]\n\n\n\ndef pca_dct(cep, left_ctx=12, right_ctx=12, p=None):\n \"\"\"Apply DCT PCA as in [McLaren 2015] paper:\n Mitchell McLaren and Yun Lei, 'Improved Speaker Recognition \n Using DCT coefficients as features' in ICASSP, 2015\n \n A 1D-dct is applied to the cepstral coefficients on a temporal\n sliding window.\n The resulting matrix is then flatten and reduced by using a Principal\n Component Analysis.\n \n :param cep: a matrix of cepstral cefficients, 1 line per feature vector\n :param left_ctx: number of frames to consider for left context\n :param right_ctx: number of frames to consider for right context\n :param p: a PCA matrix trained on a developpment set to reduce the\n dimension of the features. P is a portait matrix\n \"\"\"\n y = numpy.r_[numpy.resize(cep[0, :], (left_ctx, cep.shape[1])),\n cep,\n numpy.resize(cep[-1, :], (right_ctx, cep.shape[1]))]\n\n ceps = framing(y, win_size=left_ctx + 1 + right_ctx).transpose(0, 2, 1)\n dct_temp = (dct_basis(left_ctx + 1 + right_ctx, left_ctx + 1 + right_ctx)).T\n if p is None:\n p = numpy.eye(dct_temp.shape[0] * cep.shape[1], dtype=PARAM_TYPE)\n return (numpy.dot(ceps.reshape(-1, dct_temp.shape[0]),\n dct_temp).reshape(ceps.shape[0], -1)).dot(p)\n\n\n\ndef shifted_delta_cepstral(cep, d=1, p=3, k=7):\n \"\"\"\n Compute the Shifted-Delta-Cepstral features for language identification\n \n :param cep: matrix of feature, 1 vector per line\n :param d: represents the time advance and delay for the delta computation\n :param k: number of delta-cepstral blocks whose delta-cepstral \n coefficients are stacked to form the final feature vector\n :param p: time shift between consecutive blocks.\n \n return: cepstral coefficient concatenated with shifted deltas\n \"\"\"\n\n y = numpy.r_[numpy.resize(cep[0, :], (d, cep.shape[1])),\n cep,\n numpy.resize(cep[-1, :], (k * 3 + d, cep.shape[1]))]\n\n delta = compute_delta(y, win=d, method='diff')\n sdc = numpy.empty((cep.shape[0], cep.shape[1] * k))\n\n idx = numpy.zeros(delta.shape[0], dtype='bool')\n for ii in range(k):\n idx[d + ii * p] = True\n for ff in range(len(cep)):\n sdc[ff, :] = delta[idx, :].reshape(1, -1)\n idx = numpy.roll(idx, 1)\n return numpy.hstack((cep, sdc))\n\n\n\ndef trfbank(fs, nfft, lowfreq, maxfreq, nlinfilt, nlogfilt, midfreq=1000):\n \"\"\"Compute triangular filterbank for cepstral coefficient computation.\n\n :param fs: sampling frequency of the original signal.\n :param nfft: number of points for the Fourier Transform\n :param lowfreq: lower limit of the frequency band filtered\n :param maxfreq: higher limit of the frequency band filtered\n :param nlinfilt: number of linear filters to use in low frequencies\n :param nlogfilt: number of log-linear filters to use in high frequencies\n :param midfreq: frequency boundary between linear and log-linear filters\n\n :return: the filter bank and the central frequencies of each filter\n \"\"\"\n # Total number of filters\n nfilt = nlinfilt + nlogfilt\n\n # ------------------------\n # Compute the filter bank\n # ------------------------\n # Compute start/middle/end points of the triangular filters in spectral\n # domain\n frequences = numpy.zeros(nfilt + 2, dtype=PARAM_TYPE)\n if nlogfilt == 0:\n linsc = (maxfreq - lowfreq) / (nlinfilt + 1)\n frequences[:nlinfilt + 2] = lowfreq + numpy.arange(nlinfilt + 2) * linsc\n elif nlinfilt == 0:\n low_mel = hz2mel(lowfreq)\n max_mel = hz2mel(maxfreq)\n mels = numpy.zeros(nlogfilt + 2)\n # mels[nlinfilt:]\n melsc = (max_mel - low_mel) / (nfilt + 1)\n mels[:nlogfilt + 2] = low_mel + numpy.arange(nlogfilt + 2) * melsc\n # Back to the frequency domain\n frequences = mel2hz(mels)\n else:\n # Compute linear filters on [0;1000Hz]\n linsc = (min([midfreq, maxfreq]) - lowfreq) / (nlinfilt + 1)\n frequences[:nlinfilt] = lowfreq + numpy.arange(nlinfilt) * linsc\n # Compute log-linear filters on [1000;maxfreq]\n low_mel = hz2mel(min([1000, maxfreq]))\n max_mel = hz2mel(maxfreq)\n mels = numpy.zeros(nlogfilt + 2, dtype=PARAM_TYPE)\n melsc = (max_mel - low_mel) / (nlogfilt + 1)\n\n # Verify that mel2hz(melsc)>linsc\n while mel2hz(melsc) < linsc:\n # in this case, we add a linear filter\n nlinfilt += 1\n nlogfilt -= 1\n frequences[:nlinfilt] = lowfreq + numpy.arange(nlinfilt) * linsc\n low_mel = hz2mel(frequences[nlinfilt - 1] + 2 * linsc)\n max_mel = hz2mel(maxfreq)\n mels = numpy.zeros(nlogfilt + 2, dtype=PARAM_TYPE)\n melsc = (max_mel - low_mel) / (nlogfilt + 1)\n\n mels[:nlogfilt + 2] = low_mel + numpy.arange(nlogfilt + 2) * melsc\n # Back to the frequency domain\n frequences[nlinfilt:] = mel2hz(mels)\n\n heights = 2. / (frequences[2:] - frequences[0:-2])\n\n # Compute filterbank coeff (in fft domain, in bins)\n fbank = numpy.zeros((nfilt, int(numpy.floor(nfft / 2)) + 1), dtype=PARAM_TYPE)\n # FFT bins (in Hz)\n n_frequences = numpy.arange(nfft) / (1. * nfft) * fs\n\n for i in range(nfilt):\n low = frequences[i]\n cen = frequences[i + 1]\n hi = frequences[i + 2]\n\n lid = numpy.arange(numpy.floor(low * nfft / fs) + 1, numpy.floor(cen * nfft / fs) + 1, dtype=numpy.int)\n left_slope = heights[i] / (cen - low)\n rid = numpy.arange(numpy.floor(cen * nfft / fs) + 1,\n min(numpy.floor(hi * nfft / fs) + 1, nfft), dtype=numpy.int)\n right_slope = heights[i] / (hi - cen)\n fbank[i][lid] = left_slope * (n_frequences[lid] - low)\n fbank[i][rid[:-1]] = right_slope * (hi - n_frequences[rid[:-1]])\n\n return fbank, frequences\n\n\n\ndef mel_filter_bank(fs, nfft, lowfreq, maxfreq, widest_nlogfilt, widest_lowfreq, widest_maxfreq,):\n \"\"\"Compute triangular filterbank for cepstral coefficient computation.\n\n :param fs: sampling frequency of the original signal.\n :param nfft: number of points for the Fourier Transform\n :param lowfreq: lower limit of the frequency band filtered\n :param maxfreq: higher limit of the frequency band filtered\n :param widest_nlogfilt: number of log filters\n :param widest_lowfreq: lower frequency of the filter bank\n :param widest_maxfreq: higher frequency of the filter bank\n :param widest_maxfreq: higher frequency of the filter bank\n\n :return: the filter bank and the central frequencies of each filter\n \"\"\"\n\n # ------------------------\n # Compute the filter bank\n # ------------------------\n # Compute start/middle/end points of the triangular filters in spectral\n # domain\n widest_freqs = numpy.zeros(widest_nlogfilt + 2, dtype=PARAM_TYPE)\n low_mel = hz2mel(widest_lowfreq)\n max_mel = hz2mel(widest_maxfreq)\n mels = numpy.zeros(widest_nlogfilt+2)\n melsc = (max_mel - low_mel) / (widest_nlogfilt + 1)\n mels[:widest_nlogfilt + 2] = low_mel + numpy.arange(widest_nlogfilt + 2) * melsc\n # Back to the frequency domain\n widest_freqs = mel2hz(mels)\n\n # Select filters in the narrow band\n sub_band_freqs = numpy.array([fr for fr in widest_freqs if lowfreq <= fr <= maxfreq], dtype=PARAM_TYPE)\n\n heights = 2./(sub_band_freqs[2:] - sub_band_freqs[0:-2])\n nfilt = sub_band_freqs.shape[0] - 2\n\n # Compute filterbank coeff (in fft domain, in bins)\n fbank = numpy.zeros((nfilt, numpy.floor(nfft/2)+1), dtype=PARAM_TYPE)\n # FFT bins (in Hz)\n nfreqs = numpy.arange(nfft) / (1. * nfft) * fs\n\n for i in range(nfilt):\n low = sub_band_freqs[i]\n cen = sub_band_freqs[i+1]\n hi = sub_band_freqs[i+2]\n lid = numpy.arange(numpy.floor(low * nfft / fs) + 1, numpy.floor(cen * nfft / fs) + 1, dtype=numpy.int)\n left_slope = heights[i] / (cen - low)\n rid = numpy.arange(numpy.floor(cen * nfft / fs) + 1, min(numpy.floor(hi * nfft / fs) + 1,\n nfft), dtype=numpy.int)\n right_slope = heights[i] / (hi - cen)\n fbank[i][lid] = left_slope * (nfreqs[lid] - low)\n fbank[i][rid[:-1]] = right_slope * (hi - nfreqs[rid[:-1]])\n\n return fbank, sub_band_freqs\n\n\n\ndef power_spectrum(input_sig,\n fs=8000,\n win_time=0.025,\n shift=0.01,\n prefac=0.97):\n \"\"\"\n Compute the power spectrum of the signal.\n :param input_sig:\n :param fs:\n :param win_time:\n :param shift:\n :param prefac:\n :return:\n \"\"\"\n window_length = int(round(win_time * fs))\n overlap = window_length - int(shift * fs)\n framed = framing(input_sig, window_length, win_shift=window_length-overlap).copy()\n \n\n # Pre-emphasis filtering is applied after framing to be consistent with stream processing\n #framed = pre_emphasis(framed, prefac)\n\n l = framed.shape[0]\n n_fft = 2 ** int(numpy.ceil(numpy.log2(window_length)))\n # Windowing has been changed to hanning which is supposed to have less noisy sidelobes\n # ham = numpy.hamming(window_length)\n window = numpy.hanning(window_length+2)\n window=window[1:-1]\n spec = numpy.ones((l, int(n_fft / 2) + 1), dtype=PARAM_TYPE)\n #log_energy = numpy.log((framed**2).sum(axis=1))\n dec = 500000\n start = 0\n stop = min(dec, l)\n while start < l:\n ahan = framed[start:stop, :] * numpy.matlib.repmat(window, stop-start, 1)\n mag = numpy.fft.rfft(ahan, n_fft, axis=-1)\n spec[start:stop, :] = mag.real**2 + mag.imag**2\n start = stop\n stop = min(stop + dec, l)\n\n return spec #, log_energy\n\n\n\ndef mfcc(input_sig,\n lowfreq=100, maxfreq=8000,\n nlinfilt=0, nlogfilt=24,\n nwin=0.025,\n fs=16000,\n nceps=13,\n shift=0.01,\n get_spec=False,\n get_mspec=False,\n prefac=0.97):\n \"\"\"Compute Mel Frequency Cepstral Coefficients.\n\n :param input_sig: input signal from which the coefficients are computed.\n Input audio is supposed to be RAW PCM 16bits\n :param lowfreq: lower limit of the frequency band filtered. \n Default is 100Hz.\n :param maxfreq: higher limit of the frequency band filtered.\n Default is 8000Hz.\n :param nlinfilt: number of linear filters to use in low frequencies.\n Default is 0.\n :param nlogfilt: number of log-linear filters to use in high frequencies.\n Default is 24.\n :param nwin: length of the sliding window in seconds\n Default is 0.025.\n :param fs: sampling frequency of the original signal. Default is 16000Hz.\n :param nceps: number of cepstral coefficients to extract. \n Default is 13.\n :param shift: shift between two analyses. Default is 0.01 (10ms).\n :param get_spec: boolean, if true returns the spectrogram\n :param get_mspec: boolean, if true returns the output of the filter banks\n :param prefac: pre-emphasis filter value\n\n :return: the cepstral coefficients in a ndaray as well as \n the Log-spectrum in the mel-domain in a ndarray.\n\n .. note:: MFCC are computed as follows:\n \n - Pre-processing in time-domain (pre-emphasizing)\n - Compute the spectrum amplitude by windowing with a Hamming window\n - Filter the signal in the spectral domain with a triangular filter-bank, whose filters are approximatively\n linearly spaced on the mel scale, and have equal bandwith in the mel scale\n - Compute the DCT of the log-spectrom\n - Log-energy is returned as first coefficient of the feature vector.\n \n For more details, refer to [Davis80]_.\n \"\"\"\n # Compute power spectrum\n spec, log_energy = power_spectrum(input_sig,\n fs,\n win_time=nwin,\n shift=shift,\n prefac=prefac)\n\n # Filter the spectrum through the triangle filter-bank\n n_fft = 2 ** int(numpy.ceil(numpy.log2(int(round(nwin * fs)))))\n fbank = trfbank(fs, n_fft, lowfreq, maxfreq, nlinfilt, nlogfilt)[0]\n\n mspec = numpy.log(numpy.dot(spec, fbank.T)) # A tester avec log10 et log\n\n # Use the DCT to 'compress' the coefficients (spectrum -> cepstrum domain)\n # The C0 term is removed as it is the constant term\n ceps = dct(mspec, type=2, norm='ortho', axis=-1)[:, 1:nceps + 1]\n lst = list()\n lst.append(ceps)\n lst.append(log_energy)\n if get_spec:\n lst.append(spec)\n else:\n lst.append(None)\n del spec\n if get_mspec:\n lst.append(mspec)\n else:\n lst.append(None)\n del mspec\n\n return lst\n\n\n\ndef fft2barkmx(n_fft, fs, nfilts=0, width=1., minfreq=0., maxfreq=8000):\n \"\"\"\n Generate a matrix of weights to combine FFT bins into Bark\n bins. n_fft defines the source FFT size at sampling rate fs.\n Optional nfilts specifies the number of output bands required\n (else one per bark), and width is the constant width of each\n band in Bark (default 1).\n While wts has n_fft columns, the second half are all zero.\n Hence, Bark spectrum is fft2barkmx(n_fft,fs) * abs(fft(xincols, n_fft));\n 2004-09-05 [email protected] based on rastamat/audspec.m\n\n :param n_fft: the source FFT size at sampling rate fs\n :param fs: sampling rate\n :param nfilts: number of output bands required\n :param width: constant width of each band in Bark (default 1)\n :param minfreq:\n :param maxfreq:\n :return: a matrix of weights to combine FFT bins into Bark bins\n \"\"\"\n maxfreq = min(maxfreq, fs / 2.)\n\n min_bark = hz2bark(minfreq)\n nyqbark = hz2bark(maxfreq) - min_bark\n\n if nfilts == 0:\n nfilts = numpy.ceil(nyqbark) + 1\n\n wts = numpy.zeros((nfilts, n_fft))\n\n # bark per filt\n step_barks = nyqbark / (nfilts - 1)\n\n # Frequency of each FFT bin in Bark\n binbarks = hz2bark(numpy.arange(n_fft / 2 + 1) * fs / n_fft)\n\n for i in range(nfilts):\n f_bark_mid = min_bark + i * step_barks\n # Linear slopes in log-space (i.e. dB) intersect to trapezoidal window\n lof = (binbarks - f_bark_mid - 0.5)\n hif = (binbarks - f_bark_mid + 0.5)\n wts[i, :n_fft // 2 + 1] = 10 ** (numpy.minimum(numpy.zeros_like(hif), numpy.minimum(hif, -2.5 * lof) / width))\n\n return wts\n\n\n\ndef fft2melmx(n_fft,\n fs=8000,\n nfilts=0,\n width=1.,\n minfreq=0,\n maxfreq=4000,\n htkmel=False,\n constamp=False):\n \"\"\"\n Generate a matrix of weights to combine FFT bins into Mel\n bins. n_fft defines the source FFT size at sampling rate fs.\n Optional nfilts specifies the number of output bands required\n (else one per \"mel/width\"), and width is the constant width of each\n band relative to standard Mel (default 1).\n While wts has n_fft columns, the second half are all zero.\n Hence, Mel spectrum is fft2melmx(n_fft,fs)*abs(fft(xincols,n_fft));\n minfreq is the frequency (in Hz) of the lowest band edge;\n default is 0, but 133.33 is a common standard (to skip LF).\n maxfreq is frequency in Hz of upper edge; default fs/2.\n You can exactly duplicate the mel matrix in Slaney's mfcc.m\n as fft2melmx(512, 8000, 40, 1, 133.33, 6855.5, 0);\n htkmel=1 means use HTK's version of the mel curve, not Slaney's.\n constamp=1 means make integration windows peak at 1, not sum to 1.\n frqs returns bin center frqs.\n\n % 2004-09-05 [email protected] based on fft2barkmx\n\n :param n_fft:\n :param fs:\n :param nfilts:\n :param width:\n :param minfreq:\n :param maxfreq:\n :param htkmel:\n :param constamp:\n :return:\n \"\"\"\n maxfreq = min(maxfreq, fs / 2.)\n\n if nfilts == 0:\n nfilts = numpy.ceil(hz2mel(maxfreq, htkmel) / 2.)\n\n wts = numpy.zeros((nfilts, n_fft))\n\n # Center freqs of each FFT bin\n fftfrqs = numpy.arange(n_fft / 2 + 1) / n_fft * fs\n\n # 'Center freqs' of mel bands - uniformly spaced between limits\n minmel = hz2mel(minfreq, htkmel)\n maxmel = hz2mel(maxfreq, htkmel)\n binfrqs = mel2hz(minmel + numpy.arange(nfilts + 2) / (nfilts + 1) * (maxmel - minmel), htkmel)\n\n for i in range(nfilts):\n _fs = binfrqs[i + numpy.arange(3, dtype=int)]\n # scale by width\n _fs = _fs[1] + width * (_fs - _fs[1])\n # lower and upper slopes for all bins\n loslope = (fftfrqs - _fs[0]) / (_fs[1] - __fs[0])\n hislope = (_fs[2] - fftfrqs)/(_fs[2] - _fs[1])\n\n wts[i, 1 + numpy.arange(n_fft//2 + 1)] =numpy.maximum(numpy.zeros_like(loslope),numpy.minimum(loslope, hislope))\n\n if not constamp:\n # Slaney-style mel is scaled to be approx constant E per channel\n wts = numpy.dot(numpy.diag(2. / (binfrqs[2 + numpy.arange(nfilts)] - binfrqs[numpy.arange(nfilts)])) , wts)\n\n # Make sure 2nd half of FFT is zero\n wts[:, n_fft // 2 + 1: n_fft] = 0\n\n return wts, binfrqs\n\n\n\ndef audspec(power_spectrum,\n fs=16000,\n nfilts=None,\n fbtype='bark',\n minfreq=0,\n maxfreq=8000,\n sumpower=True,\n bwidth=1.):\n \"\"\"\n\n :param power_spectrum:\n :param fs:\n :param nfilts:\n :param fbtype:\n :param minfreq:\n :param maxfreq:\n :param sumpower:\n :param bwidth:\n :return:\n \"\"\"\n if nfilts is None:\n nfilts = int(numpy.ceil(hz2bark(fs / 2)) + 1)\n\n if not fs == 16000:\n maxfreq = min(fs / 2, maxfreq)\n\n nframes, nfreqs = power_spectrum.shape\n n_fft = (nfreqs -1 ) * 2\n\n if fbtype == 'bark':\n wts = fft2barkmx(n_fft, fs, nfilts, bwidth, minfreq, maxfreq)\n elif fbtype == 'mel':\n wts = fft2melmx(n_fft, fs, nfilts, bwidth, minfreq, maxfreq)\n elif fbtype == 'htkmel':\n wts = fft2melmx(n_fft, fs, nfilts, bwidth, minfreq, maxfreq, True, True)\n elif fbtype == 'fcmel':\n wts = fft2melmx(n_fft, fs, nfilts, bwidth, minfreq, maxfreq, True, False)\n else:\n print('fbtype {} not recognized'.format(fbtype))\n\n wts = wts[:, :nfreqs]\n\n if sumpower:\n audio_spectrum = power_spectrum.dot(wts.T)\n else:\n audio_spectrum = numpy.dot(numpy.sqrt(power_spectrum), wts.T)**2\n\n return audio_spectrum #, wts\n\n\n\ndef postaud(x, fmax, fbtype='bark', broaden=0):\n \"\"\"\n do loudness equalization and cube root compression\n\n :param x:\n :param fmax:\n :param fbtype:\n :param broaden:\n :return:\n \"\"\"\n nframes, nbands = x.shape\n\n # Include frequency points at extremes, discard later\n nfpts = nbands + 2 * broaden\n\n if fbtype == 'bark':\n bandcfhz = bark2hz(numpy.linspace(0, hz2bark(fmax), num=nfpts))\n elif fbtype == 'mel':\n bandcfhz = mel2hz(numpy.linspace(0, hz2bark(fmax), num=nfpts))\n elif fbtype == 'htkmel' or fbtype == 'fcmel':\n bandcfhz = mel2hz(numpy.linspace(0, hz2mel(fmax,1), num=nfpts),1)\n else:\n print('unknown fbtype {}'.format(fbtype))\n\n # Remove extremal bands (the ones that will be duplicated)\n bandcfhz = bandcfhz[broaden:(nfpts - broaden)]\n\n # Hynek's magic equal-loudness-curve formula\n fsq = bandcfhz ** 2\n ftmp = fsq + 1.6e5\n eql = ((fsq / ftmp) ** 2) * ((fsq + 1.44e6) / (fsq + 9.61e6))\n\n # weight the critical bands\n z = numpy.matlib.repmat(eql.T,nframes,1) * x\n\n # cube root compress\n z = z ** .33\n\n # replicate first and last band (because they are unreliable as calculated)\n if broaden == 1:\n y = z[:, numpy.hstack((0,numpy.arange(nbands), nbands - 1))]\n else:\n y = z[:, numpy.hstack((1,numpy.arange(1, nbands - 1), nbands - 2))]\n\n return y, eql\n\n\n\ndef dolpc(x, model_order=8):\n \"\"\"\n compute autoregressive model from spectral magnitude samples\n\n :param x:\n :param model_order:\n :return:\n \"\"\"\n nframes, nbands = x.shape\n\n r = numpy.real(numpy.fft.ifft(numpy.hstack((x,x[:,numpy.arange(nbands-2,0,-1)]))))\n\n # First half only\n r = r[:, :nbands]\n\n # Find LPC coeffs by Levinson-Durbin recursion\n y_lpc = numpy.ones((r.shape[0], model_order + 1))\n\n for ff in range(r.shape[0]):\n y_lpc[ff, 1:], e, _ = levinson(r[ff, :-1].T, order=model_order, allow_singularity=True)\n # Normalize each poly by gain\n y_lpc[ff, :] /= e\n\n return y_lpc\n\n\n\ndef lpc2cep(a, nout):\n \"\"\"\n Convert the LPC 'a' coefficients in each column of lpcas\n into frames of cepstra.\n nout is number of cepstra to produce, defaults to size(lpcas,1)\n 2003-04-11 [email protected]\n\n :param a:\n :param nout:\n :return:\n \"\"\"\n ncol , nin = a.shape\n\n order = nin - 1\n\n if nout is None:\n nout = order + 1\n\n c = numpy.zeros((ncol, nout))\n\n # First cep is log(Error) from Durbin\n c[:, 0] = -numpy.log(a[:, 0])\n\n # Renormalize lpc A coeffs\n a /= numpy.tile(a[:, 0][:, None], (1, nin))\n\n for n in range(1, nout):\n sum = 0\n for m in range(1, n):\n sum += (n - m) * a[:, m] * c[:, n - m]\n c[:, n] = -(a[:, n] + sum / n)\n\n return c\n\n\n\ndef lpc2spec(lpcas, nout=17):\n \"\"\"\n Convert LPC coeffs back into spectra\n nout is number of freq channels, default 17 (i.e. for 8 kHz)\n\n :param lpcas:\n :param nout:\n :return:\n \"\"\"\n [cols, rows] = lpcas.shape\n order = rows - 1\n\n gg = lpcas[:, 0]\n aa = lpcas / numpy.tile(gg, (rows,1)).T\n\n # Calculate the actual z-plane polyvals: nout points around unit circle\n zz = numpy.exp((-1j * numpy.pi / (nout - 1)) * numpy.outer(numpy.arange(nout).T, numpy.arange(order + 1)))\n\n # Actual polyvals, in power (mag^2)\n features = ( 1./numpy.abs(aa.dot(zz.T))**2) / numpy.tile(gg, (nout, 1)).T\n\n F = numpy.zeros((cols, rows-1))\n M = numpy.zeros((cols, rows-1))\n\n for c in range(cols):\n aaa = aa[c, :]\n rr = numpy.roots(aaa)\n ff = numpy.angle(rr.T)\n zz = numpy.exp(1j * numpy.outer(ff, numpy.arange(len(aaa))))\n mags = numpy.sqrt(((1./numpy.abs(zz.dot(aaa)))**2)/gg[c])\n ix = numpy.argsort(ff)\n keep = ff[ix] > 0\n ix = ix[keep]\n F[c, numpy.arange(len(ix))] = ff[ix]\n M[c, numpy.arange(len(ix))] = mags[ix]\n\n F = F[:, F.sum(axis=0) != 0]\n M = M[:, M.sum(axis=0) != 0]\n\n return features, F, M\n\n\n\ndef spec2cep(spec, ncep=13, type=2):\n \"\"\"\n Calculate cepstra from spectral samples (in columns of spec)\n Return ncep cepstral rows (defaults to 9)\n This one does type II dct, or type I if type is specified as 1\n dctm returns the DCT matrix that spec was multiplied by to give cep.\n\n :param spec:\n :param ncep:\n :param type:\n :return:\n \"\"\"\n nrow, ncol = spec.shape\n\n # Make the DCT matrix\n dctm = numpy.zeros(ncep, nrow);\n #if type == 2 || type == 3\n # # this is the orthogonal one, the one you want\n # for i = 1:ncep\n # dctm(i,:) = cos((i-1)*[1:2:(2*nrow-1)]/(2*nrow)*pi) * sqrt(2/nrow);\n\n # if type == 2\n # # make it unitary! (but not for HTK type 3)\n # dctm(1,:) = dctm(1,:)/sqrt(2);\n\n #elif type == 4: # type 1 with implicit repeating of first, last bins\n # \"\"\"\n # Deep in the heart of the rasta/feacalc code, there is the logic\n # that the first and last auditory bands extend beyond the edge of\n # the actual spectra, and they are thus copied from their neighbors.\n # Normally, we just ignore those bands and take the 19 in the middle,\n # but when feacalc calculates mfccs, it actually takes the cepstrum\n # over the spectrum *including* the repeated bins at each end.\n # Here, we simulate 'repeating' the bins and an nrow+2-length\n # spectrum by adding in extra DCT weight to the first and last\n # bins.\n # \"\"\"\n # for i = 1:ncep\n # dctm(i,:) = cos((i-1)*[1:nrow]/(nrow+1)*pi) * 2;\n # # Add in edge points at ends (includes fixup scale)\n # dctm(i,1) = dctm(i,1) + 1;\n # dctm(i,nrow) = dctm(i,nrow) + ((-1)^(i-1));\n\n # dctm = dctm / (2*(nrow+1));\n #else % dpwe type 1 - same as old spec2cep that expanded & used fft\n # for i = 1:ncep\n # dctm(i,:) = cos((i-1)*[0:(nrow-1)]/(nrow-1)*pi) * 2 / (2*(nrow-1));\n # dctm(:,[1 nrow]) = dctm(:, [1 nrow])/2;\n\n #cep = dctm*log(spec);\n return None, None, None\n\n\n\ndef lifter(x, lift=0.6, invs=False):\n \"\"\"\n Apply lifter to matrix of cepstra (one per column)\n lift = exponent of x i^n liftering\n or, as a negative integer, the length of HTK-style sin-curve liftering.\n If inverse == 1 (default 0), undo the liftering.\n\n :param x:\n :param lift:\n :param invs:\n :return:\n \"\"\"\n nfrm , ncep = x.shape\n\n if lift == 0:\n y = x\n else:\n if lift > 0:\n if lift > 10:\n print('Unlikely lift exponent of {} did you mean -ve?'.format(lift))\n liftwts = numpy.hstack((1, numpy.arange(1, ncep)**lift))\n\n elif lift < 0:\n # Hack to support HTK liftering\n L = float(-lift)\n if (L != numpy.round(L)):\n print('HTK liftering value {} must be integer'.format(L))\n\n liftwts = numpy.hstack((1, 1 + L/2*numpy.sin(numpy.arange(1, ncep) * numpy.pi / L)))\n\n if invs:\n liftwts = 1 / liftwts\n\n y = x.dot(numpy.diag(liftwts))\n\n return y\n\n\n\ndef plp(input_sig,\n nwin=0.025,\n fs=16000,\n plp_order=13,\n shift=0.01,\n get_spec=False,\n get_mspec=False,\n prefac=0.97,\n rasta=True):\n \"\"\"\n output is matrix of features, row = feature, col = frame\n\n % fs is sampling rate of samples, defaults to 8000\n % dorasta defaults to 1; if 0, just calculate PLP\n % modelorder is order of PLP model, defaults to 8. 0 -> no PLP\n\n :param input_sig:\n :param fs: sampling rate of samples default is 8000\n :param rasta: default is True, if False, juste compute PLP\n :param model_order: order of the PLP model, default is 8, 0 means no PLP\n\n :return: matrix of features, row = features, column are frames\n \"\"\"\n plp_order -= 1\n\n # first compute power spectrum\n powspec, log_energy = power_spectrum(input_sig, fs, nwin, shift, prefac)\n\n # next group to critical bands\n audio_spectrum = audspec(powspec, fs)[0]\n nbands = audio_spectrum.shape[0]\n\n if rasta:\n # put in log domain\n nl_aspectrum = numpy.log(audio_spectrum)\n\n # next do rasta filtering\n ras_nl_aspectrum = rasta_filt(nl_aspectrum)\n\n # do inverse log\n audio_spectrum = numpy.exp(ras_nl_aspectrum)\n\n # do final auditory compressions\n post_spectrum = postaud(audio_spectrum, fs / 2.)[0]\n\n if plp_order > 0:\n\n # LPC analysis\n lpcas = dolpc(post_spectrum, plp_order)\n\n # convert lpc to cepstra\n cepstra = lpc2cep(lpcas, plp_order + 1)\n\n # .. or to spectra\n spectra, F, M = lpc2spec(lpcas, nbands)\n\n else:\n\n # No LPC smoothing of spectrum\n spectra = post_spectrum\n cepstra = spec2cep(spectra)\n\n cepstra = lifter(cepstra, 0.6)\n\n lst = list()\n lst.append(cepstra)\n lst.append(log_energy)\n if get_spec:\n lst.append(powspec)\n else:\n lst.append(None)\n del powspec\n if get_mspec:\n lst.append(post_spectrum)\n else:\n lst.append(None)\n del post_spectrum\n\n return lst\n\n\n\ndef framing(sig, win_size, win_shift=1, context=(0, 0), pad='zeros'):\n \"\"\"\n :param sig: input signal, can be mono or multi dimensional\n :param win_size: size of the window in term of samples\n :param win_shift: shift of the sliding window in terme of samples\n :param context: tuple of left and right context\n :param pad: can be zeros or edge\n \"\"\"\n dsize = sig.dtype.itemsize\n if sig.ndim == 1:\n sig = sig[:, numpy.newaxis]\n # Manage padding\n c = (context, ) + (sig.ndim - 1) * ((0, 0), )\n _win_size = win_size + sum(context)\n shape = (int((sig.shape[0] - win_size) / win_shift) + 1, 1, _win_size, sig.shape[1])\n strides = tuple(map(lambda x: x * dsize, [win_shift * sig.shape[1], 1, sig.shape[1], 1]))\n if pad == 'zeros':\n return numpy.lib.stride_tricks.as_strided(numpy.lib.pad(sig, c, 'constant', constant_values=(0,)),\n shape=shape,\n strides=strides).squeeze()\n elif pad == 'edge':\n return numpy.lib.stride_tricks.as_strided(numpy.lib.pad(sig, c, 'edge'),\n shape=shape,\n strides=strides).squeeze()\n\n\n\ndef dct_basis(nbasis, length):\n \"\"\"\n :param nbasis: number of CT coefficients to keep\n :param length: length of the matrix to process\n :return: a basis of DCT coefficients\n \"\"\"\n return scipy.fftpack.idct(numpy.eye(nbasis, length), norm='ortho')\n\n\n\ndef levinson(r, order=None, allow_singularity=False):\n r\"\"\"Levinson-Durbin recursion.\n\n Find the coefficients of a length(r)-1 order autoregressive linear process\n\n :param r: autocorrelation sequence of length N + 1 (first element being the zero-lag autocorrelation)\n :param order: requested order of the autoregressive coefficients. default is N.\n :param allow_singularity: false by default. Other implementations may be True (e.g., octave)\n\n :return:\n * the `N+1` autoregressive coefficients :math:`A=(1, a_1...a_N)`\n * the prediction errors\n * the `N` reflections coefficients values\n\n This algorithm solves the set of complex linear simultaneous equations\n using Levinson algorithm.\n\n .. math::\n\n \\bold{T}_M \\left( \\begin{array}{c} 1 \\\\ \\bold{a}_M \\end{array} \\right) =\n \\left( \\begin{array}{c} \\rho_M \\\\ \\bold{0}_M \\end{array} \\right)\n\n where :math:`\\bold{T}_M` is a Hermitian Toeplitz matrix with elements\n :math:`T_0, T_1, \\dots ,T_M`.\n\n .. note:: Solving this equations by Gaussian elimination would\n require :math:`M^3` operations whereas the levinson algorithm\n requires :math:`M^2+M` additions and :math:`M^2+M` multiplications.\n\n This is equivalent to solve the following symmetric Toeplitz system of\n linear equations\n\n .. math::\n\n \\left( \\begin{array}{cccc}\n r_1 & r_2^* & \\dots & r_{n}^*\\\\\n r_2 & r_1^* & \\dots & r_{n-1}^*\\\\\n \\dots & \\dots & \\dots & \\dots\\\\\n r_n & \\dots & r_2 & r_1 \\end{array} \\right)\n \\left( \\begin{array}{cccc}\n a_2\\\\\n a_3 \\\\\n \\dots \\\\\n a_{N+1} \\end{array} \\right)\n =\n \\left( \\begin{array}{cccc}\n -r_2\\\\\n -r_3 \\\\\n \\dots \\\\\n -r_{N+1} \\end{array} \\right)\n\n where :math:`r = (r_1 ... r_{N+1})` is the input autocorrelation vector, and\n :math:`r_i^*` denotes the complex conjugate of :math:`r_i`. The input r is typically\n a vector of autocorrelation coefficients where lag 0 is the first\n element :math:`r_1`.\n\n\n .. doctest::\n\n >>> import numpy; from spectrum import LEVINSON\n >>> T = numpy.array([3., -2+0.5j, .7-1j])\n >>> a, e, k = LEVINSON(T)\n\n \"\"\"\n #from numpy import isrealobj\n T0 = numpy.real(r[0])\n T = r[1:]\n M = len(T)\n\n if order is None:\n M = len(T)\n else:\n assert order <= M, 'order must be less than size of the input data'\n M = order\n\n realdata = numpy.isrealobj(r)\n if realdata is True:\n A = numpy.zeros(M, dtype=float)\n ref = numpy.zeros(M, dtype=float)\n else:\n A = numpy.zeros(M, dtype=complex)\n ref = numpy.zeros(M, dtype=complex)\n\n P = T0\n\n for k in range(M):\n save = T[k]\n if k == 0:\n temp = -save / P\n else:\n #save += sum([A[j]*T[k-j-1] for j in range(0,k)])\n for j in range(0, k):\n save = save + A[j] * T[k-j-1]\n temp = -save / P\n if realdata:\n P = P * (1. - temp**2.)\n else:\n P = P * (1. - (temp.real**2+temp.imag**2))\n\n if (P <= 0).any() and allow_singularity==False:\n raise ValueError(\"singular matrix\")\n A[k] = temp\n ref[k] = temp # save reflection coeff at each step\n if k == 0:\n continue\n\n khalf = (k+1)//2\n if realdata is True:\n for j in range(0, khalf):\n kj = k-j-1\n save = A[j]\n A[j] = save + temp * A[kj]\n if j != kj:\n A[kj] += temp*save\n else:\n for j in range(0, khalf):\n kj = k-j-1\n save = A[j]\n A[j] = save + temp * A[kj].conjugate()\n if j != kj:\n A[kj] = A[kj] + temp * save.conjugate()\n\n return A, P, ref"
] | [
[
"numpy.diag",
"numpy.dot",
"numpy.resize",
"numpy.minimum",
"numpy.sqrt",
"numpy.round",
"numpy.zeros_like",
"scipy.fftpack.realtransforms.dct",
"numpy.hanning",
"numpy.exp",
"numpy.roll",
"numpy.hstack",
"numpy.arange",
"numpy.eye",
"numpy.roots",
"numpy.ceil",
"numpy.real",
"numpy.isrealobj",
"numpy.matlib.repmat",
"numpy.zeros",
"numpy.lib.pad",
"numpy.log",
"numpy.log10",
"numpy.floor",
"numpy.argsort",
"numpy.array",
"numpy.arcsinh",
"numpy.convolve",
"numpy.log2",
"numpy.fft.rfft",
"numpy.tile",
"numpy.sinh",
"numpy.ones",
"numpy.angle",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"0.15",
"1.4",
"0.16",
"1.0",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"0.10",
"0.17",
"1.3"
],
"tensorflow": []
}
] |
lindylin1817/pytorch-image-models | [
"207b3607d196c4c095b13bcfd056b8c4617f0721"
] | [
"timm/models/layers/classifier.py"
] | [
"\"\"\" Classifier head and layer factory\n\nHacked together by / Copyright 2020 Ross Wightman\n\"\"\"\nfrom torch import nn as nn\nfrom torch.nn import functional as F\n\nfrom .adaptive_avgmax_pool import SelectAdaptivePool2d\nfrom .linear import Linear\n\n\ndef _create_pool(num_features, num_classes, pool_type='avg', use_conv=False):\n flatten_in_pool = not use_conv # flatten when we use a Linear layer after pooling\n if not pool_type:\n assert num_classes == 0 or use_conv,\\\n 'Pooling can only be disabled if classifier is also removed or conv classifier is used'\n flatten_in_pool = False # disable flattening if pooling is pass-through (no pooling)\n global_pool = SelectAdaptivePool2d(pool_type=pool_type, flatten=flatten_in_pool)\n num_pooled_features = num_features * global_pool.feat_mult()\n return global_pool, num_pooled_features\n\n\ndef _create_fc(num_features, num_classes, use_conv=False):\n print(\"------- classifier.py: num_classes = \" + str(num_classes))\n if num_classes <= 0:\n fc = nn.Identity() # pass-through (no classifier)\n elif use_conv:\n fc = nn.Conv2d(num_features, num_classes, 1, bias=True)\n else:\n # Default case, we will run into this branch\n # NOTE: using my Linear wrapper that fixes AMP + torchscript casting issue\n print(\" ---------- classifier.py: num_features = \" + str(num_features))\n fc = Linear(num_features, num_classes, bias=True)\n return fc\n\n\ndef create_classifier(num_features, num_classes, pool_type='avg', use_conv=False):\n global_pool, num_pooled_features = _create_pool(num_features, num_classes, pool_type, use_conv=use_conv)\n fc = _create_fc(num_pooled_features, num_classes, use_conv=use_conv)\n return global_pool, fc\n\n\nclass ClassifierHead(nn.Module):\n \"\"\"Classifier head w/ configurable global pooling and dropout.\"\"\"\n\n def __init__(self, in_chs, num_classes, pool_type='avg', drop_rate=0., use_conv=False):\n super(ClassifierHead, self).__init__()\n self.drop_rate = drop_rate\n self.global_pool, num_pooled_features = _create_pool(in_chs, num_classes, pool_type, use_conv=use_conv)\n self.fc = _create_fc(num_pooled_features, num_classes, use_conv=use_conv)\n self.flatten = nn.Flatten(1) if use_conv and pool_type else nn.Identity()\n\n def forward(self, x):\n x = self.global_pool(x)\n if self.drop_rate:\n x = F.dropout(x, p=float(self.drop_rate), training=self.training)\n x = self.fc(x)\n x = self.flatten(x)\n return x\n"
] | [
[
"torch.nn.Identity",
"torch.nn.Conv2d",
"torch.nn.Flatten"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Leedehai/taichi | [
"3aae973ae4e214c5c0f8d6fe8a5b290a9ade5fc9"
] | [
"examples/particle_renderer.py"
] | [
"import taichi as ti\nimport numpy as np\nimport math\nimport time\nfrom renderer_utils import out_dir, ray_aabb_intersection, inf, eps, \\\n intersect_sphere, sphere_aabb_intersect_motion, inside_taichi\n\nti.init(arch=ti.cuda, device_memory_GB=4)\n\nres = 1280, 720\nnum_spheres = 1024\ncolor_buffer = ti.Vector(3, dt=ti.f32)\nbbox = ti.Vector(3, dt=ti.f32, shape=2)\ngrid_density = ti.var(dt=ti.i32)\nvoxel_has_particle = ti.var(dt=ti.i32)\nmax_ray_depth = 4\nuse_directional_light = True\n\nparticle_x = ti.Vector(3, dt=ti.f32)\nparticle_v = ti.Vector(3, dt=ti.f32)\nparticle_color = ti.Vector(3, dt=ti.f32)\npid = ti.var(ti.i32)\nnum_particles = ti.var(ti.i32, shape=())\n\nfov = 0.23\ndist_limit = 100\n\nexposure = 1.5\ncamera_pos = ti.Vector([0.5, 0.32, 2.7])\nvignette_strength = 0.9\nvignette_radius = 0.0\nvignette_center = [0.5, 0.5]\nlight_direction = [1.2, 0.3, 0.7]\nlight_direction_noise = 0.03\nlight_color = [1.0, 1.0, 1.0]\n\ngrid_visualization_block_size = 16\ngrid_resolution = 256 // grid_visualization_block_size\n\nframe_id = 0\n\nrender_voxel = False # see dda()\ninv_dx = 256.0\ndx = 1.0 / inv_dx\n\ncamera_pos = ti.Vector([0.5, 0.27, 2.7])\nsupporter = 2\nshutter_time = 0.5e-3 # half the frame time (1e-3)\nsphere_radius = 0.0015\nparticle_grid_res = 256\nmax_num_particles_per_cell = 8192 * 1024\nmax_num_particles = 1024 * 1024 * 4\n\nassert sphere_radius * 2 * particle_grid_res < 1\n\n\[email protected]\ndef buffers():\n ti.root.dense(ti.ij,\n (res[0] // 8, res[1] // 8)).dense(ti.ij,\n 8).place(color_buffer)\n\n ti.root.dense(ti.ijk, 2).dense(ti.ijk, particle_grid_res // 8).dense(\n ti.ijk, 8).place(voxel_has_particle)\n ti.root.dense(ti.ijk, 4).pointer(ti.ijk, particle_grid_res // 8).dense(\n ti.ijk, 8).dynamic(ti.l, max_num_particles_per_cell, 512).place(pid)\n\n ti.root.dense(ti.l, max_num_particles).place(particle_x, particle_v,\n particle_color)\n ti.root.dense(ti.ijk, grid_resolution // 8).dense(ti.ijk,\n 8).place(grid_density)\n\n\[email protected]\ndef inside_grid(ipos):\n return ipos.min() >= 0 and ipos.max() < grid_resolution\n\n\n# The dda algorithm requires the voxel grid to have one surrounding layer of void region\n# to correctly render the outmost voxel faces\[email protected]\ndef inside_grid_loose(ipos):\n return ipos.min() >= -1 and ipos.max() <= grid_resolution\n\n\[email protected]\ndef query_density_int(ipos):\n inside = inside_grid(ipos)\n ret = 0\n if inside:\n ret = grid_density[ipos]\n else:\n ret = 0\n return ret\n\n\[email protected]\ndef voxel_color(pos):\n p = pos * grid_resolution\n\n p -= ti.Matrix.floor(p)\n\n boundary = 0.1\n count = 0\n for i in ti.static(range(3)):\n if p[i] < boundary or p[i] > 1 - boundary:\n count += 1\n f = 0.0\n if count >= 2:\n f = 1.0\n return ti.Vector([0.2, 0.3, 0.2]) * (2.3 - 2 * f)\n\n\[email protected]\ndef sdf(o):\n dist = 0.0\n if ti.static(supporter == 0):\n o -= ti.Vector([0.5, 0.002, 0.5])\n p = o\n h = 0.02\n ra = 0.29\n rb = 0.005\n d = (ti.Vector([p[0], p[2]]).norm() - 2.0 * ra + rb, abs(p[1]) - h)\n dist = min(max(d[0], d[1]), 0.0) + ti.Vector(\n [max(d[0], 0.0), max(d[1], 0)]).norm() - rb\n elif ti.static(supporter == 1):\n o -= ti.Vector([0.5, 0.002, 0.5])\n dist = (o.abs() - ti.Vector([0.5, 0.02, 0.5])).max()\n else:\n dist = o[1] - 0.027\n\n return dist\n\n\[email protected]\ndef ray_march(p, d):\n j = 0\n dist = 0.0\n limit = 200\n while j < limit and sdf(p + dist * d) > 1e-8 and dist < dist_limit:\n dist += sdf(p + dist * d)\n j += 1\n if dist > dist_limit:\n dist = inf\n return dist\n\n\[email protected]\ndef sdf_normal(p):\n d = 1e-3\n n = ti.Vector([0.0, 0.0, 0.0])\n for i in ti.static(range(3)):\n inc = p\n dec = p\n inc[i] += d\n dec[i] -= d\n n[i] = (0.5 / d) * (sdf(inc) - sdf(dec))\n return ti.Matrix.normalized(n)\n\n\[email protected]\ndef sdf_color(p):\n scale = 0.4\n if inside_taichi(ti.Vector([p[0], p[2]])):\n scale = 1\n return ti.Vector([0.3, 0.5, 0.7]) * scale\n\n\n# Digital differential analyzer for the grid visualization (render_voxels=True)\[email protected]\ndef dda(eye_pos, d):\n for i in ti.static(range(3)):\n if abs(d[i]) < 1e-6:\n d[i] = 1e-6\n rinv = 1.0 / d\n rsign = ti.Vector([0, 0, 0])\n for i in ti.static(range(3)):\n if d[i] > 0:\n rsign[i] = 1\n else:\n rsign[i] = -1\n\n bbox_min = ti.Vector([0.0, 0.0, 0.0]) - 10 * eps\n bbox_max = ti.Vector([1.0, 1.0, 1.0]) + 10 * eps\n inter, near, far = ray_aabb_intersection(bbox_min, bbox_max, eye_pos, d)\n hit_distance = inf\n normal = ti.Vector([0.0, 0.0, 0.0])\n c = ti.Vector([0.0, 0.0, 0.0])\n if inter:\n near = max(0, near)\n\n pos = eye_pos + d * (near + 5 * eps)\n\n o = grid_resolution * pos\n ipos = ti.Matrix.floor(o).cast(int)\n dis = (ipos - o + 0.5 + rsign * 0.5) * rinv\n running = 1\n i = 0\n hit_pos = ti.Vector([0.0, 0.0, 0.0])\n while running:\n last_sample = query_density_int(ipos)\n if not inside_grid_loose(ipos):\n running = 0\n # normal = [0, 0, 0]\n\n if last_sample:\n mini = (ipos - o + ti.Vector([0.5, 0.5, 0.5]) -\n rsign * 0.5) * rinv\n hit_distance = mini.max() * (1 / grid_resolution) + near\n hit_pos = eye_pos + hit_distance * d\n c = voxel_color(hit_pos)\n running = 0\n else:\n mm = ti.Vector([0, 0, 0])\n if dis[0] <= dis[1] and dis[0] < dis[2]:\n mm[0] = 1\n elif dis[1] <= dis[0] and dis[1] <= dis[2]:\n mm[1] = 1\n else:\n mm[2] = 1\n dis += mm * rsign * rinv\n ipos += mm * rsign\n normal = -mm * rsign\n i += 1\n return hit_distance, normal, c\n\n\[email protected]\ndef inside_particle_grid(ipos):\n pos = ipos * dx\n return bbox[0][0] <= pos[0] and pos[0] < bbox[1][0] and bbox[0][1] <= pos[\n 1] and pos[1] < bbox[1][1] and bbox[0][2] <= pos[2] and pos[2] < bbox[\n 1][2]\n\n\n# DDA for the particle visualization (render_voxels=False)\[email protected]\ndef dda_particle(eye_pos, d, t):\n grid_res = particle_grid_res\n\n # bounding box\n bbox_min = bbox[0]\n bbox_max = bbox[1]\n\n hit_pos = ti.Vector([0.0, 0.0, 0.0])\n normal = ti.Vector([0.0, 0.0, 0.0])\n c = ti.Vector([0.0, 0.0, 0.0])\n for i in ti.static(range(3)):\n if abs(d[i]) < 1e-6:\n d[i] = 1e-6\n\n inter, near, far = ray_aabb_intersection(bbox_min, bbox_max, eye_pos, d)\n near = max(0, near)\n\n closest_intersection = inf\n\n if inter:\n pos = eye_pos + d * (near + eps)\n\n rinv = 1.0 / d\n rsign = ti.Vector([0, 0, 0])\n for i in ti.static(range(3)):\n if d[i] > 0:\n rsign[i] = 1\n else:\n rsign[i] = -1\n\n o = grid_res * pos\n ipos = ti.Matrix.floor(o).cast(int)\n dis = (ipos - o + 0.5 + rsign * 0.5) * rinv\n running = 1\n # DDA for voxels with at least one particle\n while running:\n inside = inside_particle_grid(ipos)\n\n if inside:\n # once we actually intersect with a voxel that contains at least one particle, loop over the particle list\n num_particles = voxel_has_particle[ipos]\n if num_particles != 0:\n num_particles = ti.length(pid.parent(), ipos)\n for k in range(num_particles):\n p = pid[ipos[0], ipos[1], ipos[2], k]\n v = particle_v[p]\n x = particle_x[p] + t * v\n color = particle_color[p]\n # ray-sphere intersection\n dist, poss = intersect_sphere(eye_pos, d, x, sphere_radius)\n hit_pos = poss\n if dist < closest_intersection and dist > 0:\n hit_pos = eye_pos + dist * d\n closest_intersection = dist\n normal = ti.Matrix.normalized(hit_pos - x)\n c = color\n else:\n running = 0\n normal = [0, 0, 0]\n\n if closest_intersection < inf:\n running = 0\n else:\n # hits nothing. Continue ray marching\n mm = ti.Vector([0, 0, 0])\n if dis[0] <= dis[1] and dis[0] <= dis[2]:\n mm[0] = 1\n elif dis[1] <= dis[0] and dis[1] <= dis[2]:\n mm[1] = 1\n else:\n mm[2] = 1\n dis += mm * rsign * rinv\n ipos += mm * rsign\n\n return closest_intersection, normal, c\n\n\[email protected]\ndef next_hit(pos, d, t):\n closest = inf\n normal = ti.Vector([0.0, 0.0, 0.0])\n c = ti.Vector([0.0, 0.0, 0.0])\n if ti.static(render_voxel):\n closest, normal, c = dda(pos, d)\n else:\n closest, normal, c = dda_particle(pos, d, t)\n\n if d[2] != 0:\n ray_closest = -(pos[2] + 5.5) / d[2]\n if ray_closest > 0 and ray_closest < closest:\n closest = ray_closest\n normal = ti.Vector([0.0, 0.0, 1.0])\n c = ti.Vector([0.6, 0.7, 0.7])\n\n ray_march_dist = ray_march(pos, d)\n if ray_march_dist < dist_limit and ray_march_dist < closest:\n closest = ray_march_dist\n normal = sdf_normal(pos + d * closest)\n c = sdf_color(pos + d * closest)\n\n return closest, normal, c\n\n\naspect_ratio = res[0] / res[1]\n\n\[email protected]\ndef render():\n for u, v in color_buffer:\n pos = camera_pos\n d = ti.Vector([(2 * fov * (u + ti.random(ti.f32)) / res[1] -\n fov * aspect_ratio - 1e-5),\n 2 * fov * (v + ti.random(ti.f32)) / res[1] - fov - 1e-5,\n -1.0])\n d = ti.Matrix.normalized(d)\n t = (ti.random() - 0.5) * shutter_time\n\n contrib = ti.Vector([0.0, 0.0, 0.0])\n throughput = ti.Vector([1.0, 1.0, 1.0])\n\n depth = 0\n hit_sky = 1\n ray_depth = 0\n\n while depth < max_ray_depth:\n closest, normal, c = next_hit(pos, d, t)\n hit_pos = pos + closest * d\n depth += 1\n ray_depth = depth\n if normal.norm() != 0:\n d = out_dir(normal)\n pos = hit_pos + 1e-4 * d\n throughput *= c\n\n if ti.static(use_directional_light):\n dir_noise = ti.Vector([\n ti.random() - 0.5,\n ti.random() - 0.5,\n ti.random() - 0.5\n ]) * light_direction_noise\n direct = ti.Matrix.normalized(\n ti.Vector(light_direction) + dir_noise)\n dot = direct.dot(normal)\n if dot > 0:\n dist, _, _ = next_hit(pos, direct, t)\n if dist > dist_limit:\n contrib += throughput * ti.Vector(\n light_color) * dot\n else: # hit sky\n hit_sky = 1\n depth = max_ray_depth\n\n max_c = throughput.max()\n if ti.random() > max_c:\n depth = max_ray_depth\n throughput = [0, 0, 0]\n else:\n throughput /= max_c\n\n if hit_sky:\n if ray_depth != 1:\n # contrib *= max(d[1], 0.05)\n pass\n else:\n # directly hit sky\n pass\n else:\n throughput *= 0\n\n # contrib += throughput\n color_buffer[u, v] += contrib\n\n\nsupport = 2\n\n\[email protected]\ndef initialize_particle_grid():\n for p in range(num_particles[None]):\n x = particle_x[p]\n v = particle_v[p]\n ipos = ti.Matrix.floor(x * particle_grid_res).cast(ti.i32)\n for i in range(-support, support + 1):\n for j in range(-support, support + 1):\n for k in range(-support, support + 1):\n offset = ti.Vector([i, j, k])\n box_ipos = ipos + offset\n if inside_particle_grid(box_ipos):\n box_min = box_ipos * (1 / particle_grid_res)\n box_max = (box_ipos + ti.Vector([1, 1, 1])) * (\n 1 / particle_grid_res)\n if sphere_aabb_intersect_motion(\n box_min, box_max, x - 0.5 * shutter_time * v,\n x + 0.5 * shutter_time * v, sphere_radius):\n ti.append(pid.parent(), box_ipos, p)\n voxel_has_particle[box_ipos] = 1\n\n\[email protected]\ndef copy(img: ti.ext_arr(), samples: ti.i32):\n for i, j in color_buffer:\n u = 1.0 * i / res[0]\n v = 1.0 * j / res[1]\n\n darken = 1.0 - vignette_strength * max(\n (ti.sqrt((u - vignette_center[0])**2 +\n (v - vignette_center[1])**2) - vignette_radius), 0)\n\n for c in ti.static(range(3)):\n img[i, j, c] = ti.sqrt(color_buffer[i, j][c] * darken * exposure /\n samples)\n\n\ndef main():\n num_part = 100000\n np_x = np.random.rand(num_part, 3).astype(np.float32) * 0.4 + 0.2\n np_v = np.random.rand(num_part, 3).astype(np.float32) * 0\n np_c = np.zeros((num_part, 3)).astype(np.float32)\n np_c[:, 0] = 0.85\n np_c[:, 1] = 0.9\n np_c[:, 2] = 1\n\n for i in range(3):\n # bbox values must be multiples of dx\n # bbox values are the min and max particle coordinates, with 3 dx margin\n bbox[0][i] = (math.floor(np_x[:, i].min() * particle_grid_res) -\n 3.0) / particle_grid_res\n bbox[1][i] = (math.floor(np_x[:, i].max() * particle_grid_res) +\n 3.0) / particle_grid_res\n\n num_particles[None] = num_part\n print('num_input_particles =', num_part)\n\n @ti.kernel\n def initialize_particle_x(x: ti.ext_arr(), v: ti.ext_arr(),\n color: ti.ext_arr()):\n for i in range(num_particles[None]):\n for c in ti.static(range(3)):\n particle_x[i][c] = x[i, c]\n particle_v[i][c] = v[i, c]\n particle_color[i][c] = color[i, c]\n\n for k in ti.static(range(27)):\n base_coord = (inv_dx * particle_x[i] - 0.5).cast(\n ti.i32) + ti.Vector([k // 9, k // 3 % 3, k % 3])\n grid_density[base_coord // grid_visualization_block_size] = 1\n\n initialize_particle_x(np_x, np_v, np_c)\n initialize_particle_grid()\n\n gui = ti.GUI('Particle Renderer', res)\n\n last_t = 0\n for i in range(500):\n render()\n\n interval = 10\n if i % interval == 0:\n img = np.zeros((res[0], res[1], 3), dtype=np.float32)\n copy(img, i + 1)\n if last_t != 0:\n print(\"time per spp = {:.2f} ms\".format(\n (time.time() - last_t) * 1000 / interval))\n last_t = time.time()\n gui.set_image(img)\n gui.show()\n\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"numpy.zeros",
"numpy.random.rand"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
crazysal/chemml | [
"300ed183c623fc8762ed2343e48c9e2ac5102c0f"
] | [
"chemml/chem/magpie_python/attributes/generators/crystal/CoulombMatrixAttributeGenerator.py"
] | [
"import types\nimport numpy as np\nimport pandas as pd\nfrom ....data.materials.CrystalStructureEntry import CrystalStructureEntry\nfrom ....models.regression.crystal.CoulombSineMatrixRegression import \\\n CoulombSineMatrixRegression\n\nclass CoulombMatrixAttributeGenerator:\n \"\"\"Class to compute attributes using the Coulomb Sine Matrix\n representation. Based on work by Faber et al. [1].\n\n Attributes\n ----------\n n_eigenvalues : int\n Maximum number of atoms to consider. Defines number of attributes.\n\n Notes\n -----\n This method works by computing an approximation for the Coulomb matrix\n that considers periodicity. Specifically, we use the Coulomb Sine matrix,\n which is described in detail in the Faber et al.[1]. For molecules,\n the Coulomb matrix is defined as\n\n .. math:: C_{i,j} &= Z_i^{2.4} & \\text{if} i=j\\\\\n &= Z_i Z_j / r_ij & \\text{if} i != j\n\n The eigenvalues of this matrix are then used as attributes. In order to\n provided a fixed number of attributes, the first N attributes are defined\n to be the N eigenvalues from the Coulomb matrix. The remaining attributes\n are defined to be zero.\n\n The Coulomb Matrix attributes are dependant on unit cell choice.\n Please consider transforming your input crystal structures to the primitive\n cell before using these attributes.\n\n References\n ----------\n .. [1] F. Faber, A. Lindmaa, O. A. von Lilienfeld, and R. Armiento,\n \"Crystal structure representations for machine learning models of\n formation energies,\" International Journal of Quantum Chemistry,\n vol. 115, no. 16, pp. 1094--1101, Apr. 2015.\n\n \"\"\"\n\n def __init__(self):\n \"\"\"Function to create instance and initialize fields.\n \"\"\"\n\n # Maximum number of atoms to consider. Defines number of attributes.\n self.n_eigenvalues = 30\n\n def set_n_eigenvalues(self, x):\n \"\"\"Function to set the number of eigenvalues used in representation.\n\n Parameters\n ----------\n x : int\n Desired number.\n\n \"\"\"\n\n self.n_eigenvalues = x\n\n def generate_features(self, entries):\n \"\"\"Function to generate features as mentioned in the class description.\n\n Parameters\n ----------\n entries : array-like\n Crystal structures for which features are to be generated. A list\n of CrystalStructureEntry's.\n\n Returns\n ----------\n features : DataFrame\n Features for the given entries. Pandas data frame containing the\n names and values of the descriptors.\n\n Raises\n ------\n ValueError\n If input is not of type list.\n If items in the list are not CrystalStructureEntry instances.\n\n \"\"\"\n\n # Initialize list of feature values for pandas data frame.\n feat_values = []\n\n # Raise exception if input argument is not of type list of\n # CrystalStructureEntry's.\n if not isinstance(entries, list):\n raise ValueError(\"Argument should be of type list of \"\n \"CrystalStructureEntry's\")\n elif (entries and not isinstance(entries[0], CrystalStructureEntry)):\n raise ValueError(\"Argument should be of type list of \"\n \"CrystalStructureEntry's\")\n\n # Insert header names here.\n feat_headers = [\"CoulombMatrix_Eigenvalue\" + str(i) for i in range(\n self.n_eigenvalues)]\n\n # Create tool to compute eigenvalues.\n tool = CoulombSineMatrixRegression()\n\n # Generate features.\n for entry in entries:\n eigenvalues = tool.compute_representation(entry.get_structure())\n tmp_array = np.zeros(self.n_eigenvalues, dtype=float)\n if len(eigenvalues) < self.n_eigenvalues:\n tmp_array[:len(eigenvalues)] = eigenvalues[:]\n else:\n tmp_array[:] = eigenvalues[:self.n_eigenvalues]\n feat_values.append(tmp_array)\n\n features = pd.DataFrame(feat_values, columns=feat_headers)\n return features"
] | [
[
"numpy.zeros",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
wjbKimberly/DetectAndTrack-wjb | [
"e8f065ce389d559307f48b5de3fbb0a417b7faea"
] | [
"lib/datasets/posetrack/poseval/py/evaluatePCKh.py"
] | [
"import numpy as np\nimport json\nimport os\nimport sys\n\nimport eval_helpers\n\ndef computeDist(gtFrames,prFrames):\n assert(len(gtFrames) == len(prFrames))\n\n nJoints = eval_helpers.Joint().count\n distAll = {}\n for pidx in range(nJoints):\n distAll[pidx] = np.zeros([0,0])\n \n for imgidx in range(len(gtFrames)):\n # ground truth\n gtFrame = gtFrames[imgidx]\n # prediction\n detFrame = prFrames[imgidx]\n if (gtFrames[imgidx][\"annorect\"] != None):\n for ridx in range(len(gtFrames[imgidx][\"annorect\"])):\n rectGT = gtFrames[imgidx][\"annorect\"][ridx]\n rectPr = prFrames[imgidx][\"annorect\"][ridx]\n if (\"annopoints\" in rectGT.keys() and rectGT[\"annopoints\"] != None):\n pointsGT = rectGT[\"annopoints\"][0][\"point\"]\n pointsPr = rectPr[\"annopoints\"][0][\"point\"]\n for pidx in range(len(pointsGT)):\n pointGT = [pointsGT[pidx][\"x\"][0],pointsGT[pidx][\"y\"][0]]\n idxGT = pointsGT[pidx][\"id\"][0]\n p = eval_helpers.getPointGTbyID(pointsPr,idxGT)\n if (len(p) > 0 and\n (type(p[\"x\"][0]) == int or type(p[\"x\"][0]) == float) and\n (type(p[\"y\"][0]) == int or type(p[\"y\"][0]) == float)):\n pointPr = [p[\"x\"][0],p[\"y\"][0]]\n # compute distance between GT and prediction\n d = np.linalg.norm(np.subtract(pointGT,pointPr))\n # compute head size for distance normalization\n headSize = eval_helpers.getHeadSize(rectGT[\"x1\"][0],rectGT[\"y1\"][0],\n rectGT[\"x2\"][0],rectGT[\"y2\"][0])\n # normalize distance\n dNorm = d/headSize\n else:\n dNorm = np.inf\n distAll[idxGT] = np.append(distAll[idxGT],[[dNorm]])\n\n return distAll\n\n\ndef computePCK(distAll,distThresh):\n\n pckAll = np.zeros([len(distAll)+1,1])\n nCorrect = 0\n nTotal = 0\n for pidx in range(len(distAll)):\n idxs = np.argwhere(distAll[pidx] <= distThresh)\n pck = 100.0*len(idxs)/len(distAll[pidx])\n pckAll[pidx,0] = pck\n nCorrect += len(idxs)\n nTotal += len(distAll[pidx])\n pckAll[len(distAll),0] = 100.0*nCorrect/nTotal\n \n return pckAll\n\n\ndef evaluatePCKh(gtFramesAll,prFramesAll):\n\n distThresh = 0.5\n \n # compute distances\n distAll = computeDist(gtFramesAll,prFramesAll)\n\n # compute PCK metric\n pckAll = computePCK(distAll,distThresh)\n\n return pckAll\n"
] | [
[
"numpy.subtract",
"numpy.append",
"numpy.zeros",
"numpy.argwhere"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
shih29242890/x100x1000_donkeycar | [
"cdd75d64843d1e5d20ad8a0aa68c9f311c33bcfb"
] | [
"donkeycar/templates/complete.py"
] | [
"#!/usr/bin/env python3\n\"\"\"\nScripts to drive a donkey 2 car\n\nUsage:\n manage.py (drive) [--model=<model>] [--js] [--type=(linear|categorical|rnn|imu|behavior|3d|localizer|latent)] [--camera=(single|stereo)] [--meta=<key:value> ...]\n manage.py (train) [--tub=<tub1,tub2,..tubn>] [--file=<file> ...] (--model=<model>) [--transfer=<model>] [--type=(linear|categorical|rnn|imu|behavior|3d|localizer)] [--continuous] [--aug]\n\n\nOptions:\n -h --help Show this screen.\n --js Use physical joystick.\n -f --file=<file> A text file containing paths to tub files, one per line. Option may be used more than once.\n --meta=<key:value> Key/Value strings describing describing a piece of meta data about this drive. Option may be used more than once.\n\"\"\"\nimport os\nimport time\n\nfrom docopt import docopt\nimport numpy as np\n\nimport donkeycar as dk\n\n#import parts\nfrom donkeycar.parts.transform import Lambda, TriggeredCallback, DelayedTrigger\nfrom donkeycar.parts.datastore import TubHandler\nfrom donkeycar.parts.controller import LocalWebController, JoystickController\nfrom donkeycar.parts.throttle_filter import ThrottleFilter\nfrom donkeycar.parts.behavior import BehaviorPart\nfrom donkeycar.parts.file_watcher import FileWatcher\nfrom donkeycar.parts.launch import AiLaunch\nfrom donkeycar.utils import *\n\ndef drive(cfg, model_path=None, use_joystick=False, model_type=None, camera_type='single', meta=[] ):\n '''\n Construct a working robotic vehicle from many parts.\n Each part runs as a job in the Vehicle loop, calling either\n it's run or run_threaded method depending on the constructor flag `threaded`.\n All parts are updated one after another at the framerate given in\n cfg.DRIVE_LOOP_HZ assuming each part finishes processing in a timely manner.\n Parts may have named outputs and inputs. The framework handles passing named outputs\n to parts requesting the same named input.\n '''\n\n if cfg.DONKEY_GYM:\n #the simulator will use cuda and then we usually run out of resources\n #if we also try to use cuda. so disable for donkey_gym.\n os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"-1\" \n\n if model_type is None:\n if cfg.TRAIN_LOCALIZER:\n model_type = \"localizer\"\n elif cfg.TRAIN_BEHAVIORS:\n model_type = \"behavior\"\n else:\n model_type = cfg.DEFAULT_MODEL_TYPE\n \n #Initialize car\n V = dk.vehicle.Vehicle()\n\n if camera_type == \"stereo\":\n\n if cfg.CAMERA_TYPE == \"WEBCAM\":\n from donkeycar.parts.camera import Webcam \n\n camA = Webcam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 0)\n camB = Webcam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 1)\n\n elif cfg.CAMERA_TYPE == \"CVCAM\":\n from donkeycar.parts.cv import CvCam\n\n camA = CvCam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 0)\n camB = CvCam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 1)\n else:\n raise(Exception(\"Unsupported camera type: %s\" % cfg.CAMERA_TYPE))\n\n V.add(camA, outputs=['cam/image_array_a'], threaded=True)\n V.add(camB, outputs=['cam/image_array_b'], threaded=True)\n\n from donkeycar.parts.image import StereoPair\n\n V.add(StereoPair(), inputs=['cam/image_array_a', 'cam/image_array_b'], \n outputs=['cam/image_array'])\n\n else:\n print(\"cfg.CAMERA_TYPE\", cfg.CAMERA_TYPE)\n if cfg.DONKEY_GYM:\n from donkeycar.parts.dgym import DonkeyGymEnv \n \n inputs = []\n threaded = True\n print(\"cfg.CAMERA_TYPE\", cfg.CAMERA_TYPE)\n if cfg.DONKEY_GYM:\n from donkeycar.parts.dgym import DonkeyGymEnv \n cam = DonkeyGymEnv(cfg.DONKEY_SIM_PATH, env_name=cfg.DONKEY_GYM_ENV_NAME)\n threaded = True\n inputs = ['angle', 'throttle']\n elif cfg.CAMERA_TYPE == \"PICAM\":\n from donkeycar.parts.camera import PiCamera\n cam = PiCamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, framerate=cfg.CAMERA_FRAMERATE, vflip=cfg.VFLIP, hflip=cfg.HFLIP)\n elif cfg.CAMERA_TYPE == \"WEBCAM\":\n from donkeycar.parts.camera import Webcam\n cam = Webcam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH)\n elif cfg.CAMERA_TYPE == \"CVCAM\":\n from donkeycar.parts.cv import CvCam\n cam = CvCam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH)\n elif cfg.CAMERA_TYPE == \"CSIC\":\n from donkeycar.parts.camera import CSICamera\n cam = CSICamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, framerate=cfg.CAMERA_FRAMERATE, gstreamer_flip=cfg.CSIC_CAM_GSTREAMER_FLIP_PARM)\n elif cfg.CAMERA_TYPE == \"V4L\":\n from donkeycar.parts.camera import V4LCamera\n cam = V4LCamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, framerate=cfg.CAMERA_FRAMERATE)\n elif cfg.CAMERA_TYPE == \"MOCK\":\n from donkeycar.parts.camera import MockCamera\n cam = MockCamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH)\n else:\n raise(Exception(\"Unkown camera type: %s\" % cfg.CAMERA_TYPE))\n \n V.add(cam, inputs=inputs, outputs=['cam/image_array'], threaded=threaded)\n \n if use_joystick or cfg.USE_JOYSTICK_AS_DEFAULT:\n #modify max_throttle closer to 1.0 to have more power\n #modify steering_scale lower than 1.0 to have less responsive steering\n from donkeycar.parts.controller import get_js_controller\n \n ctr = get_js_controller(cfg)\n \n if cfg.USE_NETWORKED_JS:\n from donkeycar.parts.controller import JoyStickSub\n netwkJs = JoyStickSub(cfg.NETWORK_JS_SERVER_IP)\n V.add(netwkJs, threaded=True)\n ctr.js = netwkJs\n\n else: \n #This web controller will create a web server that is capable\n #of managing steering, throttle, and modes, and more.\n ctr = LocalWebController()\n\n \n V.add(ctr, \n inputs=['cam/image_array'],\n outputs=['user/angle', 'user/throttle', 'user/mode', 'recording'],\n threaded=True)\n\n #this throttle filter will allow one tap back for esc reverse\n th_filter = ThrottleFilter()\n V.add(th_filter, inputs=['user/throttle'], outputs=['user/throttle'])\n \n #See if we should even run the pilot module. \n #This is only needed because the part run_condition only accepts boolean\n class PilotCondition:\n def run(self, mode):\n if mode == 'user':\n return False\n else:\n return True \n\n V.add(PilotCondition(), inputs=['user/mode'], outputs=['run_pilot'])\n \n class LedConditionLogic:\n def __init__(self, cfg):\n self.cfg = cfg\n\n def run(self, mode, recording, recording_alert, behavior_state, model_file_changed, track_loc):\n #returns a blink rate. 0 for off. -1 for on. positive for rate.\n \n if track_loc is not None:\n led.set_rgb(*self.cfg.LOC_COLORS[track_loc])\n return -1\n\n if model_file_changed:\n led.set_rgb(self.cfg.MODEL_RELOADED_LED_R, self.cfg.MODEL_RELOADED_LED_G, self.cfg.MODEL_RELOADED_LED_B)\n return 0.1\n else:\n led.set_rgb(self.cfg.LED_R, self.cfg.LED_G, self.cfg.LED_B)\n\n if recording_alert:\n led.set_rgb(*recording_alert)\n return self.cfg.REC_COUNT_ALERT_BLINK_RATE\n else:\n led.set_rgb(self.cfg.LED_R, self.cfg.LED_G, self.cfg.LED_B)\n \n if behavior_state is not None and model_type == 'behavior':\n r, g, b = self.cfg.BEHAVIOR_LED_COLORS[behavior_state]\n led.set_rgb(r, g, b)\n return -1 #solid on\n\n if recording:\n return -1 #solid on\n elif mode == 'user':\n return 1\n elif mode == 'local_angle':\n return 0.5\n elif mode == 'local':\n return 0.1\n return 0\n\n if cfg.HAVE_RGB_LED and not cfg.DONKEY_GYM:\n from donkeycar.parts.led_status import RGB_LED\n led = RGB_LED(cfg.LED_PIN_R, cfg.LED_PIN_G, cfg.LED_PIN_B, cfg.LED_INVERT)\n led.set_rgb(cfg.LED_R, cfg.LED_G, cfg.LED_B) \n \n V.add(LedConditionLogic(cfg), inputs=['user/mode', 'recording', \"records/alert\", 'behavior/state', 'modelfile/modified', \"pilot/loc\"],\n outputs=['led/blink_rate'])\n\n V.add(led, inputs=['led/blink_rate'])\n \n\n def get_record_alert_color(num_records):\n col = (0, 0, 0)\n for count, color in cfg.RECORD_ALERT_COLOR_ARR:\n if num_records >= count:\n col = color\n return col \n\n class RecordTracker:\n def __init__(self):\n self.last_num_rec_print = 0\n self.dur_alert = 0\n self.force_alert = 0\n\n def run(self, num_records):\n if num_records is None:\n return 0\n \n if self.last_num_rec_print != num_records or self.force_alert:\n self.last_num_rec_print = num_records\n\n if num_records % 10 == 0:\n print(\"recorded\", num_records, \"records\")\n \n if num_records % cfg.REC_COUNT_ALERT == 0 or self.force_alert:\n self.dur_alert = num_records // cfg.REC_COUNT_ALERT * cfg.REC_COUNT_ALERT_CYC\n self.force_alert = 0\n \n if self.dur_alert > 0:\n self.dur_alert -= 1\n\n if self.dur_alert != 0:\n return get_record_alert_color(num_records)\n\n return 0\n\n rec_tracker_part = RecordTracker()\n V.add(rec_tracker_part, inputs=[\"tub/num_records\"], outputs=['records/alert'])\n\n if cfg.AUTO_RECORD_ON_THROTTLE and isinstance(ctr, JoystickController):\n #then we are not using the circle button. hijack that to force a record count indication\n def show_record_acount_status():\n rec_tracker_part.last_num_rec_print = 0\n rec_tracker_part.force_alert = 1\n ctr.set_button_down_trigger('circle', show_record_acount_status)\n\n #Sombrero\n if cfg.HAVE_SOMBRERO:\n from donkeycar.parts.sombrero import Sombrero\n s = Sombrero()\n\n #IMU\n if cfg.HAVE_IMU:\n from donkeycar.parts.imu import Mpu6050\n imu = Mpu6050()\n V.add(imu, outputs=['imu/acl_x', 'imu/acl_y', 'imu/acl_z',\n 'imu/gyr_x', 'imu/gyr_y', 'imu/gyr_z'], threaded=True)\n\n class ImgPreProcess():\n '''\n preprocess camera image for inference.\n normalize and crop if needed.\n '''\n def __init__(self, cfg):\n self.cfg = cfg\n\n def run(self, img_arr):\n return normalize_and_crop(img_arr, self.cfg)\n\n if \"coral\" in model_type:\n inf_input = 'cam/image_array'\n else:\n inf_input = 'cam/normalized/cropped'\n V.add(ImgPreProcess(cfg),\n inputs=['cam/image_array'],\n outputs=[inf_input],\n run_condition='run_pilot')\n\n #Behavioral state\n if cfg.TRAIN_BEHAVIORS:\n bh = BehaviorPart(cfg.BEHAVIOR_LIST)\n V.add(bh, outputs=['behavior/state', 'behavior/label', \"behavior/one_hot_state_array\"])\n try:\n ctr.set_button_down_trigger('L1', bh.increment_state)\n except:\n pass\n\n inputs = [inf_input, \"behavior/one_hot_state_array\"] \n #IMU\n elif model_type == \"imu\":\n assert(cfg.HAVE_IMU)\n #Run the pilot if the mode is not user.\n inputs=[inf_input,\n 'imu/acl_x', 'imu/acl_y', 'imu/acl_z',\n 'imu/gyr_x', 'imu/gyr_y', 'imu/gyr_z']\n else:\n inputs=[inf_input]\n\n def load_model(kl, model_path):\n start = time.time()\n print('loading model', model_path)\n kl.load(model_path)\n print('finished loading in %s sec.' % (str(time.time() - start)) )\n\n def load_weights(kl, weights_path):\n start = time.time()\n try:\n print('loading model weights', weights_path)\n kl.model.load_weights(weights_path)\n print('finished loading in %s sec.' % (str(time.time() - start)) )\n except Exception as e:\n print(e)\n print('ERR>> problems loading weights', weights_path)\n\n def load_model_json(kl, json_fnm):\n start = time.time()\n print('loading model json', json_fnm)\n from tensorflow.python import keras\n try:\n with open(json_fnm, 'r') as handle:\n contents = handle.read()\n kl.model = keras.models.model_from_json(contents)\n print('finished loading json in %s sec.' % (str(time.time() - start)) )\n except Exception as e:\n print(e)\n print(\"ERR>> problems loading model json\", json_fnm)\n\n if model_path:\n #When we have a model, first create an appropriate Keras part\n kl = dk.utils.get_model_by_type(model_type, cfg)\n\n model_reload_cb = None\n\n if '.h5' in model_path or '.uff' in model_path or 'tflite' in model_path or '.pkl' in model_path:\n #when we have a .h5 extension\n #load everything from the model file\n load_model(kl, model_path)\n\n def reload_model(filename):\n load_model(kl, filename)\n\n model_reload_cb = reload_model\n\n elif '.json' in model_path:\n #when we have a .json extension\n #load the model from there and look for a matching\n #.wts file with just weights\n load_model_json(kl, model_path)\n weights_path = model_path.replace('.json', '.weights')\n load_weights(kl, weights_path)\n\n def reload_weights(filename):\n weights_path = filename.replace('.json', '.weights')\n load_weights(kl, weights_path)\n \n model_reload_cb = reload_weights\n\n else:\n print(\"ERR>> Unknown extension type on model file!!\")\n return\n\n #this part will signal visual LED, if connected\n V.add(FileWatcher(model_path, verbose=True), outputs=['modelfile/modified'])\n\n #these parts will reload the model file, but only when ai is running so we don't interrupt user driving\n V.add(FileWatcher(model_path), outputs=['modelfile/dirty'], run_condition=\"ai_running\")\n V.add(DelayedTrigger(100), inputs=['modelfile/dirty'], outputs=['modelfile/reload'], run_condition=\"ai_running\")\n V.add(TriggeredCallback(model_path, model_reload_cb), inputs=[\"modelfile/reload\"], run_condition=\"ai_running\")\n\n outputs=['pilot/angle', 'pilot/throttle']\n\n if cfg.TRAIN_LOCALIZER:\n outputs.append(\"pilot/loc\")\n \n V.add(kl, inputs=inputs, \n outputs=outputs,\n run_condition='run_pilot') \n \n #Choose what inputs should change the car.\n class DriveMode:\n def run(self, mode, \n user_angle, user_throttle,\n pilot_angle, pilot_throttle):\n if mode == 'user': \n return user_angle, user_throttle\n \n elif mode == 'local_angle':\n return pilot_angle, user_throttle\n \n else: \n return pilot_angle, pilot_throttle * cfg.AI_THROTTLE_MULT\n \n V.add(DriveMode(), \n inputs=['user/mode', 'user/angle', 'user/throttle',\n 'pilot/angle', 'pilot/throttle'], \n outputs=['angle', 'throttle'])\n\n \n #to give the car a boost when starting ai mode in a race.\n aiLauncher = AiLaunch(cfg.AI_LAUNCH_DURATION, cfg.AI_LAUNCH_THROTTLE, cfg.AI_LAUNCH_KEEP_ENABLED)\n \n V.add(aiLauncher,\n inputs=['user/mode', 'throttle'],\n outputs=['throttle'])\n\n if isinstance(ctr, JoystickController):\n ctr.set_button_down_trigger(cfg.AI_LAUNCH_ENABLE_BUTTON, aiLauncher.enable_ai_launch)\n\n\n class AiRunCondition:\n '''\n A bool part to let us know when ai is running.\n '''\n def run(self, mode):\n if mode == \"user\":\n return False\n return True\n\n V.add(AiRunCondition(), inputs=['user/mode'], outputs=['ai_running'])\n\n #Ai Recording\n class AiRecordingCondition:\n '''\n return True when ai mode, otherwize respect user mode recording flag\n '''\n def run(self, mode, recording):\n if mode == 'user':\n return recording\n return True\n\n if cfg.RECORD_DURING_AI:\n V.add(AiRecordingCondition(), inputs=['user/mode', 'recording'], outputs=['recording'])\n \n #Drive train setup\n if cfg.DONKEY_GYM:\n pass\n\n elif cfg.DRIVE_TRAIN_TYPE == \"SERVO_ESC\":\n from donkeycar.parts.actuator import PCA9685, PWMSteering, PWMThrottle\n\n steering_controller = PCA9685(cfg.STEERING_CHANNEL, cfg.PCA9685_I2C_ADDR, busnum=cfg.PCA9685_I2C_BUSNUM)\n steering = PWMSteering(controller=steering_controller,\n left_pulse=cfg.STEERING_LEFT_PWM, \n right_pulse=cfg.STEERING_RIGHT_PWM)\n \n throttle_controller = PCA9685(cfg.THROTTLE_CHANNEL, cfg.PCA9685_I2C_ADDR, busnum=cfg.PCA9685_I2C_BUSNUM)\n throttle = PWMThrottle(controller=throttle_controller,\n max_pulse=cfg.THROTTLE_FORWARD_PWM,\n zero_pulse=cfg.THROTTLE_STOPPED_PWM, \n min_pulse=cfg.THROTTLE_REVERSE_PWM)\n\n V.add(steering, inputs=['angle'])\n V.add(throttle, inputs=['throttle'])\n \n\n elif cfg.DRIVE_TRAIN_TYPE == \"DC_STEER_THROTTLE\":\n from donkeycar.parts.actuator import Mini_HBridge_DC_Motor_PWM\n \n steering = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_LEFT, cfg.HBRIDGE_PIN_RIGHT)\n throttle = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_FWD, cfg.HBRIDGE_PIN_BWD)\n\n V.add(steering, inputs=['angle'])\n V.add(throttle, inputs=['throttle'])\n \n\n elif cfg.DRIVE_TRAIN_TYPE == \"DC_TWO_WHEEL\":\n from donkeycar.parts.actuator import TwoWheelSteeringThrottle, Adafruit_DCMotor_Hat #Mini_HBridge_DC_Motor_PWM\n\n left_motor = Adafruit_DCMotor_Hat(1) #Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_LEFT_FWD, cfg.HBRIDGE_PIN_LEFT_BWD)\n right_motor = Adafruit_DCMotor_Hat(2) #Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_RIGHT_FWD, cfg.HBRIDGE_PIN_RIGHT_BWD)\n two_wheel_control = TwoWheelSteeringThrottle()\n\n V.add(two_wheel_control, \n inputs=['throttle', 'angle'],\n outputs=['left_motor_speed', 'right_motor_speed'])\n\n V.add(left_motor, inputs=['left_motor_speed'])\n V.add(right_motor, inputs=['right_motor_speed'])\n\n elif cfg.DRIVE_TRAIN_TYPE == \"SERVO_HBRIDGE_PWM\":\n from donkeycar.parts.actuator import ServoBlaster, PWMSteering\n steering_controller = ServoBlaster(cfg.STEERING_CHANNEL) #really pin\n #PWM pulse values should be in the range of 100 to 200\n assert(cfg.STEERING_LEFT_PWM <= 200)\n assert(cfg.STEERING_RIGHT_PWM <= 200)\n steering = PWMSteering(controller=steering_controller,\n left_pulse=cfg.STEERING_LEFT_PWM, \n right_pulse=cfg.STEERING_RIGHT_PWM)\n \n\n from donkeycar.parts.actuator import Mini_HBridge_DC_Motor_PWM\n motor = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_FWD, cfg.HBRIDGE_PIN_BWD)\n\n V.add(steering, inputs=['angle'])\n V.add(motor, inputs=[\"throttle\"])\n\n \n #add tub to save data\n\n inputs=['cam/image_array',\n 'user/angle', 'user/throttle', \n 'user/mode']\n\n types=['image_array',\n 'float', 'float',\n 'str']\n\n if cfg.TRAIN_BEHAVIORS:\n inputs += ['behavior/state', 'behavior/label', \"behavior/one_hot_state_array\"]\n types += ['int', 'str', 'vector']\n \n if cfg.HAVE_IMU:\n inputs += ['imu/acl_x', 'imu/acl_y', 'imu/acl_z',\n 'imu/gyr_x', 'imu/gyr_y', 'imu/gyr_z']\n\n types +=['float', 'float', 'float',\n 'float', 'float', 'float']\n\n if cfg.RECORD_DURING_AI:\n inputs += ['pilot/angle', 'pilot/throttle']\n types += ['float', 'float']\n \n th = TubHandler(path=cfg.DATA_PATH)\n tub = th.new_tub_writer(inputs=inputs, types=types, user_meta=meta)\n V.add(tub, inputs=inputs, outputs=[\"tub/num_records\"], run_condition='recording')\n\n if cfg.PUB_CAMERA_IMAGES:\n from donkeycar.parts.network import TCPServeValue\n from donkeycar.parts.image import ImgArrToJpg\n pub = TCPServeValue(\"camera\")\n V.add(ImgArrToJpg(), inputs=['cam/image_array'], outputs=['jpg/bin'])\n V.add(pub, inputs=['jpg/bin'])\n\n if type(ctr) is LocalWebController:\n print(\"You can now go to <your pi ip address>:8887 to drive your car.\")\n elif isinstance(ctr, JoystickController):\n print(\"You can now move your joystick to drive your car.\")\n #tell the controller about the tub \n ctr.set_tub(tub)\n \n if cfg.BUTTON_PRESS_NEW_TUB:\n \n def new_tub_dir():\n V.parts.pop()\n tub = th.new_tub_writer(inputs=inputs, types=types, user_meta=meta)\n V.add(tub, inputs=inputs, outputs=[\"tub/num_records\"], run_condition='recording')\n ctr.set_tub(tub)\n \n ctr.set_button_down_trigger('cross', new_tub_dir)\n ctr.print_controls()\n\n #run the vehicle for 20 seconds\n V.start(rate_hz=cfg.DRIVE_LOOP_HZ, \n max_loop_count=cfg.MAX_LOOPS)\n\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n cfg = dk.load_config()\n \n if args['drive']:\n model_type = args['--type']\n camera_type = args['--camera']\n drive(cfg, model_path=args['--model'], use_joystick=args['--js'], model_type=model_type, camera_type=camera_type,\n meta=args['--meta'])\n \n if args['train']:\n from train import multi_train, preprocessFileList\n \n tub = args['--tub']\n model = args['--model']\n transfer = args['--transfer']\n model_type = args['--type']\n continuous = args['--continuous']\n aug = args['--aug'] \n\n dirs = preprocessFileList( args['--file'] )\n if tub is not None:\n tub_paths = [os.path.expanduser(n) for n in tub.split(',')]\n dirs.extend( tub_paths )\n\n multi_train(cfg, dirs, model, transfer, model_type, continuous, aug)\n\n"
] | [
[
"tensorflow.python.keras.models.model_from_json"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.5",
"1.4"
]
}
] |
ArvindSoma/HumanEstimation | [
"8bbdfbe54ce377d197a477cbef0b8a89154531eb"
] | [
"utils/prep_densepose.py"
] | [
"import os\nimport sys\nimport argparse\nimport pickle\nimport numpy as np\nimport cv2\nimport torch\nfrom scipy import io as io\n\nfrom pycocotools.coco import COCO\nimport pycocotools.mask as mask_util\n\nimport trimesh\nfrom tqdm import tqdm\n\nfrom utils.render_utils import Render, match_faces\n\n\nfrom external.smplx.smplx import body_models\nsys.path.insert(0, '../external/pyrender')\n\n\ndef GetDensePoseMask(Polys):\n MaskGen = np.zeros([256,256])\n for i in range(1,15):\n if(Polys[i-1]):\n current_mask = mask_util.decode(Polys[i-1])\n MaskGen[current_mask>0] = i\n return MaskGen\n\n\ndef main(opt):\n coco_folder = os.environ['COCO']\n save_annotation_file = opt.output\n\n if not os.path.exists(save_annotation_file):\n os.mkdir(save_annotation_file)\n annotation_dict = {'minival': [COCO(coco_folder + '/annotations/densepose_coco_2014_minival.json'),\n COCO(coco_folder + '/annotations/person_keypoints_val2014.json'),\n 'val2014'],\n 'valminusminival': [COCO(coco_folder + '/annotations/densepose_coco_2014_valminusminival.json'),\n COCO(coco_folder + '/annotations/person_keypoints_val2014.json'),\n 'val2014'],\n 'train': [COCO(coco_folder + '/annotations/densepose_coco_2014_train.json'),\n COCO(coco_folder + '/annotations/person_keypoints_train2014.json'),\n 'train2014'],\n 'test': [COCO(coco_folder + '/annotations/densepose_coco_2014_test.json'),\n 'test2014']}\n\n #################################\n\n # SMPL prep\n\n model = body_models.create(model_path='../3d_data/models', model_type='smpl', gender='male', ext='pkl')\n smpl = pickle.load(open('../3d_data/densepose_uv.pkl', 'rb'))\n faces = np.array(smpl['f_extended'], dtype=np.int64).reshape((-1, 3))\n uv_faceid = io.loadmat('../3d_data/DensePoseData/UV_data/UV_Processed.mat')['All_FaceIndices']\n uv = smpl['uv']\n uv_vertices = (uv * 2) - 1\n # with open('../3d_data/nongrey_male_0110.jpg', 'rb') as file:\n # texture = cv2.imread('../3d_data/nongrey_male_0110.jpg')\n\n seg_path = os.path.join(coco_folder, 'background')\n if not os.path.exists(seg_path):\n os.mkdir(seg_path)\n\n output = model(return_verts=True)\n vertices = output.vertices.detach().cpu().numpy().squeeze()\n\n smpl_vertices = np.array([vertices[i] for i in smpl['v_extended']])\n\n smpl_render = Render(width=opt.image_width, height=opt.image_height)\n\n smpl_render.set_render(vertices=smpl_vertices, faces=faces)\n\n smpl_norm_vertices = smpl_render.vertices\n\n # smpl_uv = smpl_render.render_interpolate(vertices=uv, skip_cull=False)\n # smpl_noc = smpl_render.render_interpolate(vertices=smpl_norm_vertices).interpolated\n\n aggregate_textures = np.array([], dtype='float64').reshape((0, 3, opt.image_height, opt.image_width))\n\n uv_render = Render(width=opt.image_width, height=opt.image_height)\n\n kernel = np.ones((3, 3), np.uint8)\n\n for idx in range(1, 25):\n # face_select = faces[uv_faceid[:, 0] == idx, :]\n id_select = np.unique(np.hstack(\n np.where(faces == vert)[0] for face in faces[uv_faceid[:, 0] == idx, :] for vert in face))\n\n face_select = faces[id_select, :]\n\n uv_render.set_render(vertices=uv_vertices, faces=face_select, normalize=False)\n\n out_view = np.flip(uv_render.render_interpolate(vertices=smpl_norm_vertices).interpolated.transpose([2, 0, 1]),\n axis=1)\n aggregate_textures = np.concatenate([aggregate_textures, out_view.reshape((1,) + out_view.shape)])\n\n texture_map = torch.from_numpy(aggregate_textures)\n\n print(\"SMPL textures loaded in memory.\\n\")\n\n #################################\n\n for key in annotation_dict:\n dp_coco = annotation_dict[key][0]\n person_coco = annotation_dict[key][1]\n parent_dir = annotation_dict[key][2]\n\n seg_key_path = os.path.join(seg_path, parent_dir)\n if not os.path.exists(seg_key_path):\n os.mkdir(seg_key_path)\n\n im_ids = dp_coco.getImgIds()\n # len_ids = len(im_ids)\n key_list = []\n for idx, im_id in enumerate(tqdm(im_ids, desc=\"Key [{}] Progress\".format(key), ncols=100)):\n im_dict = {}\n im = dp_coco.loadImgs(im_id)[0]\n person_im = person_coco.loadImgs(im_id)[0]\n im_name = os.path.join(coco_folder, parent_dir, im['file_name'])\n image = cv2.imread(im_name)\n # im_dict['image'] = image\n\n im_dict['file_name'] = os.path.join(parent_dir, im['file_name'])\n\n ann_ids = dp_coco.getAnnIds(imgIds=im['id'])\n anns = dp_coco.loadAnns(ann_ids)\n person_anns = person_coco.loadAnns(ann_ids)\n\n im_dict['points'] = {}\n zero_im = np.zeros((image.shape[0], image.shape[1]))\n\n person_seg = np.zeros((image.shape[0], image.shape[1]))\n point_dict = im_dict['points']\n point_dict['yx'] = np.array([], dtype='int').reshape((0, 2))\n point_dict['iuv'] = np.array([]).reshape((0, 3))\n\n xy_mask = np.zeros((image.shape[0], image.shape[1], 1))\n zero_point_iuv = np.zeros_like(image)\n zero_point_uv = np.zeros((24, image.shape[0], image.shape[1], 2))\n\n for person_ann in person_anns:\n person_seg += person_coco.annToMask(person_ann)\n\n for ann in anns:\n\n if 'dp_masks' in ann.keys():\n\n bbr = (np.array(ann['bbox'])).astype('int')\n mask = GetDensePoseMask(ann['dp_masks'])\n x1, y1, x2, y2 = bbr[0], bbr[1], bbr[0] + bbr[2], bbr[1] + bbr[3]\n x2 = min([x2, image.shape[1]])\n y2 = min([y2, image.shape[0]])\n\n mask_im = cv2.resize(mask, (int(x2 - x1), int(y2 - y1)), interpolation=cv2.INTER_NEAREST)\n # mask_bool = np.tile((mask_im == 0)[:, :, np.newaxis], [1, 1, 3])\n zero_im[y1:y2, x1:x2] += mask_im\n\n img_x = np.array(ann['dp_x']) / 255. * bbr[2] + x1 # Stretch the points to current box.\n img_y = np.array(ann['dp_y']) / 255. * bbr[3] + y1 # Stretch the points to current box.\n img_x = img_x.astype('int') - 1 * (img_x >= image.shape[1])\n img_y = img_y.astype('int') - 1 * (img_y >= image.shape[0])\n\n point_dict['yx'] = np.concatenate([point_dict['yx'], np.array([img_y, img_x]).T])\n\n point_i = np.array(ann['dp_I']).astype('int')\n point_u = np.array(ann['dp_U'])\n point_v = np.array(ann['dp_V'])\n point_dict['iuv'] = np.concatenate((point_dict['iuv'], np.array([point_i, point_u, point_v]).T))\n\n zero_point_iuv[img_y, img_x, :] = np.array([point_i, point_u, point_v]).T\n\n xy_mask[img_y, img_x, 0] = 1\n\n zero_point_uv[point_i - 1, img_y, img_x] = np.array([point_u, point_v]).T\n\n uv_stack = torch.from_numpy((zero_point_uv * 2) - 1)\n\n output_noc = 0\n for idx in range(0, 24):\n output_noc += torch.nn.functional.grid_sample(texture_map[idx: idx + 1],\n uv_stack[idx: idx + 1],\n mode='bilinear', padding_mode='border')\n\n output_noc = output_noc[0].cpu().numpy().transpose([1, 2, 0])\n\n zero_im = zero_im + person_seg\n\n zero_im = (zero_im > 0).astype('float32')\n zero_im = cv2.dilate(zero_im, kernel, iterations=1)\n\n cv2.imwrite(os.path.join(seg_key_path, im['file_name']), (zero_im == 0.0).astype('uint8'))\n\n point_dict['noc'] = output_noc[point_dict['yx'][:, 0], point_dict['yx'][:, 1], :]\n # print(np.min(point_dict['yx']))\n key_list.append(im_dict)\n\n # cv2.imshow(\"Image\", image)\n # cv2.imshow(\"Background Image\", (zero_im == 0.0).astype('uint8') * 255)\n # cv2.imshow(\"IUV\", (zero_point_iuv * 30).astype('uint8'))\n # cv2.imshow(\"NOC sampled\", (output_noc * 255).astype('uint8'))\n #\n # cv2.waitKey(0)\n\n # progress_bar(idx + 1, len_ids, prefix=\"Progress for {}:\".format(key), suffix=\"Complete\")\n\n save_file = os.path.join(save_annotation_file, '{}.pkl'.format(key))\n with open(save_file, 'wb') as write_file:\n pickle.dump(key_list, write_file, protocol=pickle.HIGHEST_PROTOCOL)\n\n\n\ndef parse_args(args):\n def 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 parser = argparse.ArgumentParser()\n parser.add_argument('--output', type=str, default='./data/new_annotation.pkl', help='# of samples of human poses')\n parser.add_argument('--image_width', type=int, default=64, help='image width')\n parser.add_argument('--image_height', type=int, default=64, help='image height')\n\n return parser.parse_args(args)\n\n\nif __name__ == '__main__':\n opt = parse_args(['--output=../data/dp_annotation',\n '--image_width=340',\n '--image_height=340'])\n main(opt)\n"
] | [
[
"scipy.io.loadmat",
"torch.from_numpy",
"numpy.ones",
"numpy.zeros_like",
"torch.nn.functional.grid_sample",
"numpy.array",
"numpy.zeros",
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
stefan-f-bucher/PyDDM | [
"6476a7268daebab4e599e1f1ab566a4100947a55"
] | [
"integration_tests.py"
] | [
"import unittest\nfrom unittest import TestCase, main\nimport numpy as np\nfrom math import fsum\nimport pandas\n\nimport ddm\n\nSHOW_PLOTS = False\n\nif SHOW_PLOTS:\n import ddm.plot\n import matplotlib.pyplot as plt\n\ndef _modeltest_numerical_vs_analytical(m, conditions={}, method=None, max_diff=.1, mean_diff=.05, prob_diff=.01):\n a = m.solve_analytical(conditions=conditions)\n if method is None:\n n = m.solve_numerical(conditions=conditions)\n elif method == \"cn\":\n n = m.solve_numerical_cn(conditions=conditions)\n elif method == \"implicit\":\n n = m.solve_numerical_implicit(conditions=conditions)\n elif method == \"explicit\":\n n = m.solve_numerical_explicit(conditions=conditions)\n if SHOW_PLOTS:\n ddm.plot.plot_solution_pdf(a)\n ddm.plot.plot_solution_pdf(n)\n plt.show()\n max_difference = np.max(np.abs(a.pdf_corr() - n.pdf_corr()))\n mean_difference = np.sum(np.abs(a.pdf_corr() - n.pdf_corr()))/len(m.t_domain())\n print(max_difference, mean_difference)\n assert max_difference < max_diff, \"Maximum distance between correct distributions was too high\"\n assert mean_difference < mean_diff, \"Mean distance between correct distributions was too high\"\n max_difference = np.max(np.abs(a.pdf_err() - n.pdf_err()))\n mean_difference = np.sum(np.abs(a.pdf_err() - n.pdf_err()))/len(m.t_domain())\n assert max_difference < max_diff, \"Maximum distance between error distributions was too high\"\n assert mean_difference < mean_diff, \"Mean distance between error distributions was too high\"\n assert abs(a.prob_correct() - n.prob_correct()) < prob_diff, \"Correct probability was too different\"\n assert abs(a.prob_error() - n.prob_error()) < prob_diff, \"Error probability was too different\"\n assert abs(a.prob_undecided() - n.prob_undecided()) < prob_diff, \"Undecided probability was too different\"\n\n\ndef _modeltest_pdf_evolution(m, conditions={}, max_diff=.1, max_deviation=.01):\n sol_with_evolution = m.solve_numerical_implicit(conditions=conditions, returnEvolution=True) \n sol_without_evolution = np.zeros((len(sol_with_evolution.model.x_domain(conditions)), len(sol_with_evolution.model.t_domain()))) \n sol_without_evolution[:,0] = m.IC(conditions=conditions)/m.dx\n for t_ind, t in enumerate(sol_with_evolution.model.t_domain()[1:]):\n T_dur_backup = m.T_dur\n m.T_dur = t\n sol = m.solve_numerical_implicit(conditions=conditions, returnEvolution=False) \n m.T_dur = T_dur_backup\n sol_without_evolution[:,t_ind+1] = sol.pdf_undec()\n difference = sol_with_evolution.pdf_evolution() - sol_without_evolution\n max_difference = np.max(np.abs(difference))\n print(max_difference)\n sums = np.array([sum(sol_with_evolution.pdf_corr()[0:t]*m.dt) + sum(sol_with_evolution.pdf_err()[0:t]*m.dt) + sum(sol_with_evolution.pdf_evolution()[:,t]*m.dx) for t in range(1,len(sol_with_evolution.model.t_domain()))])\n print(np.max(np.abs(sums-1)))\n assert max_difference < max_diff, \"Maximum distance between pdf evolutions was too high\"\n assert np.max(np.abs(sums-1)) < max_deviation, \"PDF does not sum up to 1\"\n\n\ndef _verify_param_match(dependence, parameter, m1, m2, tol=.1):\n p1 = getattr(m1.get_dependence(dependence), parameter)\n p2 = getattr(m2.get_dependence(dependence), parameter)\n assert abs(p1 - p2) < 0.1 * p1, \"%s param from %s dependence doesn't match: %.4f != %.4f\" % (parameter, dependence, p1, p2)\n\nclass TestSimulation(TestCase):\n \"\"\"Numerical solutions should be close to analytical solutions\"\"\"\n def setUp(self):\n self.basic = ddm.Model(dx=.005, dt=.01, T_dur=2,\n drift=ddm.DriftConstant(drift=.4),\n noise=ddm.NoiseConstant(noise=1),\n bound=ddm.BoundConstant(B=1))\n class NoiseCond(ddm.Noise):\n name = \"Noise with a condition\"\n required_conditions = ['cond']\n required_parameters = []\n def get_noise(self, conditions, **kwargs):\n return conditions[\"cond\"]\n self.withcond = ddm.Model(noise=NoiseCond())\n def test_basic_cn(self):\n \"\"\"Simple DDM, Crank-Nicolson\"\"\"\n _modeltest_numerical_vs_analytical(self.basic, method=\"cn\")\n def test_basic_implicit(self):\n \"\"\"Simple DDM\"\"\"\n _modeltest_numerical_vs_analytical(self.basic, method=\"implicit\")\n def test_basic_explicit(self):\n \"\"\"Simple DDM with explicit method. For a reasonable runtime we need terrible numerics\"\"\"\n prev_dx = self.basic.dx\n prev_dt = self.basic.dt\n self.basic.dx = .05\n self.basic.dt = .001\n _modeltest_numerical_vs_analytical(self.basic, method=\"explicit\",\n max_diff=.3, mean_diff=.2, prob_diff=.05)\n self.basic.dx = prev_dx\n self.basic.dt = prev_dt\n def test_overlay_chain_distribution_integrates_to_1(self):\n \"\"\"Overlays integrate to 1\"\"\"\n m = ddm.Model(name=\"Overlay_test\", drift=ddm.DriftConstant(drift=2), T_dur=5,\n overlay=ddm.OverlayChain(overlays=[ddm.OverlayPoissonMixture(pmixturecoef=.2, rate=2),\n ddm.OverlayUniformMixture(umixturecoef=.2),\n ddm.OverlayNonDecision(nondectime=.2)]))\n s = m.solve()\n distsum = s.prob_correct() + s.prob_error()\n assert .99 < distsum < 1.0001, \"Distribution doesn't sum to 1\"\n def test_with_condition(self):\n \"\"\"With conditions\"\"\"\n _modeltest_numerical_vs_analytical(self.withcond, method=\"cn\", conditions={\"cond\": .2})\n _modeltest_numerical_vs_analytical(self.withcond, method=\"cn\", conditions={\"cond\": .6})\n def test_pdf_evolution(self):\n \"\"\"PDF evolution in simple DDM\"\"\"\n _modeltest_pdf_evolution(self.basic)\n\nclass TestFit(TestCase):\n def setUp(self):\n from integration_test_models import DriftCond\n self.DriftCond = DriftCond\n self.cond_m = ddm.Model(drift=self.DriftCond(param=1))\n self.cond_s = self.cond_m.solve(conditions={\"cond\": .1}).resample(4000) + \\\n self.cond_m.solve(conditions={\"cond\": 1}).resample(4000) + \\\n self.cond_m.solve(conditions={\"cond\": 2}).resample(4000)\n def test_fit_drift(self):\n \"\"\"A simple one-parameter fit\"\"\"\n m = ddm.Model(name=\"DDM\", drift=ddm.DriftConstant(drift=2))\n s = m.solve()\n sample = s.resample(10000)\n mfit = ddm.Model(name=\"DDM\", drift=ddm.DriftConstant(drift=ddm.Fittable(minval=0, maxval=10)))\n ddm.fit_adjust_model(model=mfit, sample=sample)\n # Within 10%\n if SHOW_PLOTS:\n mfit.name = \"Fitted solution\"\n sfit = mfit.solve()\n plot_compare_solutions(s, sfit)\n plt.show()\n _verify_param_match(\"drift\", \"drift\", m, mfit)\n def test_fit_with_condition(self):\n \"\"\"A simple one-parameter fit with conditions\"\"\"\n m = self.cond_m\n s = self.cond_s\n mfit = ddm.Model(drift=self.DriftCond(param=ddm.Fittable(minval=.1, maxval=3)))\n ddm.fit_adjust_model(model=mfit, sample=s)\n # Within 10%\n if SHOW_PLOTS:\n mfit.name = \"Fitted solution\"\n sfit = mfit.solve()\n plot_compare_solutions(s, sfit)\n plt.show()\n _verify_param_match(\"drift\", \"param\", m, mfit)\n def test_fit_with_condition_parallel(self):\n \"\"\"A simple one-parameter fit with conditions, parallelized\"\"\"\n ddm.set_N_cpus(2)\n self.test_fit_with_condition()\n ddm.set_N_cpus(1)\n def test_double_fit(self):\n \"\"\"Fit different parameters in the same (or a different) model using a single Fittable object\"\"\"\n class NoiseDouble(ddm.Noise):\n name = \"time-varying noise\"\n required_parameters = [\"noise1\", \"noise2\"]\n def get_noise(self, **kwargs):\n if np.random.rand() > .5:\n return self.noise1\n else:\n return self.noise2\n class NoiseConstantButNot(ddm.Noise): # To avoid the numerical simulations\n name = \"almost noise constant\"\n required_parameters = [\"noise\"]\n def get_noise(self, **kwargs):\n return self.noise\n # Generate data\n m = ddm.Model(name=\"DDM\",\n drift=ddm.DriftConstant(drift=1),\n noise=ddm.NoiseConstant(noise=1.7))\n s = m.solve_numerical() # Solving analytical and then fitting numerical may give a bias\n sample = s.resample(10000)\n mone = ddm.fit_model(sample, drift=ddm.DriftConstant(drift=1),\n noise=NoiseConstantButNot(noise=ddm.Fittable(minval=.5, maxval=3)))\n sigs = ddm.Fittable(minval=.5, maxval=3)\n msam = ddm.fit_model(sample, drift=ddm.DriftConstant(drift=1),\n noise=NoiseDouble(noise1=sigs,\n noise2=sigs))\n assert msam._noisedep.noise1 == msam._noisedep.noise2, \"Fitting to be the same failed\"\n assert abs(msam._noisedep.noise1 - mone._noisedep.noise) < 0.1 * mone._noisedep.noise\n\n"
] | [
[
"numpy.random.rand",
"matplotlib.pyplot.show",
"numpy.abs"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jlandercy/odapi | [
"781aa95ef346f8d5f1d727a19ae078687cc4cc36"
] | [
"odapi/toolbox/psychro.py"
] | [
"import numpy as np\nfrom scipy import optimize\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Polygon\nfrom matplotlib.collections import PatchCollection\n\n\nclass Constants:\n \"\"\"\n Physical Constants\n \"\"\"\n R = 8.314472 # [J/mol.K]\n T0K = 273.15 # [K]\n\n @staticmethod\n def TK(TC):\n \"\"\"\n Temperature Conversion from Celcius to Kelvin\n \"\"\"\n return TC + Constants.T0K\n\n @staticmethod\n def TC(TK):\n \"\"\"\n Temperature Conversion from Kelvin to Celcius\n \"\"\"\n return TK - Constants.T0K\n\n\nclass Conditions:\n \"\"\"\n Standard Conditions\n \"\"\"\n p0 = 1.01325e5 # [Pa]\n T0 = 0 + Constants.T0K # [K]\n\n\nclass Water:\n \"\"\"\n Water Physical/Chemical Description\n \"\"\"\n M = 18.0153e-3 # [Kg/mol]\n Tvap = 99.94 + Constants.T0K # [K]\n cp = 1.826e3 # [J/kg.K]\n Hv = 40.662e3 # [J/mol]\n lv = Hv/M # [J/Kg]\n\n\nclass Air:\n \"\"\"\n Dry Air Physical/Chemical Description\n \"\"\"\n M = 28.6953e-3 # [Kg/mol]\n cp = 1.006e3 # [J/Kg.K]\n\n\nclass Mix:\n \"\"\"\n Mix of Gas and Liquid\n All quantities are expressed in Standard Units System\n \"\"\"\n \n C = Constants\n CSTP = Conditions\n gas = Air\n liquid = Water\n \n Mr = liquid.M/gas.M\n\n @staticmethod\n def psat(T):\n \"\"\"\n Saturation Pressure p_sat(T) [Pa]\n as a Temperature T [K] function\n \"\"\"\n return Mix.CSTP.p0*np.exp(-Mix.liquid.Hv/Mix.C.R*(1/T - 1/Mix.liquid.Tvap))\n\n @staticmethod\n def xpw(pw):\n \"\"\"\n Vapour Mass Ratio x(p_w) [Kg Liquid/Kg Gas]\n as a function of Liquid Partial Pressure p_w [Pa] \n \"\"\"\n return Mix.Mr*pw/(Mix.CSTP.p0-pw)\n\n @staticmethod\n def xw(T, phi):\n \"\"\"\n Vapour Mass Ratio x(p_w) [Kg Liquid/Kg Gas]\n as a function of Liquid Partial Pressure p_w [Pa] \n \"\"\"\n return Mix.pisow(T, phi=phi)\n\n @staticmethod\n def pwx(x):\n \"\"\"\n Liquid Partial Pressure p_w(x) [Pa]\n as a function of Vapour Mass Ratio x [Kg Liquid/Kg Gas]\n \"\"\"\n return Mix.CSTP.p0*x/(x + Mix.Mr)\n\n @staticmethod\n def pisow(T, phi=1.):\n \"\"\"\n Isopleth: Iso Relative Humidity (phi) Curve w(T)=k [-]\n as a function of Temperature T [K]\n Relative Humidity is defined as the ratio of Liquid Partial Pressure p_w [Pa]\n and Saturation Pressure p_sat(T) [Pa]: w = p_w/p_sat(T)\n \"\"\"\n return phi*Mix.psat(T)\n\n @staticmethod\n def pisov(T, v):\n \"\"\"\n Isopleth (Isochoric): Iso Specific Volume Curve v(T)=k [m^3 Mix/Kg Gas]\n as a function of Temperature T [K]\n \"\"\"\n return Mix.CSTP.p0 - (Mix.C.R*T)/(Mix.gas.M*v)\n\n @staticmethod\n def pisoh(T, h):\n \"\"\"\n Isopleth (Isenthalpic): Iso Specific Enthalpy Curve h(T)=k [J/Kg Gas]\n as a function of Temperature T [K]\n \"\"\"\n dT = (T - Mix.CSTP.T0)\n return Mix.CSTP.p0*(h - Mix.gas.cp*dT)/((h + Mix.Mr*Mix.liquid.lv) + (Mix.Mr*Mix.liquid.cp - Mix.gas.cp)*dT)\n\n @staticmethod\n def Tmin_score(f, k):\n \"\"\"\n Score function for then intersection of the k-isopleth of kind f and Saturation Curve p_sat(T)\n as a function of Temperature T [K]\n Score function is designed to determine Tmin [K] for Psychrometric Chart Display\n \"\"\"\n def inner(T):\n return Mix.psat(T) - f(T, k)\n return inner\n\n @staticmethod\n def Tmin(f, k, tol=5e-3):\n \"\"\"\n Solve score function to determine Tmin [K] for Psychrometric Chart Display\n \"\"\"\n return optimize.root(Mix.Tmin_score(f, k), 0.1, tol=tol)\n\n @staticmethod\n def Tmax(f, k, tol=5e-3):\n \"\"\"\n Find root of the k-isopleth of kind f to get Tmax [K] for Psychrometric Chart Display\n \"\"\"\n return optimize.root(lambda T: f(T, k), 0.1, tol=tol)\n\n @staticmethod\n def get_limits(f, konsts, Tmin, Tmax):\n \"\"\"\n Compute Temperature Boundaries for a given isopleth of a kind f of level k\n \"\"\"\n n = konsts.size\n Ts = np.full((n, 2), np.nan)\n for i, k in enumerate(konsts):\n rmin = Mix.Tmin(f, k)\n if rmin.success:\n Ts[i, 0] = max(rmin.x[0], Tmin)\n rmax = Mix.Tmax(f, k)\n if rmax.success:\n Ts[i, 1] = min(rmax.x[0], Tmax)\n return Ts\n\n @staticmethod\n def domestic_ranges():\n \"\"\"\n Basic Ranges for Domestic Use\n \"\"\"\n return {\n 'Tmin': +0. + Constants.T0K, # [K]\n 'Tmax': +35. + Constants.T0K, # [K]\n 'isow': np.arange(0.1, 0.91, 0.1), # [-]\n 'isov': np.arange(0.76, 0.95, 0.01), # [m^3/kg]\n 'isoh': np.arange(-1.e4, 13.1e4, 1e4), # [J/Kg]\n 'kOy': 1000., # [KJ/J]\n 'ylim': [0., 5.e3], # [Pa]\n 'Tmode': 'kelvin',\n 'ymode': 'partial'\n }\n\n @staticmethod\n def compute(f, konsts, Tmin, Tmax, ns=101):\n \"\"\"\n Compute k-isopleths of kind f for the given Temperature Range (Tmin, Tmax) [K]\n Temperature Range is refined to real Temperature Boundaries (keep resolution equals, nice display)\n \"\"\"\n nk = konsts.size\n T = np.full((ns, nk), np.nan)\n xT = np.full((ns, nk), np.nan)\n Ts = Mix.get_limits(f, konsts, Tmin, Tmax)\n for i, k in enumerate(konsts):\n T[:, i] = np.linspace(*Ts[i, :], ns)\n xT[:, i] = f(T[:, i], k)\n return T, xT\n \n _requiredKeys = ('Tmin', 'Tmax', 'isow', 'isov', 'isoh', 'ylim')\n\n @staticmethod\n def plot(Tmin=None, Tmax=None, ns=101, rtype='domestic', area=True,\n isow=None, isov=None, isoh=None, kOy=None, ylim=None, Tmode=None, ymode=None):\n \"\"\"\n Plot Psychrometric Chart for the given Temperature Range (Tmin, Tmax) [K]\n Including k-isopleths of each kind (iso-w, iso-v, iso-h)\n Also perform Units Conversion for readability sake\n \"\"\"\n \n # Parameters:\n ranges = getattr(Mix, '{}_ranges'.format(rtype))()\n Tmin = Tmin or ranges['Tmin']\n Tmax = Tmax or ranges['Tmax']\n isow = isoh or ranges['isow']\n isov = isoh or ranges['isov']\n isoh = isoh or ranges['isoh']\n ylim = ylim or ranges['ylim']\n kOy = kOy or ranges['kOy']\n Tmode = Tmode or ranges['Tmode']\n ymode = ymode or ranges['ymode']\n\n # Temperature:\n T = np.linspace(Tmin, Tmax, ns)\n \n # Curves:\n psat = Mix.psat(T)/kOy\n pphi = np.array([Mix.pisow(T, phi=phi)/kOy for phi in isow]).T\n Tv, pv = Mix.compute(Mix.pisov, isov, Tmin, Tmax, ns)\n Th, ph = Mix.compute(Mix.pisoh, isoh, Tmin, Tmax, ns)\n \n # Polygons:\n if area:\n T1 = Constants.TK(np.linspace(15, 27, 10))\n X1 = np.concatenate((Mix.pisow(T1, phi=0.4), np.array([0., 0.])))/kOy\n T1 = np.concatenate((T1, Constants.TK(np.array([27, 15]))), axis=0)\n P1 = Polygon(np.array([T1, X1]).T, True, color='blue', alpha=0.4)\n\n T2 = Constants.TK(np.linspace(15, 23, 10))\n X2 = np.concatenate((Mix.pisow(T2, phi=0.7), Mix.pisow(np.flip(T2), phi=1.)), axis=0)/kOy\n T2 = np.concatenate((T2, np.flip(T2)), axis=0)\n P2 = Polygon(np.array([T2, X2]).T, True, color='red', alpha=0.4)\n\n T3 = Constants.TK(np.linspace(23, 27, 10))\n X3 = np.concatenate((Mix.pisow(T3, phi=0.7), Mix.pisow(np.flip(T3), phi=1.)), axis=0)/kOy\n T3 = np.concatenate((T3, np.flip(T3)), axis=0)\n P3 = Polygon(np.array([T3, X3]).T, True, color='orange', alpha=0.4)\n\n T4 = Constants.TK(np.array([17, 17, 26, 26]))\n X4 = Mix.pisow(T4, phi=np.array([0.45, 0.8, 0.5, 0.35]))/kOy\n P4 = Polygon(np.array([T4, X4]).T, True, color='green', alpha=0.4)\n \n # Figure:\n fig, axe = plt.subplots()\n\n l1 = axe.plot(T, psat, color='black', linewidth=2.0)\n l2 = axe.plot(T, pphi, color='black', linewidth=0.75)\n l3 = axe.plot(Tv, pv/kOy, color='blue', linewidth=0.75)\n l4 = axe.plot(Th, ph/kOy, color='violet', linewidth=0.75)\n ls = [l1[0], l2[0], l3[0], l4[0]]\n ll = ['Saturation', 'Isohydric', 'Isochoric', 'Isenthalpic']\n\n if area:\n l5 = axe.add_line(P1)\n l6 = axe.add_line(P2)\n l7 = axe.add_line(P3)\n l8 = axe.add_line(P4)\n ls.extend([l5, l6, l7, l8])\n ll.extend([\"Dry Zone\", \"Mold Zone\", \"Mite Zone\", \"Comfort Zone\"])\n \n axe.set_title(r\"{} Psychrometric Chart: $p_0 = {:.3f}$ $[\\mathrm{{kPa}}]$\".format(\n Mix.liquid.__name__, Mix.CSTP.p0/kOy))\n axe.set_xlabel(r\"Temperature, $T$ $[\\mathrm{K}]$\")\n axe.set_ylabel(r\"Partial Pressure, $p_w$ $[\\mathrm{kPa}]$\")\n\n axe.set_xlim(T[[0, -1]])\n axe.set_ylim(np.array(ylim)/kOy)\n\n lgd = axe.legend(ls, ll, bbox_to_anchor=(0, 1), loc='upper left', ncol=2)\n\n #axe.get_figure().tight_layout()\n axe.grid()\n return axe\n\n\ndef main():\n axe = Mix.plot()\n plt.show(axe.get_figure())\n #axe.get_figure().savefig(\"psychro.png\")\n\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"numpy.linspace",
"numpy.arange",
"matplotlib.pyplot.subplots",
"numpy.full",
"numpy.array",
"numpy.exp",
"numpy.flip"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
albertaillet/MLP_function_approx | [
"8b91467b8321eefd1de6aa29dd8593f7e6d5d08b"
] | [
"MLP_squared.py"
] | [
"# This script trains a MLP to approximate x^2\n# Model source: https://sonnet.dev/\n# Number of trainable source:\n# https://stackoverflow.com/questions/38160940/how-to-count-total-number-of-trainable-parameters-in-a-tensorflow-model\nimport numpy as np\nimport sonnet as snt\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\n\n# %% Parameters.\n# All parameters to be tweaked.\nmlp_dimensions = [5, 5, 1]\nnum_training_iterations = 1000\nlearning_rate = 1e-3\nrange_tr = (-1, 1)\nrange_plt = (-2, 2)\niteration_print = 100\n\n# Parameters depending on the tweaked ones.\nx_plot = np.linspace(*range_plt, num=100)\n\n\n# %% Data generator.\ndef get_data(low, high):\n x_np = np.random.uniform(low=low, high=high, size=(1, 1))\n y_np = np.square(x_np)\n x_tf = tf.convert_to_tensor(x_np, dtype=tf.float32)\n y_tf = tf.convert_to_tensor(y_np, dtype=tf.float32)\n return x_tf, y_tf\n\n\n# %% Restart Training.\n# Model.\nmodel = snt.nets.MLP(mlp_dimensions)\n\n# Optimizer.\noptimizer = snt.optimizers.Adam(learning_rate)\n\n# Starting values for training.\nlast_iteration = 0\nloss_list = []\n\n# %% Training (can be run multiple times for added num_training_iterations iterations).\ngradients = None\nfor iteration in range(last_iteration, last_iteration + num_training_iterations):\n last_iteration = iteration\n x, y = get_data(*range_tr)\n with tf.GradientTape() as tape:\n y_pred = model(x)\n loss = tf.compat.v1.losses.mean_squared_error(y, y_pred)\n gradients = tape.gradient(loss, model.trainable_variables)\n loss_list.append(loss.numpy())\n if (iteration + 1) % iteration_print == 0:\n optimizer.apply(gradients, model.trainable_variables)\n print(f\"Iteration: {iteration + 1}, Mean Loss: {np.mean(loss_list[-iteration_print:-1])}\")\n\n\n#%% Plot results.\nnum_trainable_variables = np.sum([np.prod(v.shape) for v in model.trainable_variables])\ny_plot = np.array([model(tf.convert_to_tensor([[x_i]], dtype=tf.float32)).numpy().squeeze() for x_i in x_plot])\nplt.plot(x_plot, np.square(x_plot), \"k-\") # Ground truth\nplt.plot(x_plot, y_plot, \"k--\") # Model predicted\nplt.legend((\"Ground truth\", \"MLP predicted\"), loc='upper center')\nplt.title(rf\"MLP tries to predict $x^2$ with {num_trainable_variables} trainable variables\")\nplt.show()\n\n#%% Plot loss\nstart = 100\nend = len(loss_list)\nplt.plot(range(start, end), loss_list[start:end])\nplt.ylabel(\"Loss (MSE)\")\nplt.xlabel(\"Training examples\")\nplt.show()\n\n# %% Test\nx, y = get_data(*range_tr)\ny_pred = model(x)\nprint(\"x={:.2f}, y={:.3f}, y_pred={:.3f}, diff={:.3f}\".format(*(i.numpy().squeeze() for i in (x, y, y_pred, y-y_pred))))\n"
] | [
[
"numpy.square",
"matplotlib.pyplot.legend",
"tensorflow.convert_to_tensor",
"matplotlib.pyplot.title",
"numpy.linspace",
"tensorflow.compat.v1.losses.mean_squared_error",
"matplotlib.pyplot.plot",
"numpy.random.uniform",
"tensorflow.GradientTape",
"numpy.mean",
"numpy.prod",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"2.9",
"2.5",
"2.8",
"2.10"
]
}
] |
JoshuaHaustein/oracle_server | [
"9dc54cd03e28eee6d546b811ce32bcc4d16cec0c"
] | [
"python_src/utils.py"
] | [
"import torch\nfrom torch.autograd import Variable\n\n\nclass Normalization(torch.nn.Module):\n\n def __init__(self, n_features):\n super(Normalization, self).__init__()\n self.register_buffer('mean', torch.zeros(n_features))\n self.register_buffer('std', torch.ones(n_features))\n \n def forward(self, x):\n return (x - Variable(self.mean)) / Variable(self.std)\n\nclass NormalizationInverse(torch.nn.Module):\n\n def __init__(self, n_features):\n super(NormalizationInverse, self).__init__()\n self.register_buffer('mean', torch.zeros(n_features))\n self.register_buffer('std', torch.ones(n_features))\n\n def forward(self, x):\n return x * Variable(self.std) + Variable(self.mean)\n"
] | [
[
"torch.autograd.Variable",
"torch.ones",
"torch.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ratschlab/projects2017-kG | [
"dfbebe4139d248ed229d783b72fb309d97bc9c84"
] | [
"kv/kv_class.py"
] | [
"# Copyright 2017 Max Planck Society\n# Distributed under the BSD-3 Software license,\n# (See accompanying file ./LICENSE.txt or copy at\n# https://opensource.org/licenses/BSD-3-Clause)\n\"\"\"This class implements VAE training.\n\n\"\"\"\n\nimport os\nimport logging\nimport tensorflow as tf\nimport utils\nfrom utils import ProgressBar\nfrom utils import TQDM\nimport numpy as np\nimport ops\nfrom metrics import Metrics\nfrom ais import ais\n#from ais2 import ais\nimport vae as VAE\nimport classifier as CLASSIFIER\n\nclass kVae(object):\n \"\"\"A base class for running individual VAEs.\n\n \"\"\"\n def __init__(self, opts, data, weights, test_data = None, test_weights = None):\n\n # Create a new session with session.graph = default graph\n self._session = tf.Session()\n self._trained = False\n self._data = data\n self._data_weights = np.copy(weights)\n self._test_data = test_data\n self._test_weights = np.copy(test_weights)\n # Latent noise sampled ones to apply decoder while training\n self._noise_for_plots = utils.generate_noise(opts, 500)\n # Placeholders\n self._real_points_ph = None\n self._noise_ph = None\n self._hard_assigned = np.ones(opts['number_of_kGANs'])*1.*len(data.data)\n # Main operations\n # FIX\n self._loss = None\n self._loss_reconstruct = None\n self._loss_kl = None\n self._generated = None\n self._reconstruct_x = None\n\n # Optimizers\n self.optim = None\n\n with self._session.as_default(), self._session.graph.as_default():\n logging.error('Building the graph...')\n self._build_model_internal(opts)\n\n # Make sure AdamOptimizer, if used in the Graph, is defined before\n # calling global_variables_initializer().\n init = tf.global_variables_initializer()\n self._session.run(init)\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n # Cleaning the whole default Graph\n logging.error('Cleaning the graph...')\n tf.reset_default_graph()\n logging.error('Closing the session...')\n # Finishing the session\n self._session.close()\n\n def train_vaes(self, opts):\n \"\"\"Train the kVAEs.\n\n \"\"\"\n with self._session.as_default(), self._session.graph.as_default():\n self._train_internal_vaes(opts)\n for k in range(opts['number_of_kGANs']): \n self.kVAEs[k]._trained = True\n\n def train_class(self, opts, fake_images):\n \"\"\"Train the k classifiers.\n\n \"\"\"\n with self._session.as_default(), self._session.graph.as_default():\n return self._train_internal_classifiers(opts, fake_images)\n def reinit_classifiers(self,opts):\n logging.error(\"Reinitializing classifiers.\")\n prefix = 'CLASSIFIER'\n for k in range(0,opts['number_of_kGANs']):\n t_vars = tf.trainable_variables()\n c_vars = [var for var in t_vars if prefix+str(k)+'/' in var.name]\n [self._session.run(var.initializer) for var in c_vars]\n\n def sample(self, opts, num=100):\n \"\"\"Sample points from the trained VAE model.\n\n \"\"\"\n assert self._trained, 'Can not sample from the un-trained VAE'\n with self._session.as_default(), self._session.graph.as_default():\n return self._sample_internal(opts, num)\n\n def train_mixture_discriminator(self, opts, fake_images):\n \"\"\"Train classifier separating true data from points in fake_images.\n\n Return:\n prob_real: probabilities of the points from training data being the\n real points according to the trained mixture classifier.\n Numpy vector of shape (self._data.num_points,)\n prob_fake: probabilities of the points from fake_images being the\n real points according to the trained mixture classifier.\n Numpy vector of shape (len(fake_images),)\n\n \"\"\"\n with self._session.as_default(), self._session.graph.as_default():\n return self._train_mixture_discriminator_internal(opts, fake_images)\n\n\n def _run_batch(self, opts, operation, placeholder, feed,\n placeholder2=None, feed2=None):\n \"\"\"Wrapper around session.run to process huge data.\n\n It is asumed that (a) first dimension of placeholder enumerates\n separate points, and (b) that operation is independently applied\n to every point, i.e. we can split it point-wisely and then merge\n the results. The second placeholder is meant either for is_train\n flag for batch-norm or probabilities of dropout.\n\n TODO: write util function which will be called both from this method\n and MNIST classification evaluation as well.\n\n \"\"\"\n assert len(feed.shape) > 0, 'Empry feed.'\n num_points = feed.shape[0]\n batch_size = opts['tf_run_batch_size']\n batches_num = int(np.ceil((num_points + 0.) / batch_size))\n result = []\n for idx in xrange(batches_num):\n if idx == batches_num - 1:\n if feed2 is None:\n res = self._session.run(\n operation,\n feed_dict={placeholder: feed[idx * batch_size:]})\n else:\n res = self._session.run(\n operation,\n feed_dict={placeholder: feed[idx * batch_size:],\n placeholder2: feed2})\n else:\n if feed2 is None:\n res = self._session.run(\n operation,\n feed_dict={placeholder: feed[idx * batch_size:\n (idx + 1) * batch_size]})\n else:\n res = self._session.run(\n operation,\n feed_dict={placeholder: feed[idx * batch_size:\n (idx + 1) * batch_size],\n placeholder2: feed2})\n\n if len(res.shape) == 1:\n # convert (n,) vector to (n,1) array\n res = np.reshape(res, [-1, 1])\n result.append(res)\n result = np.vstack(result)\n assert len(result) == num_points\n return result\n\n def _build_model_internal(self, opts):\n \"\"\"Build a TensorFlow graph with all the necessary ops.\n\n \"\"\"\n assert False, 'VAE base class has no build_model method defined.'\n\n def _train_internal(self, opts):\n assert False, 'VAE base class has no train method defined.'\n\n def _sample_internal(self, opts, num):\n assert False, 'VAE base class has no sample method defined.'\n\n def _train_mixture_discriminator_internal(self, opts, fake_images):\n assert False, 'VAE base class has no mixture discriminator method defined.'\n\n\n#class GeneratorAdapter(object):\n#\n# def __init__(self, generator, input_dim, output_dim):\n# self._generator = generator\n# self.input_dim = input_dim\n# self.output_dim = output_dim\n#\n# def __call__(self, z):\n# return self._generator(z)\n\n\n\nclass kToyVae(kVae):\n \"\"\"A simple VAE implementation, suitable for toy dataset.\n\n \"\"\"\n\n def __init__(self, opts, data, weights):\n\n # One more placeholder for batch norm\n self._is_training_ph = None\n\n kVae.__init__(self, opts, data, weights)\n\n\n\n def _build_model_internal(self, opts):\n \"\"\"Build the Graph corresponding to VAE implementation.\n\n \"\"\"\n data_shape = self._data.data_shape\n real_points_phs = []\n noise_phs = []\n is_training_phs = []\n lr_decay_phs = []\n vae_class = VAE.ToyVae\n classifier = CLASSIFIER.ToyClassifier\n kVAEs = [] \n kCLASSs = []\n optims = []\n class_real_pts_phs = []\n class_fake_pts_phs = []\n class_optims = []\n for k in range(opts['number_of_kGANs']):\n device = k%opts['number_of_gpus']\n with tf.device('/device:GPU:%d' %device):\n new_vae = vae_class(opts, self._data, model_idx = k, sess = self._session) \n new_class = classifier(opts, self._data, model_idx = k, sess = self._session )\n kVAEs.append(new_vae)\n kCLASSs.append(new_class)\n real_points_phs.append(new_vae._real_points_ph)\n noise_phs.append(new_vae._noise_ph)\n optims.append(new_vae._optim)\n is_training_phs.append(new_vae._is_training_ph)\n lr_decay_phs.append(new_vae._lr_decay_ph)\n class_real_pts_phs.append(new_class._real_points_ph)\n class_fake_pts_phs.append(new_class._fake_points_ph)\n class_optims.append(new_class._c_optim)\n\n # Operations\n\n #latent_x_mean, log_latent_sigmas = self.discriminator(\n # opts, real_points_ph, is_training_ph)\n #scaled_noise = tf.multiply(\n # tf.sqrt(1e-6 + tf.exp(log_latent_sigmas)), noise_ph)\n #loss_kl = 0.5 * tf.reduce_sum(\n # tf.exp(log_latent_sigmas) +\n # tf.square(latent_x_mean) -\n # log_latent_sigmas, axis=1)\n #if opts['recon_loss'] == 'l2sq':\n # reconstruct_x = self.generator(opts, latent_x_mean + scaled_noise,\n # is_training_ph)\n # loss_reconstruct = tf.reduce_sum(\n # tf.square(real_points_ph - reconstruct_x), axis=[1,2,3])\n # loss_reconstruct = loss_reconstruct / 2. / opts['vae_sigma']\n #elif opts['recon_loss'] == 'cross_entropy':\n # if opts['input_normalize_sym']:\n # expected = (real_points_ph + 1.0) / 2.0\n # else:\n # expected = real_points_ph\n # reconstruct_x_logits = self.generator(\n # opts, latent_x_mean + scaled_noise,\n # is_training_ph, return_logits=True)\n # loss_reconstruct = tf.reduce_sum(\n # tf.nn.sigmoid_cross_entropy_with_logits(\n # labels=expected, logits=reconstruct_x_logits),\n # axis=[1,2,3])\n #else:\n # raise ValueError(\"Unknown recon loss value %s\" % opts['recon_loss'])\n #dec_enc_x = self.generator(opts, latent_x_mean,\n # is_training=False, reuse=True)\n #self.loss_pp = loss_reconstruct\n #loss_reconstruct = tf.reduce_mean(loss_reconstruct)\n #loss_kl = tf.reduce_mean(loss_kl)\n #loss = loss_kl + loss_reconstruct\n # loss = tf.Print(loss, [loss, loss_kl, loss_reconstruct], 'Loss, KL, reconstruct')\n #optim = ops.optimizer(opts, decay=lr_decay_ph).minimize(loss)\n\n #generated_images = self.generator(opts, noise_ph,\n # is_training_ph, reuse=True)\n\n self._real_points_phs = real_points_phs\n self._noise_phs = noise_phs\n self._is_training_phs = is_training_phs\n self._optims = optims\n #self._loss = loss\n #self._loss_reconstruct = loss_reconstruct\n self._lr_decay_phs = lr_decay_phs\n self._class_real_pts_phs = class_real_pts_phs\n self._class_fake_pts_phs = class_fake_pts_phs\n self._class_optims = class_optims\n self.kVAEs = kVAEs\n self.kCLASS = kCLASSs\n #self._loss_kl = loss_kl\n #self._generated = generated_images\n #self._reconstruct_x = dec_enc_x\n #self._enc_mean = latent_x_mean\n #self._enc_log_var = log_latent_sigmas\n\n #saver = tf.train.Saver(max_to_keep=10)\n #tf.add_to_collection('real_points_ph', self._real_points_ph)\n #tf.add_to_collection('noise_ph', self._noise_ph)\n #tf.add_to_collection('is_training_ph', self._is_training_ph)\n #tf.add_to_collection('encoder_mean', self._enc_mean)\n #tf.add_to_collection('encoder_log_sigma', self._enc_log_var)\n #tf.add_to_collection('decoder', self._generated)\n #print \"Building the AIS model...\"\n #decoder = (lambda x, o=opts, i=is_training_ph:\n # self.generator(o, x, i, reuse=True))\n\n #output_dim = np.prod(list(data_shape))\n #self._ais_model = ais.AIS(\n # generator=GeneratorAdapter(decoder,\n # opts['latent_space_dim'],\n # output_dim),\n # prior=ais.NormalPrior(),\n # kernel=ais.ParsenDensityEstimator(),\n # sigma=0.1,\n # num_samples=1000,\n # stepsize=0.1)\n #print \"Building the AIS model: DONE\"\n #self._saver = saver\n\n #logging.error(\"Building Graph Done.\")\n\n\n def _train_internal_vaes(self, opts):\n \"\"\"Train a VAE model.\n\n \"\"\"\n\n batches_num = self._data.num_points / opts['batch_size']\n #if opts['one_batch'] == True:\n # batches_num = 1\n train_size = self._data.num_points\n num_plot = 320\n sample_prev = np.zeros([num_plot] + list(self._data.data_shape))\n l2s = []\n\n counter = 0\n decay = 1.\n logging.error('Training VAE')\n for _epoch in xrange(opts[\"gan_epoch_num\"]):\n\n if opts['decay_schedule'] == \"manual\":\n if _epoch == 30:\n decay = decay / 2.\n if _epoch == 50:\n decay = decay / 5.\n if _epoch == 100:\n decay = decay / 10.\n\n if False and _epoch > 0 and _epoch % opts['save_every_epoch'] == 0:\n os.path.join(opts['work_dir'], opts['ckpt_dir'])\n #self._saver.save(self._session,\n # os.path.join(opts['work_dir'],\n # opts['ckpt_dir'],\n # 'trained-pot'),\n # global_step=counter)\n\n for _idx in xrange(batches_num):\n # logging.error('Step %d of %d' % (_idx, batches_num ) )\n dict_ph = {}\n optimizers = []\n for k in range(opts['number_of_kGANs']):\n if self._hard_assigned[k] >= opts['batch_size']: \n data_ids = np.random.choice(train_size, opts['batch_size'],\n replace=False, p=self._data_weights[:,k])\n batch_images = self._data.data[data_ids].astype(np.float)\n batch_noise = utils.generate_noise(opts, opts['batch_size'])\n dict_ph[self._real_points_phs[k]] = batch_images\n dict_ph[self._noise_phs[k]] = batch_noise\n dict_ph[self._lr_decay_phs[k]] = decay\n dict_ph[self._is_training_phs[k]] = True\n optimizers.append(self._optims[k])\n #_, loss, loss_kl, loss_reconstruct = self._session.run(\n # [self._optim, self._loss, self._loss_kl,\n # self._loss_reconstruct],\n # feed_dict={self._real_points_ph: batch_images,\n # self._noise_ph: batch_noise,\n # self._lr_decay_ph: decay,\n # self._is_training_ph: True})\n self._session.run(\n optimizers,\n feed_dict=dict_ph)\n counter += 1\n\n #if False and opts['verbose'] and counter % opts['plot_every'] == 0:\n # debug_str = 'Epoch: %d/%d, batch:%d/%d' % (\n # _epoch+1, opts['gan_epoch_num'], _idx+1, batches_num)\n # debug_str += ' [L=%.2g, Recon=%.2g, KLQ=%.2g]' % (\n # loss, loss_reconstruct, loss_kl)\n # logging.error(debug_str)\n\n #if False and opts['verbose'] and counter % opts['plot_every'] == 0:\n # metrics = Metrics()\n # points_to_plot = self._run_batch(\n # opts, self._generated, self._noise_ph,\n # self._noise_for_plots[0:num_plot],\n # self._is_training_ph, False)\n # l2s.append(np.sum((points_to_plot - sample_prev)**2))\n # metrics.l2s = l2s[:]\n # metrics.make_plots(\n # opts,\n # counter,\n # None,\n # points_to_plot,\n # prefix='sample_e%04d_mb%05d_' % (_epoch, _idx))\n # reconstructed = self._session.run(\n # self._reconstruct_x,\n # feed_dict={self._real_points_ph: batch_images,\n # self._is_training_ph: False})\n # metrics.l2s = None\n # metrics.make_plots(\n # opts,\n # counter,\n # None,\n # reconstructed,\n # prefix='reconstr_e%04d_mb%05d_' % (_epoch, _idx))\n #if opts['early_stop'] > 0 and counter > opts['early_stop']:\n # break\n #if _epoch > 0:\n # os.path.join(opts['work_dir'], opts['ckpt_dir'])\n # self._saver.save(self._session,\n # os.path.join(opts['work_dir'],\n # opts['ckpt_dir'],\n # 'trained-pot-final'),\n # global_step=counter)\n \n def _train_internal_classifiers(self, opts, fake_images):\n \"\"\"Train a classifier separating true data from points in fake_images.\n \n \"\"\"\n batches_num = self._data.num_points / opts['batch_size_classifier']\n if opts['one_batch'] == True:\n batches_num = 1\n logging.debug('Training a mixture discriminator')\n for epoch in xrange(opts[\"mixture_c_epoch_num\"]):\n for idx in xrange(batches_num):\n dict_ph = {}\n for k in range(0,opts['number_of_kGANs']): \n ids = np.random.choice(len(fake_images[0]), opts['batch_size_classifier'],replace=False)\n batch_fake_images = fake_images[k,ids]\n dict_ph[self._class_fake_pts_phs[k]] = batch_fake_images\n\n ids = np.random.choice(self._data.num_points, opts['batch_size_classifier'],replace=False)\n batch_real_images = self._data.data[ids]\n dict_ph[self._class_real_pts_phs[k]] = batch_real_images\n _ = self._session.run(\n self._class_optims,\n feed_dict = dict_ph)\n res = np.zeros((len(self._data.data),opts['number_of_kGANs']))\n for k in range(0,opts['number_of_kGANs']):\n res[:,k] = self._run_batch(\n opts, self.kCLASS[k]._c_training,\n self.kCLASS[k]._real_points_ph, self._data.data).flatten()\n\n return res\n\n\n #def _sample_internal(self, opts, num):\n # \"\"\"Sample from the trained GAN model.\n #\n # \"\"\"\n # noise = utils.generate_noise(opts, num)\n # sample = self._run_batch(\n # opts, self._generated, self._noise_ph, noise,\n # self._is_training_ph, False)\n # return sample\n\n #def compute_ais(self):\n # self._ais_model.set_session(self._session)\n # batch_size = 64\n # train_size = self._data.num_points\n # batch_size = min(batch_size, len(np.argwhere(self._data_weights != 0)))\n # data_ids = np.random.choice(train_size, batch_size,\n # replace=False, p=self._data_weights)\n # current_batch = self._data.data[data_ids].astype(np.float)\n # current_batch = np.reshape(current_batch, [batch_size, -1])\n # lld = self._ais_model.ais(current_batch,\n # ais.get_schedule(400, rad=4))\n #print \"=== Step: {} ===\".format(current_step)\n #print \"loss: {}\".format(loss)\n #print \"log-likelihood: {}\".format(lld)\n #print \"mean(log-likelihood): {}\".format(np.mean(lld))\n # return np.mean(lld)\n\n #def compute_ais_test(self):\n # self._ais_model.set_session(self._session)\n # batch_size = 64\n # train_size = len(self._test_data)\n # batch_size = min(batch_size, train_size)\n # data_ids = np.random.choice(train_size, batch_size,\n # replace=False, p=self._test_weights)\n # current_batch = self._test_data[data_ids].astype(np.float)\n # current_batch = np.reshape(current_batch, [batch_size, -1])\n # lld = self._ais_model.ais(current_batch,\n # ais.get_schedule(400, rad=4))\n #print \"=== Step: {} ===\".format(current_step)\n #print \"loss: {}\".format(loss)\n #print \"log-likelihood: {}\".format(lld)\n #print \"mean(log-likelihood): {}\".format(np.mean(lld))\n # return np.mean(lld)\n #def loss_pt(self, opts):\n # num_points = self._data.num_points\n # batch_noise = utils.generate_noise(opts, self._data.num_points)\n # batch_size = opts['tf_run_batch_size']\n # batches_num = int(np.ceil((num_points + 0.) / batch_size))\n # result = []\n # for idx in xrange(batches_num):\n # if idx == batches_num - 1:\n # res = self._session.run(\n # self.loss_pp,\n # feed_dict={self._real_points_ph: self._data.data[idx * batch_size:],\n # self._noise_ph: batch_noise[idx * batch_size:],\n # self._is_training_ph: False})\n # else:\n # res = self._session.run(\n # self.loss_pp,\n # feed_dict={self._real_points_ph: self._data.data[idx * batch_size:(idx + 1) * batch_size],\n # self._noise_ph: batch_noise[idx * batch_size:(idx + 1) * batch_size],\n # self._is_training_ph: False})\n # if len(res.shape) == 1:\n # convert (n,) vector to (n,1) array\n # res = np.reshape(res, [-1, 1])\n # result.append(res)\n # result = np.vstack(result)\n # return result \n\n\nclass kImageVae(kVae):\n \"\"\"A simple VAE implementation, suitable for pictures.\n\n \"\"\"\n\n def __init__(self, opts, data, weights):\n\n # One more placeholder for batch norm\n self._is_training_ph = None\n self._use_second_ais = True\n\n kVae.__init__(self, opts, data, weights)\n\n def generator(self, opts, noise, is_training, reuse=False, return_logits=False):\n \"\"\"Generator function, suitable for simple picture experiments.\n\n Args:\n noise: [num_points, dim] array, where dim is dimensionality of the\n latent noise space.\n is_training: bool, defines whether to use batch_norm in the train\n or test mode.\n return_logits: bool, if true returns the \"logits\" instead of being\n normalized (by tanh or sigmoid depending on \"input_normalize_sym\".\n Returns:\n [num_points, dim1, dim2, dim3] array, where the first coordinate\n indexes the points, which all are of the shape (dim1, dim2, dim3).\n \"\"\"\n\n output_shape = self._data.data_shape # (dim1, dim2, dim3)\n # Computing the number of noise vectors on-the-go\n dim1 = tf.shape(noise)[0]\n num_filters = opts['g_num_filters']\n num_layers = opts['g_num_layers']\n #keep_prob = opts['dropout_keep_prob']\n with tf.variable_scope(\"GENERATOR\", reuse=reuse):\n\n height = output_shape[0] / 2**(num_layers - 1)\n width = output_shape[1] / 2**(num_layers - 1)\n h0 = ops.linear(opts, noise, num_filters * height * width,\n scope='h0_lin')\n h0 = tf.reshape(h0, [-1, height, width, num_filters])\n h0 = tf.nn.relu(h0)\n\n layer_x = h0\n for i in xrange(num_layers-1):\n scale = 2**(i+1)\n _out_shape = [dim1, height * scale, width * scale, num_filters / scale]\n layer_x = ops.deconv2d(opts, layer_x, _out_shape, scope='h%d_deconv' % i)\n if opts['batch_norm']:\n layer_x = ops.batch_norm(opts, layer_x, is_training, reuse, scope='bn%d' % i)\n layer_x = tf.nn.relu(layer_x)\n if opts['dropout']:\n _keep_prob = tf.minimum(\n 1., 0.9 - (0.9 - keep_prob) * float(i + 1) / (num_layers - 1))\n layer_x = tf.nn.dropout(layer_x, _keep_prob)\n\n # # h0 = ops.lrelu(h0)\n # _out_shape = [dim1, height * 2, width * 2, num_filters / 2]\n # # for 28 x 28 does 7 x 7 --> 14 x 14\n # h1 = ops.deconv2d(opts, h0, _out_shape, scope='h1_deconv')\n # h1 = ops.batch_norm(opts, h1, is_training, reuse, scope='bn_layer2')\n # h1 = tf.nn.relu(h1)\n # # h1 = ops.lrelu(h1)\n # _out_shape = [dim1, height * 4, width * 4, num_filters / 4]\n # # for 28 x 28 does 14 x 14 --> 28 x 28\n # h2 = ops.deconv2d(opts, h1, _out_shape, scope='h2_deconv')\n # h2 = ops.batch_norm(opts, h2, is_training, reuse, scope='bn_layer3')\n # h2 = tf.nn.relu(h2)\n # # h2 = ops.lrelu(h2)\n\n _out_shape = [dim1] + list(output_shape)\n # data_shape[0] x data_shape[1] x ? -> data_shape\n h3 = ops.deconv2d(opts, layer_x, _out_shape,\n d_h=1, d_w=1, scope='hlast_deconv')\n # h3 = ops.batch_norm(opts, h3, is_training, reuse, scope='bn_layer4')\n\n if return_logits:\n return h3\n if opts['input_normalize_sym']:\n return tf.nn.tanh(h3)\n else:\n return tf.nn.sigmoid(h3)\n\n def discriminator(self, opts, input_, is_training,\n prefix='DISCRIMINATOR', reuse=False):\n \"\"\"Encoder function, suitable for simple toy experiments.\n\n \"\"\"\n num_filters = opts['d_num_filters']\n\n with tf.variable_scope(prefix, reuse=reuse):\n h0 = ops.conv2d(opts, input_, num_filters / 8, scope='h0_conv')\n h0 = ops.batch_norm(opts, h0, is_training, reuse, scope='bn_layer1')\n h0 = tf.nn.relu(h0)\n h1 = ops.conv2d(opts, h0, num_filters / 4, scope='h1_conv')\n h1 = ops.batch_norm(opts, h1, is_training, reuse, scope='bn_layer2')\n h1 = tf.nn.relu(h1)\n h2 = ops.conv2d(opts, h1, num_filters / 2, scope='h2_conv')\n h2 = ops.batch_norm(opts, h2, is_training, reuse, scope='bn_layer3')\n h2 = tf.nn.relu(h2)\n h3 = ops.conv2d(opts, h2, num_filters, scope='h3_conv')\n h3 = ops.batch_norm(opts, h3, is_training, reuse, scope='bn_layer4')\n h3 = tf.nn.relu(h3)\n # Already has NaNs!!\n latent_mean = ops.linear(opts, h3, opts['latent_space_dim'], scope='h3_lin')\n log_latent_sigmas = ops.linear(opts, h3, opts['latent_space_dim'], scope='h3_lin_sigma')\n\n return latent_mean, log_latent_sigmas\n\n def _build_model_internal(self, opts):\n \"\"\"Build the Graph corresponding to VAE implementation.\n\n \"\"\"\n data_shape = self._data.data_shape\n real_points_phs = []\n noise_phs = []\n is_training_phs = []\n lr_decay_phs = []\n vae_class = VAE.ImageVae\n classifier = CLASSIFIER.ImageClassifier\n kVAEs = [] \n kCLASSs = []\n optims = []\n class_real_pts_phs = []\n class_fake_pts_phs = []\n class_optims = []\n for k in range(opts['number_of_kGANs']): \n device = k%opts['number_of_gpus']\n with tf.device('/device:GPU:%d' %device):\n new_vae = vae_class(opts, self._data, model_idx = k, sess = self._session) \n new_class = classifier(opts, self._data, model_idx = k, sess = self._session )\n kVAEs.append(new_vae)\n kCLASSs.append(new_class)\n real_points_phs.append(new_vae._real_points_ph)\n noise_phs.append(new_vae._noise_ph)\n optims.append(new_vae._optim)\n is_training_phs.append(new_vae._is_training_ph)\n lr_decay_phs.append(new_vae._lr_decay_ph)\n class_real_pts_phs.append(new_class._real_points_ph)\n class_fake_pts_phs.append(new_class._fake_points_ph)\n class_optims.append(new_class._c_optim)\n\n\n self._real_points_phs = real_points_phs\n self._noise_phs = noise_phs\n self._is_training_phs = is_training_phs\n self._optims = optims\n #self._loss = loss\n #self._loss_reconstruct = loss_reconstruct\n self._lr_decay_phs = lr_decay_phs\n self._class_real_pts_phs = class_real_pts_phs\n self._class_fake_pts_phs = class_fake_pts_phs\n self._class_optims = class_optims\n self.kVAEs = kVAEs\n self.kCLASS = kCLASSs\n\n logging.error(\"Building Graph Done.\")\n\n\n def _train_internal_vaes(self, opts):\n \"\"\"Train a VAE model.\n\n \"\"\"\n\n batches_num = self._data.num_points / opts['batch_size']\n #if opts['one_batch'] == True:\n # batches_num = 1\n train_size = self._data.num_points\n num_plot = 320\n sample_prev = np.zeros([num_plot] + list(self._data.data_shape))\n l2s = []\n\n decay = 1.\n logging.error('Training VAE')\n for _epoch in xrange(opts[\"gan_epoch_num\"]):\n\n if opts['decay_schedule'] == \"manual\":\n if _epoch == 30:\n decay = decay / 2.\n if _epoch == 50:\n decay = decay / 5.\n if _epoch == 100:\n decay = decay / 10.\n\n if _epoch > 0 and _epoch % opts['save_every_epoch'] == 0:\n os.path.join(opts['work_dir'], opts['ckpt_dir'])\n #self._saver.save(self._session,\n # os.path.join(opts['work_dir'],\n # opts['ckpt_dir'],\n # 'trained-pot'),\n # global_step=counter)\n\n for _idx in xrange(batches_num):\n # logging.error('Step %d of %d' % (_idx, batches_num ) )\n dict_ph = {}\n optimizers = []\n for k in range(opts['number_of_kGANs']):\n if self._hard_assigned[k] != 0: \n data_ids = np.random.choice(train_size, opts['batch_size'],\n replace=False, p=self._data_weights[:,k])\n batch_images = self._data.data[data_ids].astype(np.float)\n batch_noise = utils.generate_noise(opts, opts['batch_size'])\n dict_ph[self._real_points_phs[k]] = batch_images\n dict_ph[self._noise_phs[k]] = batch_noise\n dict_ph[self._lr_decay_phs[k]] = decay\n dict_ph[self._is_training_phs[k]] = True\n optimizers.append(self._optims[k])\n #_, loss, loss_kl, loss_reconstruct = self._session.run(\n # [self._optim, self._loss, self._loss_kl,\n # self._loss_reconstruct],\n # feed_dict={self._real_points_ph: batch_images,\n # self._noise_ph: batch_noise,\n # self._lr_decay_ph: decay,\n # self._is_training_ph: True})\n self._session.run(\n optimizers,\n feed_dict=dict_ph)\n \n \n \n def _train_internal_classifiers(self, opts, fake_images):\n \"\"\"Train a classifier separating true data from points in fake_images.\n \n \"\"\"\n batches_num = self._data.num_points / opts['batch_size_classifier']\n if opts['one_batch'] == True:\n batches_num = 1\n logging.debug('Training a mixture discriminator')\n for epoch in xrange(opts[\"mixture_c_epoch_num\"]):\n for idx in xrange(batches_num):\n dict_ph = {}\n for k in range(0,opts['number_of_kGANs']): \n ids = np.random.choice(len(fake_images[0]), opts['batch_size_classifier'],replace=False)\n batch_fake_images = fake_images[k,ids]\n dict_ph[self._class_fake_pts_phs[k]] = batch_fake_images\n\n ids = np.random.choice(self._data.num_points, opts['batch_size_classifier'],replace=False)\n batch_real_images = self._data.data[ids]\n dict_ph[self._class_real_pts_phs[k]] = batch_real_images\n dict_ph[self.kCLASS[k]._is_training_ph] = True\n _ = self._session.run(\n self._class_optims,\n feed_dict = dict_ph)\n res = np.zeros((len(self._data.data),opts['number_of_kGANs']))\n for k in range(0,opts['number_of_kGANs']):\n res[:,k] = self._run_batch(\n opts, self.kCLASS[k]._c_training,\n self.kCLASS[k]._real_points_ph, self._data.data,self.kCLASS[k]._is_training_ph, False).flatten()\n\n return res\n"
] | [
[
"tensorflow.nn.relu",
"tensorflow.device",
"tensorflow.nn.sigmoid",
"tensorflow.shape",
"numpy.reshape",
"numpy.random.choice",
"tensorflow.reshape",
"tensorflow.nn.tanh",
"numpy.ones",
"tensorflow.global_variables_initializer",
"numpy.copy",
"tensorflow.reset_default_graph",
"numpy.ceil",
"tensorflow.variable_scope",
"tensorflow.Session",
"tensorflow.trainable_variables",
"numpy.vstack",
"tensorflow.nn.dropout"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
ClementLalanne/alphacsc | [
"754cf9bb354d542a7fcebc34efe7d84705c65f55"
] | [
"alphacsc/learn_d_z_trend.py"
] | [
"# Authors: Mainak Jas <[email protected]>\n# Tom Dupre La Tour <[email protected]>\n# Umut Simsekli <[email protected]>\n# Alexandre Gramfort <[email protected]>\n\nfrom __future__ import print_function\nimport time\n\nimport numpy as np\nfrom scipy import linalg\nfrom joblib import Parallel\n\nfrom .init_dict import init_dictionary\nfrom .utils import construct_X_trend, check_random_state\nfrom .utils.dictionary import get_lambda_max\nfrom .update_z import update_z\nfrom .update_d import update_d_block\nfrom .update_trend import update_trend\n\ndef pen_tv(trend):\n return np.sum(np.abs(np.diff(trend, axis=-1)))\n\n\ndef objective(X, X_hat, z_hat, trend, reg_z, reg_trend, pen_trend=pen_tv, sample_weights=None):\n residual = X - X_hat\n if sample_weights is not None:\n residual *= np.sqrt(sample_weights)\n obj = 0.5 * linalg.norm(residual, 'fro') ** 2 + reg_z * z_hat.sum() + reg_trend * pen_trend(trend)\n return obj\n\n\ndef compute_X_and_objective(X, z_hat, d_hat, trend, reg_z, reg_trend, pen_trend=pen_tv, sample_weights=None,\n feasible_evaluation=True):\n X_hat = construct_X_trend(z_hat, d_hat, trend)\n\n if feasible_evaluation:\n z_hat = z_hat.copy()\n d_hat = d_hat.copy()\n # project to unit norm\n d_norm = np.linalg.norm(d_hat, axis=1)\n mask = d_norm >= 1\n d_hat[mask] /= d_norm[mask][:, None]\n # update z in the opposite way\n z_hat[mask] *= d_norm[mask][:, None, None]\n\n return objective(X, X_hat, z_hat, trend, reg_z, reg_trend, pen_trend, sample_weights)\n\n\ndef learn_d_z_trend(X, n_atoms, n_times_atom, func_d=update_d_block, reg_z=0.1, reg_trend=0.1, pen_trend=pen_tv,\n lmbd_max='fixed', n_iter=60, trend_init=None, random_state=None, n_jobs=1,\n solver_z='l-bfgs', solver_d_kwargs=dict(),\n solver_z_kwargs=dict(), ds_init=None, ds_init_params=dict(),\n sample_weights=None, verbose=10, callback=None,\n stopping_pobj=None):\n \"\"\"Univariate Convolutional Sparse Coding.\n\n Parameters\n ----------\n X : array, shape (n_trials, n_times)\n The data on which to perform CSC.\n n_atoms : int\n The number of atoms to learn.\n n_times_atom : int\n The support of the atom.\n func_d : callable\n The function to update the atoms.\n reg_z : float\n The regularization parameter for the sparsity in z\n reg_trend : float\n The regularization parameter for the trend\n pen_trend : callable \n The penalization function for the trend\n lmbd_max : 'fixed' | 'scaled' | 'per_atom' | 'shared'\n If not fixed, adapt the regularization rate as a ratio of lambda_max:\n - 'scaled': the regularization parameter is fixed as a ratio of its\n maximal value at init i.e. reg_used = reg * lmbd_max(uv_init)\n - 'shared': the regularization parameter is set at each iteration as\n a ratio of its maximal value for the current dictionary estimate\n i.e. reg_used = reg * lmbd_max(uv_hat)\n - 'per_atom': the regularization parameter is set per atom and at\n each iteration as a ratio of its maximal value for this atom i.e.\n reg_used[k] = reg * lmbd_max(uv_hat[k])\n n_iter : int\n The number of coordinate-descent iterations.\n trend_init : array, shape (n_trials, n_times)\n The prior on the trend\n random_state : int | None\n The random state.\n n_jobs : int\n The number of parallel jobs.\n solver_z : str\n The solver to use for the z update. Options are\n 'l-bfgs' (default) | 'ista' | 'fista'\n solver_d_kwargs : dict\n Additional keyword arguments to provide to update_d\n solver_z_kwargs : dict\n Additional keyword arguments to pass to update_z\n ds_init : str or array, shape (n_atoms, n_times_atom)\n The initial atoms or an initialization scheme in {'kmeans' | 'ssa' |\n 'chunk' | 'random'}.\n ds_init_params : dict\n Dictionnary of parameters for the kmeans init method.\n sample_weights : array, shape (n_trials, n_times)\n The weights in the alphaCSC problem. Should be None\n when using vanilla CSC.\n verbose : int\n The verbosity level.\n callback : func\n A callback function called at the end of each loop of the\n coordinate descent.\n\n Returns\n -------\n pobj : list\n The objective function value at each step of the coordinate descent.\n times : list\n The cumulative time for each iteration of the coordinate descent.\n d_hat : array, shape (n_atoms, n_times)\n The estimated atoms.\n z_hat : array, shape (n_atoms, n_trials, n_times - n_times_atom + 1)\n The sparse activation matrix.\n reg : float\n Regularization parameter used.\n \"\"\"\n n_trials, n_times = X.shape\n\n rng = check_random_state(random_state)\n\n # trend init \n if (trend_init==None).all():\n trend = np.zeros((n_trials, n_times))\n else:\n assert trend_init.shape == X.shape\n trend = trend_init\n\n # reuse multivariate atoms init function\n if isinstance(ds_init, np.ndarray):\n ds_init = ds_init[:, None, :]\n d_hat = init_dictionary((X-trend)[:, None, :], n_atoms, n_times_atom,\n D_init=ds_init, rank1=False,\n D_init_params=ds_init_params, random_state=rng)\n d_hat = d_hat[:, 0, :]\n\n # strategy for rescaling the regularization parameter\n reg_z0 = reg_z\n lambda_max = get_lambda_max(X, d_hat, sample_weights).max()\n if lmbd_max == \"scaled\":\n reg = reg_z0 * lambda_max\n\n pobj = list()\n times = list()\n\n if 'ista' in solver_z:\n b_hat_0 = rng.randn(n_atoms * (n_times - n_times_atom + 1))\n else:\n b_hat_0 = None\n\n lambd0 = None\n z_hat = np.zeros((n_atoms, n_trials, n_times - n_times_atom + 1))\n\n pobj.append(compute_X_and_objective(X, z_hat, d_hat, trend, reg_z, reg_trend, pen_trend, sample_weights))\n times.append(0.)\n with Parallel(n_jobs=n_jobs) as parallel:\n for ii in range(n_iter): # outer loop of coordinate descent\n if verbose == 1:\n msg = '.' if (ii % 50 != 0) else 'V_%d/%d ' % (ii, n_iter)\n print(msg, end='', flush=True)\n if verbose > 1:\n print('Coordinate descent loop %d / %d [n_jobs=%d]' %\n (ii, n_iter, n_jobs))\n\n if lmbd_max not in ['fixed', 'scaled']:\n lambda_max = get_lambda_max(X, d_hat, sample_weights)\n reg = reg_z0 * lambda_max\n if lmbd_max == 'shared':\n reg = reg.max()\n\n start = time.time()\n z_hat = update_z(X-trend, d_hat, reg_z, z0=z_hat, parallel=parallel,\n solver=solver_z, b_hat_0=b_hat_0,\n solver_kwargs=solver_z_kwargs,\n sample_weights=sample_weights)\n times.append(time.time() - start)\n\n # monitor cost function\n pobj.append(\n compute_X_and_objective(X, z_hat, d_hat, trend, reg_z, reg_trend, pen_trend, sample_weights))\n if verbose > 1:\n print('[seed %s] Objective (z_hat) : %0.8f' % (random_state,\n pobj[-1]))\n\n if len(z_hat.nonzero()[0]) == 0:\n import warnings\n warnings.warn(\"Regularization parameter `reg` is too large \"\n \"and all the activations are zero. No atoms has\"\n \" been learned.\", UserWarning)\n break\n\n start = time.time()\n d_hat, lambd0 = func_d(X-trend, z_hat, n_times_atom, lambd0=lambd0,\n ds_init=d_hat, verbose=verbose,\n solver_kwargs=solver_d_kwargs,\n sample_weights=sample_weights)\n times.append(time.time() - start)\n\n\n trend = update_trend(X, z_hat, d_hat, reg_trend)\n\n # monitor cost function\n pobj.append(\n compute_X_and_objective(X, z_hat, d_hat, trend, reg_z, reg_trend, pen_trend, sample_weights))\n if verbose > 1:\n print('[seed %s] Objective (d) %0.8f' % (random_state,\n pobj[-1]))\n\n if callable(callback):\n callback(X, d_hat, z_hat, trend, reg_z, reg_trend, pen_trend)\n\n if stopping_pobj is not None and pobj[-1] < stopping_pobj:\n break\n\n if verbose == 1:\n print('')\n\n return pobj, times, d_hat, z_hat, trend, reg_z, reg_trend\n"
] | [
[
"numpy.sqrt",
"numpy.linalg.norm",
"numpy.diff",
"scipy.linalg.norm",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"0.14",
"0.15",
"0.12",
"0.10"
],
"tensorflow": []
}
] |
jwitch/CallingCard | [
"2dc6dc7ce42a4f82f053a28fbb40f879e7893d26"
] | [
"CallingCards_current.py"
] | [
"#!/usr/bin/python\n\n##########################################################\n#Project: Calling_Cards\n#Date:2018/01/01\n#Author: Zontai Qi with modifications by JNW, modified for python 3\n##########################################################\n\n'''\nInput: working directory, csv with exp+ref pairs\nWrapper for Calling card seq pipeline\nOutput: text file of insertion cluster with info associated with the cluster including # inserts and stats compared to reference\n*cutoff is used for filter out the independent insertions based on their own count which is the 3rd column of the input dataset\n*pwd is the directory that has Reference.txt and Experimental.txt. example: A21_gnashy_files/Input/\n'''\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport os\nimport subprocess\nimport sys\nfrom scipy.stats import poisson\nfrom scipy.stats import hypergeom\nfrom tabulate import tabulate\npd.options.mode.chained_assignment = None\nfrom pybedtools import BedTool\nimport operator\nimport csv\nfrom genes import RefGenome\nfrom genes import RefGene\nfrom copy import deepcopy\n\ndef CallingCards(pwd,exprefpairs,cutoff,subclustdist,alpha,fake):\n ##creates pandas dataframe for exp+ref pairs\n ##loops through pairs to collect calling card hits\n ##pwd needs to end in /\n ##exprefpairsdf=pd.read_csv(exprefpairs)\n for row in range(0,len(exprefpairs)):\n #print exprefpairs.iloc[row]\n exp=exprefpairs.iloc[row][0]\n ref=exprefpairs.iloc[row][1]\n out=exp+'_'+ref+'_Output/'\n if not os.path.exists(pwd+out):\n os.mkdir(pwd+out) \n Precutchr(pwd,out,exp,ref,cutoff)\n QTcluster(pwd,out,exp,subclustdist)\n Combine(pwd,out,exp,ref)\n Simpletest(pwd,out,exp,ref,alpha,fake)\n Annotated(pwd,out)\n\ndef Precutchr(pwd,out,exp,ref,cutoff):\n print(\"Precutchr start!\")\n\n for librarygnashy in [str(exp),str(ref)]:\n #print librarygnashy\n precutpath=pwd+out+'PrecutOut/'+librarygnashy\n #print precutpath\n if not os.path.exists(precutpath):\n os.makedirs(precutpath)\n gnashy_infile=pwd+'Input/'+librarygnashy+'.txt'\n #print gnashy_infile\n with open(gnashy_infile,'r') as infile:\n inf=infile.readlines()\n chr={\n 1:[],2:[],3:[],4:[],5:[],6:[],7:[],8:[],9:[]\n }\n for i in inf:\n #print i\n a=i.split('\\t',2)\n #print a\n a[0]=int(a[0]) #chromosome\n a[1]=int(a[1]) #coordinate\n a[2]=int(a[2].replace('\\n','')) #num of reads\n if a[2]>cutoff: #remove aberrant reads\n chr[a[0]].append([a[1],a[2]])\n for i in chr.keys():\n if len(chr[i])>0:\n chr[i]=np.array(chr[i])\n uniq=np.unique(chr[i][:,0])\n new=np.zeros((len(uniq),4),dtype='int32')\n new[:,1]=uniq\n new[:,0]=i\n for n in range(len(uniq)):\n freq=chr[i][chr[i][:,0]==uniq[n]]\n freq=freq[:,0]\n new[n,3]=len(freq)\n if len(freq)==1:\n new[n,2]=1\n else:\n new[n,2]=len(freq)+5**len(freq)\t#add bonus for multiple independent tns\t\n outf=precutpath+'/chr'+str(i)+'.txt'\n with open(outf,'wb') as of:\n of.write(b'Chromosome\\tPosition\\tIndependent_Insertions_withBonus\\tIndependent_Insertions\\n')\n np.savetxt(of, new,fmt=\"%d\")\n\n reffilenames = ['chr1.txt', 'chr2.txt', 'chr3.txt', 'chr4.txt', 'chr5.txt', 'chr6.txt', 'chr7.txt', 'chr8.txt', 'chr9.txt']\n with open(pwd+out+'PrecutOut/'+ref+'/combine.txt', 'w+') as outfile:\n ##if chr1.txt file exists...\n if os.path.isfile(pwd+out+'PrecutOut/'+ref+'/chr1.txt'):\n with open(pwd+out+'PrecutOut/'+ref+'/chr1.txt', 'r') as infile:\n #print infile.readline().strip()\n outfile.write(infile.readline().strip())\n for fname in reffilenames:\n if os.path.exists(pwd+out+'PrecutOut/'+ref+'/'+fname):\n with open(pwd+out+'PrecutOut/'+ref+'/'+fname, 'r') as infile:\n for line in infile.readlines()[1:]:\n #print line\n outfile.write(line)\n ##if chr2.txt file exists...\n elif os.path.isfile(pwd+out+'PrecutOut/'+ref+'/chr2.txt'):\n with open(pwd+out+'PrecutOut/'+ref+'/chr2.txt', 'r') as infile:\n #print infile.readline().strip()\n outfile.write(infile.readline().strip())\n for fname in reffilenames:\n if os.path.exists(pwd+out+'PrecutOut/'+ref+'/'+fname):\n with open(pwd+out+'PrecutOut/'+ref+'/'+fname, 'r') as infile:\n for line in infile.readlines()[1:]:\n #print line\n outfile.write(line)\n ##if chr3.txt file exists...\n elif os.path.isfile(pwd+out+'PrecutOut/'+ref+'/chr3.txt'):\n with open(pwd+out+'PrecutOut/'+ref+'/chr3.txt', 'r') as infile:\n #print infile.readline().strip()\n outfile.write(infile.readline().strip())\n for fname in reffilenames:\n if os.path.exists(pwd+out+'PrecutOut/'+ref+'/'+fname):\n with open(pwd+out+'PrecutOut/'+ref+'/'+fname, 'r') as infile:\n for line in infile.readlines()[1:]:\n #print line\n outfile.write(line)\n ##if chr4.txt file exists...\n elif os.path.isfile(pwd+out+'PrecutOut/'+ref+'/chr4.txt'):\n with open(pwd+out+'PrecutOut/'+ref+'/chr4.txt', 'r') as infile:\n #print infile.readline().strip()\n outfile.write(infile.readline().strip())\n for fname in reffilenames:\n if os.path.exists(pwd+out+'PrecutOut/'+ref+'/'+fname):\n with open(pwd+out+'PrecutOut/'+ref+'/'+fname, 'r') as infile:\n for line in infile.readlines()[1:]:\n #print line\n outfile.write(line)\n ##if chr5.txt file exists...\n elif os.path.isfile(pwd+out+'PrecutOut/'+ref+'/chr5.txt'):\n with open(pwd+out+'PrecutOut/'+ref+'/chr5.txt', 'r') as infile:\n #print infile.readline().strip()\n outfile.write(infile.readline().strip())\n for fname in reffilenames:\n if os.path.exists(pwd+out+'PrecutOut/'+ref+'/'+fname):\n with open(pwd+out+'PrecutOut/'+ref+'/'+fname, 'r') as infile:\n for line in infile.readlines()[1:]:\n #print line\n outfile.write(line)\n ##if chr6.txt file exists...\n elif os.path.isfile(pwd+out+'PrecutOut/'+ref+'/chr6.txt'):\n with open(pwd+out+'PrecutOut/'+ref+'/chr6.txt', 'r') as infile:\n #print infile.readline().strip()\n outfile.write(infile.readline().strip())\n for fname in reffilenames:\n if os.path.exists(pwd+out+'PrecutOut/'+ref+'/'+fname):\n with open(pwd+out+'PrecutOut/'+ref+'/'+fname, 'r') as infile:\n for line in infile.readlines()[1:]:\n #print line\n outfile.write(line)\n ##if chr7.txt file exists...\n elif os.path.isfile(pwd+out+'PrecutOut/'+ref+'/chr7.txt'):\n with open(pwd+out+'PrecutOut/'+ref+'/chr7.txt', 'r') as infile:\n #print infile.readline().strip()\n outfile.write(infile.readline().strip())\n for fname in reffilenames:\n if os.path.exists(pwd+out+'PrecutOut/'+ref+'/'+fname):\n with open(pwd+out+'PrecutOut/'+ref+'/'+fname, 'r') as infile:\n for line in infile.readlines()[1:]:\n #print line\n outfile.write(line)\n ##if chr8.txt file exists...\n elif os.path.isfile(pwd+out+'PrecutOut/'+ref+'/chr8.txt'):\n with open(pwd+out+'PrecutOut/'+ref+'/chr8.txt', 'r') as infile:\n #print infile.readline().strip()\n outfile.write(infile.readline().strip())\n for fname in reffilenames:\n if os.path.exists(pwd+out+'PrecutOut/'+ref+'/'+fname):\n with open(pwd+out+'PrecutOut/'+ref+'/'+fname, 'r') as infile:\n for line in infile.readlines()[1:]:\n #print line\n outfile.write(line)\n \n'''Define Function _SUBCLUST_:\n\tINPUT: \n index:\n\t\tpos:\n\t\td: universal variate, the max diameter\n\tOUTPUT: subclusters of input points and within distance le 2.5 kb\n'''\ndef _SUBCLUST_ (index,pos,subclustdist):\n\taa=0\n\tpos=sorted(pos)\n\twhile aa==0:\n\t\tleft_index=min(index)\n\t\tright_index=max(index)\n\t\tsub=[pos[x] for x in index] \n\t\tif left_index==0 and right_index<len(pos)-1 and pos[right_index+1]-pos[left_index]<=subclustdist:\n\t\t\tsub.append(pos[right_index+1])\t\n\t\t\tindex.append(right_index+1)\n\t\telif right_index==len(pos)-1 and left_index>0 and pos[right_index]-pos[left_index-1]<=subclustdist:\n\t\t\tindex.append(left_index-1)\n\t\t\tsub.append(pos[left_index-1])\n\t\telif left_index>0 and right_index<len(pos)-1:\n\t\t\tleft=pos[left_index-1] \n\t\t\tright=pos[right_index+1]\n\t\t\tcenter=(pos[right_index]+pos[left_index])/2\n\t\t\tif center-left>right-center and right-pos[left_index]<=subclustdist:\n sub.append(right)\n index.append(right_index+1)\n\t\t\telif center-left<right-center and pos[right_index]-left<=subclustdist:\n sub.append(left)\n index.append(left_index-1)\n\t\t\telif center-left==right-center and right-left<=subclustdist:\n sub.append(right)\n sub.append(left)\n index.append(left_index-1)\n index.append(right_index+1)\n\t\t\telse: aa=1\n\t\telse: aa=2\n\treturn sub\n\n'''Define Function _MAX_:\n\tINPUT: position list\n\tOUTPUT: one subcluster with maximun within distance\n''' \n\ndef _MAX_ (pos,subclustdist):\n\tMAX=0\n\tMAX_sub=[]\n\tfor p in range(len(pos)):\n\t\tindex=[p]\n\t\tsubp=_SUBCLUST_(index,pos,subclustdist)\n\t\tif max(subp)-min(subp)>=MAX:\n MAX=max(subp)-min(subp)\n MAX_sub=subp\n\treturn MAX_sub\n\n'''Define Function _QTCLUST_\n\tINPUT: pos:position set\n\tOUTPUT: subclustered data with format 'position number_of_cluster'\n\t\tps. 99999 refers to singleton \n'''\ndef _QTCLUST_(pos,subclustdist):\n subnum=0\n pp=0\n qtclustered=[]\n while pp==0:\n pos=sorted(pos)\n length=len(pos)\n if length==0: \n pp=1\n if length==1:\n pp=2\n qtclustered.append([pos[0],99999])\n elif length>1:\n sub=_MAX_(pos,subclustdist)\n if len(sub)==1:\n qtclustered.append([sub[0],99999])\n else:\n subnum=subnum+1 \n for b in sub:\n qtclustered.append([b,subnum])\n pos=list(set(pos)-set(sub))\n pos=sorted(pos)\n return qtclustered\n\n'''Read one Chr once and process\n\tInput: Chr sorted by pos with format 'chr position count'\nOutput: save QTclustered dataframe data for each chr with format'Chr,Position,Window,Count'\n'''\n\ndef QTcluster(pwd,out,exp,subclustdist):\n print(\"QTcluster.py start!\")\n print(\"The maximum distance for a subcluster is: \", subclustdist)\n\n if not os.path.exists(pwd+out+'PrecutOut/'+exp):\n print(\"Wrong Directory, please put the one that contains the experiment data\")\n sys.exit(\"Ending Script\")\t \n\n if not os.path.exists(pwd+out+'QTout'):\n os.makedirs(pwd+out+'QTout')\n for i in range(1,9):\n inf=str(pwd)+str(out)+'PrecutOut/'+str(exp)+'/chr'+str(i)+'.txt'\n if os.path.isfile(inf):\n chr=np.loadtxt(inf,skiprows=1,dtype=int)\n #sfprint 'chr'+str(i)\n if len(chr.shape)==2:\n positions=chr[:,1]\n qtc=np.array(_QTCLUST_(positions,subclustdist))\n df=pd.DataFrame(qtc,index=qtc[:,0],columns=['Position','Cluster'])\n s1=pd.Series(chr[:,2],index=chr[:,1])\n s2=pd.Series(chr[:,3],index=chr[:,1])\n df['Independent_Insertion_withBonus']=s1\n df['Independent_Insertion']=s2\n df['Chromosome']=i\n df=df.sort_values(by='Position',axis=0)\t\n else:\n df=pd.DataFrame(columns=[\"Position\",\"Cluster\",\"Independent_Insertion_withBonus\",\"Independent_Insertion\",\"Chromosome\"])\n df['Chromosome']=[chr[0]]\n df[\"Position\"]=[chr[1]]\n df[\"Cluster\"]=['99999']\n df[\"Independent_Insertion_withBonus\"]=[chr[2]]\n df[\"Independent_Insertion\"]=[chr[3]]\n outf=pwd+out+'QTout/chr'+str(i)+'clustered.csv'\n df.to_csv(outf, index=False,header=\"Position,Cluster,Independent_Insertion_withBonus,Independent_Insertion,Chromosome\") \n\n print(\"QTcluster completed!\")\n\ndef Combine(pwd,out,exp,ref):\n print(\"Combine.py started\")\n outpath=pwd+out\n if not os.path.exists(outpath):\n print(\"Wrong Directory, please put the one ended with Output/\")\n sys.exit(\"Ending Script\")\n outf=outpath+'QTout/'+ref+'_Combine.csv'\n #print outf\n counter=0\n for chromosome in range(1,9): ##changed for C albicans\n expf=outpath+'QTout/chr'+str(chromosome)+'clustered.csv'\n #print expf\n bkgf=outpath+'PrecutOut/'+ref+'/chr'+str(chromosome)+'.txt'\n #print bkgf\n if os.path.isfile(expf):\n #print \"True\"\n counter=counter+1\n exp=pd.read_csv(expf)\n clust=np.array(exp['Cluster']).tolist()\n bkg=np.loadtxt(bkgf,skiprows=1,dtype=int)\n comb=_COMBINE_(exp,bkg,chromosome)\n if len(np.unique(clust))==1:\n comb=_TRANS1_(comb,chromosome)\n if len(np.unique(clust))>1:\n clust=np.unique(clust)[-2]\n comb=_FILL_(comb,clust)\n comb=_TRANS_(comb,clust,chromosome)\n comb=comb.astype('int64')\n if counter==1:\n comb.to_csv(outf,header=True,index=False)\n else:\n comb.to_csv(outf,header=False,index=False,mode='a')\n counter=counter+1\n print('Combine.py Completed!')\n\n\n\ndef _COMBINE_ (exp,bkg,chromosome):\n exppos=exp['Position'].tolist()\n window=exp['Cluster'].tolist()\n window=pd.Series(window,index=exppos)\n expcount=exp['Independent_Insertion_withBonus'].tolist()\n expcount2=exp['Independent_Insertion'].tolist()\n expcount=pd.Series(expcount,index=exppos)\n expcount2=pd.Series(expcount2,index=exppos)\n bkgcount=pd.Series(list(bkg[:,2]),index=bkg[:,1])\n bkgcount2=pd.Series(list(bkg[:,3]),index=bkg[:,1])\n pos=np.append(np.array(exppos),bkg[:,1])\n pos=np.unique(pos)\n pos=pd.Series(list(pos),index=list(pos))\n new=pd.DataFrame({'Position':pos,'Cluster':window,'ExpHop_withBonus':expcount,'BkgHop_withBonus':bkgcount,'ExpHop':expcount2,'BkgHop':bkgcount2})\n new.index=range(len(new))\n return new\n\ndef _FILL_ (comb,clust):\n for p in range(1,clust+1):\n ind=comb[comb['Cluster']==p].index\n if len(ind)>2 and (ind[-1]-ind[0]-len(ind)) != -1:\n for a in range(ind[0],ind[-1]+1):\n comb.loc[a,'Cluster']=p\n comb=comb.fillna(0)\n return \tcomb\n\ndef _TRANS_ (comb,clust,chromosome):\n data=comb[comb['Cluster']==99999]\n data.insert(0,'Chromosome',chromosome)\n s=data['Cluster']\n del data['Cluster']\n data.insert(1,'Cluster',s)\n data.insert(2,'Start',data['Position'])\n data.insert(3,'Stop',data['Position'])\n del data['Position'] \n if not data.empty:\n idx=data.index[-1]\n data=data.astype('int64')\n for grp in range(1,clust+1):\n block=comb[comb['Cluster']==grp]\n N=np.array(block['Position'])\n data.loc[idx+grp,'Chromosome']=chromosome\n data.loc[idx+grp,'Start']=np.amin(N)\n data.loc[idx+grp,'Stop']=np.amax(N)\n data.loc[idx+grp,'BkgHop']=sum(block['BkgHop'])\n data.loc[idx+grp,'ExpHop']=sum(block['ExpHop'])\n data.loc[idx+grp,'BkgHop_withBonus']=sum(block['BkgHop_withBonus'])\n data.loc[idx+grp,'ExpHop_withBonus']=sum(block['ExpHop_withBonus'])\n data.loc[idx+grp,'Cluster']=grp\n data.index=range(len(data))\n return data\n\ndef _TRANS1_(comb,chromosome):\n comb=comb.fillna(0)\n data=comb[comb['Cluster']==99999]\n data.insert(0,'Chromosome',chromosome)\n s=data['Cluster']\n del data['Cluster']\n data.insert(1,'Cluster',s)\n data.insert(2,'Start',data['Position'])\n data.insert(3,'Stop',data['Position'])\n del data['Position']\n if not data.empty:\n idx=data.index[-1]\n data=data.astype('int64')\n return data\n\n\ndef Simpletest(pwd,out,exp,ref,alpha,fake):\n print(\"Simpletest started!\")\n \n if not os.path.exists(pwd+out+'QTout'):\n print(\"Wrong Directory, please put the one contains a folder QTout which has a file named Combine.csv.\")\n sys.exit(\"Ending Script\")\n if not os.path.exists(pwd+out+'Annotation'):\n os.makedirs(pwd+out+'Annotation')\n summary=[]\n outfile_name=pwd+out+'Annotation/Total_Insertions_P_value.txt'\n infile_name=pwd+out+'QTout/'+ref+'_Combine.csv'\n #print \"infile_name\"\n bkgtotal=pwd+out+'PrecutOut/'+ref+'/combine.txt'\n bkgtotal=np.loadtxt(bkgtotal,dtype=int,skiprows=1)\n #print bkgtotal\n bkgtotal=sum(bkgtotal[:,3])\n ALL=pd.read_csv(infile_name)\n exptotal=sum(ALL['ExpHop'])\n counter=0\n\n for c in range(1,9):\n #print c\n block=ALL[ALL['Chromosome']==c]\n if len(block)>0:\n counter=counter+1\n #print counter\n out=_TEST_(block,exptotal,bkgtotal,alpha,float(fake))\t\n block=out[0]\n x='chr'+str(c)\n block['Chromosome']=x\n singleton=block[block['Cluster']==99999]\n singleton=len(singleton[singleton['ExpHop']==1])\n summary.append([x,(len(block)-singleton),singleton,out[1],out[2]])\n del block['Cluster']\n if counter==1:\n block.to_csv(outfile_name,sep='\\t',header=True,index=False)\n else:\n #print outfile_name\n block.to_csv(outfile_name,sep='\\t',header=False,index=False,mode='a')\n total=['Total',0,0,0,0]\n for item in summary:\n total[1]=total[1]+item[1]\n total[2]=total[2]+item[2]\n total[3]=total[3]+item[3]\n total[4]=total[4]+item[4]\n\n summary.append(total)\n print(\"Simpletest Result Summary:\")\n print(\"Reference total Hops:\", bkgtotal)\n print(\"Experiment Total Hops:\", exptotal)\n print(tabulate(summary,headers=['Chr','Cluster','Singleton','Sigificant_By_Poisson_CDF','Significant_By_Hypergeometric_CDF'],tablefmt='orgtbl'))\n print(\"Simpletest.py Completed!\")\n\n\n'''\n Function _TEST_: Test the Null Hypothesis that the SP1 == WT.\n\t#1.Poisson distribution.\n\t# Test statistics: Pr(X>=SP1hop|WT)\n\t#2.Hypergeometirc districution\n # scistat.hypergeom.cdf(x,M,n,N)\n # where x is observed number of type I events (white balls in draw) (experiment hops at locus)\n # M is total number of balls (total number of hops,wt+exp total)\n # n is total number of white balls (total number of experimental hops)\n # N is the number of balls drawn (total hops at a locus)\n\n'''\ndef _TEST_ (block,exptotal,bkgtotal,alpha,pseudo_count):\n sigPoi=0\n sigHyp=0\n ind=block.index\n for i in block.index:\n lamda=block.loc[i,'BkgHop_withBonus']\n obs=block.loc[i,'ExpHop_withBonus']\n BkgHop=block.loc[i,'BkgHop']\n ExpHop=block.loc[i,'ExpHop']\n P_poisson=1-poisson.cdf(int(obs)-1,lamda+pseudo_count)\n if int(BkgHop) < 100000000 and int(ExpHop) < 100000000:\n P_hyper=1-hypergeom.cdf(ExpHop-1,(bkgtotal+exptotal),exptotal, (ExpHop+BkgHop))\n else:\n P_hyper='***'\n block.loc[i,'BkgFraction']=float(BkgHop/bkgtotal)\n block.loc[i,'ExpFraction']=float(ExpHop/exptotal)\n block.loc[i,'P_Hyper']= P_hyper\n block.loc[i,'P_Poisson']=P_poisson\n if P_poisson < alpha and lamda*obs != 0:\n sigPoi=sigPoi+1\n if P_hyper < alpha:\n sigHyp=sigHyp+1\n return block, sigPoi, sigHyp\n\ndef Annotated(pwd,out):\n print(\"Annotated.py Starts!\")\n outfolder=pwd+out\n if not os.path.exists(outfolder+'Annotation'):\n os.makedirs(outfolder+'Annotation')\n Ref=pwd+'genome/C_albicans_genes.bed'\n ##Create file with following headers [Chromosome Start End BkgHop BkgHop_withBonus ExpHop ExpHop_withBonus BkgFraction ExpFraction P_Hyper P_Poisson CUTStart CUTEnd Closest_Upstream_Gene Closest_Upstream_Gene_Common_Name CUTstrand\tCDTStart CDTEnd\tClosest_Downstream_Gene\tClosest_Downstream_Gene_Common_Name CDTstrand]\n with open(outfolder+\"Annotation/Total_Insertions_P_value.txt\",'r') as testfile:\n test_list=testfile.readlines()\n ##print test_list\n ##List of lists that will be output to Total_Insertions_Full_Annotation.txt\n formatted_list=[]\n for i in range(1,len(test_list)):\n line=test_list[i]\n line=line.split('\\t')\n line[10]=line[10].replace('\\r','') ##double check last element\n line[10]=line[10].replace('\\n','')\n line[1]=int(line[1]) ##in case sort doesn't like a string of numbers\n formatted_list.append(line)\n\n sorted_list=formatted_list\n #print(sorted_list)\n sorted_list.sort(key=lambda row: (row[0],row[1]))\n ##print sorted_list\n with open(outfolder+'/Annotation/Total_Insertions.sorted.bed','w') as inserts:\n for line in sorted_list: \n inserts.writelines(line[0]+'\\t'+str(line[1])+'\\t'+line[2]+'\\n')\n\n with open(outfolder+'/Annotation/Total_Insertions.sorted.txt','w') as inserts:\n for line in sorted_list:\n inserts.writelines(line[0]+'\\t'+str(line[1])+'\\t'+line[2]+'\\t'+line[3]+'\\t'+line[4]+'\\t'+line[5]+'\\t'+line[6]+'\\t'+line[7]+'\\t'+line[8]+'\\t'+line[9]+'\\t'+line[10]+'\\n')\n\n subprocess.call(\"closest-features --dist \"+outfolder+\"/Annotation/Total_Insertions.sorted.bed \" +Ref+\" > \"+outfolder+\"/Annotation/Total_Insertions.sorted.annotated.txt\" ,shell=True)\n\n f = open(outfolder+\"/Annotation/Total_Insertions.sorted.annotated.txt\",'r')\n filedata = f.read()\n f.close()\n\n newdata = filedata.replace(\"\\n|\",\"\\t\")\n newdata = newdata.replace(\"|\",\"\\t\")\n\n f = open(outfolder+\"/Annotation/Total_Insertions.sorted.annotated.replace.txt\",'w')\n f.write(newdata)\n f.close()\n \n subprocess.call(\"sed -e 's:NA:NA\\tNA\\tNA\\tNA\\tNA\\tNA\\t:g' -e 's/|/\\t/g' \"+outfolder+\"/Annotation/Total_Insertions.sorted.annotated.replace.txt > \"+outfolder+\"/Annotation/Total_Insertions.sorted.annotated2.txt\", shell=True)\n subprocess.call(\"cat \"+outfolder+\"/Annotation/Total_Insertions.sorted.annotated2.txt |awk '{print $5,$6,$7,$8,$9,$10,$12,$13,$14,$15,$16,$17}' OFS='\\t' > \"+outfolder+\"/Annotation/Total_Insertions.sorted.annotated3.txt\",shell=True)\n subprocess.call(\"paste \"+outfolder+\"/Annotation/Total_Insertions.Sorted.txt \"+outfolder+\"/Annotation/Total_Insertions.sorted.annotated3.txt > \"+outfolder+\"/Annotation/Total_Insertions_P_value_Full_Annotation.txt\",shell=True )\n# subprocess.call(\"sed -i '1iChromosome\tStart\tEnd\tBkgHop\tBkgHop_withBonus\tExpHop\tExpHop_withBonus\tBkgFraction\tExpFraction\tP_Hyper\tP_Poisson\tCUTStart\tCUTEnd\tClosest_Upstream_Gene\tClosest_Upstream_Gene_Common_Name\tCUTstrand\tCDTStart\tCDTEnd\tClosest_Downstream_Gene\tClosest_Downstream_Gene_Common_Name\tCDTstrand' \"+outfolder+\"/Annotation/Total_Insertions_P_value_Full_Annotation.txt\",shell=True )\n # subprocess.call(\"rm \"+outfolder+\"/Annotation/Total_Insertions.sorted.annotated*.txt \"+outfolder+\"/Annotation/Total_Insertions.sorted.bed\", shell=True)\n\n## genome=RefGenome(Ref).get_genome()\n\n## intergenics=[] ##create list of intergenic regions\n## for idx in range(0,len(genome)-1):\n## #print(idx)\n## intergenics.append(genome[idx][:]+genome[idx+1][:])\n## \n## cluster_assignment=deepcopy(sorted_list)\n## for insert in cluster_assignment:\n## for line in intergenics: #now takes into account ends of chromosomes\n## if insert[0] == line[0] and line[0] == line[6]: #make sure data on same chromosome\n## insertStart=int(insert[1])\n## insertEnd=int(insert[2])\n## intergenic5start=int(line[1])\n## intergenic5end=int(line[2])\n## intergenic3start=int(line[7])\n## intergenic3end=int(line[8])\n## if (insertStart > intergenic5start and insertEnd < intergenic3end): #make sure data is bounded\n## insert.extend(line[1:6])\n## insert.append(insertStart-intergenic5end)\n## insert.extend(line[7:12])\n## insert.append(intergenic3start-insertStart)\n## ##can result in two different intergenic regions concatenated if insert is in the middle of a gene\n##\n## #print(insert)\n## cluster_assignment_cut=[]\n## for i in range(0,len(cluster_assignment)):\n## insert=cluster_assignment[i]\n## #print(insert)\n## if len(insert) > 23 and len(insert) < 36:\n## #print(insert)\n## if abs(int(insert[16])) < abs(int(insert[34])):\n## firstinsert=insert[0:23]\n## cluster_assignment_cut.append(firstinsert)\n## elif abs(int(insert[16])) > abs(int(insert[34])):\n## #print(insert)\n## secondinsert=insert[0:11]\n## secondinsert.extend(insert[23:])\n## #print(secondinsert)\n## cluster_assignment_cut.append(secondinsert)\n## #elif len(insert) > 29 and len(insert) < 40:\n## #print(insert)\n## else:\n## cluster_assignment_cut.append(insert)\n\n## filenohead=pd.read_csv(outfolder+\"/Annotation/Total_Insertions_P_value_Full_Annotation.txt\",sep=\"\\t\",header=None)\n## filehead=filenohead.to_csv(outfolder+\"/Annotation/Total_Insertions_P_value_Full_Annotation.txt\",sep=\"\\t\",header=['Chromosome', 'Start', 'End', 'BkgHop', 'BkgHop_withBonus', 'ExpHop', 'ExpHop_withBonus','BkgFraction',\n## 'ExpFraction', 'P_Hyper', 'P_Poisson','CUTStart', 'CUTEnd',\n## 'Closest_Upstream_Gene', 'Closest_Upstream_Gene_Common_Name', 'CUTstrand','CUTdistance',\n## 'CDTStart', 'CDTEnd','Closest_Downstream_Gene','Closest_Downstream_Gene_Common_Name', 'CDTstrand','CDTdistance'])\n## with open(outfolder+'Annotation/Total_Inserts_Full_Annotation.txt','w') as outfile:\n## annotation=csv.writer(outfile, delimiter=',')\n## annotation.writerow(['Chromosome', 'Start', 'End', 'BkgHop', 'BkgHop_withBonus', 'ExpHop', 'ExpHop_withBonus','BkgFraction',\n## 'ExpFraction', 'P_Hyper', 'P_Poisson','CUTStart', 'CUTEnd',\n## 'Closest_Upstream_Gene', 'Closest_Upstream_Gene_Common_Name', 'CUTstrand','CUTdistance',\n## 'CDTStart', 'CDTEnd','Closest_Downstream_Gene','Closest_Downstream_Gene_Common_Name', 'CDTstrand','CDTdistance'])\n#### for line in cluster_assignment_cut:\n## annotation.writerow(line)\n \n print(\"Annotated.py Completed!\")\n"
] | [
[
"numpy.amax",
"pandas.read_csv",
"pandas.Series",
"numpy.unique",
"numpy.amin",
"pandas.DataFrame",
"scipy.stats.hypergeom.cdf",
"numpy.savetxt",
"numpy.array",
"numpy.loadtxt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
gitter-badger/HEPAutoencoders | [
"43010cd66fa4335a04b30b87926148e1c8d92de9"
] | [
"HEPAutoencoders/utils.py"
] | [
"import os.path\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport time\nimport pickle\n\nimport torch\nimport torch.nn as nn\n# import torch.optim as optim\nimport torch.utils.data\n\nfrom torch.utils.data import TensorDataset\n\nimport my_matplotlib_style as ms\n\nfrom fastai import basic_data, basic_train\nfrom fastai import train as tr\n\nfrom HEPAutoencoders.nn_utils import get_data\n\n\n# Functions for evaluation\ndef count_parameters(model):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\n\ndef time_encode_decode(model, dataframe, verbose=False):\n \"\"\"Time the model's endoce and decode functions.\n\n Parameters\n ----------\n model : torch.nn.Module\n The model to evaluate.\n dataframe : type\n A pandas DataFrame containing data to encode and decode.\n\n Returns\n -------\n tuple\n Tuple containing (encode_time_per_jet, decode_time_per_jet).\n\n \"\"\"\n data = torch.tensor(dataframe.values, dtype=torch.float)\n start_encode = time.time()\n latent = model.encode(data)\n end_encode = time.time()\n encode_time = end_encode - start_encode\n\n start_decode = time.time()\n _ = model.decode(latent)\n end_decode = time.time()\n decode_time = end_decode - start_decode\n\n n_jets = len(dataframe)\n decode_time_per_jet = decode_time / n_jets\n encode_time_per_jet = encode_time / n_jets\n\n if verbose:\n print('Encode time/jet: %e seconds' % encode_time_per_jet)\n print('Decode time/jet: %e seconds' % decode_time_per_jet)\n\n return encode_time_per_jet, decode_time_per_jet\n\n\ndef rms(arr):\n arr = arr.flatten()\n arr[arr == np.nan] = 1\n return np.sqrt(np.sum(arr**2) / len(arr))\n\n\ndef nanrms(x, axis=None):\n return np.sqrt(np.nanmean(x**2, axis=axis))\n\n\ndef std_error(x, axis=None, ddof=0):\n return np.nanstd(x, axis=axis, ddof=ddof) / np.sqrt(2 * len(x))\n\n\ndef loss_batch(model, loss_func, xb, yb, opt=None):\n loss = loss_func(model(xb), yb)\n\n if opt is not None:\n loss.backward()\n opt.step()\n opt.zero_grad()\n\n return loss.item(), len(xb)\n\n\ndef validate(model, dl, loss_func):\n for batch in dl:\n losses, nums = zip(*[loss_batch(model, loss_func, xb, yb) for xb, yb in dl])\n val_loss = np.sum(np.multiply(losses, nums)) / np.sum(nums)\n print(val_loss)\n return val_loss\n\n\n# Functions for data retreival\ndef get_orig_unnormed_data(path=None):\n if path is None:\n train = pd.read_pickle('../../processed_data/train.pkl')\n test = pd.read_pickle('../../processed_data/test.pkl')\n else:\n train = pd.read_pickle(path)\n test = pd.read_pickle(path)\n return train, test\n\n\ndef get_sub_data(ii):\n path_to_data = '../../../data/split_data/'\n train = pd.read_pickle(path_to_data + 'sub_train_%d' % ii)\n test = pd.read_pickle(path_to_data + 'sub_test_%d' % ii)\n return train, test\n\n\ndef db_from_df(train, test, bs=1024):\n # Create TensorDatasets\n train_ds = TensorDataset(torch.tensor(train.values), torch.tensor(train.values))\n valid_ds = TensorDataset(torch.tensor(test.values), torch.tensor(test.values))\n # Create DataLoaders\n train_dl, valid_dl = get_data(train_ds, valid_ds, bs=bs)\n # Return DataBunch\n return basic_data.DataBunch(train_dl, valid_dl)\n\n\n# Functions for data normalization and reconstruction\ndef normalized_reconstructions(model, unnormed_df, force_mean=None, force_std=None, idxs=None):\n if force_mean is None:\n mean = unnormed_df.mean()\n std = unnormed_df.std()\n else:\n mean = force_mean\n std = force_std\n # Normalize\n normed_df = (unnormed_df - mean) / std\n\n if idxs is not None:\n data = torch.tensor(normed_df[idxs[0]:idxs[1]].values)\n unnormed_df = torch.tensor(unnormed_df[idxs[0]:idxs[1]].values)\n else:\n data = torch.tensor(normed_df.values)\n unnormed_df = torch.tensor(unnormed_df.values)\n\n pred = model(data).detach()\n\n return pred, data\n\n\ndef unnormalized_reconstructions(model, unnormed_df, force_mean=None, force_std=None, idxs=None):\n if force_mean is None:\n mean = unnormed_df.mean()\n std = unnormed_df.std()\n else:\n mean = force_mean\n std = force_std\n # Normalize\n normed_df = (unnormed_df - mean) / std\n\n if idxs is not None:\n data = torch.tensor(normed_df[idxs[0]:idxs[1]].values)\n unnormed_df = torch.tensor(unnormed_df[idxs[0]:idxs[1]].values)\n else:\n data = torch.tensor(normed_df.values)\n unnormed_df = torch.tensor(unnormed_df.values)\n\n pred = model(data).detach().numpy()\n pred = np.multiply(pred, std.values)\n pred = np.add(pred, mean.values)\n pred = torch.tensor(pred)\n #data = np.multiply(data, std.values)\n #data = np.add(data, mean.values)\n\n return pred, unnormed_df\n\n\ndef normalize(train, test, force_mean=None, force_std=None):\n # Normalize\n if force_mean is not None:\n train_mean = force_mean\n train_std = force_std\n else:\n train_mean = train.mean()\n train_std = train.std()\n\n train = (train - train_mean) / train_std\n test = (test - train_mean) / train_std\n return train, test\n\n\ndef log_normalize(train, test=None):\n train['pT'] = train['pT'].apply(lambda x: np.log10(x) / 3.)\n train['E'] = train['E'].apply(lambda x: np.log10(x) / 3.)\n train['eta'] = train['eta'] / 3.\n train['phi'] = train['phi'] / 3.\n if test is not None:\n test['pT'] = test['pT'].apply(lambda x: np.log10(x) / 3.)\n test['E'] = test['E'].apply(lambda x: np.log10(x) / 3.)\n test['eta'] = test['eta'] / 3.\n test['phi'] = test['phi'] / 3.\n\n return train.astype('float32'), test.astype('float32')\n else:\n return train.astype('float32')\n\n\ndef get_log_normalized_dls(train, test, bs=1024):\n \"\"\"Get lognormalized DataLoaders from train and test DataFrames.\n\n Parameters\n ----------\n train : DataFrame\n Training data.\n test : DataFrame\n Test data.\n bs : int\n Batch size.\n\n Returns\n -------\n (DataLoader, DataLoader)\n Train and test DataLoaders.\n\n \"\"\"\n train, test = log_normalize(train, test)\n train_x = train\n test_x = test\n train_y = train_x # y = x since we are building and AE\n test_y = test_x\n\n train_ds = TensorDataset(torch.tensor(train_x.values, dtype=torch.float), torch.tensor(train_y.values, dtype=torch.float))\n valid_ds = TensorDataset(torch.tensor(test_x.values, dtype=torch.float), torch.tensor(test_y.values, dtype=torch.float))\n train_dl, valid_dl = get_data(train_ds, valid_ds, bs)\n return train_dl, valid_dl\n\n\ndef logunnormalized_reconstructions(model, unnormed_df, idxs=None):\n normed_df = log_normalize(unnormed_df.copy())\n\n if idxs is not None:\n data = torch.tensor(normed_df[idxs[0]:idxs[1]].values)\n unnormed_df = torch.tensor(unnormed_df[idxs[0]:idxs[1]].values)\n else:\n data = torch.tensor(normed_df.values)\n unnormed_df = torch.tensor(unnormed_df.values)\n\n pred = model(data)\n pred = pred * 3\n pred[:, 0] = 10**(pred[:, 0])\n pred[:, 3] = 10**(pred[:, 3])\n\n return pred\n\n\n# Plotting functions\ndef plot_residuals(pred, data, range=None, variable_names=['pT', 'eta', 'phi', 'E'], bins=1000, save=None, title=None):\n alph = 0.8\n residuals = (pred.numpy() - data.numpy()) / data.numpy()\n for kk in np.arange(4):\n plt.figure()\n n_hist_pred, bin_edges, _ = plt.hist(residuals[:, kk], label='Residuals', alpha=alph, bins=bins, range=range)\n if title is None:\n plt.suptitle('Residuals of %s' % variable_names[kk])\n else:\n plt.suptitle(title)\n plt.xlabel(r'$(%s_{recon} - %s_{true}) / %s_{true}$' % (variable_names[kk], variable_names[kk], variable_names[kk]))\n plt.ylabel('Number of events')\n ms.sciy()\n if save is not None:\n plt.savefig(save + '_%s' % variable_names[kk])\n\n\ndef plot_histograms(pred, data, bins, same_bin_edges=True, colors=['orange', 'c'], variable_list=[r'$p_T$', r'$\\eta$', r'$\\phi$', r'$E$'], variable_names=['pT', 'eta', 'phi', 'E'], unit_list=['[GeV]', '[rad]', '[rad]', '[GeV]'], title=None):\n alph = 0.8\n n_bins = bins\n for kk in np.arange(4):\n plt.figure()\n n_hist_data, bin_edges, _ = plt.hist(data[:, kk], color=colors[1], label='Input', alpha=1, bins=n_bins)\n if same_bin_edges:\n n_bins_2 = bin_edges\n else:\n n_bins_2 = bins\n n_hist_pred, _, _ = plt.hist(pred[:, kk], color=colors[0], label='Output', alpha=alph, bins=n_bins_2)\n if title is None:\n plt.suptitle(variable_names[kk])\n else:\n plt.suptitle(title)\n plt.xlabel(variable_list[kk] + ' ' + unit_list[kk])\n plt.ylabel('Number of events')\n ms.sciy()\n plt.legend()\n\n\ndef plot_activations(learn, figsize=(12, 9), lines=['-', ':'], save=None, linewd=1, fontsz=14):\n plt.figure(figsize=figsize)\n for i in range(learn.activation_stats.stats.shape[1]):\n thiscol = ms.colorprog(i, learn.activation_stats.stats.shape[1])\n plt.plot(learn.activation_stats.stats[0][i], linewidth=linewd, color=thiscol, label=str(learn.activation_stats.modules[i]).split(',')[0], linestyle=lines[i % len(lines)])\n plt.title('Weight means')\n plt.legend(fontsize=fontsz)\n plt.xlabel('Mini-batch')\n if save is not None:\n plt.savefig(save + '_means')\n plt.figure(figsize=(12, 9))\n for i in range(learn.activation_stats.stats.shape[1]):\n thiscol = ms.colorprog(i, learn.activation_stats.stats.shape[1])\n plt.plot(learn.activation_stats.stats[1][i], linewidth=linewd, color=thiscol, label=str(learn.activation_stats.modules[i]).split(',')[0], linestyle=lines[i % len(lines)])\n plt.title('Weight standard deviations')\n plt.xlabel('Mini-batch')\n plt.legend(fontsize=fontsz)\n if save is not None:\n plt.savefig(save + '_stds')\n\n\n# Miscellaneous\ndef replaceline_and_save(fname, findln, newline, override=False):\n if findln not in newline and not override:\n raise ValueError('Detected inconsistency!!!!')\n\n with open(fname, 'r') as fid:\n lines = fid.readlines()\n\n found = False\n pos = None\n for ii, line in enumerate(lines):\n if findln in line:\n pos = ii\n found = True\n break\n\n if not found:\n raise ValueError('Not found!!!!')\n\n if '\\n' in newline:\n lines[pos] = newline\n else:\n lines[pos] = newline + '\\n'\n\n with open(fname, 'w') as fid:\n fid.writelines(lines)\n\n\n# Custom normalization for AOD data\neta_div = 5\nemfrac_div = 1.6\nnegE_div = 1.6\nphi_div = 3\nm_div = 1.8\nwidth_div = .6\nN90_div = 20\ntiming_div = 40\nhecq_div = 1\ncenterlambda_div = 2\nsecondlambda_div = 1\nsecondR_div = .6\nlarqf_div = 2.5\npt_div = 1.2\ncentroidR_div = 0.8\narea4vecm_div = 0.18\narea4vecpt_div = 0.7\narea4vec_div = 0.8\nOot_div = 0.3\nlarq_div = 0.6\n\nlog_add = 100\nlog_sub = 2\nm_add = 1\ncentroidR_sub = 3\npt_sub = 1.3\narea4vecm_sub = 0.15\n\n\ndef filter_jets(train):\n train['pt'] = train['pt'] / 1000. # Convert to GeV\n train['m'] = train['m'] / 1000. # Convert to GeV\n train['LeadingClusterPt'] = train['LeadingClusterPt'] / 1000. # Convert to GeV\n train['LeadingClusterSecondR'] = train['LeadingClusterSecondR'] / 1000. # Convert to GeV\n train['LeadingClusterSecondLambda'] = train['LeadingClusterSecondLambda'] / 1000. # Convert to GeV\n train['NegativeE'] = train['NegativeE'] / 1000. # Convert to GeV\n\n if 'JetGhostArea' in train.keys():\n train.pop('JetGhostArea')\n if 'BchCorrCell' in train.keys():\n train.pop('BchCorrCell')\n\n # Remove all jets with EMFrac outside (-2, 2)\n train = train[(np.abs(train['EMFrac']) < 5)]\n train = train[np.invert((np.abs(train['EMFrac']) < 0.05) & (np.abs(train['eta']) >= 2))]\n train = train[np.invert((train['AverageLArQF'] > .8) & (train['EMFrac'] > .95) & (train['LArQuality'] > .8) & (np.abs(train['eta']) < 2.8))]\n train = train[np.abs(train['NegativeE']) < 60 * 5]\n\n # Filter out extreme jets\n train = train[np.invert((train['AverageLArQF'] > .8) & (np.abs(train['HECQuality']) > 0.5) & (np.abs(train['HECFrac']) > 0.5))]\n train = train[train['OotFracClusters10'] > -0.1]\n train = train[train['OotFracClusters5'] > -0.1]\n if 'Width' in train.keys():\n train = train[np.abs(train['Width']) < 5]\n train = train[np.invert(train['Width'] == -1)]\n if 'WidthPhi' in train.keys():\n train = train[np.abs(train['WidthPhi']) < 5]\n train = train[np.abs(train['Timing']) < 125]\n train = train[train['LArQuality'] < 4]\n train = train[np.abs(train['HECQuality']) < 2.5]\n # train = train[train['m'] > 1e-3]\n\n return train\n\n\ndef unit_convert_jets(leading, subleading):\n leading_orig = leading.copy()\n leading['pt'] = leading['pt'] / 1000. # Convert to GeV\n subleading['pt'] = subleading['pt'] / 1000. # Convert to GeV\n leading_orig['pt'] = leading_orig['pt'] / 1000. # Convert to GeV\n leading['m'] = leading['m'] / 1000. # Convert to GeV\n subleading['m'] = subleading['m'] / 1000. # Convert to GeV\n leading_orig['m'] = leading_orig['m'] / 1000. # Convert to GeV\n leading['LeadingClusterPt'] = leading['LeadingClusterPt'] / 1000. # Convert to GeV\n subleading['LeadingClusterPt'] = subleading['LeadingClusterPt'] / 1000. # Convert to GeV\n leading_orig['LeadingClusterPt'] = leading_orig['LeadingClusterPt'] / 1000. # Convert to GeV\n leading['LeadingClusterSecondR'] = leading['LeadingClusterSecondR'] / 1000. # Convert to GeV\n subleading['LeadingClusterSecondR'] = subleading['LeadingClusterSecondR'] / 1000. # Convert to GeV\n leading_orig['LeadingClusterSecondR'] = leading_orig['LeadingClusterSecondR'] / 1000. # Convert to GeV\n leading['LeadingClusterSecondLambda'] = leading['LeadingClusterSecondLambda'] / 1000. # Convert to GeV\n subleading['LeadingClusterSecondLambda'] = subleading['LeadingClusterSecondLambda'] / 1000. # Convert to GeV\n leading_orig['LeadingClusterSecondLambda'] = leading_orig['LeadingClusterSecondLambda'] / 1000. # Convert to GeV\n leading['NegativeE'] = leading['NegativeE'] / 1000. # Convert to GeV\n subleading['NegativeE'] = subleading['NegativeE'] / 1000. # Convert to GeV\n leading_orig['NegativeE'] = leading_orig['NegativeE'] / 1000. # Convert to GeV\n\n\ndef filter_mc_jets(leading, subleading):\n leading_orig = leading.copy()\n leading_orig['pt'] = leading_orig['pt'] / 1000. # Convert to GeV\n leading_orig['m'] = leading_orig['m'] / 1000. # Convert to GeV\n leading_orig['LeadingClusterPt'] = leading_orig['LeadingClusterPt'] / 1000. # Convert to GeV\n leading_orig['LeadingClusterSecondR'] = leading_orig['LeadingClusterSecondR'] / 1000. # Convert to GeV\n leading_orig['LeadingClusterSecondLambda'] = leading_orig['LeadingClusterSecondLambda'] / 1000. # Convert to GeV\n leading_orig['NegativeE'] = leading_orig['NegativeE'] / 1000. # Convert to GeV\n\n if 'JetGhostArea' in leading.keys():\n leading.pop('JetGhostArea')\n subleading.pop('JetGhostArea')\n leading_orig.pop('JetGhostArea')\n if 'BchCorrCell' in leading.keys():\n leading.pop('BchCorrCell')\n subleading.pop('BchCorrCell')\n leading_orig.pop('BchCorrCell')\n\n # Remove all jets with EMFrac outside (-2, 2)\n leading = leading[(np.abs(leading_orig['EMFrac']) < 2)]\n subleading = subleading[(np.abs(leading_orig['EMFrac']) < 2)]\n leading_orig = leading_orig[(np.abs(leading_orig['EMFrac']) < 2)]\n leading = leading[np.invert((np.abs(leading_orig['EMFrac']) < 0.05) & (np.abs(leading_orig['eta']) >= 2))]\n subleading = subleading[np.invert((np.abs(leading_orig['EMFrac']) < 0.05) & (np.abs(leading_orig['eta']) >= 2))]\n leading_orig = leading_orig[np.invert((np.abs(leading_orig['EMFrac']) < 0.05) & (np.abs(leading_orig['eta']) >= 2))]\n leading = leading[np.invert((leading_orig['AverageLArQF'] > .8) & (leading_orig['EMFrac'] > .95) & (leading_orig['LArQuality'] > .8) & (np.abs(leading_orig['eta']) < 2.8))]\n subleading = subleading[np.invert((leading_orig['AverageLArQF'] > .8) & (leading_orig['EMFrac'] > .95) & (leading_orig['LArQuality'] > .8) & (np.abs(leading_orig['eta']) < 2.8))]\n leading_orig = leading_orig[np.invert((leading_orig['AverageLArQF'] > .8) & (leading_orig['EMFrac'] > .95) & (leading_orig['LArQuality'] > .8) & (np.abs(leading_orig['eta']) < 2.8))]\n leading = leading[np.abs(leading_orig['NegativeE']) < 60]\n subleading = subleading[np.abs(leading_orig['NegativeE']) < 60]\n leading_orig = leading_orig[np.abs(leading_orig['NegativeE']) < 60]\n\n # Filter out extreme jets\n leading = leading[np.invert((leading_orig['AverageLArQF'] > .8) & (np.abs(leading_orig['HECQuality']) > 0.5) & (np.abs(leading_orig['HECFrac']) > 0.5))]\n subleading = subleading[np.invert((leading_orig['AverageLArQF'] > .8) & (np.abs(leading_orig['HECQuality']) > 0.5) & (np.abs(leading_orig['HECFrac']) > 0.5))]\n leading_orig = leading_orig[np.invert((leading_orig['AverageLArQF'] > .8) & (np.abs(leading_orig['HECQuality']) > 0.5) & (np.abs(leading_orig['HECFrac']) > 0.5))]\n leading = leading[leading_orig['OotFracClusters10'] > -0.1]\n subleading = subleading[leading_orig['OotFracClusters10'] > -0.1]\n leading_orig = leading_orig[leading_orig['OotFracClusters10'] > -0.1]\n leading = leading[leading_orig['OotFracClusters5'] > -0.1]\n subleading = subleading[leading_orig['OotFracClusters5'] > -0.1]\n leading_orig = leading_orig[leading_orig['OotFracClusters5'] > -0.1]\n if 'Width' in leading.keys():\n leading = leading[leading_orig['Width'] < 100]\n subleading = subleading[leading_orig['Width'] < 100]\n leading_orig = leading_orig[leading_orig['Width'] < 100]\n if 'WidthPhi' in leading.keys():\n leading = leading[leading_orig['WidthPhi'] < 100]\n subleading = subleading[leading_orig['WidthPhi'] < 100]\n leading_orig = leading_orig[leading_orig['WidthPhi'] < 100]\n leading = leading[np.abs(leading_orig['Timing']) < 120]\n subleading = subleading[np.abs(leading_orig['Timing']) < 120]\n leading_orig = leading_orig[np.abs(leading_orig['Timing']) < 120]\n leading = leading[leading_orig['LArQuality'] < 2]\n subleading = subleading[leading_orig['LArQuality'] < 2]\n leading_orig = leading_orig[leading_orig['LArQuality'] < 2]\n leading = leading[leading['HECQuality'] > -100000]\n subleading = subleading[leading_orig['HECQuality'] > -100000]\n leading_orig = leading_orig[leading['HECQuality'] > -100000]\n leading = leading[leading_orig['m'] > 1e-3]\n subleading = subleading[leading_orig['m'] > 1e-3]\n leading_orig = leading_orig[leading_orig['m'] > 1e-3]\n\n return leading, subleading\n\n\ndef custom_normalization(train, test):\n train_cp = train.copy()\n test_cp = test.copy()\n\n for data in [train_cp, test_cp]:\n data['DetectorEta'] = data['DetectorEta'] / eta_div\n data['ActiveArea4vec_eta'] = data['ActiveArea4vec_eta'] / eta_div\n data['EMFrac'] = data['EMFrac'] / emfrac_div\n data['NegativeE'] = np.log10(-data['NegativeE'] + 1) / negE_div\n data['eta'] = data['eta'] / eta_div\n data['phi'] = data['phi'] / phi_div\n data['ActiveArea4vec_phi'] = data['ActiveArea4vec_phi'] / phi_div\n if 'Width' in data.keys():\n data['Width'] = data['Width'] / width_div\n else:\n print('Wdith not found when normalizing')\n if 'WidthPhi' in data.keys():\n data['WidthPhi'] = data['WidthPhi'] / width_div\n else:\n print('WdithPhi not found when normalizing')\n data['N90Constituents'] = data['N90Constituents'] / N90_div\n data['Timing'] = data['Timing'] / timing_div\n data['HECQuality'] = data['HECQuality'] / hecq_div\n data['ActiveArea'] = data['ActiveArea'] / area4vec_div\n data['ActiveArea4vec_m'] = data['ActiveArea4vec_m'] / area4vecm_div - area4vecm_sub\n data['ActiveArea4vec_pt'] = data['ActiveArea4vec_pt'] / area4vecpt_div\n data['LArQuality'] = data['LArQuality'] / larq_div\n\n data['m'] = np.log10(data['m'] + m_add) / m_div\n data['LeadingClusterCenterLambda'] = (np.log10(data['LeadingClusterCenterLambda'] + log_add) - log_sub) / centerlambda_div\n data['LeadingClusterSecondLambda'] = (np.log10(data['LeadingClusterSecondLambda'] + log_add) - log_sub) / secondlambda_div\n data['LeadingClusterSecondR'] = (np.log10(data['LeadingClusterSecondR'] + log_add) - log_sub) / secondR_div\n data['AverageLArQF'] = (np.log10(data['AverageLArQF'] + log_add) - log_sub) / larqf_div\n data['pt'] = (np.log10(data['pt']) - pt_sub) / pt_div\n data['LeadingClusterPt'] = np.log10(data['LeadingClusterPt']) / pt_div\n data['CentroidR'] = (np.log10(data['CentroidR']) - centroidR_sub) / centroidR_div\n data['OotFracClusters10'] = np.log10(data['OotFracClusters10'] + 1) / Oot_div\n data['OotFracClusters5'] = np.log10(data['OotFracClusters5'] + 1) / Oot_div\n\n return train_cp, test_cp\n\n\ndef custom_unnormalize(normalized_data):\n data = normalized_data.copy()\n data['DetectorEta'] = data['DetectorEta'] * eta_div\n data['ActiveArea4vec_eta'] = data['ActiveArea4vec_eta'] * eta_div\n data['EMFrac'] = data['EMFrac'] * emfrac_div\n data['eta'] = data['eta'] * eta_div\n data['phi'] = data['phi'] * phi_div\n data['ActiveArea4vec_phi'] = data['ActiveArea4vec_phi'] * phi_div\n if 'Width' in data.keys():\n data['Width'] = data['Width'] * width_div\n else:\n print('Width not found when unnormalizing')\n if 'WidthPhi' in data.keys():\n data['WidthPhi'] = data['WidthPhi'] * width_div\n else:\n print('WidthPhi not found when unnormalizing')\n data['N90Constituents'] = data['N90Constituents'] * N90_div\n data['Timing'] = data['Timing'] * timing_div\n data['HECQuality'] = data['HECQuality'] * hecq_div\n data['ActiveArea'] = data['ActiveArea'] * area4vec_div\n data['ActiveArea4vec_m'] = (data['ActiveArea4vec_m'] + area4vecm_sub) * area4vecm_div\n data['ActiveArea4vec_pt'] = data['ActiveArea4vec_pt'] * area4vecpt_div\n data['LArQuality'] = data['LArQuality'] * larq_div\n\n data['NegativeE'] = 1 - np.power(10, negE_div * data['NegativeE'])\n data['m'] = np.power(10, m_div * data['m']) - m_add\n data['LeadingClusterCenterLambda'] = np.power(10, centerlambda_div * data['LeadingClusterCenterLambda'] + log_sub) - log_add\n data['LeadingClusterSecondLambda'] = np.power(10, secondlambda_div * data['LeadingClusterSecondLambda'] + log_sub) - log_add\n data['LeadingClusterSecondR'] = np.power(10, secondR_div * data['LeadingClusterSecondR'] + log_sub) - log_add\n data['AverageLArQF'] = np.power(10, larqf_div * data['AverageLArQF'] + log_sub) - log_add\n data['pt'] = np.power(10, pt_div * data['pt'] + pt_sub)\n data['LeadingClusterPt'] = np.power(10, pt_div * data['LeadingClusterPt'])\n data['CentroidR'] = np.power(10, centroidR_div * data['CentroidR'] + centroidR_sub)\n data['OotFracClusters10'] = np.power(10, Oot_div * data['OotFracClusters10']) - 1\n data['OotFracClusters5'] = np.power(10, Oot_div * data['OotFracClusters5']) - 1\n\n return data\n\n\ndef round_to_input(pred, uniques, variable):\n var = pred[variable].values.reshape(-1, 1)\n diff = (var - uniques)\n ind = np.apply_along_axis(lambda x: np.argmin(np.abs(x)), axis=1, arr=diff)\n new_arr = -np.ones_like(var)\n for ii in np.arange(new_arr.shape[0]):\n new_arr[ii] = uniques[ind[ii]]\n pred[variable] = new_arr\n"
] | [
[
"matplotlib.pyplot.legend",
"numpy.add",
"numpy.nanmean",
"numpy.nanstd",
"numpy.ones_like",
"numpy.arange",
"torch.tensor",
"matplotlib.pyplot.figure",
"numpy.multiply",
"matplotlib.pyplot.title",
"numpy.power",
"numpy.invert",
"matplotlib.pyplot.savefig",
"numpy.log10",
"matplotlib.pyplot.suptitle",
"numpy.sum",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel",
"numpy.abs",
"matplotlib.pyplot.xlabel",
"pandas.read_pickle"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
JB1959/Python | [
"b6ca263983933c3ecc06ed0083dd11b6faf870c8"
] | [
"dynamic_programming/max_sub_array.py"
] | [
"\"\"\"\nauthor : Mayank Kumar Jha (mk9440)\n\"\"\"\nfrom typing import List\n\n\ndef find_max_sub_array(A, low, high):\n if low == high:\n return low, high, A[low]\n else:\n mid = (low + high) // 2\n left_low, left_high, left_sum = find_max_sub_array(A, low, mid)\n right_low, right_high, right_sum = find_max_sub_array(A, mid + 1, high)\n cross_left, cross_right, cross_sum = find_max_cross_sum(A, low, mid, high)\n if left_sum >= right_sum and left_sum >= cross_sum:\n return left_low, left_high, left_sum\n elif right_sum >= left_sum and right_sum >= cross_sum:\n return right_low, right_high, right_sum\n else:\n return cross_left, cross_right, cross_sum\n\n\ndef find_max_cross_sum(A, low, mid, high):\n left_sum, max_left = -999999999, -1\n right_sum, max_right = -999999999, -1\n summ = 0\n for i in range(mid, low - 1, -1):\n summ += A[i]\n if summ > left_sum:\n left_sum = summ\n max_left = i\n summ = 0\n for i in range(mid + 1, high + 1):\n summ += A[i]\n if summ > right_sum:\n right_sum = summ\n max_right = i\n return max_left, max_right, (left_sum + right_sum)\n\n\ndef max_sub_array(nums: List[int]) -> int:\n \"\"\"\n Finds the contiguous subarray which has the largest sum and return its sum.\n\n >>> max_sub_array([-2, 1, -3, 4, -1, 2, 1, -5, 4])\n 6\n\n An empty (sub)array has sum 0.\n >>> max_sub_array([])\n 0\n\n If all elements are negative, the largest subarray would be the empty array,\n having the sum 0.\n >>> max_sub_array([-1, -2, -3])\n 0\n >>> max_sub_array([5, -2, -3])\n 5\n >>> max_sub_array([31, -41, 59, 26, -53, 58, 97, -93, -23, 84])\n 187\n \"\"\"\n best = 0\n current = 0\n for i in nums:\n current += i\n if current < 0:\n current = 0\n best = max(best, current)\n return best\n\n\nif __name__ == \"__main__\":\n \"\"\"\n A random simulation of this algorithm.\n \"\"\"\n import time\n from random import randint\n\n from matplotlib import pyplot as plt\n\n inputs = [10, 100, 1000, 10000, 50000, 100000, 200000, 300000, 400000, 500000]\n tim = []\n for i in inputs:\n li = [randint(1, i) for j in range(i)]\n strt = time.time()\n (find_max_sub_array(li, 0, len(li) - 1))\n end = time.time()\n tim.append(end - strt)\n print(\"No of Inputs Time Taken\")\n for i in range(len(inputs)):\n print(inputs[i], \"\\t\\t\", tim[i])\n plt.plot(inputs, tim)\n plt.xlabel(\"Number of Inputs\")\n plt.ylabel(\"Time taken in seconds \")\n plt.show()\n"
] | [
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
etzinis/nldrp | [
"3b6e24aa86a6d43bfd6f753b346739c00c282de3"
] | [
"nldrp/dnn/models/test.py"
] | [
"import os\n\nfrom nldrp.dnn.config import DNN_BASE_PATH\nfrom nldrp.dnn.experiments.data_splits import generate_speaker_splits, \\\n generate_folds\n\nfrom sklearn.externals import joblib\n\nIEMOCAP_PATH = os.path.join(DNN_BASE_PATH, 'data',\n \"IEMOCAP_linear_emobase2010_segl_1.0_segol_0.5\")\n\nfeatures_dic = joblib.load(IEMOCAP_PATH)\nfor split in generate_folds(features_dic, \"dependent\"):\n train_speakers, val_speaker, test_speaker = split\n print(\"-\" * 40)\n print(\"train_speakers: \", train_speakers)\n print(\"val_speaker: \", val_speaker)\n print(\"test_speaker: \", test_speaker)\n"
] | [
[
"sklearn.externals.joblib.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
e-koch/fil_finder | [
"aa03e4e7b7f443d6d9dbd127a46a18eb67680499"
] | [
"fil_finder/pixel_ident.py"
] | [
"# Licensed under an MIT open source license - see LICENSE\n\nfrom .length import *\nfrom .utilities import distance\n\nimport numpy as np\nimport scipy.ndimage as nd\nimport matplotlib.pyplot as p\nimport copy\n\n\ndef isolateregions(binary_array, size_threshold=0, pad_size=0,\n fill_hole=False, rel_size=0.1, morph_smooth=False):\n '''\n\n Labels regions in a boolean array and returns individual arrays for each\n region. Regions below a threshold can optionally be removed. Small holes\n may also be filled in.\n\n Parameters\n ----------\n binary_array : numpy.ndarray\n A binary array of regions.\n size_threshold : int, optional\n Sets the pixel size on the size of regions.\n pad_size : int, optional\n Padding to be added to the individual arrays.\n fill_hole : int, optional\n Enables hole filling.\n rel_size : float or int, optional\n If < 1.0, sets the minimum size a hole must be relative to the area\n of the mask. Otherwise, this is the maximum number of pixels the hole\n must have to be deleted.\n morph_smooth : bool, optional\n Morphologically smooth the image using a binar opening and closing.\n\n Returns\n -------\n output_arrays : list\n Regions separated into individual arrays.\n num : int\n Number of filaments\n corners : list\n Contains the indices where each skeleton array was taken from\n the original.\n\n '''\n\n output_arrays = []\n corners = []\n\n # Label skeletons\n labels, num = nd.label(binary_array, eight_con())\n\n # Remove skeletons which have fewer pixels than the threshold.\n if size_threshold != 0:\n sums = nd.sum(binary_array, labels, range(1, num + 1))\n remove_fils = np.where(sums <= size_threshold)[0]\n for lab in remove_fils:\n binary_array[np.where(labels == lab + 1)] = 0\n\n # Relabel after deleting short skeletons.\n labels, num = nd.label(binary_array, eight_con())\n\n # Split each skeleton into its own array.\n for n in range(1, num + 1):\n x, y = np.where(labels == n)\n # Make an array shaped to the skeletons size and padded on each edge\n # the +1 is because, e.g., range(0, 5) only has 5 elements, but the\n # indices we're using are range(0, 6)\n shapes = (x.max() - x.min() + 2 * pad_size + 1,\n y.max() - y.min() + 2 * pad_size + 1)\n eachfil = np.zeros(shapes)\n eachfil[x - x.min() + pad_size, y - y.min() + pad_size] = 1\n # Fill in small holes\n if fill_hole:\n eachfil = _fix_small_holes(eachfil, rel_size=rel_size)\n if morph_smooth:\n eachfil = nd.binary_opening(eachfil, np.ones((3, 3)))\n eachfil = nd.binary_closing(eachfil, np.ones((3, 3)))\n output_arrays.append(eachfil)\n # Keep the coordinates from the original image\n lower = (max(0, x.min() - pad_size), max(0, y.min() - pad_size))\n upper = (x.max() + pad_size + 1, y.max() + pad_size + 1)\n corners.append([lower, upper])\n\n return output_arrays, num, corners\n\n\ndef find_filpix(branches, labelfil, final=True, debug=False):\n '''\n\n Identifies the types of pixels in the given skeletons. Identification is\n based on the connectivity of the pixel.\n\n Parameters\n ----------\n branches : list\n Contains the number of branches in each skeleton.\n labelfil : list\n Contains the arrays of each skeleton.\n final : bool, optional\n If true, corner points, intersections, and body points are all\n labeled as a body point for use when the skeletons have already\n been cleaned.\n debug : bool, optional\n Enable to print out (a lot) of extra info on pixel classification.\n\n Returns\n -------\n fila_pts : list\n All points on the body of each skeleton.\n inters : list\n All points associated with an intersection in each skeleton.\n labelfil : list\n Contains the arrays of each skeleton where all intersections\n have been removed.\n endpts_return : list\n The end points of each branch of each skeleton.\n '''\n\n initslices = []\n initlist = []\n shiftlist = []\n sublist = []\n endpts = []\n blockpts = []\n bodypts = []\n slices = []\n vallist = []\n shiftvallist = []\n cornerpts = []\n subvallist = []\n subslist = []\n pix = []\n filpix = []\n intertemps = []\n fila_pts = []\n inters = []\n repeat = []\n temp_group = []\n all_pts = []\n pairs = []\n endpts_return = []\n\n for k in range(1, branches + 1):\n x, y = np.where(labelfil == k)\n for i in range(len(x)):\n if x[i] < labelfil.shape[0] - 1 and y[i] < labelfil.shape[1] - 1:\n pix.append((x[i], y[i]))\n initslices.append(np.array([[labelfil[x[i] - 1, y[i] + 1],\n labelfil[x[i], y[i] + 1],\n labelfil[x[i] + 1, y[i] + 1]],\n [labelfil[x[i] - 1, y[i]], 0,\n labelfil[x[i] + 1, y[i]]],\n [labelfil[x[i] - 1, y[i] - 1],\n labelfil[x[i], y[i] - 1],\n labelfil[x[i] + 1, y[i] - 1]]]))\n\n filpix.append(pix)\n slices.append(initslices)\n initslices = []\n pix = []\n\n for i in range(len(slices)):\n for k in range(len(slices[i])):\n initlist.append([slices[i][k][0, 0],\n slices[i][k][0, 1],\n slices[i][k][0, 2],\n slices[i][k][1, 2],\n slices[i][k][2, 2],\n slices[i][k][2, 1],\n slices[i][k][2, 0],\n slices[i][k][1, 0]])\n vallist.append(initlist)\n initlist = []\n\n for i in range(len(slices)):\n for k in range(len(slices[i])):\n shiftlist.append(shifter(vallist[i][k], 1))\n shiftvallist.append(shiftlist)\n shiftlist = []\n\n for k in range(len(slices)):\n for i in range(len(vallist[k])):\n for j in range(8):\n sublist.append(\n int(vallist[k][i][j]) - int(shiftvallist[k][i][j]))\n subslist.append(sublist)\n sublist = []\n subvallist.append(subslist)\n subslist = []\n\n # x represents the subtracted list (step-ups) and y is the values of the\n # surrounding pixels. The categories of pixels are ENDPTS (x<=1),\n # BODYPTS (x=2,y=2),CORNERPTS (x=2,y=3),BLOCKPTS (x=3,y>=4), and\n # INTERPTS (x>=3).\n # A cornerpt is [*,0,0] (*s) associated with an intersection,\n # but their exclusion from\n # [1,*,0] the intersection keeps eight-connectivity, they are included\n # [0,1,0] intersections for this reason.\n # A blockpt is [1,0,1] They are typically found in a group of four,\n # where all four\n # [0,*,*] constitute a single intersection.\n # [1,*,*]\n # A T-pt has the same connectivity as a block point, but with two 8-conns\n # [*, *, *]\n # [0, 1, 0]\n # The \"final\" designation is used when finding the final branch lengths.\n # At this point, blockpts and cornerpts should be eliminated.\n for k in range(branches):\n for l in range(len(filpix[k])):\n x = [j for j, y in enumerate(subvallist[k][l]) if y == k + 1]\n y = [j for j, z in enumerate(vallist[k][l]) if z == k + 1]\n\n if len(x) <= 1:\n if debug:\n print(\"End pt. {}\".format(filpix[k][l]))\n endpts.append(filpix[k][l])\n endpts_return.append(filpix[k][l])\n elif len(x) == 2:\n if final:\n bodypts.append(filpix[k][l])\n else:\n if len(y) == 2:\n if debug:\n print(\"Body pt. {}\".format(filpix[k][l]))\n bodypts.append(filpix[k][l])\n\n elif is_tpoint(vallist[k][l]):\n # If there are only 3 connections to the t-point, it\n # is an end point\n if len(y) == 3:\n if debug:\n print(\"T-point end {}\".format(filpix[k][l]))\n endpts.append(filpix[k][l])\n endpts_return.append(filpix[k][l])\n # If there are 4, it is a body point\n elif len(y) == 4:\n if debug:\n print(\"T-point body {}\".format(filpix[k][l]))\n\n bodypts.append(filpix[k][l])\n # Otherwise it is a part of an intersection\n else:\n if debug:\n print(\"T-point inter {}\".format(filpix[k][l]))\n intertemps.append(filpix[k][l])\n elif is_blockpoint(vallist[k][l]):\n if debug:\n print(\"Block pt. {}\".format(filpix[k][l]))\n blockpts.append(filpix[k][l])\n else:\n if debug:\n print(\"Corner pt. {}\".format(filpix[k][l]))\n cornerpts.append(filpix[k][l])\n elif len(x) >= 3:\n if debug:\n print(\"Inter pt. {}\".format(filpix[k][l]))\n intertemps.append(filpix[k][l])\n endpts = list(set(endpts))\n bodypts = list(set(bodypts))\n dups = set(endpts) & set(bodypts)\n if len(dups) > 0:\n for i in dups:\n bodypts.remove(i)\n # Cornerpts without a partner diagonally attached can be included as a\n # bodypt.\n if debug:\n print(\"Cornerpts: {}\".format(cornerpts))\n\n if len(cornerpts) > 0:\n deleted_cornerpts = []\n\n for i, j in zip(cornerpts, cornerpts):\n if i != j:\n if distance(i[0], j[0], i[1], j[1]) == np.sqrt(2.0):\n proximity = [(i[0], i[1] - 1),\n (i[0], i[1] + 1),\n (i[0] - 1, i[1]),\n (i[0] + 1, i[1]),\n (i[0] - 1, i[1] + 1),\n (i[0] + 1, i[1] + 1),\n (i[0] - 1, i[1] - 1),\n (i[0] + 1, i[1] - 1)]\n match = set(intertemps) & set(proximity)\n if len(match) == 1:\n print(\"MATCH\")\n bodypts.extend([i, j])\n # pairs.append([i, j])\n deleted_cornerpts.append(i)\n deleted_cornerpts.append(j)\n cornerpts = list(set(cornerpts).difference(set(deleted_cornerpts)))\n\n if len(cornerpts) > 0:\n for l in cornerpts:\n proximity = [(l[0], l[1] - 1),\n (l[0], l[1] + 1),\n (l[0] - 1, l[1]),\n (l[0] + 1, l[1]),\n (l[0] - 1, l[1] + 1),\n (l[0] + 1, l[1] + 1),\n (l[0] - 1, l[1] - 1),\n (l[0] + 1, l[1] - 1)]\n\n # Check if the matching corner point is an end point\n # Otherwise the pixel will be combined into a 2-pixel intersec\n match_ends = set(endpts) & set(proximity[-4:])\n if len(match_ends) == 1:\n fila_pts.append(endpts + bodypts + [l])\n continue\n\n match = set(intertemps) & set(proximity)\n if len(match) == 1:\n intertemps.append(l)\n fila_pts.append(endpts + bodypts)\n else:\n fila_pts.append(endpts + bodypts + [l])\n else:\n fila_pts.append(endpts + bodypts)\n\n # Reset lists\n cornerpts = []\n endpts = []\n bodypts = []\n\n if len(pairs) > 0:\n for i in range(len(pairs)):\n for j in pairs[i]:\n all_pts.append(j)\n if len(blockpts) > 0:\n for i in blockpts:\n all_pts.append(i)\n if len(intertemps) > 0:\n for i in intertemps:\n all_pts.append(i)\n # Pairs of cornerpts, blockpts, and interpts are combined into an\n # array. If there is eight connectivity between them, they are labelled\n # as a single intersection.\n arr = np.zeros((labelfil.shape))\n for z in all_pts:\n labelfil[z[0], z[1]] = 0\n arr[z[0], z[1]] = 1\n lab, nums = nd.label(arr, eight_con())\n for k in range(1, nums + 1):\n objs_pix = np.where(lab == k)\n for l in range(len(objs_pix[0])):\n temp_group.append((objs_pix[0][l], objs_pix[1][l]))\n inters.append(temp_group)\n temp_group = []\n for i in range(len(inters) - 1):\n if inters[i] == inters[i + 1]:\n repeat.append(inters[i])\n for i in repeat:\n inters.remove(i)\n\n if debug:\n print(\"Fila pts: {}\".format(fila_pts))\n print(\"Intersections: {}\".format(inters))\n print(\"End pts: {}\".format(endpts_return))\n print(labelfil)\n\n return fila_pts, inters, labelfil, endpts_return\n\n\ndef find_extran(branches, labelfil, debug=False):\n '''\n Identify pixels that are not necessary to keep the connectivity of the\n skeleton. It uses the same labeling process as find_filpix. Extraneous\n pixels tend to be those from former intersections, whose attached branch\n was eliminated in the cleaning process.\n\n Parameters\n ----------\n branches : list\n Contains the number of branches in each skeleton.\n labelfil : list\n Contains arrays of the labeled versions of each skeleton.\n debug : bool, optional\n Enable plotting of each filament array to visualize where the deleted\n pixels are.\n\n Returns\n -------\n labelfil : list\n Contains the updated labeled arrays with extraneous pieces\n removed.\n '''\n\n initslices = []\n initlist = []\n shiftlist = []\n sublist = []\n extran = []\n slices = []\n vallist = []\n shiftvallist = []\n subvallist = []\n subslist = []\n pix = []\n filpix = []\n\n for k in range(1, branches + 1):\n x, y = np.where(labelfil == k)\n for i in range(len(x)):\n if x[i] < labelfil.shape[0] - 1 and y[i] < labelfil.shape[1] - 1:\n pix.append((x[i], y[i]))\n initslices.append(np.array([[labelfil[x[i] - 1, y[i] + 1],\n labelfil[x[i], y[i] + 1],\n labelfil[x[i] + 1, y[i] + 1]],\n [labelfil[x[i] - 1, y[i]], 0,\n labelfil[x[i] + 1, y[i]]],\n [labelfil[x[i] - 1, y[i] - 1],\n labelfil[x[i], y[i] - 1],\n labelfil[x[i] + 1, y[i] - 1]]]))\n\n filpix.append(pix)\n slices.append(initslices)\n initslices = []\n pix = []\n\n for i in range(len(slices)):\n for k in range(len(slices[i])):\n initlist.append([slices[i][k][0, 0],\n slices[i][k][0, 1],\n slices[i][k][0, 2],\n slices[i][k][1, 2],\n slices[i][k][2, 2],\n slices[i][k][2, 1],\n slices[i][k][2, 0],\n slices[i][k][1, 0]])\n vallist.append(initlist)\n initlist = []\n\n for i in range(len(slices)):\n for k in range(len(slices[i])):\n shiftlist.append(shifter(vallist[i][k], 1))\n shiftvallist.append(shiftlist)\n shiftlist = []\n\n for k in range(len(slices)):\n for i in range(len(vallist[k])):\n for j in range(8):\n sublist.append(\n int(vallist[k][i][j]) - int(shiftvallist[k][i][j]))\n subslist.append(sublist)\n sublist = []\n subvallist.append(subslist)\n subslist = []\n\n for k in range(len(slices)):\n for l in range(len(filpix[k])):\n x = [j for j, y in enumerate(subvallist[k][l]) if y == k + 1]\n y = [j for j, z in enumerate(vallist[k][l]) if z == k + 1]\n\n if len(x) == 0:\n if debug:\n print(\"Extran removal unconnect: {}\".format(filpix[k][l]))\n labelfil[filpix[k][l][0], filpix[k][l][1]] = 0\n extran.append(filpix[k][l])\n\n if len(x) == 1:\n if len(y) >= 2:\n if debug:\n print(\"Extran removal: {}\".format(filpix[k][l]))\n extran.append(filpix[k][l])\n labelfil[filpix[k][l][0], filpix[k][l][1]] = 0\n # if len(extran) >= 2:\n # for i in extran:\n # for j in extran:\n # if i != j:\n # if distance(i[0], j[0], i[1], j[1]) == np.sqrt(2.0):\n # proximity = [(i[0], i[1] - 1),\n # (i[0], i[1] + 1),\n # (i[0] - 1, i[1]),\n # (i[0] + 1, i[1]),\n # (i[0] - 1, i[1] + 1),\n # (i[0] + 1, i[1] + 1),\n # (i[0] - 1, i[1] - 1),\n # (i[0] + 1, i[1] - 1)]\n # match = set(filpix[k]) & set(proximity)\n # if len(match) > 0:\n # for z in match:\n # labelfil[z[0], z[1]] = 0\n\n if debug:\n import matplotlib.pyplot as plt\n plt.imshow(labelfil, origin='lower')\n for pix in extran:\n plt.plot(pix[1], pix[0], 'bD')\n plt.draw()\n raw_input(\"?\")\n plt.clf()\n\n return labelfil\n\n\n######################################################################\n# Wrapper Functions\n######################################################################\n\n\ndef pix_identify(isolatefilarr, num, debug=False):\n '''\n This function is essentially a wrapper on find_filpix. It returns the\n outputs of find_filpix in the form that are used during the analysis.\n\n Parameters\n ----------\n isolatefilarr : list\n Contains individual arrays of each skeleton.\n num : int\n The number of skeletons.\n debug : bool, optional\n Print out identification steps in find_filpix.\n\n Returns\n -------\n interpts : list\n Contains lists of all intersections points in each skeleton.\n hubs : list\n Contains the number of intersections in each filament. This is\n useful for identifying those with no intersections as their analysis\n is straight-forward.\n ends : list\n Contains the positions of all end points in each skeleton.\n filbranches : list\n Contains the number of branches in each skeleton.\n labelisofil : list\n Contains individual arrays for each skeleton where the\n branches are labeled and the intersections have been removed.\n '''\n\n interpts = []\n hubs = []\n ends = []\n filbranches = []\n labelisofil = []\n\n for n in range(num):\n funcreturn = find_filpix(1, isolatefilarr[n], final=False, debug=debug)\n interpts.append(funcreturn[1])\n hubs.append(len(funcreturn[1]))\n isolatefilarr.pop(n)\n isolatefilarr.insert(n, funcreturn[2])\n ends.append(funcreturn[3])\n\n # isolatefilarr contains end and body pts. We need to make sure the end\n # points don't touch, and if they do, label them independently of the\n # others. Touching endpoints can only occur for 1-pixel branches\n\n # First label the end points\n ends_arr = np.zeros_like(isolatefilarr[n])\n for end in ends[n]:\n ends_arr[end[0], end[1]] = True\n end_label, num_end = nd.label(ends_arr, eight_con())\n # If none are connected, label normally\n if len(ends[n]) == num_end:\n label_branch, num_branch = nd.label(isolatefilarr[n], eight_con())\n else:\n # Find the connected ends, then label and remove them\n conn_ends = np.where(nd.sum(ends_arr, end_label,\n range(1, num_end + 1)) > 1)[0] + 1\n if conn_ends.size == 0:\n raise ValueError(\"This should not be possible, since \"\n \"num_end != len(ends[n]), but no connected\"\n \" structure was found? Possible bug.\")\n\n fil_arr = isolatefilarr[n].copy()\n\n end_branches = []\n for conn in conn_ends:\n end_posns = np.where(end_label == conn)\n for posn in zip(*end_posns):\n end_branches.append(posn)\n fil_arr[end_posns] = False\n\n # Label the version without those ends\n label_branch, num_branch = nd.label(fil_arr, eight_con())\n\n # Now re-add those connected ends with a new label\n for i, posn in enumerate(end_branches):\n label_branch[posn[0], posn[1]] = num_branch + i + 1\n\n num_branch = label_branch.max()\n\n filbranches.append(num_branch)\n labelisofil.append(label_branch)\n\n return interpts, hubs, ends, filbranches, labelisofil\n\n\ndef extremum_pts(labelisofil, extremum, ends):\n '''\n This function returns the the farthest extents of each filament. This\n is useful for determining how well the shortest path algorithm has worked.\n\n Parameters\n ----------\n labelisofil : list\n Contains individual arrays for each skeleton.\n extremum : list\n Contains the extents as determined by the shortest\n path algorithm.\n ends : list\n Contains the positions of each end point in eahch filament.\n\n Returns\n -------\n extrem_pts : list\n Contains the indices of the extremum points.\n '''\n\n num = len(labelisofil)\n extrem_pts = []\n\n for n in range(num):\n per_fil = []\n for i, j in ends[n]:\n if labelisofil[n][i, j] == extremum[n][0] or labelisofil[n][i, j] == extremum[n][1]:\n per_fil.append([i, j])\n extrem_pts.append(per_fil)\n\n return extrem_pts\n\n\ndef make_final_skeletons(labelisofil, inters, verbose=False, save_png=False,\n save_name=None):\n '''\n Creates the final skeletons outputted by the algorithm.\n\n Parameters\n ----------\n labelisofil : list\n List of labeled skeletons.\n inters : list\n Positions of the intersections in each skeleton.\n verbose : bool, optional\n Enables plotting of the final skeleton.\n save_png : bool, optional\n Saves the plot made in verbose mode. Disabled by default.\n save_name : str, optional\n For use when ``save_png`` is enabled.\n **MUST be specified when ``save_png`` is enabled.**\n\n Returns\n -------\n filament_arrays : list\n List of the final skeletons.\n '''\n\n filament_arrays = []\n\n for n, (skel_array, intersec) in enumerate(zip(labelisofil, inters)):\n copy_array = np.zeros(skel_array.shape, dtype=int)\n\n for inter in intersec:\n for pts in inter:\n x, y = pts\n copy_array[x, y] = 1\n\n copy_array[np.where(skel_array >= 1)] = 1\n\n cleaned_array = find_extran(1, copy_array)\n\n filament_arrays.append(cleaned_array)\n\n if verbose or save_png:\n if save_png and save_name is None:\n ValueError(\"Must give a save_name when save_png is enabled. No\"\n \" plots will be created.\")\n\n p.clf()\n p.imshow(cleaned_array, origin='lower', interpolation='nearest')\n\n if save_png:\n p.savefig(save_name)\n p.close()\n if verbose:\n p.show()\n if in_ipynb():\n p.clf()\n\n return filament_arrays\n\n\ndef recombine_skeletons(skeletons, offsets, orig_size, pad_size):\n '''\n Takes a list of skeleton arrays and combines them back into\n the original array.\n\n Parameters\n ----------\n skeletons : list\n Arrays of each skeleton.\n offsets : list\n Coordinates where the skeleton arrays have been sliced from the\n image.\n orig_size : tuple\n Size of the image.\n pad_size : int\n Size of the array padding.\n\n Returns\n -------\n master_array : numpy.ndarray\n Contains all skeletons placed in their original positions in the image.\n '''\n\n num = len(skeletons)\n\n master_array = np.zeros(orig_size)\n for n in range(num):\n # These are the coordinates of the bottom left in the master array.\n x_off, y_off = offsets[n][0]\n x_top, y_top = offsets[n][1]\n\n # Now check if padding will put the array outside of the original array\n # size\n excess_x_top = x_top - orig_size[0]\n\n excess_y_top = y_top - orig_size[1]\n\n copy_skeleton = copy.copy(skeletons[n])\n\n if excess_x_top > 0:\n copy_skeleton = copy_skeleton[:-excess_x_top, :]\n\n if excess_y_top > 0:\n copy_skeleton = copy_skeleton[:, :-excess_y_top]\n\n if x_off < 0:\n copy_skeleton = copy_skeleton[-x_off:, :]\n x_off = 0\n\n if y_off < 0:\n copy_skeleton = copy_skeleton[:, -y_off:]\n y_off = 0\n\n x, y = np.where(copy_skeleton >= 1)\n for i in range(len(x)):\n master_array[x[i] + x_off, y[i] + y_off] = 1\n\n return master_array\n\n\ndef _fix_small_holes(mask_array, rel_size=0.1):\n '''\n Helper function to remove only small holes within a masked region.\n\n Parameters\n ----------\n mask_array : numpy.ndarray\n Array containing the masked region.\n\n rel_size : float, optional\n If < 1.0, sets the minimum size a hole must be relative to the area\n of the mask. Otherwise, this is the maximum number of pixels the hole\n must have to be deleted.\n\n Returns\n -------\n mask_array : numpy.ndarray\n Altered array.\n '''\n\n if rel_size <= 0.0:\n raise ValueError(\"rel_size must be positive.\")\n elif rel_size > 1.0:\n pixel_flag = True\n else:\n pixel_flag = False\n\n # Find the region area\n reg_area = len(np.where(mask_array == 1)[0])\n\n # Label the holes\n holes = np.logical_not(mask_array).astype(float)\n lab_holes, n_holes = nd.label(holes, eight_con())\n\n # If no holes, return\n if n_holes == 1:\n return mask_array\n\n # Ignore area outside of the region.\n out_label = lab_holes[0, 0]\n # Set size to be just larger than the region. Thus it can never be\n # deleted.\n holes[np.where(lab_holes == out_label)] = reg_area + 1.\n\n # Sum up the regions and find holes smaller than the threshold.\n sums = nd.sum(holes, lab_holes, range(1, n_holes + 1))\n if pixel_flag: # Use number of pixels\n delete_holes = np.where(sums < rel_size)[0]\n else: # Use relative size of holes.\n delete_holes = np.where(sums / reg_area < rel_size)[0]\n\n # Return if there is nothing to delete.\n if len(delete_holes) == 0:\n return mask_array\n\n # Add one to take into account 0 in list if object label 1.\n delete_holes += 1\n for label in delete_holes:\n mask_array[np.where(lab_holes == label)] = 1\n\n return mask_array\n\n\ndef is_blockpoint(vallist):\n '''\n Determine if point is part of a block:\n [X X]\n [X X]\n\n Will have 3 connected sides, with one as an 8-connection.\n '''\n\n vals = np.array(vallist)\n\n if vals.sum() < 3:\n return False\n\n arrangements = [np.array([0, 1, 7]), np.array([1, 2, 3]),\n np.array([3, 4, 5]), np.array([5, 6, 7])]\n\n posns = np.where(vals)[0]\n\n # Check if all 3 in an arrangement are within the vallist\n for arrange in arrangements:\n if np.in1d(posns, arrange).sum() == 3:\n return True\n\n return False\n\n\ndef is_tpoint(vallist):\n '''\n Determine if point is part of a block:\n [X X X]\n [0 X 0]\n And all 90 deg rotation of this shape\n\n If there are only 3 connections, this is an end point. If there are 4,\n it is a body point, and if there are 5, it remains an intersection\n\n '''\n\n vals = np.array(vallist)\n\n if vals.sum() < 3:\n return False\n\n arrangements = [np.array([0, 6, 7]), np.array([0, 1, 2]),\n np.array([2, 3, 4]), np.array([4, 5, 6])]\n\n posns = np.where(vals)[0]\n\n # Check if all 3 in an arrangement are within the vallist\n for arrange in arrangements:\n if np.in1d(posns, arrange).sum() == 3:\n return True\n\n return False\n\n\ndef merge_nodes(node, G):\n '''\n Combine a node into its neighbors.\n '''\n\n neigb = list(G[node])\n\n if len(neigb) != 2:\n return G\n\n new_weight = G[node][neigb[0]]['weight'] + \\\n G[node][neigb[1]]['weight']\n\n G.remove_node(node)\n G.add_edge(neigb[0], neigb[1], weight=new_weight)\n\n return G\n"
] | [
[
"numpy.logical_not",
"matplotlib.pyplot.imshow",
"numpy.sqrt",
"numpy.in1d",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.plot",
"numpy.ones",
"matplotlib.pyplot.clf",
"numpy.zeros_like",
"matplotlib.pyplot.close",
"numpy.array",
"numpy.zeros",
"numpy.where",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kevinjacksonm/eudract_ae | [
"3769ef63326c0ce3a8052cd6f28ced3690a78e88"
] | [
"eudract_ae.py"
] | [
"\nfrom lxml import etree\nimport argparse\nimport os\nimport pandas as pd\n\n# names of spreadsheets created by SP, one for serious events and one for non-serious events\nnsae_xlsx=\"t-teae-nonser-5pct.xlsx\"\nsae_xlsx =\"t-teae-ser.xlsx\"\n\n# set up XML namespaces necessary EudraCT XML file\n\nns_eudra_ae=\"http://eudract.ema.europa.eu/schema/clinical_trial_result/adverse_events\"\nns_xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\n# create dictionary of XML namespace mappings\nNSMAP = { \"ae\" : ns_eudra_ae,\n\t\t\t\t\t\"xsi\" : ns_xsi}\n\n# Suppress pandas warning\t\t\t\t\t\t\npd.options.mode.chained_assignment = None\n\n# Read Body System Code lookup from an outside spreadsheet into dataframe\ndf_spor_lookup = pd.read_excel(\"SPOR_lookup.xlsx\", sheet_name=\"Terms\")\nspor_id=dict(zip(df_spor_lookup.Body_System, df_spor_lookup.SPOR_identifier))\nspor_version=df_spor_lookup.Version[0]\nspor_term_version=dict(zip(df_spor_lookup.Body_System, df_spor_lookup.Version))\n\t\t\n###################################################################\n# Parse and validate command line arguments\n###################################################################\nparser = argparse.ArgumentParser(description='Eudra CT utility ')\nparser.add_argument('-d','--directory',\t\thelp='Directory path where Eudra CT spreadsheets are located')\nparser.add_argument('-f','--file',\t\t\t help='Name of adverse events XML output file (without XML extension)')\n\nargs = parser.parse_args()\n\nfilename=\"eudract_adverse_events.xml\"\nif (args.file):\n\t\tfilename=args.file+\".xml\"\n\nif (args.directory):\n\t\tdirectory=args.directory\n\t\tif not directory.endswith('/'):\n\t\t\t\tdirectory=args.directory+'/';\t\t\n\t\tif not (os.path.exists(directory)):\n\t\t\t\tprint ('Directory ' + directory + 'specified in -d parameter does not exist')\n\t\t\t\texit(1)\n\t\telse:\n\t\t\t\tif not os.path.isfile(directory+nsae_xlsx) or not os.path.isfile(directory+sae_xlsx):\n\t\t\t\t\t\tprint (\"Cannot locate one or both of spreadsheets\", nsae_xlsx, 'or', sae_xlsx, 'in directory', directory)\n\t\t\t\t\t\texit(1)\n\t\tfilename=directory+filename\n\t\tprint (filename)\nelse:\n\t\tprint ('Directory ' + directory + ' must specified in -d parameter')\n\t\texit(1)\n\n###################################################################\n# Write XML out to file\n#\n# root - root node of XML\n###################################################################\ndef write_xml(root):\n\n\t\t# doing this makes pretty_print work\n\t\tfor element in root.iter():\n\t\t element.tail = None\n\t\t\t\n\t\t# create the xml string\n\t\tobj_xml = etree.tostring(root,\n\t\t pretty_print=True,\n\t\t xml_declaration=True, \n\t\t encoding='UTF-8')\n\t\t\n\t\t\n\t\twith open(filename, \"wb\") as xml_writer:\n\t\t\t\txml_writer.write(obj_xml)\n\n###################################################################\n# Build reporting groups section of XML file\n#\n# df_counts = dataframe loaded from spreadsheet with overall counts\n###################################################################\ndef build_xml_reporting_groups(node, df_counts):\n repgroups_node=etree.SubElement(node,\"reportingGroups\")\n\n for index, row in df_counts.iterrows():\n repgroupnode=etree.SubElement(repgroups_node,\"reportingGroup\")\n \n repgroupnode.set(\"id\",\"ReportingGroup-\"+str(index))\n \n title=etree.SubElement(repgroupnode,\"title\")\n \n rpname=row[\"Treatment_Groups\"]\n if len(rpname)>1:\n \t\ttitle.text=rpname \t\n else:\n \t\ttitle.text='Group ' + rpname \t\t\n\n description=etree.SubElement(repgroupnode,\"description\")\n description.text=\"Patients who received \"+rpname\n subs_affected_nsae=etree.SubElement(repgroupnode,\"subjectsAffectedByNonSeriousAdverseEvents\")\n subs_affected_nsae.text=str(int(row[\"NSAE_Subjects_Affected\"])) \n subs_affected_sae=etree.SubElement(repgroupnode,\"subjectsAffectedBySeriousAdverseEvents\")\n subs_affected_sae.text=str(int(row[\"SAE_Subjects_Affected\"]))\n subs_exposed=etree.SubElement(repgroupnode,\"subjectsExposed\")\n subs_exposed.text=str(int(row[\"Subjects_Exposed_Number\"]))\n deaths_all_causes=etree.SubElement(repgroupnode,\"deathsAllCauses\")\n if not pd.isna(row[\"Fatalities_Number\"]): \t\t\t\t\t\n \t\tdeaths_all_causes.text=str(int(row[\"Fatalities_Number\"]))\n else:\n deaths_all_causes.text=\"0\" \n deaths_resulting_from_aes=etree.SubElement(repgroupnode,\"deathsResultingFromAdverseEvents\")\n if not pd.isna(row[\"Fatalities_Causally_Related_to_Treatment_Number\"]): \n deaths_resulting_from_aes.text=str(int(row[\"Fatalities_Causally_Related_to_Treatment_Number\"]))\n else:\n deaths_resulting_from_aes.text=\"0\"\n\n###################################################################\n# Build non-serious adverse events XML\n#\n# node = parent node with tag <ae:adverseEvents>\n# df_terms = dataframe loaded from non-serious ae spreadsheet\n# reporting_groups = dictionary of reportting groups with ID #\n###################################################################\ndef build_xml_non_serious_events(node, df_terms, reporting_groups):\n \n\t\t# non-serious adverse events\n\t\tnsaes=etree.SubElement(node,\"nonSeriousAdverseEvents\")\n\t\torgan_system=\"\"\n\t\tpref_term=\"\"\n\t\tfor index, row in df_terms.iterrows():\n\t\t\t\tif organ_system != row[\"System_Organ_Class\"] or pref_term != row[\"Preferred_Term\"]:\n\t\t\t\t\t\torgan_system = row[\"System_Organ_Class\"]\n\t\t\t\t\t\tpref_term = row[\"Preferred_Term\"]\n\t\t\t\t\t\tnsae=etree.SubElement(nsaes,\"nonSeriousAdverseEvent\")\n\t\t\t\t\t\tterm=etree.SubElement(nsae,\"term\")\n\t\t\t\t\t\tterm.text=pref_term\n\t\t\t\t\t\tsoc=etree.SubElement(nsae,\"organSystem\")\n\t\t\t\t\t\teutctid=etree.SubElement(soc,\"eutctId\")\n\t\t\t\t\t\teutctid.text=str(spor_id[organ_system])\n\t\t\t\t\t\tversion=etree.SubElement(soc,\"version\")\n\t\t\t\t\t\tversion.text=str(spor_term_version[organ_system])\n\t\t\t\t\t\tassessmth=etree.SubElement(nsae,\"assessmentMethod\")\n\t\t\t\t\t\tdict_override=etree.SubElement(nsae,\"dictionaryOverridden\")\n\t\t\t\t\t\tdict_override.text='false'\n\t\t\t\t\t\tvalue=etree.SubElement(assessmth,\"value\")\n\t\t\t\t\t\tvalue.text=\"ADV_EVT_ASSESS_TYPE.systematic\"\n\t\t\t\t\t\tvalues=etree.SubElement(nsae,\"values\")\n\n\t\t\t\tvalue=etree.SubElement(values,\"value\")\n\t\t\t\trpname=row[\"Treatment_Groups\"]\n\t\t\t\tvalue.set(\"reportingGroupId\",\"ReportingGroup-\"+reporting_groups[row[\"Treatment_Groups\"]])\n\t\t\t\toccurrences=etree.SubElement(value,\"occurrences\")\n\t\t\t\toccurrences.text=str(int(row[\"Occurrences_All_Number\"]))\n\t\t\t\tsubs_affected=etree.SubElement(value,\"subjectsAffected\")\n\t\t\t\tsubs_affected.text=str(row[\"Subjects_Affected_Number\"])\n\t\t\t\tsubs_exposed=etree.SubElement(value,\"subjectsExposed\")\n\t\t\t\tsubs_exposed.text=str(int(row[\"Subjects_Exposed_Number\"]))\n\n###################################################################\n# Build serious adverse events XML\n#\n# node = parent node with tag <ae:adverseEvents>\n# df_terms = dataframe loaded from serious ae spreadsheet\n# reporting_groups = dictionary of reportting groups with ID #\n################################################################### \ndef build_xml_serious_events(node, df_terms, reporting_groups):\n \n\t\t# serious adverse events\n\t\tsaes=etree.SubElement(node,\"seriousAdverseEvents\")\n\t\torgan_system=\"\"\n\t\tpref_term=\"\"\n\t\tfor index, row in df_terms.iterrows():\n\t\t\t\tif organ_system != row[\"System_Organ_Class\"] or pref_term != row[\"Preferred_Term\"]:\n\t\t\t\t\t\torgan_system = row[\"System_Organ_Class\"]\n\t\t\t\t\t\tpref_term = row[\"Preferred_Term\"]\n\t\t\t\t\t\tsae=etree.SubElement(saes,\"seriousAdverseEvent\") \n\t\t\t\t\t\tterm=etree.SubElement(sae,\"term\")\n\t\t\t\t\t\tterm.text=pref_term\n\t\t\t\t\t\tsoc=etree.SubElement(sae,\"organSystem\")\n\t\t\t\t\t\teutctid=etree.SubElement(soc,\"eutctId\")\n\t\t\t\t\t\teutctid.text=str(spor_id[organ_system])\n\t\t\t\t\t\tversion=etree.SubElement(soc,\"version\")\n\t\t\t\t\t\tversion.text=str(spor_term_version[organ_system])\n\t\t\t\t\t\tassessmth=etree.SubElement(sae,\"assessmentMethod\")\n\t\t\t\t\t\tdict_override=etree.SubElement(sae,\"dictionaryOverridden\")\n\t\t\t\t\t\tdict_override.text='false'\n\t\t\t\t\t\tvalue=etree.SubElement(assessmth,\"value\")\n\t\t\t\t\t\tvalue.text=\"ADV_EVT_ASSESS_TYPE.systematic\"\n\t\t\t\t\t\tvalues=etree.SubElement(sae,\"values\")\n\n\t\t\t\tvalue=etree.SubElement(values,\"value\")\n\t\t\t\trpname=row[\"Treatment_Groups\"]\n\t\t\t\t#print (reporting_groups[rpname])\n\t\t\t\tvalue.set(\"reportingGroupId\",\"ReportingGroup-\"+reporting_groups[row[\"Treatment_Groups\"]])\n\t\t\t\toccurrences=etree.SubElement(value,\"occurrences\")\n\t\t\t\toccurrences.text=str(int(row[\"Occurrences_All_Number\"]))\n\t\t\t\tsubs_affected=etree.SubElement(value,\"subjectsAffected\")\n\t\t\t\tsubs_affected.text=str(int(row[\"Subjects_Affected_Number\"]))\n\t\t\t\tsubs_exposed=etree.SubElement(value,\"subjectsExposed\")\n\t\t\t\tsubs_exposed.text=str(int(row[\"Subjects_Exposed_Number\"]))\n\n\t\t\t\tocrttn=etree.SubElement(value,\"occurrencesCausallyRelatedToTreatment\")\n\t\t\t\tif not pd.isna(row[\"Occurrences_Causally_Related_to_Treatment_Number\"]):\n\t\t\t\t ocrttn.text=str(int(row[\"Occurrences_Causally_Related_to_Treatment_Number\"]))\n\t\t\t\telse:\n\t\t\t\t ocrttn.text=\"0\"\n\t\t\t\tfatalities=etree.SubElement(value,\"fatalities\")\n\t\t\t\tdeaths=etree.SubElement(fatalities,\"deaths\")\n\t\t\t\tif not pd.isna(row[\"Fatalities_Number\"]):\n\t\t\t\t deaths.text=str(int(row[\"Fatalities_Number\"]))\n\t\t\t\telse: \n\t\t\t\t deaths.text=\"0\"\n\t\t\t\tdcrtt=etree.SubElement(fatalities,\"deathsCausallyRelatedToTreatment\") \n\t\t\t\tif not pd.isna(row[\"Fatalities_Causally_Related_to_Treatment_Number\"]):\n\t\t\t\t dcrtt.text=str(int(row[\"Fatalities_Causally_Related_to_Treatment_Number\"]))\n\t\t\t\telse:\n\t\t\t\t dcrtt.text=\"0\"\n\n###################################################################\n# Main function\n#\n# Read Spreadsheets into dataframe\n# Create dataframe with overall counts for reporting groups section\n# Create dataframe with serious adverse events\n# Create dataframe wtih non-serious adverse events\n################################################################### \ndef build_XML():\n\t\n\t\t# load non-serious adverse event data from xlsx file to pandas dataframe\n\t\tdf_nsae = pd.read_excel(directory + nsae_xlsx, sheet_name=0)\n\t\tdf_nsae.Treatment_Groups=df_nsae.Treatment_Groups.str.replace('~ ', '')\n\n\t\t# Get rows with overall count by reporting group. Overall count rows have System Organ Class = null\n\t\tdf_nsae_counts=df_nsae[df_nsae.System_Organ_Class.isnull()]\n\t\tdf_nsae_counts=df_nsae_counts[[\"Treatment_Groups\",\"Subjects_Affected_Number\",\"Subjects_Exposed_Number\"]]\n\t\tdf_nsae_counts.rename(columns={\"Subjects_Affected_Number\": \"NSAE_Subjects_Affected\"}, inplace=True)\n\t\t\n\t\t# Get rows with individual terms into dataframe\n\t\tdf_nsae_terms=df_nsae[df_nsae.System_Organ_Class.notnull()]\n\t\tdf_nsae_terms.Occurrences_All_Number = df_nsae_terms.Occurrences_All_Number.astype('int64')\n\t\tdf_nsae_terms.MedDRA_Version = df_nsae_terms.MedDRA_Version.astype('int64')\n\n\t\t# load serious adverse event data from xlsx file to pandas dataframe\n\t\tdf_sae = pd.read_excel(directory + sae_xlsx, sheet_name=0)\n\t\tdf_sae.Treatment_Groups=df_sae.Treatment_Groups.str.replace('~ ', '')\t\t\n\n\t\t# Get rows with overall count by reporting group\n\t\tdf_sae_counts=df_sae[df_sae.System_Organ_Class.isnull()]\n\t\tdf_sae_counts=df_sae_counts[[\"Treatment_Groups\",\"Subjects_Affected_Number\",\"Fatalities_Number\",\"Fatalities_Causally_Related_to_Treatment_Number\"]]\n\t\tdf_sae_counts.rename(columns={\"Subjects_Affected_Number\": \"SAE_Subjects_Affected\"}, inplace=True)\n\t\tdf_sae_counts.Treatment_Groups=df_sae_counts.Treatment_Groups.str.replace('~ ', '')\n\t\tprint (df_sae_counts)\n\t\t\n\t\t# Get rows with individual terms into dataframe\t\t\t\n\t\tdf_sae_terms=df_sae[df_sae.System_Organ_Class.notnull()]\n\t\tdf_sae_terms.MedDRA_Version = df_sae_terms.MedDRA_Version.astype('int64')\n\t\t\n\t\t# Merge SAE and NSAE count dataframes to get all counts we need into one row on a dataframe\n\t\tdf_combined_counts=pd.merge(how='inner', left=df_sae_counts, right=df_nsae_counts, left_on='Treatment_Groups', right_on='Treatment_Groups')\n\t\t#df_combined_counts.Fatalities_Number = df_combined_counts.Fatalities_Number.astype('int64')\n\n\t\t# create adverse event element which is root element of entire file\n\t\tae=etree.Element(\"{%s}adverseEvents\" % (ns_eudra_ae), nsmap = NSMAP)\n\t\tthrshold=etree.SubElement(ae,\"nonSeriousEventFrequencyThreshold\")\n\t\t\n\t\t# non-serious event threshhold is always 5\n\t\tthrshold.text=\"5\"\n\t\ttimeframe=etree.SubElement(ae,\"timeFrame\")\n\t\ttimeframe.text=\"timeframe text\"\n\t\n\t\t# assessment method is always the same, thus hardcoded\n\t\tassessmth=etree.SubElement(ae,\"assessmentMethod\")\n\t\tvalue=etree.SubElement(assessmth,\"value\")\n\t\tvalue.text=\"ADV_EVT_ASSESS_TYPE.systematic\"\n\n\t\t# dictionary info \n\t\tdictionary=etree.SubElement(ae,\"dictionary\")\n\t\tothername=etree.SubElement(dictionary,\"otherName\")\n\t\tothername.set(\"{%s}nil\" % (ns_xsi), \"true\")\n\t\tversion=etree.SubElement(dictionary,\"version\")\n\t\tversion.text=str(spor_version)\n\t\tdictname=etree.SubElement(dictionary,\"name\")\n\t\tvalue=etree.SubElement(dictname,\"value\")\n\t\tvalue.text=\"ADV_EVT_DICTIONARY_NAME.meddra\"\n\n\t\t# create dictionary of treatment group names to reporting group id. used later to tie reporting groups in individual terms\n\t\treporting_groups = {}\n\t\tstandard_cols=[\"adverseEventType\",\"assessmentType\",\"additionalDescription\",\"organSystemName\",\"sourceVocabulary\",\"term\"]\n\t\tfor index, row in df_combined_counts.iterrows():\n\t\t reporting_groups[row[\"Treatment_Groups\"]]=str(index)\t\t\n\t\t \n\t\t# build XML nodes\n\t\tbuild_xml_reporting_groups(ae, df_combined_counts)\n\t\tbuild_xml_non_serious_events(ae, df_nsae_terms, reporting_groups)\n\t\tbuild_xml_serious_events(ae, df_sae_terms, reporting_groups)\n\t\t\n\t\t# write XML out to file\n\t\twrite_xml(ae)\n\t\t\nbuild_XML()\n\n"
] | [
[
"pandas.isna",
"pandas.merge",
"pandas.read_excel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"0.24",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
hanseungwook/BigGAN-PyTorch | [
"d9314ee435efec7cd921a23271398761f4d1df84"
] | [
"inception_utils_baseline.py"
] | [
"''' Inception utilities\n This file contains methods for calculating IS and FID, using either\n the original numpy code or an accelerated fully-pytorch version that \n uses a fast newton-schulz approximation for the matrix sqrt. There are also\n methods for acquiring a desired number of samples from the Generator,\n and parallelizing the inbuilt PyTorch inception network.\n \n NOTE that Inception Scores and FIDs calculated using these methods will \n *not* be directly comparable to values calculated using the original TF\n IS/FID code. You *must* use the TF model if you wish to report and compare\n numbers. This code tends to produce IS values that are 5-10% lower than\n those obtained through TF. \n''' \nimport numpy as np\nfrom scipy import linalg # For numpy FID\nimport time\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import Parameter as P\nfrom torchvision.models.inception import inception_v3\n\n\n# Module that wraps the inception network to enable use with dataparallel and\n# returning pool features and logits.\nclass WrapInception(nn.Module):\n def __init__(self, net):\n super(WrapInception,self).__init__()\n self.net = net\n self.mean = P(torch.tensor([0.485, 0.456, 0.406]).view(1, -1, 1, 1),\n requires_grad=False)\n self.std = P(torch.tensor([0.229, 0.224, 0.225]).view(1, -1, 1, 1),\n requires_grad=False)\n def forward(self, x):\n # Normalize x\n x = (x + 1.) / 2.0\n x = (x - self.mean) / self.std\n # Upsample if necessary\n if x.shape[2] != 299 or x.shape[3] != 299:\n x = F.interpolate(x, size=(299, 299), mode='bilinear', align_corners=True)\n # 299 x 299 x 3\n x = self.net.Conv2d_1a_3x3(x)\n # 149 x 149 x 32\n x = self.net.Conv2d_2a_3x3(x)\n # 147 x 147 x 32\n x = self.net.Conv2d_2b_3x3(x)\n # 147 x 147 x 64\n x = F.max_pool2d(x, kernel_size=3, stride=2)\n # 73 x 73 x 64\n x = self.net.Conv2d_3b_1x1(x)\n # 73 x 73 x 80\n x = self.net.Conv2d_4a_3x3(x)\n # 71 x 71 x 192\n x = F.max_pool2d(x, kernel_size=3, stride=2)\n # 35 x 35 x 192\n x = self.net.Mixed_5b(x)\n # 35 x 35 x 256\n x = self.net.Mixed_5c(x)\n # 35 x 35 x 288\n x = self.net.Mixed_5d(x)\n # 35 x 35 x 288\n x = self.net.Mixed_6a(x)\n # 17 x 17 x 768\n x = self.net.Mixed_6b(x)\n # 17 x 17 x 768\n x = self.net.Mixed_6c(x)\n # 17 x 17 x 768\n x = self.net.Mixed_6d(x)\n # 17 x 17 x 768\n x = self.net.Mixed_6e(x)\n # 17 x 17 x 768\n # 17 x 17 x 768\n x = self.net.Mixed_7a(x)\n # 8 x 8 x 1280\n x = self.net.Mixed_7b(x)\n # 8 x 8 x 2048\n x = self.net.Mixed_7c(x)\n # 8 x 8 x 2048\n pool = torch.mean(x.view(x.size(0), x.size(1), -1), 2)\n # 1 x 1 x 2048\n logits = self.net.fc(F.dropout(pool, training=False).view(pool.size(0), -1))\n # 1000 (num_classes)\n return pool, logits\n\n\n# A pytorch implementation of cov, from Modar M. Alfadly\n# https://discuss.pytorch.org/t/covariance-and-gradient-support/16217/2\ndef torch_cov(m, rowvar=False):\n '''Estimate a covariance matrix given data.\n Covariance indicates the level to which two variables vary together.\n If we examine N-dimensional samples, `X = [x_1, x_2, ... x_N]^T`,\n then the covariance matrix element `C_{ij}` is the covariance of\n `x_i` and `x_j`. The element `C_{ii}` is the variance of `x_i`.\n Args:\n m: A 1-D or 2-D array containing multiple variables and observations.\n Each row of `m` represents a variable, and each column a single\n observation of all those variables.\n rowvar: If `rowvar` is True, then each row represents a\n variable, with observations in the columns. Otherwise, the\n relationship is transposed: each column represents a variable,\n while the rows contain observations.\n Returns:\n The covariance matrix of the variables.\n '''\n if m.dim() > 2:\n raise ValueError('m has more than 2 dimensions')\n if m.dim() < 2:\n m = m.view(1, -1)\n if not rowvar and m.size(0) != 1:\n m = m.t()\n # m = m.type(torch.double) # uncomment this line if desired\n fact = 1.0 / (m.size(1) - 1)\n m -= torch.mean(m, dim=1, keepdim=True)\n mt = m.t() # if complex: mt = m.t().conj()\n return fact * m.matmul(mt).squeeze()\n\n\n# Pytorch implementation of matrix sqrt, from Tsung-Yu Lin, and Subhransu Maji\n# https://github.com/msubhransu/matrix-sqrt \ndef sqrt_newton_schulz(A, numIters, dtype=None):\n with torch.no_grad():\n if dtype is None:\n dtype = A.type()\n batchSize = A.shape[0]\n dim = A.shape[1]\n normA = A.mul(A).sum(dim=1).sum(dim=1).sqrt()\n Y = A.div(normA.view(batchSize, 1, 1).expand_as(A));\n I = torch.eye(dim,dim).view(1, dim, dim).repeat(batchSize,1,1).type(dtype)\n Z = torch.eye(dim,dim).view(1, dim, dim).repeat(batchSize,1,1).type(dtype)\n for i in range(numIters):\n T = 0.5*(3.0*I - Z.bmm(Y))\n Y = Y.bmm(T)\n Z = T.bmm(Z)\n sA = Y*torch.sqrt(normA).view(batchSize, 1, 1).expand_as(A)\n return sA\n\n\n# FID calculator from TTUR--consider replacing this with GPU-accelerated cov\n# calculations using torch?\ndef numpy_calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):\n \"\"\"Numpy implementation of the Frechet Distance.\n Taken from https://github.com/bioinf-jku/TTUR\n The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)\n and X_2 ~ N(mu_2, C_2) is\n d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).\n Stable version by Dougal J. Sutherland.\n Params:\n -- mu1 : Numpy array containing the activations of a layer of the\n inception net (like returned by the function 'get_predictions')\n for generated samples.\n -- mu2 : The sample mean over activations, precalculated on an \n representive data set.\n -- sigma1: The covariance matrix over activations for generated samples.\n -- sigma2: The covariance matrix over activations, precalculated on an \n representive data set.\n Returns:\n -- : The Frechet Distance.\n \"\"\"\n\n mu1 = np.atleast_1d(mu1)\n mu2 = np.atleast_1d(mu2)\n\n sigma1 = np.atleast_2d(sigma1)\n sigma2 = np.atleast_2d(sigma2)\n\n assert mu1.shape == mu2.shape, \\\n 'Training and test mean vectors have different lengths'\n assert sigma1.shape == sigma2.shape, \\\n 'Training and test covariances have different dimensions'\n\n diff = mu1 - mu2\n\n # Product might be almost singular\n covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)\n if not np.isfinite(covmean).all():\n msg = ('fid calculation produces singular product; '\n 'adding %s to diagonal of cov estimates') % eps\n print(msg)\n offset = np.eye(sigma1.shape[0]) * eps\n covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))\n\n # Numerical error might give slight imaginary component\n if np.iscomplexobj(covmean):\n print('wat')\n if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):\n m = np.max(np.abs(covmean.imag))\n raise ValueError('Imaginary component {}'.format(m))\n covmean = covmean.real \n\n tr_covmean = np.trace(covmean) \n\n out = diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean\n return out\n\n\ndef torch_calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):\n \"\"\"Pytorch implementation of the Frechet Distance.\n Taken from https://github.com/bioinf-jku/TTUR\n The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)\n and X_2 ~ N(mu_2, C_2) is\n d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).\n Stable version by Dougal J. Sutherland.\n Params:\n -- mu1 : Numpy array containing the activations of a layer of the\n inception net (like returned by the function 'get_predictions')\n for generated samples.\n -- mu2 : The sample mean over activations, precalculated on an \n representive data set.\n -- sigma1: The covariance matrix over activations for generated samples.\n -- sigma2: The covariance matrix over activations, precalculated on an \n representive data set.\n Returns:\n -- : The Frechet Distance.\n \"\"\"\n\n\n assert mu1.shape == mu2.shape, \\\n 'Training and test mean vectors have different lengths'\n assert sigma1.shape == sigma2.shape, \\\n 'Training and test covariances have different dimensions'\n\n diff = mu1 - mu2\n # Run 50 itrs of newton-schulz to get the matrix sqrt of sigma1 dot sigma2\n covmean = sqrt_newton_schulz(sigma1.mm(sigma2).unsqueeze(0), 50).squeeze() \n out = (diff.dot(diff) + torch.trace(sigma1) + torch.trace(sigma2)\n - 2 * torch.trace(covmean))\n return out\n\n\n# Calculate Inception Score mean + std given softmax'd logits and number of splits\ndef calculate_inception_score(pred, num_splits=10):\n scores = []\n for index in range(num_splits):\n pred_chunk = pred[index * (pred.shape[0] // num_splits): (index + 1) * (pred.shape[0] // num_splits), :]\n kl_inception = pred_chunk * (np.log(pred_chunk) - np.log(np.expand_dims(np.mean(pred_chunk, 0), 0)))\n kl_inception = np.mean(np.sum(kl_inception, 1))\n scores.append(np.exp(kl_inception))\n return np.mean(scores), np.std(scores)\n\n\n# Loop and run the sampler and the net until it accumulates num_inception_images\n# activations. Return the pool, the logits, and the labels (if one wants \n# Inception Accuracy the labels of the generated class will be needed)\ndef accumulate_inception_activations(sample, net, num_inception_images=50000):\n pool, logits, labels = [], [], []\n while (torch.cat(logits, 0).shape[0] if len(logits) else 0) < num_inception_images:\n with torch.no_grad():\n images, labels_val = sample()\n pool_val, logits_val = net(images.float())\n pool += [pool_val]\n logits += [F.softmax(logits_val, 1)]\n labels += [labels_val]\n return torch.cat(pool, 0), torch.cat(logits, 0), torch.cat(labels, 0)\n\n\n# Load and wrap the Inception model\ndef load_inception_net(parallel=False):\n inception_model = inception_v3(pretrained=True, transform_input=False)\n inception_model = WrapInception(inception_model.eval()).cuda()\n if parallel:\n print('Parallelizing Inception module...')\n inception_model = nn.DataParallel(inception_model)\n return inception_model\n\n\n# This produces a function which takes in an iterator which returns a set number of samples\n# and iterates until it accumulates config['num_inception_images'] images.\n# The iterator can return samples with a different batch size than used in\n# training, using the setting confg['inception_batchsize']\ndef prepare_inception_metrics(dataset, parallel, no_fid=False):\n # Load metrics; this is intentionally not in a try-except loop so that\n # the script will crash here if it cannot find the Inception moments.\n # By default, remove the \"hdf5\" from dataset\n dataset = dataset.strip('_hdf5')\n data_mu = np.load(dataset+'_inception_moments.npz')['mu']\n data_sigma = np.load(dataset+'_inception_moments.npz')['sigma']\n # Load network\n net = load_inception_net(parallel)\n def get_inception_metrics(sample, num_inception_images, num_splits=10, \n prints=True, use_torch=True):\n if prints:\n print('Gathering activations...')\n pool, logits, labels = accumulate_inception_activations(sample, net, num_inception_images)\n if prints: \n print('Calculating Inception Score...')\n IS_mean, IS_std = calculate_inception_score(logits.cpu().numpy(), num_splits)\n if no_fid:\n FID = 9999.0\n else:\n if prints:\n print('Calculating means and covariances...')\n if use_torch:\n mu, sigma = torch.mean(pool, 0), torch_cov(pool, rowvar=False)\n else:\n mu, sigma = np.mean(pool.cpu().numpy(), axis=0), np.cov(pool.cpu().numpy(), rowvar=False)\n if prints:\n print('Covariances calculated, getting FID...')\n if use_torch:\n FID = torch_calculate_frechet_distance(mu, sigma, torch.tensor(data_mu).float().cuda(), torch.tensor(data_sigma).float().cuda())\n FID = float(FID.cpu().numpy())\n else:\n FID = numpy_calculate_frechet_distance(mu.cpu().numpy(), sigma.cpu().numpy(), data_mu, data_sigma)\n # Delete mu, sigma, pool, logits, and labels, just in case\n del mu, sigma, pool, logits, labels\n return IS_mean, IS_std, FID\n return get_inception_metrics"
] | [
[
"torch.mean",
"torch.nn.functional.softmax",
"torch.cat",
"torch.nn.functional.dropout",
"torch.no_grad",
"numpy.mean",
"torch.nn.functional.interpolate",
"numpy.iscomplexobj",
"numpy.exp",
"torch.trace",
"numpy.trace",
"torch.sqrt",
"numpy.eye",
"torch.eye",
"torch.tensor",
"numpy.atleast_1d",
"numpy.std",
"numpy.load",
"torch.nn.functional.max_pool2d",
"numpy.log",
"numpy.atleast_2d",
"numpy.sum",
"numpy.diagonal",
"numpy.abs",
"numpy.isfinite",
"torch.nn.DataParallel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
donna-legal/allennlp | [
"fd1e3cfaed07ec3ba03b922d12eee47f8be16837"
] | [
"allennlp/nn/util.py"
] | [
"\"\"\"\nAssorted utilities for working with neural networks in AllenNLP.\n\"\"\"\n\nfrom collections import defaultdict\nfrom typing import Any, Dict, List, Optional, Sequence, Tuple, TypeVar, Union\nimport logging\nimport copy\nimport math\nimport json\nimport numpy\n\nimport torch\n\nfrom allennlp.common.checks import ConfigurationError\n\nlogger = logging.getLogger(__name__)\n\nT = TypeVar(\"T\")\n\n\ndef has_tensor(obj) -> bool:\n \"\"\"\n Given a possibly complex data structure,\n check if it has any torch.Tensors in it.\n \"\"\"\n if isinstance(obj, torch.Tensor):\n return True\n elif isinstance(obj, dict):\n return any(has_tensor(value) for value in obj.values())\n elif isinstance(obj, (list, tuple)):\n return any(has_tensor(item) for item in obj)\n else:\n return False\n\n\ndef move_to_device(obj, cuda_device: int):\n \"\"\"\n Given a structure (possibly) containing Tensors on the CPU,\n move all the Tensors to the specified GPU (or do nothing, if they should be on the CPU).\n \"\"\"\n\n if cuda_device < 0 or not has_tensor(obj):\n return obj\n elif isinstance(obj, torch.Tensor):\n return obj.cuda(cuda_device)\n elif isinstance(obj, dict):\n return {key: move_to_device(value, cuda_device) for key, value in obj.items()}\n elif isinstance(obj, list):\n return [move_to_device(item, cuda_device) for item in obj]\n elif isinstance(obj, tuple) and hasattr(obj, \"_fields\"):\n # This is the best way to detect a NamedTuple, it turns out.\n return obj.__class__(*[move_to_device(item, cuda_device) for item in obj])\n elif isinstance(obj, tuple):\n return tuple([move_to_device(item, cuda_device) for item in obj])\n else:\n return obj\n\n\ndef clamp_tensor(tensor, minimum, maximum):\n \"\"\"\n Supports sparse and dense tensors.\n Returns a tensor with values clamped between the provided minimum and maximum,\n without modifying the original tensor.\n \"\"\"\n if tensor.is_sparse:\n coalesced_tensor = tensor.coalesce()\n\n coalesced_tensor._values().clamp_(minimum, maximum)\n return coalesced_tensor\n else:\n return tensor.clamp(minimum, maximum)\n\n\ndef batch_tensor_dicts(\n tensor_dicts: List[Dict[str, torch.Tensor]], remove_trailing_dimension: bool = False\n) -> Dict[str, torch.Tensor]:\n \"\"\"\n Takes a list of tensor dictionaries, where each dictionary is assumed to have matching keys,\n and returns a single dictionary with all tensors with the same key batched together.\n\n Parameters\n ----------\n tensor_dicts : ``List[Dict[str, torch.Tensor]]``\n The list of tensor dictionaries to batch.\n remove_trailing_dimension : ``bool``\n If ``True``, we will check for a trailing dimension of size 1 on the tensors that are being\n batched, and remove it if we find it.\n \"\"\"\n key_to_tensors: Dict[str, List[torch.Tensor]] = defaultdict(list)\n for tensor_dict in tensor_dicts:\n for key, tensor in tensor_dict.items():\n key_to_tensors[key].append(tensor)\n batched_tensors = {}\n for key, tensor_list in key_to_tensors.items():\n batched_tensor = torch.stack(tensor_list)\n if remove_trailing_dimension and all(tensor.size(-1) == 1 for tensor in tensor_list):\n batched_tensor = batched_tensor.squeeze(-1)\n batched_tensors[key] = batched_tensor\n return batched_tensors\n\n\ndef get_lengths_from_binary_sequence_mask(mask: torch.Tensor):\n \"\"\"\n Compute sequence lengths for each batch element in a tensor using a\n binary mask.\n\n Parameters\n ----------\n mask : torch.Tensor, required.\n A 2D binary mask of shape (batch_size, sequence_length) to\n calculate the per-batch sequence lengths from.\n\n Returns\n -------\n A torch.LongTensor of shape (batch_size,) representing the lengths\n of the sequences in the batch.\n \"\"\"\n return mask.long().sum(-1)\n\n\ndef get_mask_from_sequence_lengths(sequence_lengths: torch.Tensor, max_length: int) -> torch.Tensor:\n \"\"\"\n Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch\n element, this function returns a ``(batch_size, max_length)`` mask variable. For example, if\n our input was ``[2, 2, 3]``, with a ``max_length`` of 4, we'd return\n ``[[1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0]]``.\n\n We require ``max_length`` here instead of just computing it from the input ``sequence_lengths``\n because it lets us avoid finding the max, then copying that value from the GPU to the CPU so\n that we can use it to construct a new tensor.\n \"\"\"\n # (batch_size, max_length)\n ones = sequence_lengths.new_ones(sequence_lengths.size(0), max_length)\n range_tensor = ones.cumsum(dim=1)\n return (sequence_lengths.unsqueeze(1) >= range_tensor).long()\n\n\ndef sort_batch_by_length(tensor: torch.Tensor, sequence_lengths: torch.Tensor):\n \"\"\"\n Sort a batch first tensor by some specified lengths.\n\n Parameters\n ----------\n tensor : torch.FloatTensor, required.\n A batch first Pytorch tensor.\n sequence_lengths : torch.LongTensor, required.\n A tensor representing the lengths of some dimension of the tensor which\n we want to sort by.\n\n Returns\n -------\n sorted_tensor : torch.FloatTensor\n The original tensor sorted along the batch dimension with respect to sequence_lengths.\n sorted_sequence_lengths : torch.LongTensor\n The original sequence_lengths sorted by decreasing size.\n restoration_indices : torch.LongTensor\n Indices into the sorted_tensor such that\n ``sorted_tensor.index_select(0, restoration_indices) == original_tensor``\n permutation_index : torch.LongTensor\n The indices used to sort the tensor. This is useful if you want to sort many\n tensors using the same ordering.\n \"\"\"\n\n if not isinstance(tensor, torch.Tensor) or not isinstance(sequence_lengths, torch.Tensor):\n raise ConfigurationError(\"Both the tensor and sequence lengths must be torch.Tensors.\")\n\n sorted_sequence_lengths, permutation_index = sequence_lengths.sort(0, descending=True)\n sorted_tensor = tensor.index_select(0, permutation_index)\n\n index_range = torch.arange(0, len(sequence_lengths), device=sequence_lengths.device)\n # This is the equivalent of zipping with index, sorting by the original\n # sequence lengths and returning the now sorted indices.\n _, reverse_mapping = permutation_index.sort(0, descending=False)\n restoration_indices = index_range.index_select(0, reverse_mapping)\n return sorted_tensor, sorted_sequence_lengths, restoration_indices, permutation_index\n\n\ndef get_final_encoder_states(\n encoder_outputs: torch.Tensor, mask: torch.Tensor, bidirectional: bool = False\n) -> torch.Tensor:\n \"\"\"\n Given the output from a ``Seq2SeqEncoder``, with shape ``(batch_size, sequence_length,\n encoding_dim)``, this method returns the final hidden state for each element of the batch,\n giving a tensor of shape ``(batch_size, encoding_dim)``. This is not as simple as\n ``encoder_outputs[:, -1]``, because the sequences could have different lengths. We use the\n mask (which has shape ``(batch_size, sequence_length)``) to find the final state for each batch\n instance.\n\n Additionally, if ``bidirectional`` is ``True``, we will split the final dimension of the\n ``encoder_outputs`` into two and assume that the first half is for the forward direction of the\n encoder and the second half is for the backward direction. We will concatenate the last state\n for each encoder dimension, giving ``encoder_outputs[:, -1, :encoding_dim/2]`` concatenated with\n ``encoder_outputs[:, 0, encoding_dim/2:]``.\n \"\"\"\n # These are the indices of the last words in the sequences (i.e. length sans padding - 1). We\n # are assuming sequences are right padded.\n # Shape: (batch_size,)\n last_word_indices = mask.sum(1).long() - 1\n batch_size, _, encoder_output_dim = encoder_outputs.size()\n expanded_indices = last_word_indices.view(-1, 1, 1).expand(batch_size, 1, encoder_output_dim)\n # Shape: (batch_size, 1, encoder_output_dim)\n final_encoder_output = encoder_outputs.gather(1, expanded_indices)\n final_encoder_output = final_encoder_output.squeeze(1) # (batch_size, encoder_output_dim)\n if bidirectional:\n final_forward_output = final_encoder_output[:, : (encoder_output_dim // 2)]\n final_backward_output = encoder_outputs[:, 0, (encoder_output_dim // 2) :]\n final_encoder_output = torch.cat([final_forward_output, final_backward_output], dim=-1)\n return final_encoder_output\n\n\ndef get_dropout_mask(dropout_probability: float, tensor_for_masking: torch.Tensor):\n \"\"\"\n Computes and returns an element-wise dropout mask for a given tensor, where\n each element in the mask is dropped out with probability dropout_probability.\n Note that the mask is NOT applied to the tensor - the tensor is passed to retain\n the correct CUDA tensor type for the mask.\n\n Parameters\n ----------\n dropout_probability : float, required.\n Probability of dropping a dimension of the input.\n tensor_for_masking : torch.Tensor, required.\n\n\n Returns\n -------\n A torch.FloatTensor consisting of the binary mask scaled by 1/ (1 - dropout_probability).\n This scaling ensures expected values and variances of the output of applying this mask\n and the original tensor are the same.\n \"\"\"\n binary_mask = (torch.rand(tensor_for_masking.size()) > dropout_probability).to(\n tensor_for_masking.device\n )\n # Scale mask by 1/keep_prob to preserve output statistics.\n dropout_mask = binary_mask.float().div(1.0 - dropout_probability)\n return dropout_mask\n\n\ndef masked_softmax(\n vector: torch.Tensor,\n mask: torch.Tensor,\n dim: int = -1,\n memory_efficient: bool = False,\n mask_fill_value: float = -1e32,\n) -> torch.Tensor:\n \"\"\"\n ``torch.nn.functional.softmax(vector)`` does not work if some elements of ``vector`` should be\n masked. This performs a softmax on just the non-masked portions of ``vector``. Passing\n ``None`` in for the mask is also acceptable; you'll just get a regular softmax.\n\n ``vector`` can have an arbitrary number of dimensions; the only requirement is that ``mask`` is\n broadcastable to ``vector's`` shape. If ``mask`` has fewer dimensions than ``vector``, we will\n unsqueeze on dimension 1 until they match. If you need a different unsqueezing of your mask,\n do it yourself before passing the mask into this function.\n\n If ``memory_efficient`` is set to true, we will simply use a very large negative number for those\n masked positions so that the probabilities of those positions would be approximately 0.\n This is not accurate in math, but works for most cases and consumes less memory.\n\n In the case that the input vector is completely masked and ``memory_efficient`` is false, this function\n returns an array of ``0.0``. This behavior may cause ``NaN`` if this is used as the last layer of\n a model that uses categorical cross-entropy loss. Instead, if ``memory_efficient`` is true, this function\n will treat every element as equal, and do softmax over equal numbers.\n \"\"\"\n if mask is None:\n result = torch.nn.functional.softmax(vector, dim=dim)\n else:\n mask = mask.float()\n while mask.dim() < vector.dim():\n mask = mask.unsqueeze(1)\n if not memory_efficient:\n # To limit numerical errors from large vector elements outside the mask, we zero these out.\n result = torch.nn.functional.softmax(vector * mask, dim=dim)\n result = result * mask\n result = result / (result.sum(dim=dim, keepdim=True) + 1e-13)\n else:\n masked_vector = vector.masked_fill((1 - mask).to(dtype=torch.bool), mask_fill_value)\n result = torch.nn.functional.softmax(masked_vector, dim=dim)\n return result\n\n\ndef masked_log_softmax(vector: torch.Tensor, mask: torch.Tensor, dim: int = -1) -> torch.Tensor:\n \"\"\"\n ``torch.nn.functional.log_softmax(vector)`` does not work if some elements of ``vector`` should be\n masked. This performs a log_softmax on just the non-masked portions of ``vector``. Passing\n ``None`` in for the mask is also acceptable; you'll just get a regular log_softmax.\n\n ``vector`` can have an arbitrary number of dimensions; the only requirement is that ``mask`` is\n broadcastable to ``vector's`` shape. If ``mask`` has fewer dimensions than ``vector``, we will\n unsqueeze on dimension 1 until they match. If you need a different unsqueezing of your mask,\n do it yourself before passing the mask into this function.\n\n In the case that the input vector is completely masked, the return value of this function is\n arbitrary, but not ``nan``. You should be masking the result of whatever computation comes out\n of this in that case, anyway, so the specific values returned shouldn't matter. Also, the way\n that we deal with this case relies on having single-precision floats; mixing half-precision\n floats with fully-masked vectors will likely give you ``nans``.\n\n If your logits are all extremely negative (i.e., the max value in your logit vector is -50 or\n lower), the way we handle masking here could mess you up. But if you've got logit values that\n extreme, you've got bigger problems than this.\n \"\"\"\n if mask is not None:\n mask = mask.float()\n while mask.dim() < vector.dim():\n mask = mask.unsqueeze(1)\n # vector + mask.log() is an easy way to zero out masked elements in logspace, but it\n # results in nans when the whole vector is masked. We need a very small value instead of a\n # zero in the mask for these cases. log(1 + 1e-45) is still basically 0, so we can safely\n # just add 1e-45 before calling mask.log(). We use 1e-45 because 1e-46 is so small it\n # becomes 0 - this is just the smallest value we can actually use.\n vector = vector + (mask + 1e-45).log()\n return torch.nn.functional.log_softmax(vector, dim=dim)\n\n\ndef masked_max(\n vector: torch.Tensor, mask: torch.Tensor, dim: int, keepdim: bool = False, min_val: float = -1e7\n) -> torch.Tensor:\n \"\"\"\n To calculate max along certain dimensions on masked values\n\n Parameters\n ----------\n vector : ``torch.Tensor``\n The vector to calculate max, assume unmasked parts are already zeros\n mask : ``torch.Tensor``\n The mask of the vector. It must be broadcastable with vector.\n dim : ``int``\n The dimension to calculate max\n keepdim : ``bool``\n Whether to keep dimension\n min_val : ``float``\n The minimal value for paddings\n\n Returns\n -------\n A ``torch.Tensor`` of including the maximum values.\n \"\"\"\n one_minus_mask = (1.0 - mask).to(dtype=torch.bool)\n replaced_vector = vector.masked_fill(one_minus_mask, min_val)\n max_value, _ = replaced_vector.max(dim=dim, keepdim=keepdim)\n return max_value\n\n\ndef masked_mean(\n vector: torch.Tensor, mask: torch.Tensor, dim: int, keepdim: bool = False, eps: float = 1e-8\n) -> torch.Tensor:\n \"\"\"\n To calculate mean along certain dimensions on masked values\n\n Parameters\n ----------\n vector : ``torch.Tensor``\n The vector to calculate mean.\n mask : ``torch.Tensor``\n The mask of the vector. It must be broadcastable with vector.\n dim : ``int``\n The dimension to calculate mean\n keepdim : ``bool``\n Whether to keep dimension\n eps : ``float``\n A small value to avoid zero division problem.\n\n Returns\n -------\n A ``torch.Tensor`` of including the mean values.\n \"\"\"\n one_minus_mask = (1.0 - mask).to(dtype=torch.bool)\n replaced_vector = vector.masked_fill(one_minus_mask, 0.0)\n\n value_sum = torch.sum(replaced_vector, dim=dim, keepdim=keepdim)\n value_count = torch.sum(mask.float(), dim=dim, keepdim=keepdim)\n return value_sum / value_count.clamp(min=eps)\n\n\ndef masked_flip(padded_sequence: torch.Tensor, sequence_lengths: List[int]) -> torch.Tensor:\n \"\"\"\n Flips a padded tensor along the time dimension without affecting masked entries.\n\n Parameters\n ----------\n padded_sequence : ``torch.Tensor``\n The tensor to flip along the time dimension.\n Assumed to be of dimensions (batch size, num timesteps, ...)\n sequence_lengths : ``torch.Tensor``\n A list containing the lengths of each unpadded sequence in the batch.\n\n Returns\n -------\n A ``torch.Tensor`` of the same shape as padded_sequence.\n \"\"\"\n assert padded_sequence.size(0) == len(\n sequence_lengths\n ), f\"sequence_lengths length ${len(sequence_lengths)} does not match batch size ${padded_sequence.size(0)}\"\n num_timesteps = padded_sequence.size(1)\n flipped_padded_sequence = torch.flip(padded_sequence, [1])\n sequences = [\n flipped_padded_sequence[i, num_timesteps - length :]\n for i, length in enumerate(sequence_lengths)\n ]\n return torch.nn.utils.rnn.pad_sequence(sequences, batch_first=True)\n\n\ndef viterbi_decode(\n tag_sequence: torch.Tensor,\n transition_matrix: torch.Tensor,\n tag_observations: Optional[List[int]] = None,\n allowed_start_transitions: torch.Tensor = None,\n allowed_end_transitions: torch.Tensor = None,\n top_k: int = None,\n):\n \"\"\"\n Perform Viterbi decoding in log space over a sequence given a transition matrix\n specifying pairwise (transition) potentials between tags and a matrix of shape\n (sequence_length, num_tags) specifying unary potentials for possible tags per\n timestep.\n\n Parameters\n ----------\n tag_sequence : torch.Tensor, required.\n A tensor of shape (sequence_length, num_tags) representing scores for\n a set of tags over a given sequence.\n transition_matrix : torch.Tensor, required.\n A tensor of shape (num_tags, num_tags) representing the binary potentials\n for transitioning between a given pair of tags.\n tag_observations : Optional[List[int]], optional, (default = None)\n A list of length ``sequence_length`` containing the class ids of observed\n elements in the sequence, with unobserved elements being set to -1. Note that\n it is possible to provide evidence which results in degenerate labelings if\n the sequences of tags you provide as evidence cannot transition between each\n other, or those transitions are extremely unlikely. In this situation we log a\n warning, but the responsibility for providing self-consistent evidence ultimately\n lies with the user.\n allowed_start_transitions : torch.Tensor, optional, (default = None)\n An optional tensor of shape (num_tags,) describing which tags the START token\n may transition *to*. If provided, additional transition constraints will be used for\n determining the start element of the sequence.\n allowed_end_transitions : torch.Tensor, optional, (default = None)\n An optional tensor of shape (num_tags,) describing which tags may transition *to* the\n end tag. If provided, additional transition constraints will be used for determining\n the end element of the sequence.\n top_k : int, optional, (default = None)\n Optional integer specifying how many of the top paths to return. For top_k>=1, returns\n a tuple of two lists: top_k_paths, top_k_scores, For top_k==None, returns a flattened\n tuple with just the top path and its score (not in lists, for backwards compatibility).\n\n Returns\n -------\n viterbi_path : List[int]\n The tag indices of the maximum likelihood tag sequence.\n viterbi_score : torch.Tensor\n The score of the viterbi path.\n \"\"\"\n if top_k is None:\n top_k = 1\n flatten_output = True\n elif top_k >= 1:\n flatten_output = False\n else:\n raise ValueError(f\"top_k must be either None or an integer >=1. Instead received {top_k}\")\n\n sequence_length, num_tags = list(tag_sequence.size())\n\n has_start_end_restrictions = (\n allowed_end_transitions is not None or allowed_start_transitions is not None\n )\n\n if has_start_end_restrictions:\n\n if allowed_end_transitions is None:\n allowed_end_transitions = torch.zeros(num_tags)\n if allowed_start_transitions is None:\n allowed_start_transitions = torch.zeros(num_tags)\n\n num_tags = num_tags + 2\n new_transition_matrix = torch.zeros(num_tags, num_tags)\n new_transition_matrix[:-2, :-2] = transition_matrix\n\n # Start and end transitions are fully defined, but cannot transition between each other.\n\n allowed_start_transitions = torch.cat(\n [allowed_start_transitions, torch.tensor([-math.inf, -math.inf])]\n )\n allowed_end_transitions = torch.cat(\n [allowed_end_transitions, torch.tensor([-math.inf, -math.inf])]\n )\n\n # First define how we may transition FROM the start and end tags.\n new_transition_matrix[-2, :] = allowed_start_transitions\n # We cannot transition from the end tag to any tag.\n new_transition_matrix[-1, :] = -math.inf\n\n new_transition_matrix[:, -1] = allowed_end_transitions\n # We cannot transition to the start tag from any tag.\n new_transition_matrix[:, -2] = -math.inf\n\n transition_matrix = new_transition_matrix\n\n if tag_observations:\n if len(tag_observations) != sequence_length:\n raise ConfigurationError(\n \"Observations were provided, but they were not the same length \"\n \"as the sequence. Found sequence of length: {} and evidence: {}\".format(\n sequence_length, tag_observations\n )\n )\n else:\n tag_observations = [-1 for _ in range(sequence_length)]\n\n if has_start_end_restrictions:\n tag_observations = [num_tags - 2] + tag_observations + [num_tags - 1]\n zero_sentinel = torch.zeros(1, num_tags)\n extra_tags_sentinel = torch.ones(sequence_length, 2) * -math.inf\n tag_sequence = torch.cat([tag_sequence, extra_tags_sentinel], -1)\n tag_sequence = torch.cat([zero_sentinel, tag_sequence, zero_sentinel], 0)\n sequence_length = tag_sequence.size(0)\n\n path_scores = []\n path_indices = []\n\n if tag_observations[0] != -1:\n one_hot = torch.zeros(num_tags)\n one_hot[tag_observations[0]] = 100000.0\n path_scores.append(one_hot.unsqueeze(0))\n else:\n path_scores.append(tag_sequence[0, :].unsqueeze(0))\n\n # Evaluate the scores for all possible paths.\n for timestep in range(1, sequence_length):\n # Add pairwise potentials to current scores.\n summed_potentials = path_scores[timestep - 1].unsqueeze(2) + transition_matrix\n summed_potentials = summed_potentials.view(-1, num_tags)\n\n # Best pairwise potential path score from the previous timestep.\n max_k = min(summed_potentials.size()[0], top_k)\n scores, paths = torch.topk(summed_potentials, k=max_k, dim=0)\n\n # If we have an observation for this timestep, use it\n # instead of the distribution over tags.\n observation = tag_observations[timestep]\n # Warn the user if they have passed\n # invalid/extremely unlikely evidence.\n if tag_observations[timestep - 1] != -1 and observation != -1:\n if transition_matrix[tag_observations[timestep - 1], observation] < -10000:\n logger.warning(\n \"The pairwise potential between tags you have passed as \"\n \"observations is extremely unlikely. Double check your evidence \"\n \"or transition potentials!\"\n )\n if observation != -1:\n one_hot = torch.zeros(num_tags)\n one_hot[observation] = 100000.0\n path_scores.append(one_hot.unsqueeze(0))\n else:\n path_scores.append(tag_sequence[timestep, :] + scores)\n path_indices.append(paths.squeeze())\n\n # Construct the most likely sequence backwards.\n path_scores_v = path_scores[-1].view(-1)\n max_k = min(path_scores_v.size()[0], top_k)\n viterbi_scores, best_paths = torch.topk(path_scores_v, k=max_k, dim=0)\n viterbi_paths = []\n for i in range(max_k):\n viterbi_path = [best_paths[i]]\n for backward_timestep in reversed(path_indices):\n viterbi_path.append(int(backward_timestep.view(-1)[viterbi_path[-1]]))\n # Reverse the backward path.\n viterbi_path.reverse()\n\n if has_start_end_restrictions:\n viterbi_path = viterbi_path[1:-1]\n\n # Viterbi paths uses (num_tags * n_permutations) nodes; therefore, we need to modulo.\n viterbi_path = [j % num_tags for j in viterbi_path]\n viterbi_paths.append(viterbi_path)\n\n if flatten_output:\n return viterbi_paths[0], viterbi_scores[0]\n\n return viterbi_paths, viterbi_scores\n\n\ndef get_text_field_mask(\n text_field_tensors: Dict[str, torch.Tensor], num_wrapping_dims: int = 0\n) -> torch.LongTensor:\n \"\"\"\n Takes the dictionary of tensors produced by a ``TextField`` and returns a mask\n with 0 where the tokens are padding, and 1 otherwise. We also handle ``TextFields``\n wrapped by an arbitrary number of ``ListFields``, where the number of wrapping ``ListFields``\n is given by ``num_wrapping_dims``.\n\n If ``num_wrapping_dims == 0``, the returned mask has shape ``(batch_size, num_tokens)``.\n If ``num_wrapping_dims > 0`` then the returned mask has ``num_wrapping_dims`` extra\n dimensions, so the shape will be ``(batch_size, ..., num_tokens)``.\n\n There could be several entries in the tensor dictionary with different shapes (e.g., one for\n word ids, one for character ids). In order to get a token mask, we use the tensor in\n the dictionary with the lowest number of dimensions. After subtracting ``num_wrapping_dims``,\n if this tensor has two dimensions we assume it has shape ``(batch_size, ..., num_tokens)``,\n and use it for the mask. If instead it has three dimensions, we assume it has shape\n ``(batch_size, ..., num_tokens, num_features)``, and sum over the last dimension to produce\n the mask. Most frequently this will be a character id tensor, but it could also be a\n featurized representation of each token, etc.\n\n If the input ``text_field_tensors`` contains the \"mask\" key, this is returned instead of inferring the mask.\n\n TODO(joelgrus): can we change this?\n NOTE: Our functions for generating masks create torch.LongTensors, because using\n torch.ByteTensors makes it easy to run into overflow errors\n when doing mask manipulation, such as summing to get the lengths of sequences - see below.\n >>> mask = torch.ones([260]).byte()\n >>> mask.sum() # equals 260.\n >>> var_mask = torch.autograd.V(mask)\n >>> var_mask.sum() # equals 4, due to 8 bit precision - the sum overflows.\n \"\"\"\n if \"mask\" in text_field_tensors:\n return text_field_tensors[\"mask\"]\n\n tensor_dims = [(tensor.dim(), tensor) for tensor in text_field_tensors.values()]\n tensor_dims.sort(key=lambda x: x[0])\n\n smallest_dim = tensor_dims[0][0] - num_wrapping_dims\n if smallest_dim == 2:\n token_tensor = tensor_dims[0][1]\n return (token_tensor != 0).long()\n elif smallest_dim == 3:\n character_tensor = tensor_dims[0][1]\n return ((character_tensor > 0).long().sum(dim=-1) > 0).long()\n else:\n raise ValueError(\"Expected a tensor with dimension 2 or 3, found {}\".format(smallest_dim))\n\n\ndef weighted_sum(matrix: torch.Tensor, attention: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Takes a matrix of vectors and a set of weights over the rows in the matrix (which we call an\n \"attention\" vector), and returns a weighted sum of the rows in the matrix. This is the typical\n computation performed after an attention mechanism.\n\n Note that while we call this a \"matrix\" of vectors and an attention \"vector\", we also handle\n higher-order tensors. We always sum over the second-to-last dimension of the \"matrix\", and we\n assume that all dimensions in the \"matrix\" prior to the last dimension are matched in the\n \"vector\". Non-matched dimensions in the \"vector\" must be `directly after the batch dimension`.\n\n For example, say I have a \"matrix\" with dimensions ``(batch_size, num_queries, num_words,\n embedding_dim)``. The attention \"vector\" then must have at least those dimensions, and could\n have more. Both:\n\n - ``(batch_size, num_queries, num_words)`` (distribution over words for each query)\n - ``(batch_size, num_documents, num_queries, num_words)`` (distribution over words in a\n query for each document)\n\n are valid input \"vectors\", producing tensors of shape:\n ``(batch_size, num_queries, embedding_dim)`` and\n ``(batch_size, num_documents, num_queries, embedding_dim)`` respectively.\n \"\"\"\n # We'll special-case a few settings here, where there are efficient (but poorly-named)\n # operations in pytorch that already do the computation we need.\n if attention.dim() == 2 and matrix.dim() == 3:\n return attention.unsqueeze(1).bmm(matrix).squeeze(1)\n if attention.dim() == 3 and matrix.dim() == 3:\n return attention.bmm(matrix)\n if matrix.dim() - 1 < attention.dim():\n expanded_size = list(matrix.size())\n for i in range(attention.dim() - matrix.dim() + 1):\n matrix = matrix.unsqueeze(1)\n expanded_size.insert(i + 1, attention.size(i + 1))\n matrix = matrix.expand(*expanded_size)\n intermediate = attention.unsqueeze(-1).expand_as(matrix) * matrix\n return intermediate.sum(dim=-2)\n\n\ndef sequence_cross_entropy_with_logits(\n logits: torch.FloatTensor,\n targets: torch.LongTensor,\n weights: torch.FloatTensor,\n average: str = \"batch\",\n label_smoothing: float = None,\n gamma: float = None,\n alpha: Union[float, List[float], torch.FloatTensor] = None,\n) -> torch.FloatTensor:\n \"\"\"\n Computes the cross entropy loss of a sequence, weighted with respect to\n some user provided weights. Note that the weighting here is not the same as\n in the :func:`torch.nn.CrossEntropyLoss()` criterion, which is weighting\n classes; here we are weighting the loss contribution from particular elements\n in the sequence. This allows loss computations for models which use padding.\n\n Parameters\n ----------\n logits : ``torch.FloatTensor``, required.\n A ``torch.FloatTensor`` of size (batch_size, sequence_length, num_classes)\n which contains the unnormalized probability for each class.\n targets : ``torch.LongTensor``, required.\n A ``torch.LongTensor`` of size (batch, sequence_length) which contains the\n index of the true class for each corresponding step.\n weights : ``torch.FloatTensor``, required.\n A ``torch.FloatTensor`` of size (batch, sequence_length)\n average: str, optional (default = \"batch\")\n If \"batch\", average the loss across the batches. If \"token\", average\n the loss across each item in the input. If ``None``, return a vector\n of losses per batch element.\n label_smoothing : ``float``, optional (default = None)\n Whether or not to apply label smoothing to the cross-entropy loss.\n For example, with a label smoothing value of 0.2, a 4 class classification\n target would look like ``[0.05, 0.05, 0.85, 0.05]`` if the 3rd class was\n the correct label.\n gamma : ``float``, optional (default = None)\n Focal loss[*] focusing parameter ``gamma`` to reduces the relative loss for\n well-classified examples and put more focus on hard. The greater value\n ``gamma`` is, the more focus on hard examples.\n alpha : ``float`` or ``List[float]``, optional (default = None)\n Focal loss[*] weighting factor ``alpha`` to balance between classes. Can be\n used independently with ``gamma``. If a single ``float`` is provided, it\n is assumed binary case using ``alpha`` and ``1 - alpha`` for positive and\n negative respectively. If a list of ``float`` is provided, with the same\n length as the number of classes, the weights will match the classes.\n [*] T. Lin, P. Goyal, R. Girshick, K. He and P. Dollár, \"Focal Loss for\n Dense Object Detection,\" 2017 IEEE International Conference on Computer\n Vision (ICCV), Venice, 2017, pp. 2999-3007.\n\n Returns\n -------\n A torch.FloatTensor representing the cross entropy loss.\n If ``average==\"batch\"`` or ``average==\"token\"``, the returned loss is a scalar.\n If ``average is None``, the returned loss is a vector of shape (batch_size,).\n\n \"\"\"\n if average not in {None, \"token\", \"batch\"}:\n raise ValueError(\"Got average f{average}, expected one of \" \"None, 'token', or 'batch'\")\n\n # make sure weights are float\n weights = weights.float()\n # sum all dim except batch\n non_batch_dims = tuple(range(1, len(weights.shape)))\n # shape : (batch_size,)\n weights_batch_sum = weights.sum(dim=non_batch_dims)\n # shape : (batch * sequence_length, num_classes)\n logits_flat = logits.view(-1, logits.size(-1))\n # shape : (batch * sequence_length, num_classes)\n log_probs_flat = torch.nn.functional.log_softmax(logits_flat, dim=-1)\n # shape : (batch * max_len, 1)\n targets_flat = targets.view(-1, 1).long()\n # focal loss coefficient\n if gamma:\n # shape : (batch * sequence_length, num_classes)\n probs_flat = log_probs_flat.exp()\n # shape : (batch * sequence_length,)\n probs_flat = torch.gather(probs_flat, dim=1, index=targets_flat)\n # shape : (batch * sequence_length,)\n focal_factor = (1.0 - probs_flat) ** gamma\n # shape : (batch, sequence_length)\n focal_factor = focal_factor.view(*targets.size())\n weights = weights * focal_factor\n\n if alpha is not None:\n # shape : () / (num_classes,)\n if isinstance(alpha, (float, int)):\n\n # shape : (2,)\n alpha_factor = torch.tensor(\n [1.0 - float(alpha), float(alpha)], dtype=weights.dtype, device=weights.device\n )\n\n elif isinstance(alpha, (list, numpy.ndarray, torch.Tensor)):\n\n # shape : (c,)\n alpha_factor = torch.tensor(alpha, dtype=weights.dtype, device=weights.device)\n\n if not alpha_factor.size():\n # shape : (1,)\n alpha_factor = alpha_factor.view(1)\n # shape : (2,)\n alpha_factor = torch.cat([1 - alpha_factor, alpha_factor])\n else:\n raise TypeError(\n (\n \"alpha must be float, list of float, or torch.FloatTensor, \" \"{} provided.\"\n ).format(type(alpha))\n )\n # shape : (batch, max_len)\n alpha_factor = torch.gather(alpha_factor, dim=0, index=targets_flat.view(-1)).view(\n *targets.size()\n )\n weights = weights * alpha_factor\n\n if label_smoothing is not None and label_smoothing > 0.0:\n num_classes = logits.size(-1)\n smoothing_value = label_smoothing / num_classes\n # Fill all the correct indices with 1 - smoothing value.\n one_hot_targets = torch.zeros_like(log_probs_flat).scatter_(\n -1, targets_flat, 1.0 - label_smoothing\n )\n smoothed_targets = one_hot_targets + smoothing_value\n negative_log_likelihood_flat = -log_probs_flat * smoothed_targets\n negative_log_likelihood_flat = negative_log_likelihood_flat.sum(-1, keepdim=True)\n else:\n # Contribution to the negative log likelihood only comes from the exact indices\n # of the targets, as the target distributions are one-hot. Here we use torch.gather\n # to extract the indices of the num_classes dimension which contribute to the loss.\n # shape : (batch * sequence_length, 1)\n negative_log_likelihood_flat = -torch.gather(log_probs_flat, dim=1, index=targets_flat)\n # shape : (batch, sequence_length)\n negative_log_likelihood = negative_log_likelihood_flat.view(*targets.size())\n # shape : (batch, sequence_length)\n negative_log_likelihood = negative_log_likelihood * weights\n\n if average == \"batch\":\n # shape : (batch_size,)\n per_batch_loss = negative_log_likelihood.sum(non_batch_dims) / (weights_batch_sum + 1e-13)\n num_non_empty_sequences = (weights_batch_sum > 0).float().sum() + 1e-13\n return per_batch_loss.sum() / num_non_empty_sequences\n elif average == \"token\":\n return negative_log_likelihood.sum() / (weights_batch_sum.sum() + 1e-13)\n else:\n # shape : (batch_size,)\n per_batch_loss = negative_log_likelihood.sum(non_batch_dims) / (weights_batch_sum + 1e-13)\n return per_batch_loss\n\n\ndef replace_masked_values(\n tensor: torch.Tensor, mask: torch.Tensor, replace_with: float\n) -> torch.Tensor:\n \"\"\"\n Replaces all masked values in ``tensor`` with ``replace_with``. ``mask`` must be broadcastable\n to the same shape as ``tensor``. We require that ``tensor.dim() == mask.dim()``, as otherwise we\n won't know which dimensions of the mask to unsqueeze.\n\n This just does ``tensor.masked_fill()``, except the pytorch method fills in things with a mask\n value of 1, where we want the opposite. You can do this in your own code with\n ``tensor.masked_fill((1 - mask).to(dtype=torch.bool), replace_with)``.\n \"\"\"\n if tensor.dim() != mask.dim():\n raise ConfigurationError(\n \"tensor.dim() (%d) != mask.dim() (%d)\" % (tensor.dim(), mask.dim())\n )\n return tensor.masked_fill((1 - mask).to(dtype=torch.bool), replace_with)\n\n\ndef tensors_equal(tensor1: torch.Tensor, tensor2: torch.Tensor, tolerance: float = 1e-12) -> bool:\n \"\"\"\n A check for tensor equality (by value). We make sure that the tensors have the same shape,\n then check all of the entries in the tensor for equality. We additionally allow the input\n tensors to be lists or dictionaries, where we then do the above check on every position in the\n list / item in the dictionary. If we find objects that aren't tensors as we're doing that, we\n just defer to their equality check.\n\n This is kind of a catch-all method that's designed to make implementing ``__eq__`` methods\n easier, in a way that's really only intended to be useful for tests.\n \"\"\"\n\n if isinstance(tensor1, (list, tuple)):\n if not isinstance(tensor2, (list, tuple)) or len(tensor1) != len(tensor2):\n return False\n return all([tensors_equal(t1, t2, tolerance) for t1, t2 in zip(tensor1, tensor2)])\n elif isinstance(tensor1, dict):\n if not isinstance(tensor2, dict):\n return False\n if tensor1.keys() != tensor2.keys():\n return False\n return all([tensors_equal(tensor1[key], tensor2[key], tolerance) for key in tensor1])\n elif isinstance(tensor1, torch.Tensor):\n if not isinstance(tensor2, torch.Tensor):\n return False\n if tensor1.size() != tensor2.size():\n return False\n return ((tensor1 - tensor2).abs().float() < tolerance).all()\n else:\n try:\n return tensor1 == tensor2\n except RuntimeError:\n print(type(tensor1), type(tensor2))\n raise\n\n\ndef device_mapping(cuda_device: int):\n \"\"\"\n In order to `torch.load()` a GPU-trained model onto a CPU (or specific GPU),\n you have to supply a `map_location` function. Call this with\n the desired `cuda_device` to get the function that `torch.load()` needs.\n \"\"\"\n\n def inner_device_mapping(storage: torch.Storage, location) -> torch.Storage:\n if cuda_device >= 0:\n return storage.cuda(cuda_device)\n else:\n return storage\n\n return inner_device_mapping\n\n\ndef combine_tensors(combination: str, tensors: List[torch.Tensor]) -> torch.Tensor:\n \"\"\"\n Combines a list of tensors using element-wise operations and concatenation, specified by a\n ``combination`` string. The string refers to (1-indexed) positions in the input tensor list,\n and looks like ``\"1,2,1+2,3-1\"``.\n\n We allow the following kinds of combinations: ``x``, ``x*y``, ``x+y``, ``x-y``, and ``x/y``,\n where ``x`` and ``y`` are positive integers less than or equal to ``len(tensors)``. Each of\n the binary operations is performed elementwise. You can give as many combinations as you want\n in the ``combination`` string. For example, for the input string ``\"1,2,1*2\"``, the result\n would be ``[1;2;1*2]``, as you would expect, where ``[;]`` is concatenation along the last\n dimension.\n\n If you have a fixed, known way to combine tensors that you use in a model, you should probably\n just use something like ``torch.cat([x_tensor, y_tensor, x_tensor * y_tensor])``. This\n function adds some complexity that is only necessary if you want the specific combination used\n to be `configurable`.\n\n If you want to do any element-wise operations, the tensors involved in each element-wise\n operation must have the same shape.\n\n This function also accepts ``x`` and ``y`` in place of ``1`` and ``2`` in the combination\n string.\n \"\"\"\n if len(tensors) > 9:\n raise ConfigurationError(\"Double-digit tensor lists not currently supported\")\n combination = combination.replace(\"x\", \"1\").replace(\"y\", \"2\")\n to_concatenate = [_get_combination(piece, tensors) for piece in combination.split(\",\")]\n return torch.cat(to_concatenate, dim=-1)\n\n\ndef _rindex(sequence: Sequence[T], obj: T) -> int:\n \"\"\"\n Return zero-based index in the sequence of the last item whose value is equal to obj. Raises a\n ValueError if there is no such item.\n\n Parameters\n ----------\n sequence : ``Sequence[T]``\n obj : ``T``\n\n Returns\n -------\n zero-based index associated to the position of the last item equal to obj\n \"\"\"\n for i in range(len(sequence) - 1, -1, -1):\n if sequence[i] == obj:\n return i\n\n raise ValueError(f\"Unable to find {obj} in sequence {sequence}.\")\n\n\ndef _get_combination(combination: str, tensors: List[torch.Tensor]) -> torch.Tensor:\n if combination.isdigit():\n index = int(combination) - 1\n return tensors[index]\n else:\n if len(combination) != 3:\n raise ConfigurationError(\"Invalid combination: \" + combination)\n first_tensor = _get_combination(combination[0], tensors)\n second_tensor = _get_combination(combination[2], tensors)\n operation = combination[1]\n if operation == \"*\":\n return first_tensor * second_tensor\n elif operation == \"/\":\n return first_tensor / second_tensor\n elif operation == \"+\":\n return first_tensor + second_tensor\n elif operation == \"-\":\n return first_tensor - second_tensor\n else:\n raise ConfigurationError(\"Invalid operation: \" + operation)\n\n\ndef combine_tensors_and_multiply(\n combination: str, tensors: List[torch.Tensor], weights: torch.nn.Parameter\n) -> torch.Tensor:\n \"\"\"\n Like :func:`combine_tensors`, but does a weighted (linear) multiplication while combining.\n This is a separate function from ``combine_tensors`` because we try to avoid instantiating\n large intermediate tensors during the combination, which is possible because we know that we're\n going to be multiplying by a weight vector in the end.\n\n Parameters\n ----------\n combination : ``str``\n Same as in :func:`combine_tensors`\n tensors : ``List[torch.Tensor]``\n A list of tensors to combine, where the integers in the ``combination`` are (1-indexed)\n positions in this list of tensors. These tensors are all expected to have either three or\n four dimensions, with the final dimension being an embedding. If there are four\n dimensions, one of them must have length 1.\n weights : ``torch.nn.Parameter``\n A vector of weights to use for the combinations. This should have shape (combined_dim,),\n as calculated by :func:`get_combined_dim`.\n \"\"\"\n if len(tensors) > 9:\n raise ConfigurationError(\"Double-digit tensor lists not currently supported\")\n combination = combination.replace(\"x\", \"1\").replace(\"y\", \"2\")\n pieces = combination.split(\",\")\n tensor_dims = [tensor.size(-1) for tensor in tensors]\n combination_dims = [_get_combination_dim(piece, tensor_dims) for piece in pieces]\n dims_so_far = 0\n to_sum = []\n for piece, combination_dim in zip(pieces, combination_dims):\n weight = weights[dims_so_far : (dims_so_far + combination_dim)]\n dims_so_far += combination_dim\n to_sum.append(_get_combination_and_multiply(piece, tensors, weight))\n result = to_sum[0]\n for result_piece in to_sum[1:]:\n result = result + result_piece\n return result\n\n\ndef _get_combination_and_multiply(\n combination: str, tensors: List[torch.Tensor], weight: torch.nn.Parameter\n) -> torch.Tensor:\n if combination.isdigit():\n index = int(combination) - 1\n return torch.matmul(tensors[index], weight)\n else:\n if len(combination) != 3:\n raise ConfigurationError(\"Invalid combination: \" + combination)\n first_tensor = _get_combination(combination[0], tensors)\n second_tensor = _get_combination(combination[2], tensors)\n operation = combination[1]\n if operation == \"*\":\n if first_tensor.dim() > 4 or second_tensor.dim() > 4:\n raise ValueError(\"Tensors with dim > 4 not currently supported\")\n desired_dim = max(first_tensor.dim(), second_tensor.dim()) - 1\n if first_tensor.dim() == 4:\n expanded_dim = _rindex(first_tensor.size(), 1)\n first_tensor = first_tensor.squeeze(expanded_dim)\n if second_tensor.dim() == 4:\n expanded_dim = _rindex(second_tensor.size(), 1)\n second_tensor = second_tensor.squeeze(expanded_dim)\n intermediate = first_tensor * weight\n result = torch.matmul(intermediate, second_tensor.transpose(-1, -2))\n if result.dim() == desired_dim + 1:\n result = result.squeeze(-1)\n return result\n elif operation == \"/\":\n if first_tensor.dim() > 4 or second_tensor.dim() > 4:\n raise ValueError(\"Tensors with dim > 4 not currently supported\")\n desired_dim = max(first_tensor.dim(), second_tensor.dim()) - 1\n if first_tensor.dim() == 4:\n expanded_dim = _rindex(first_tensor.size(), 1)\n first_tensor = first_tensor.squeeze(expanded_dim)\n if second_tensor.dim() == 4:\n expanded_dim = _rindex(second_tensor.size(), 1)\n second_tensor = second_tensor.squeeze(expanded_dim)\n intermediate = first_tensor * weight\n result = torch.matmul(intermediate, second_tensor.pow(-1).transpose(-1, -2))\n if result.dim() == desired_dim + 1:\n result = result.squeeze(-1)\n return result\n elif operation == \"+\":\n return torch.matmul(first_tensor, weight) + torch.matmul(second_tensor, weight)\n elif operation == \"-\":\n return torch.matmul(first_tensor, weight) - torch.matmul(second_tensor, weight)\n else:\n raise ConfigurationError(\"Invalid operation: \" + operation)\n\n\ndef get_combined_dim(combination: str, tensor_dims: List[int]) -> int:\n \"\"\"\n For use with :func:`combine_tensors`. This function computes the resultant dimension when\n calling ``combine_tensors(combination, tensors)``, when the tensor dimension is known. This is\n necessary for knowing the sizes of weight matrices when building models that use\n ``combine_tensors``.\n\n Parameters\n ----------\n combination : ``str``\n A comma-separated list of combination pieces, like ``\"1,2,1*2\"``, specified identically to\n ``combination`` in :func:`combine_tensors`.\n tensor_dims : ``List[int]``\n A list of tensor dimensions, where each dimension is from the `last axis` of the tensors\n that will be input to :func:`combine_tensors`.\n \"\"\"\n if len(tensor_dims) > 9:\n raise ConfigurationError(\"Double-digit tensor lists not currently supported\")\n combination = combination.replace(\"x\", \"1\").replace(\"y\", \"2\")\n return sum([_get_combination_dim(piece, tensor_dims) for piece in combination.split(\",\")])\n\n\ndef _get_combination_dim(combination: str, tensor_dims: List[int]) -> int:\n if combination.isdigit():\n index = int(combination) - 1\n return tensor_dims[index]\n else:\n if len(combination) != 3:\n raise ConfigurationError(\"Invalid combination: \" + combination)\n first_tensor_dim = _get_combination_dim(combination[0], tensor_dims)\n second_tensor_dim = _get_combination_dim(combination[2], tensor_dims)\n operation = combination[1]\n if first_tensor_dim != second_tensor_dim:\n raise ConfigurationError('Tensor dims must match for operation \"{}\"'.format(operation))\n return first_tensor_dim\n\n\ndef logsumexp(tensor: torch.Tensor, dim: int = -1, keepdim: bool = False) -> torch.Tensor:\n \"\"\"\n A numerically stable computation of logsumexp. This is mathematically equivalent to\n `tensor.exp().sum(dim, keep=keepdim).log()`. This function is typically used for summing log\n probabilities.\n\n Parameters\n ----------\n tensor : torch.FloatTensor, required.\n A tensor of arbitrary size.\n dim : int, optional (default = -1)\n The dimension of the tensor to apply the logsumexp to.\n keepdim: bool, optional (default = False)\n Whether to retain a dimension of size one at the dimension we reduce over.\n \"\"\"\n max_score, _ = tensor.max(dim, keepdim=keepdim)\n if keepdim:\n stable_vec = tensor - max_score\n else:\n stable_vec = tensor - max_score.unsqueeze(dim)\n return max_score + (stable_vec.exp().sum(dim, keepdim=keepdim)).log()\n\n\ndef get_device_of(tensor: torch.Tensor) -> int:\n \"\"\"\n Returns the device of the tensor.\n \"\"\"\n if not tensor.is_cuda:\n return -1\n else:\n return tensor.get_device()\n\n\ndef flatten_and_batch_shift_indices(indices: torch.Tensor, sequence_length: int) -> torch.Tensor:\n \"\"\"\n This is a subroutine for :func:`~batched_index_select`. The given ``indices`` of size\n ``(batch_size, d_1, ..., d_n)`` indexes into dimension 2 of a target tensor, which has size\n ``(batch_size, sequence_length, embedding_size)``. This function returns a vector that\n correctly indexes into the flattened target. The sequence length of the target must be\n provided to compute the appropriate offsets.\n\n .. code-block:: python\n\n indices = torch.ones([2,3], dtype=torch.long)\n # Sequence length of the target tensor.\n sequence_length = 10\n shifted_indices = flatten_and_batch_shift_indices(indices, sequence_length)\n # Indices into the second element in the batch are correctly shifted\n # to take into account that the target tensor will be flattened before\n # the indices are applied.\n assert shifted_indices == [1, 1, 1, 11, 11, 11]\n\n Parameters\n ----------\n indices : ``torch.LongTensor``, required.\n sequence_length : ``int``, required.\n The length of the sequence the indices index into.\n This must be the second dimension of the tensor.\n\n Returns\n -------\n offset_indices : ``torch.LongTensor``\n \"\"\"\n # Shape: (batch_size)\n if torch.max(indices) >= sequence_length or torch.min(indices) < 0:\n raise ConfigurationError(\n f\"All elements in indices should be in range (0, {sequence_length - 1})\"\n )\n offsets = get_range_vector(indices.size(0), get_device_of(indices)) * sequence_length\n for _ in range(len(indices.size()) - 1):\n offsets = offsets.unsqueeze(1)\n\n # Shape: (batch_size, d_1, ..., d_n)\n offset_indices = indices + offsets\n\n # Shape: (batch_size * d_1 * ... * d_n)\n offset_indices = offset_indices.view(-1)\n return offset_indices\n\n\ndef batched_index_select(\n target: torch.Tensor,\n indices: torch.LongTensor,\n flattened_indices: Optional[torch.LongTensor] = None,\n) -> torch.Tensor:\n \"\"\"\n The given ``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into the sequence\n dimension (dimension 2) of the target, which has size ``(batch_size, sequence_length,\n embedding_size)``.\n\n This function returns selected values in the target with respect to the provided indices, which\n have size ``(batch_size, d_1, ..., d_n, embedding_size)``. This can use the optionally\n precomputed :func:`~flattened_indices` with size ``(batch_size * d_1 * ... * d_n)`` if given.\n\n An example use case of this function is looking up the start and end indices of spans in a\n sequence tensor. This is used in the\n :class:`~allennlp.models.coreference_resolution.CoreferenceResolver`. Model to select\n contextual word representations corresponding to the start and end indices of mentions. The key\n reason this can't be done with basic torch functions is that we want to be able to use look-up\n tensors with an arbitrary number of dimensions (for example, in the coref model, we don't know\n a-priori how many spans we are looking up).\n\n Parameters\n ----------\n target : ``torch.Tensor``, required.\n A 3 dimensional tensor of shape (batch_size, sequence_length, embedding_size).\n This is the tensor to be indexed.\n indices : ``torch.LongTensor``\n A tensor of shape (batch_size, ...), where each element is an index into the\n ``sequence_length`` dimension of the ``target`` tensor.\n flattened_indices : Optional[torch.Tensor], optional (default = None)\n An optional tensor representing the result of calling :func:~`flatten_and_batch_shift_indices`\n on ``indices``. This is helpful in the case that the indices can be flattened once and\n cached for many batch lookups.\n\n Returns\n -------\n selected_targets : ``torch.Tensor``\n A tensor with shape [indices.size(), target.size(-1)] representing the embedded indices\n extracted from the batch flattened target tensor.\n \"\"\"\n if flattened_indices is None:\n # Shape: (batch_size * d_1 * ... * d_n)\n flattened_indices = flatten_and_batch_shift_indices(indices, target.size(1))\n\n # Shape: (batch_size * sequence_length, embedding_size)\n flattened_target = target.view(-1, target.size(-1))\n\n # Shape: (batch_size * d_1 * ... * d_n, embedding_size)\n flattened_selected = flattened_target.index_select(0, flattened_indices)\n selected_shape = list(indices.size()) + [target.size(-1)]\n # Shape: (batch_size, d_1, ..., d_n, embedding_size)\n selected_targets = flattened_selected.view(*selected_shape)\n return selected_targets\n\n\ndef flattened_index_select(target: torch.Tensor, indices: torch.LongTensor) -> torch.Tensor:\n \"\"\"\n The given ``indices`` of size ``(set_size, subset_size)`` specifies subsets of the ``target``\n that each of the set_size rows should select. The `target` has size\n ``(batch_size, sequence_length, embedding_size)``, and the resulting selected tensor has size\n ``(batch_size, set_size, subset_size, embedding_size)``.\n\n Parameters\n ----------\n target : ``torch.Tensor``, required.\n A Tensor of shape (batch_size, sequence_length, embedding_size).\n indices : ``torch.LongTensor``, required.\n A LongTensor of shape (set_size, subset_size). All indices must be < sequence_length\n as this tensor is an index into the sequence_length dimension of the target.\n\n Returns\n -------\n selected : ``torch.Tensor``, required.\n A Tensor of shape (batch_size, set_size, subset_size, embedding_size).\n \"\"\"\n if indices.dim() != 2:\n raise ConfigurationError(\n \"Indices passed to flattened_index_select had shape {} but \"\n \"only 2 dimensional inputs are supported.\".format(indices.size())\n )\n # Shape: (batch_size, set_size * subset_size, embedding_size)\n flattened_selected = target.index_select(1, indices.view(-1))\n\n # Shape: (batch_size, set_size, subset_size, embedding_size)\n selected = flattened_selected.view(target.size(0), indices.size(0), indices.size(1), -1)\n return selected\n\n\ndef get_range_vector(size: int, device: int) -> torch.Tensor:\n \"\"\"\n Returns a range vector with the desired size, starting at 0. The CUDA implementation\n is meant to avoid copy data from CPU to GPU.\n \"\"\"\n if device > -1:\n return torch.cuda.LongTensor(size, device=device).fill_(1).cumsum(0) - 1\n else:\n return torch.arange(0, size, dtype=torch.long)\n\n\ndef bucket_values(\n distances: torch.Tensor, num_identity_buckets: int = 4, num_total_buckets: int = 10\n) -> torch.Tensor:\n \"\"\"\n Places the given values (designed for distances) into ``num_total_buckets``semi-logscale\n buckets, with ``num_identity_buckets`` of these capturing single values.\n\n The default settings will bucket values into the following buckets:\n [0, 1, 2, 3, 4, 5-7, 8-15, 16-31, 32-63, 64+].\n\n Parameters\n ----------\n distances : ``torch.Tensor``, required.\n A Tensor of any size, to be bucketed.\n num_identity_buckets: int, optional (default = 4).\n The number of identity buckets (those only holding a single value).\n num_total_buckets : int, (default = 10)\n The total number of buckets to bucket values into.\n\n Returns\n -------\n A tensor of the same shape as the input, containing the indices of the buckets\n the values were placed in.\n \"\"\"\n # Chunk the values into semi-logscale buckets using .floor().\n # This is a semi-logscale bucketing because we divide by log(2) after taking the log.\n # We do this to make the buckets more granular in the initial range, where we expect\n # most values to fall. We then add (num_identity_buckets - 1) because we want these indices\n # to start _after_ the fixed number of buckets which we specified would only hold single values.\n logspace_index = (distances.float().log() / math.log(2)).floor().long() + (\n num_identity_buckets - 1\n )\n # create a mask for values which will go into single number buckets (i.e not a range).\n use_identity_mask = (distances <= num_identity_buckets).long()\n use_buckets_mask = 1 + (-1 * use_identity_mask)\n # Use the original values if they are less than num_identity_buckets, otherwise\n # use the logspace indices.\n combined_index = use_identity_mask * distances + use_buckets_mask * logspace_index\n # Clamp to put anything > num_total_buckets into the final bucket.\n return combined_index.clamp(0, num_total_buckets - 1)\n\n\ndef add_sentence_boundary_token_ids(\n tensor: torch.Tensor, mask: torch.Tensor, sentence_begin_token: Any, sentence_end_token: Any\n) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Add begin/end of sentence tokens to the batch of sentences.\n Given a batch of sentences with size ``(batch_size, timesteps)`` or\n ``(batch_size, timesteps, dim)`` this returns a tensor of shape\n ``(batch_size, timesteps + 2)`` or ``(batch_size, timesteps + 2, dim)`` respectively.\n\n Returns both the new tensor and updated mask.\n\n Parameters\n ----------\n tensor : ``torch.Tensor``\n A tensor of shape ``(batch_size, timesteps)`` or ``(batch_size, timesteps, dim)``\n mask : ``torch.Tensor``\n A tensor of shape ``(batch_size, timesteps)``\n sentence_begin_token: Any (anything that can be broadcast in torch for assignment)\n For 2D input, a scalar with the <S> id. For 3D input, a tensor with length dim.\n sentence_end_token: Any (anything that can be broadcast in torch for assignment)\n For 2D input, a scalar with the </S> id. For 3D input, a tensor with length dim.\n\n Returns\n -------\n tensor_with_boundary_tokens : ``torch.Tensor``\n The tensor with the appended and prepended boundary tokens. If the input was 2D,\n it has shape (batch_size, timesteps + 2) and if the input was 3D, it has shape\n (batch_size, timesteps + 2, dim).\n new_mask : ``torch.Tensor``\n The new mask for the tensor, taking into account the appended tokens\n marking the beginning and end of the sentence.\n \"\"\"\n # TODO: matthewp, profile this transfer\n sequence_lengths = mask.sum(dim=1).detach().cpu().numpy()\n tensor_shape = list(tensor.data.shape)\n new_shape = list(tensor_shape)\n new_shape[1] = tensor_shape[1] + 2\n tensor_with_boundary_tokens = tensor.new_zeros(*new_shape)\n if len(tensor_shape) == 2:\n tensor_with_boundary_tokens[:, 1:-1] = tensor\n tensor_with_boundary_tokens[:, 0] = sentence_begin_token\n for i, j in enumerate(sequence_lengths):\n tensor_with_boundary_tokens[i, j + 1] = sentence_end_token\n new_mask = (tensor_with_boundary_tokens != 0).long()\n elif len(tensor_shape) == 3:\n tensor_with_boundary_tokens[:, 1:-1, :] = tensor\n for i, j in enumerate(sequence_lengths):\n tensor_with_boundary_tokens[i, 0, :] = sentence_begin_token\n tensor_with_boundary_tokens[i, j + 1, :] = sentence_end_token\n new_mask = ((tensor_with_boundary_tokens > 0).long().sum(dim=-1) > 0).long()\n else:\n raise ValueError(\"add_sentence_boundary_token_ids only accepts 2D and 3D input\")\n\n return tensor_with_boundary_tokens, new_mask\n\n\ndef remove_sentence_boundaries(\n tensor: torch.Tensor, mask: torch.Tensor\n) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Remove begin/end of sentence embeddings from the batch of sentences.\n Given a batch of sentences with size ``(batch_size, timesteps, dim)``\n this returns a tensor of shape ``(batch_size, timesteps - 2, dim)`` after removing\n the beginning and end sentence markers. The sentences are assumed to be padded on the right,\n with the beginning of each sentence assumed to occur at index 0 (i.e., ``mask[:, 0]`` is assumed\n to be 1).\n\n Returns both the new tensor and updated mask.\n\n This function is the inverse of ``add_sentence_boundary_token_ids``.\n\n Parameters\n ----------\n tensor : ``torch.Tensor``\n A tensor of shape ``(batch_size, timesteps, dim)``\n mask : ``torch.Tensor``\n A tensor of shape ``(batch_size, timesteps)``\n\n Returns\n -------\n tensor_without_boundary_tokens : ``torch.Tensor``\n The tensor after removing the boundary tokens of shape ``(batch_size, timesteps - 2, dim)``\n new_mask : ``torch.Tensor``\n The new mask for the tensor of shape ``(batch_size, timesteps - 2)``.\n \"\"\"\n # TODO: matthewp, profile this transfer\n sequence_lengths = mask.sum(dim=1).detach().cpu().numpy()\n tensor_shape = list(tensor.data.shape)\n new_shape = list(tensor_shape)\n new_shape[1] = tensor_shape[1] - 2\n tensor_without_boundary_tokens = tensor.new_zeros(*new_shape)\n new_mask = tensor.new_zeros((new_shape[0], new_shape[1]), dtype=torch.long)\n for i, j in enumerate(sequence_lengths):\n if j > 2:\n tensor_without_boundary_tokens[i, : (j - 2), :] = tensor[i, 1 : (j - 1), :]\n new_mask[i, : (j - 2)] = 1\n\n return tensor_without_boundary_tokens, new_mask\n\n\ndef add_positional_features(\n tensor: torch.Tensor, min_timescale: float = 1.0, max_timescale: float = 1.0e4\n):\n\n \"\"\"\n Implements the frequency-based positional encoding described\n in `Attention is all you Need\n <https://www.semanticscholar.org/paper/Attention-Is-All-You-Need-Vaswani-Shazeer/0737da0767d77606169cbf4187b83e1ab62f6077>`_ .\n\n Adds sinusoids of different frequencies to a ``Tensor``. A sinusoid of a\n different frequency and phase is added to each dimension of the input ``Tensor``.\n This allows the attention heads to use absolute and relative positions.\n\n The number of timescales is equal to hidden_dim / 2 within the range\n (min_timescale, max_timescale). For each timescale, the two sinusoidal\n signals sin(timestep / timescale) and cos(timestep / timescale) are\n generated and concatenated along the hidden_dim dimension.\n\n Parameters\n ----------\n tensor : ``torch.Tensor``\n a Tensor with shape (batch_size, timesteps, hidden_dim).\n min_timescale : ``float``, optional (default = 1.0)\n The smallest timescale to use.\n max_timescale : ``float``, optional (default = 1.0e4)\n The largest timescale to use.\n\n Returns\n -------\n The input tensor augmented with the sinusoidal frequencies.\n \"\"\" # noqa\n _, timesteps, hidden_dim = tensor.size()\n\n timestep_range = get_range_vector(timesteps, get_device_of(tensor)).data.float()\n # We're generating both cos and sin frequencies,\n # so half for each.\n num_timescales = hidden_dim // 2\n timescale_range = get_range_vector(num_timescales, get_device_of(tensor)).data.float()\n\n log_timescale_increments = math.log(float(max_timescale) / float(min_timescale)) / float(\n num_timescales - 1\n )\n inverse_timescales = min_timescale * torch.exp(timescale_range * -log_timescale_increments)\n\n # Broadcasted multiplication - shape (timesteps, num_timescales)\n scaled_time = timestep_range.unsqueeze(1) * inverse_timescales.unsqueeze(0)\n # shape (timesteps, 2 * num_timescales)\n sinusoids = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 1)\n if hidden_dim % 2 != 0:\n # if the number of dimensions is odd, the cos and sin\n # timescales had size (hidden_dim - 1) / 2, so we need\n # to add a row of zeros to make up the difference.\n sinusoids = torch.cat([sinusoids, sinusoids.new_zeros(timesteps, 1)], 1)\n return tensor + sinusoids.unsqueeze(0)\n\n\ndef clone(module: torch.nn.Module, num_copies: int) -> torch.nn.ModuleList:\n \"\"\"Produce N identical layers.\"\"\"\n return torch.nn.ModuleList([copy.deepcopy(module) for _ in range(num_copies)])\n\n\ndef combine_initial_dims(tensor: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Given a (possibly higher order) tensor of ids with shape\n (d1, ..., dn, sequence_length)\n Return a view that's (d1 * ... * dn, sequence_length).\n If original tensor is 1-d or 2-d, return it as is.\n \"\"\"\n if tensor.dim() <= 2:\n return tensor\n else:\n return tensor.view(-1, tensor.size(-1))\n\n\ndef uncombine_initial_dims(tensor: torch.Tensor, original_size: torch.Size) -> torch.Tensor:\n \"\"\"\n Given a tensor of embeddings with shape\n (d1 * ... * dn, sequence_length, embedding_dim)\n and the original shape\n (d1, ..., dn, sequence_length),\n return the reshaped tensor of embeddings with shape\n (d1, ..., dn, sequence_length, embedding_dim).\n If original size is 1-d or 2-d, return it as is.\n \"\"\"\n if len(original_size) <= 2:\n return tensor\n else:\n view_args = list(original_size) + [tensor.size(-1)]\n return tensor.view(*view_args)\n\n\ndef inspect_parameters(module: torch.nn.Module, quiet: bool = False) -> Dict[str, Any]:\n \"\"\"\n Inspects the model/module parameters and their tunability. The output is structured\n in a nested dict so that parameters in same sub-modules are grouped together.\n This can be helpful to setup module path based regex, for example in initializer.\n It prints it by default (optional) and returns the inspection dict. Eg. output::\n\n {\n \"_text_field_embedder\": {\n \"token_embedder_tokens\": {\n \"_projection\": {\n \"bias\": \"tunable\",\n \"weight\": \"tunable\"\n },\n \"weight\": \"frozen\"\n }\n }\n }\n\n \"\"\"\n results: Dict[str, Any] = {}\n for name, param in sorted(module.named_parameters()):\n keys = name.split(\".\")\n write_to = results\n for key in keys[:-1]:\n if key not in write_to:\n write_to[key] = {}\n write_to = write_to[key]\n write_to[keys[-1]] = \"tunable\" if param.requires_grad else \"frozen\"\n if not quiet:\n print(json.dumps(results, indent=4))\n return results\n\n\ndef find_embedding_layer(model: torch.nn.Module) -> torch.nn.Module:\n \"\"\"\n Takes a model (typically an AllenNLP ``Model``, but this works for any ``torch.nn.Module``) and\n makes a best guess about which module is the embedding layer. For typical AllenNLP models,\n this often is the ``TextFieldEmbedder``, but if you're using a pre-trained contextualizer, we\n really want layer 0 of that contextualizer, not the output. So there are a bunch of hacks in\n here for specific pre-trained contextualizers.\n \"\"\"\n # We'll look for a few special cases in a first pass, then fall back to just finding a\n # TextFieldEmbedder in a second pass if we didn't find a special case.\n from pytorch_pretrained_bert.modeling import BertEmbeddings as BertEmbeddingsOld\n from transformers.modeling_gpt2 import GPT2Model\n from transformers.modeling_bert import BertEmbeddings as BertEmbeddingsNew\n from allennlp.modules.text_field_embedders.text_field_embedder import TextFieldEmbedder\n from allennlp.modules.text_field_embedders.basic_text_field_embedder import (\n BasicTextFieldEmbedder,\n )\n from allennlp.modules.token_embedders.embedding import Embedding\n\n for module in model.modules():\n if isinstance(module, BertEmbeddingsOld):\n return module.word_embeddings\n if isinstance(module, BertEmbeddingsNew):\n return module.word_embeddings\n if isinstance(module, GPT2Model):\n return module.wte\n for module in model.modules():\n if isinstance(module, TextFieldEmbedder):\n\n if isinstance(module, BasicTextFieldEmbedder):\n # We'll have a check for single Embedding cases, because we can be more efficient\n # in cases like this. If this check fails, then for something like hotflip we need\n # to actually run the text field embedder and construct a vector for each token.\n if len(module._token_embedders) == 1:\n embedder = list(module._token_embedders.values())[0]\n if isinstance(embedder, Embedding):\n if embedder._projection is None:\n # If there's a projection inside the Embedding, then we need to return\n # the whole TextFieldEmbedder, because there's more computation that\n # needs to be done than just multiply by an embedding matrix.\n return embedder\n return module\n raise RuntimeError(\"No embedding module found!\")\n"
] | [
[
"torch.nn.functional.softmax",
"torch.max",
"torch.cat",
"torch.zeros",
"torch.sin",
"torch.nn.utils.rnn.pad_sequence",
"torch.sum",
"torch.topk",
"torch.ones",
"torch.tensor",
"torch.arange",
"torch.cos",
"torch.min",
"torch.zeros_like",
"torch.exp",
"torch.stack",
"torch.flip",
"torch.nn.functional.log_softmax",
"torch.cuda.LongTensor",
"torch.matmul",
"torch.gather"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
megachester/mlcomp | [
"8d30ba0a52e225144533e68295b71acb49e3c68a"
] | [
"mlcomp/contrib/model/video/resnext3d/resnext3d_stem.py"
] | [
"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport torch.nn as nn\n\nfrom .r2plus1_util import r2plus1_unit\n\n\nclass ResNeXt3DStemSinglePathway(nn.Module):\n \"\"\"\n ResNe(X)t 3D basic stem module. Assume a single pathway.\n Performs spatiotemporal Convolution, BN, and Relu following by a\n spatiotemporal pooling.\n \"\"\"\n\n def __init__(\n self,\n dim_in,\n dim_out,\n kernel,\n stride,\n padding,\n maxpool=True,\n inplace_relu=True,\n bn_eps=1e-5,\n bn_mmt=0.1,\n ):\n \"\"\"\n The `__init__` method of any subclass should also contain these arguments.\n\n Args:\n dim_in (int): the channel dimension of the input. Normally 3 is used\n for rgb input\n dim_out (int): the output dimension of the convolution in the stem\n layer.\n kernel (list): the kernel size of the convolution in the stem layer.\n temporal kernel size, height kernel size, width kernel size in\n order.\n stride (list): the stride size of the convolution in the stem layer.\n temporal kernel stride, height kernel size, width kernel size in\n order.\n padding (int): the padding size of the convolution in the stem\n layer, temporal padding size, height padding size, width\n padding size in order.\n maxpool (bool): If true, perform max pooling.\n inplace_relu (bool): calculate the relu on the original input\n without allocating new memory.\n bn_eps (float): epsilon for batch norm.\n bn_mmt (float): momentum for batch norm. Noted that BN momentum in\n PyTorch = 1 - BN momentum in Caffe2.\n \"\"\"\n super(ResNeXt3DStemSinglePathway, self).__init__()\n self.kernel = kernel\n self.stride = stride\n self.padding = padding\n self.inplace_relu = inplace_relu\n self.bn_eps = bn_eps\n self.bn_mmt = bn_mmt\n self.maxpool = maxpool\n\n # Construct the stem layer.\n self._construct_stem(dim_in, dim_out)\n\n def _construct_stem(self, dim_in, dim_out):\n self.conv = nn.Conv3d(\n dim_in,\n dim_out,\n self.kernel,\n stride=self.stride,\n padding=self.padding,\n bias=False,\n )\n self.bn = nn.BatchNorm3d(dim_out, eps=self.bn_eps,\n momentum=self.bn_mmt)\n self.relu = nn.ReLU(self.inplace_relu)\n if self.maxpool:\n self.pool_layer = nn.MaxPool3d(\n kernel_size=[1, 3, 3], stride=[1, 2, 2], padding=[0, 1, 1]\n )\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n x = self.relu(x)\n if self.maxpool:\n x = self.pool_layer(x)\n return x\n\n\nclass R2Plus1DStemSinglePathway(ResNeXt3DStemSinglePathway):\n \"\"\"\n R(2+1)D basic stem module. Assume a single pathway.\n Performs spatial convolution, temporal convolution, BN, and Relu following by a\n spatiotemporal pooling.\n \"\"\"\n\n def __init__(\n self,\n dim_in,\n dim_out,\n kernel,\n stride,\n padding,\n maxpool=True,\n inplace_relu=True,\n bn_eps=1e-5,\n bn_mmt=0.1,\n ):\n \"\"\"\n The `__init__` method of any subclass should also contain these arguments.\n\n Args:\n dim_in (int): the channel dimension of the input. Normally 3 is used\n for rgb input\n dim_out (int): the output dimension of the convolution in the stem\n layer.\n kernel (list): the kernel size of the convolution in the stem layer.\n temporal kernel size, height kernel size, width kernel size in\n order.\n stride (list): the stride size of the convolution in the stem layer.\n temporal kernel stride, height kernel size, width kernel size in\n order.\n padding (int): the padding size of the convolution in the stem\n layer, temporal padding size, height padding size, width\n padding size in order.\n maxpool (bool): If true, perform max pooling.\n inplace_relu (bool): calculate the relu on the original input\n without allocating new memory.\n bn_eps (float): epsilon for batch norm.\n bn_mmt (float): momentum for batch norm. Noted that BN momentum in\n PyTorch = 1 - BN momentum in Caffe2.\n \"\"\"\n super(R2Plus1DStemSinglePathway, self).__init__(\n dim_in,\n dim_out,\n kernel,\n stride,\n padding,\n maxpool=maxpool,\n inplace_relu=inplace_relu,\n bn_eps=bn_eps,\n bn_mmt=bn_mmt,\n )\n\n def _construct_stem(self, dim_in, dim_out):\n assert (\n self.stride[1] == self.stride[2]\n ), \"Only support identical height stride and width stride\"\n self.conv = r2plus1_unit(\n dim_in,\n dim_out,\n self.stride[0], # temporal_stride\n self.stride[1], # spatial_stride\n 1, # groups\n self.inplace_relu,\n self.bn_eps,\n self.bn_mmt,\n dim_mid=45, # hard-coded middle channels\n )\n self.bn = nn.BatchNorm3d(dim_out, eps=self.bn_eps,\n momentum=self.bn_mmt)\n self.relu = nn.ReLU(self.inplace_relu)\n if self.maxpool:\n self.pool_layer = nn.MaxPool3d(\n kernel_size=[1, 3, 3], stride=[1, 2, 2], padding=[0, 1, 1]\n )\n\n\nclass ResNeXt3DStemMultiPathway(nn.Module):\n \"\"\"\n Video 3D stem module. Provides stem operations of Conv, BN, ReLU, MaxPool\n on input data tensor for one or multiple pathways.\n \"\"\"\n\n def __init__(\n self,\n dim_in,\n dim_out,\n kernel,\n stride,\n padding,\n inplace_relu=True,\n bn_eps=1e-5,\n bn_mmt=0.1,\n maxpool=(True,),\n ):\n \"\"\"\n The `__init__` method of any subclass should also contain these\n arguments. List size of 1 for single pathway models (C2D, I3D, SlowOnly\n and etc), list size of 2 for two pathway models (SlowFast).\n\n Args:\n dim_in (list): the list of channel dimensions of the inputs.\n dim_out (list): the output dimension of the convolution in the stem\n layer.\n kernel (list): the kernels' size of the convolutions in the stem\n layers. Temporal kernel size, height kernel size, width kernel\n size in order.\n stride (list): the stride sizes of the convolutions in the stem\n layer. Temporal kernel stride, height kernel size, width kernel\n size in order.\n padding (list): the paddings' sizes of the convolutions in the stem\n layer. Temporal padding size, height padding size, width padding\n size in order.\n inplace_relu (bool): calculate the relu on the original input\n without allocating new memory.\n bn_eps (float): epsilon for batch norm.\n bn_mmt (float): momentum for batch norm. Noted that BN momentum in\n PyTorch = 1 - BN momentum in Caffe2.\n maxpool (iterable): At training time, when crop size is 224 x 224, do max\n pooling. When crop size is 112 x 112, skip max pooling.\n Default value is a (True,)\n \"\"\"\n super(ResNeXt3DStemMultiPathway, self).__init__()\n\n assert (\n len({len(dim_in), len(dim_out), len(kernel), len(stride),\n len(padding)})\n == 1\n ), \"Input pathway dimensions are not consistent.\"\n self.num_pathways = len(dim_in)\n self.kernel = kernel\n self.stride = stride\n self.padding = padding\n self.inplace_relu = inplace_relu\n self.bn_eps = bn_eps\n self.bn_mmt = bn_mmt\n self.maxpool = maxpool\n\n # Construct the stem layer.\n self._construct_stem(dim_in, dim_out)\n\n def _construct_stem(self, dim_in, dim_out):\n assert type(dim_in) == list\n assert all(dim > 0 for dim in dim_in)\n assert type(dim_out) == list\n assert all(dim > 0 for dim in dim_out)\n\n self.blocks = {}\n for p in range(len(dim_in)):\n stem = ResNeXt3DStemSinglePathway(\n dim_in[p],\n dim_out[p],\n self.kernel[p],\n self.stride[p],\n self.padding[p],\n inplace_relu=self.inplace_relu,\n bn_eps=self.bn_eps,\n bn_mmt=self.bn_mmt,\n maxpool=self.maxpool[p],\n )\n stem_name = self._stem_name(p)\n self.add_module(stem_name, stem)\n self.blocks[stem_name] = stem\n\n def _stem_name(self, path_idx):\n return \"stem-path{}\".format(path_idx)\n\n def forward(self, x):\n assert (\n len(x) == self.num_pathways\n ), \"Input tensor does not contain {} pathway\".format(self.num_pathways)\n for p in range(len(x)):\n stem_name = self._stem_name(p)\n x[p] = self.blocks[stem_name](x[p])\n return x\n\n\nclass R2Plus1DStemMultiPathway(ResNeXt3DStemMultiPathway):\n \"\"\"\n Video R(2+1)D stem module. Provides stem operations of Conv, BN, ReLU, MaxPool\n on input data tensor for one or multiple pathways.\n \"\"\"\n\n def __init__(\n self,\n dim_in,\n dim_out,\n kernel,\n stride,\n padding,\n inplace_relu=True,\n bn_eps=1e-5,\n bn_mmt=0.1,\n maxpool=(True,),\n ):\n \"\"\"\n The `__init__` method of any subclass should also contain these\n arguments. List size of 1 for single pathway models (C2D, I3D, SlowOnly\n and etc), list size of 2 for two pathway models (SlowFast).\n\n Args:\n dim_in (list): the list of channel dimensions of the inputs.\n dim_out (list): the output dimension of the convolution in the stem\n layer.\n kernel (list): the kernels' size of the convolutions in the stem\n layers. Temporal kernel size, height kernel size, width kernel\n size in order.\n stride (list): the stride sizes of the convolutions in the stem\n layer. Temporal kernel stride, height kernel size, width kernel\n size in order.\n padding (list): the paddings' sizes of the convolutions in the stem\n layer. Temporal padding size, height padding size, width padding\n size in order.\n inplace_relu (bool): calculate the relu on the original input\n without allocating new memory.\n bn_eps (float): epsilon for batch norm.\n bn_mmt (float): momentum for batch norm. Noted that BN momentum in\n PyTorch = 1 - BN momentum in Caffe2.\n maxpool (iterable): At training time, when crop size is 224 x 224, do max\n pooling. When crop size is 112 x 112, skip max pooling.\n Default value is a (True,)\n \"\"\"\n super(R2Plus1DStemMultiPathway, self).__init__(\n dim_in,\n dim_out,\n kernel,\n stride,\n padding,\n inplace_relu=inplace_relu,\n bn_eps=bn_eps,\n bn_mmt=bn_mmt,\n maxpool=maxpool,\n )\n\n def _construct_stem(self, dim_in, dim_out):\n assert type(dim_in) == list\n assert all(dim > 0 for dim in dim_in)\n assert type(dim_out) == list\n assert all(dim > 0 for dim in dim_out)\n\n self.blocks = {}\n for p in range(len(dim_in)):\n stem = R2Plus1DStemSinglePathway(\n dim_in[p],\n dim_out[p],\n self.kernel[p],\n self.stride[p],\n self.padding[p],\n inplace_relu=self.inplace_relu,\n bn_eps=self.bn_eps,\n bn_mmt=self.bn_mmt,\n maxpool=self.maxpool[p],\n )\n stem_name = self._stem_name(p)\n self.add_module(stem_name, stem)\n self.blocks[stem_name] = stem\n\n\nclass ResNeXt3DStem(nn.Module):\n def __init__(\n self, temporal_kernel, spatial_kernel, input_planes, stem_planes,\n maxpool\n ):\n super(ResNeXt3DStem, self).__init__()\n self._construct_stem(\n temporal_kernel, spatial_kernel, input_planes, stem_planes, maxpool\n )\n\n def _construct_stem(\n self, temporal_kernel, spatial_kernel, input_planes, stem_planes,\n maxpool\n ):\n self.stem = ResNeXt3DStemMultiPathway(\n [input_planes],\n [stem_planes],\n [[temporal_kernel, spatial_kernel, spatial_kernel]],\n [[1, 2, 2]], # stride\n [\n [temporal_kernel // 2, spatial_kernel // 2,\n spatial_kernel // 2]\n ], # padding\n maxpool=[maxpool],\n )\n\n def forward(self, x):\n return self.stem(x)\n\n\nclass R2Plus1DStem(ResNeXt3DStem):\n def __init__(\n self, temporal_kernel, spatial_kernel, input_planes, stem_planes,\n maxpool\n ):\n super(R2Plus1DStem, self).__init__(\n temporal_kernel, spatial_kernel, input_planes, stem_planes, maxpool\n )\n\n def _construct_stem(\n self, temporal_kernel, spatial_kernel, input_planes, stem_planes,\n maxpool\n ):\n self.stem = R2Plus1DStemMultiPathway(\n [input_planes],\n [stem_planes],\n [[temporal_kernel, spatial_kernel, spatial_kernel]],\n [[1, 2, 2]], # stride\n [\n [temporal_kernel // 2, spatial_kernel // 2,\n spatial_kernel // 2]\n ], # padding\n maxpool=[maxpool],\n )\n"
] | [
[
"torch.nn.MaxPool3d",
"torch.nn.Conv3d",
"torch.nn.BatchNorm3d",
"torch.nn.ReLU"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mathblue/Custom-Pose-Estimation-Yaw-Roll-Pitch-detection-tensorrt-compilation | [
"1a8501f0634c2cd81955d0ec3ec5837af04f893b"
] | [
"custom_pose/tensorrt/demo-trt.py"
] | [
"import argparse\n\nimport cv2\nimport numpy as np\nimport torch\nfrom torch2trt import torch2trt\nfrom torch2trt import TRTModule\n\nfrom models.with_mobilenet import PoseEstimationWithMobileNet\nfrom modules.keypoints import extract_keypoints, group_keypoints\nfrom modules.load_state import load_state\nfrom modules.pose import Pose, propagate_ids\nimport math\nfrom cfg.config import*\n#from val import normalize, pad_width\n\n\nclass ImageReader(object):\n def __init__(self, file_names):\n self.file_names = file_names\n self.max_idx = len(file_names)\n\n def __iter__(self):\n self.idx = 0\n return self\n\n def __next__(self):\n if self.idx == self.max_idx:\n raise StopIteration\n img = cv2.imread(self.file_names[self.idx], cv2.IMREAD_COLOR)\n if img.size == 0:\n raise IOError('Image {} cannot be read'.format(self.file_names[self.idx]))\n self.idx = self.idx + 1\n return img\n\n\nclass VideoReader(object):\n def __init__(self, file_name):\n self.file_name = file_name\n try: # OpenCV needs int to read from webcam\n self.file_name = int(file_name)\n except ValueError:\n pass\n\n def __iter__(self):\n self.cap = cv2.VideoCapture(self.file_name)\n if not self.cap.isOpened():\n raise IOError('Video {} cannot be opened'.format(self.file_name))\n return self\n\n def __next__(self):\n was_read, img = self.cap.read()\n if not was_read:\n raise StopIteration\n return img\n\n\ndef infer_fast(net, img, net_input_height_size, stride, upsample_ratio, cpu,\n pad_value=(0, 0, 0), img_mean=(128, 128, 128), img_scale=1/256):\n height, width, _ = img.shape\n scale = net_input_height_size / height\n\n scaled_img = cv2.resize(img, (0, 0), fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC)\n scaled_img = normalize(scaled_img, img_mean, img_scale)\n min_dims = [net_input_height_size, max(scaled_img.shape[1], net_input_height_size)]\n padded_img, pad = pad_width(scaled_img, stride, pad_value, min_dims)\n\n tensor_img = torch.from_numpy(padded_img).permute(2, 0, 1).unsqueeze(0).float()\n if not cpu:\n tensor_img = tensor_img.cuda()\n stages_output = net(tensor_img)\n stage2_heatmaps = stages_output[-2]\n heatmaps = np.transpose(stage2_heatmaps.squeeze().cpu().data.numpy(), (1, 2, 0))\n heatmaps = cv2.resize(heatmaps, (0, 0), fx=upsample_ratio, fy=upsample_ratio, interpolation=cv2.INTER_CUBIC)\n\n stage2_pafs = stages_output[-1]\n pafs = np.transpose(stage2_pafs.squeeze().cpu().data.numpy(), (1, 2, 0))\n pafs = cv2.resize(pafs, (0, 0), fx=upsample_ratio, fy=upsample_ratio, interpolation=cv2.INTER_CUBIC)\n\n return heatmaps, pafs, scale, pad\n\n\ndef run_demo(net, image_provider, height_size, cpu, track_ids):\n net = net.eval()\n if not cpu:\n net = net.cuda()\n\n stride = 8\n upsample_ratio = 4\n num_keypoints = num_keys\n previous_poses = []\n for img in image_provider:\n orig_img = img.copy()\n heatmaps, pafs, scale, pad = infer_fast(net, img, height_size, stride, upsample_ratio, cpu)\n total_keypoints_num = 0\n all_keypoints_by_type = []\n for kpt_idx in range(num_keypoints): # 19th for bg\n total_keypoints_num += extract_keypoints(heatmaps[:, :, kpt_idx], all_keypoints_by_type, total_keypoints_num)\n pose_entries, all_keypoints = group_keypoints(all_keypoints_by_type, pafs, demo=True)\n for kpt_id in range(all_keypoints.shape[0]):\n all_keypoints[kpt_id, 0] = (all_keypoints[kpt_id, 0] * stride / upsample_ratio - pad[1]) / scale\n all_keypoints[kpt_id, 1] = (all_keypoints[kpt_id, 1] * stride / upsample_ratio - pad[0]) / scale\n current_poses = []\n for n in range(len(pose_entries)):\n if len(pose_entries[n]) == 0:\n continue\n pose_keypoints = np.ones((num_keypoints, 2), dtype=np.int32) * -1\n for kpt_id in range(num_keypoints):\n if pose_entries[n][kpt_id] != -1.0: # keypoint was found\n pose_keypoints[kpt_id, 0] = int(all_keypoints[int(pose_entries[n][kpt_id]), 0])\n pose_keypoints[kpt_id, 1] = int(all_keypoints[int(pose_entries[n][kpt_id]), 1])\n pose = Pose(pose_keypoints, pose_entries[n][num_keypoints])\n current_poses.append(pose)\n pose.draw(img)\n\n img = cv2.addWeighted(orig_img, 0.6, img, 0.4, 0)\n if track_ids == True:\n propagate_ids(previous_poses, current_poses)\n previous_poses = current_poses\n for pose in current_poses:\n cv2.rectangle(img, (pose.bbox[0], pose.bbox[1]),\n (pose.bbox[0] + pose.bbox[2], pose.bbox[1] + pose.bbox[3]), (0, 255, 0))\n cv2.putText(img, 'id: {}'.format(pose.id), (pose.bbox[0], pose.bbox[1] - 16),\n cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 255))\n #cv2.imwrite('/content/out.jpg', img)\n cv2.imshow('Lightweight Human Pose Estimation Python Demo', img)\n key = cv2.waitKey(33)\n if key == 27: # esc\n return\n\ndef normalize(img, img_mean, img_scale):\n img = np.array(img, dtype=np.float32)\n img = (img - img_mean) * img_scale\n return img\n\n\ndef pad_width(img, stride, pad_value, min_dims):\n h, w, _ = img.shape\n h = min(min_dims[0], h)\n min_dims[0] = math.ceil(min_dims[0] / float(stride)) * stride\n min_dims[1] = max(min_dims[1], w)\n min_dims[1] = math.ceil(min_dims[1] / float(stride)) * stride\n pad = []\n pad.append(int(math.floor((min_dims[0] - h) / 2.0)))\n pad.append(int(math.floor((min_dims[1] - w) / 2.0)))\n pad.append(int(min_dims[0] - h - pad[0]))\n pad.append(int(min_dims[1] - w - pad[1]))\n padded_img = cv2.copyMakeBorder(img, pad[0], pad[2], pad[1], pad[3],\n cv2.BORDER_CONSTANT, value=pad_value)\n return padded_img, pad\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='''Lightweight human pose estimation python demo.\n This is just for quick results preview.\n Please, consider c++ demo for the best performance.''')\n parser.add_argument('--checkpoint-path', type=str, required=True, help='path to the checkpoint')\n parser.add_argument('--height-size', type=int, default=256, help='network input layer height size')\n parser.add_argument('--video', type=str, default='', help='path to video file or camera id')\n parser.add_argument('--images', nargs='+', default='', help='path to input image(s)')\n parser.add_argument('--cpu', action='store_true', help='run network inference on cpu')\n parser.add_argument('--track-ids', default=True, help='track poses ids')\n args = parser.parse_args()\n\n if args.video == '' and args.images == '':\n raise ValueError('Either --video or --image has to be provided')\n\n net =TRTModule()\n net.load_state_dict(torch.load('net_trt.pth'))\n #checkpoint = torch.load(args.checkpoint_path, map_location='cuda')\n #load_state(net, checkpoint)\n\n frame_provider = ImageReader(args.images)\n if args.video != '':\n frame_provider = VideoReader(args.video)\n\n run_demo(net, frame_provider, args.height_size, args.cpu, args.track_ids)\n"
] | [
[
"numpy.ones",
"numpy.array",
"torch.from_numpy",
"torch.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
29riyasaxena/MDF | [
"476e6950d0f14f29463eb4f6e3be518dfb2160a5"
] | [
"examples/PyTorch/inception.py"
] | [
"import numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom modeci_mdf.interfaces.pytorch import pytorch_to_mdf\n\n\nclass InceptionBlocks(nn.Module):\n \"\"\"An Inception-like model provided as a test case by the WebGME folks\"\"\"\n\n def __init__(self):\n super().__init__()\n\n self.asymmetric_pad = nn.ZeroPad2d((0, 1, 0, 1))\n self.conv2d = nn.Conv2d(\n in_channels=5, out_channels=64, kernel_size=(5, 5), padding=2, bias=True\n )\n self.prelu = nn.PReLU(init=0.0)\n self.averagepooling2d = nn.AvgPool2d((2, 2), stride=2, padding=0)\n self.conv2d2 = nn.Conv2d(\n in_channels=64, out_channels=48, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu2 = nn.PReLU(init=0.0)\n self.conv2d3 = nn.Conv2d(\n in_channels=48, out_channels=64, kernel_size=(3, 3), padding=1, bias=True\n )\n self.prelu3 = nn.PReLU(init=0.0)\n self.conv2d4 = nn.Conv2d(\n in_channels=64, out_channels=48, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu4 = nn.PReLU(init=0.0)\n self.averagepooling2d2 = nn.AvgPool2d((2, 2), stride=1)\n self.conv2d5 = nn.Conv2d(\n in_channels=64, out_channels=64, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu5 = nn.PReLU(init=0.0)\n self.conv2d6 = nn.Conv2d(\n in_channels=64, out_channels=48, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu6 = nn.PReLU(init=0.0)\n self.conv2d7 = nn.Conv2d(\n in_channels=48, out_channels=64, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu7 = nn.PReLU(init=0.0)\n self.conv2d8 = nn.Conv2d(\n in_channels=240, out_channels=64, kernel_size=(1, 1), padding=0, bias=True\n )\n self.conv2d9 = nn.Conv2d(\n in_channels=240, out_channels=92, kernel_size=(1, 1), padding=0, bias=True\n )\n self.conv2d10 = nn.Conv2d(\n in_channels=240, out_channels=64, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu8 = nn.PReLU(init=0.0)\n self.conv2d11 = nn.Conv2d(\n in_channels=64, out_channels=92, kernel_size=(5, 5), padding=2, bias=True\n )\n self.prelu9 = nn.PReLU(init=0.0)\n self.prelu10 = nn.PReLU(init=0.0)\n self.averagepooling2d3 = nn.AvgPool2d((2, 2), stride=1, padding=0)\n self.conv2d12 = nn.Conv2d(\n in_channels=240, out_channels=64, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu11 = nn.PReLU(init=0.0)\n self.conv2d13 = nn.Conv2d(\n in_channels=64, out_channels=92, kernel_size=(3, 3), padding=1, bias=True\n )\n self.prelu12 = nn.PReLU(init=0.0)\n self.prelu13 = nn.PReLU(init=0.0)\n self.averagepooling2d4 = nn.AvgPool2d((2, 2), stride=2, padding=0)\n self.conv2d14 = nn.Conv2d(\n in_channels=340, out_channels=92, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu14 = nn.PReLU(init=0.0)\n self.conv2d15 = nn.Conv2d(\n in_channels=92, out_channels=128, kernel_size=(5, 5), padding=2, bias=True\n )\n self.prelu15 = nn.PReLU(init=0.0)\n self.conv2d16 = nn.Conv2d(\n in_channels=340, out_channels=128, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu16 = nn.PReLU(init=0.0)\n self.conv2d17 = nn.Conv2d(\n in_channels=340, out_channels=92, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu17 = nn.PReLU(init=0.0)\n self.averagepooling2d5 = nn.AvgPool2d((2, 2), stride=1, padding=0)\n self.conv2d18 = nn.Conv2d(\n in_channels=340, out_channels=92, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu18 = nn.PReLU(init=0.0)\n self.conv2d19 = nn.Conv2d(\n in_channels=92, out_channels=128, kernel_size=(3, 3), padding=1, bias=True\n )\n self.prelu19 = nn.PReLU(init=0.0)\n self.conv2d20 = nn.Conv2d(\n in_channels=476, out_channels=92, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu20 = nn.PReLU(init=0.0)\n self.conv2d21 = nn.Conv2d(\n in_channels=92, out_channels=128, kernel_size=(3, 3), padding=1, bias=True\n )\n self.prelu21 = nn.PReLU(init=0.0)\n self.conv2d22 = nn.Conv2d(\n in_channels=476, out_channels=92, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu22 = nn.PReLU(init=0.0)\n self.averagepooling2d6 = nn.AvgPool2d((2, 2), stride=1, padding=0)\n self.conv2d23 = nn.Conv2d(\n in_channels=476, out_channels=92, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu23 = nn.PReLU(init=0.0)\n self.conv2d24 = nn.Conv2d(\n in_channels=92, out_channels=128, kernel_size=(5, 5), padding=2, bias=True\n )\n self.prelu24 = nn.PReLU(init=0.0)\n self.conv2d25 = nn.Conv2d(\n in_channels=476, out_channels=128, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu25 = nn.PReLU(init=0.0)\n self.averagepooling2d7 = nn.AvgPool2d((2, 2), stride=2, padding=0)\n self.conv2d26 = nn.Conv2d(\n in_channels=476, out_channels=92, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu26 = nn.PReLU(init=0.0)\n self.averagepooling2d8 = nn.AvgPool2d((2, 2), stride=1, padding=0)\n self.conv2d27 = nn.Conv2d(\n in_channels=476, out_channels=92, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu27 = nn.PReLU(init=0.0)\n self.conv2d28 = nn.Conv2d(\n in_channels=92, out_channels=128, kernel_size=(3, 3), padding=1, bias=True\n )\n self.prelu28 = nn.PReLU(init=0.0)\n self.conv2d29 = nn.Conv2d(\n in_channels=476, out_channels=128, kernel_size=(1, 1), padding=0, bias=True\n )\n self.prelu29 = nn.PReLU(init=0.0)\n self.dense = nn.Linear(22273, 1096, bias=True)\n self.prelu30 = nn.PReLU(init=0.0)\n self.dense2 = nn.Linear(1096, 1096, bias=True)\n self.prelu31 = nn.PReLU(init=0.0)\n self.dense3 = nn.Linear(1096, 180, bias=True)\n\n def forward(self, galaxy_images_output, ebv_output):\n conv2d_output = self.conv2d(galaxy_images_output)\n prelu_output = self.prelu(conv2d_output)\n averagepooling2d_output = self.averagepooling2d(prelu_output)\n conv2d_output2 = self.conv2d2(averagepooling2d_output)\n prelu_output2 = self.prelu2(conv2d_output2)\n conv2d_output3 = self.conv2d3(prelu_output2)\n prelu_output3 = self.prelu3(conv2d_output3)\n conv2d_output4 = self.conv2d4(averagepooling2d_output)\n prelu_output4 = self.prelu4(conv2d_output4)\n prelu_output4 = self.asymmetric_pad(prelu_output4)\n averagepooling2d_output2 = self.averagepooling2d2(prelu_output4)\n conv2d_output5 = self.conv2d5(averagepooling2d_output)\n prelu_output5 = self.prelu5(conv2d_output5)\n conv2d_output6 = self.conv2d6(averagepooling2d_output)\n prelu_output6 = self.prelu6(conv2d_output6)\n conv2d_output7 = self.conv2d7(prelu_output6)\n prelu_output7 = self.prelu7(conv2d_output7)\n concatenate_output = torch.cat(\n (prelu_output5, prelu_output3, prelu_output7, averagepooling2d_output2),\n dim=1,\n )\n conv2d_output8 = self.conv2d8(concatenate_output)\n conv2d_output9 = self.conv2d9(concatenate_output)\n conv2d_output10 = self.conv2d10(concatenate_output)\n prelu_output8 = self.prelu8(conv2d_output10)\n conv2d_output11 = self.conv2d11(prelu_output8)\n prelu_output9 = self.prelu9(conv2d_output11)\n prelu_output10 = self.prelu10(conv2d_output8)\n prelu_output10 = self.asymmetric_pad(prelu_output10)\n averagepooling2d_output3 = self.averagepooling2d3(prelu_output10)\n conv2d_output12 = self.conv2d12(concatenate_output)\n prelu_output11 = self.prelu11(conv2d_output12)\n conv2d_output13 = self.conv2d13(prelu_output11)\n prelu_output12 = self.prelu12(conv2d_output13)\n prelu_output13 = self.prelu13(conv2d_output9)\n concatenate_output2 = torch.cat(\n (prelu_output13, prelu_output12, prelu_output9, averagepooling2d_output3),\n dim=1,\n )\n averagepooling2d_output4 = self.averagepooling2d4(concatenate_output2)\n conv2d_output14 = self.conv2d14(averagepooling2d_output4)\n prelu_output14 = self.prelu14(conv2d_output14)\n conv2d_output15 = self.conv2d15(prelu_output14)\n prelu_output15 = self.prelu15(conv2d_output15)\n conv2d_output16 = self.conv2d16(averagepooling2d_output4)\n prelu_output16 = self.prelu16(conv2d_output16)\n conv2d_output17 = self.conv2d17(averagepooling2d_output4)\n prelu_output17 = self.prelu17(conv2d_output17)\n prelu_output17 = self.asymmetric_pad(prelu_output17)\n averagepooling2d_output5 = self.averagepooling2d5(prelu_output17)\n conv2d_output18 = self.conv2d18(averagepooling2d_output4)\n prelu_output18 = self.prelu18(conv2d_output18)\n conv2d_output19 = self.conv2d19(prelu_output18)\n prelu_output19 = self.prelu19(conv2d_output19)\n concatenate_output3 = torch.cat(\n (prelu_output16, prelu_output19, prelu_output15, averagepooling2d_output5),\n dim=1,\n )\n conv2d_output20 = self.conv2d20(concatenate_output3)\n prelu_output20 = self.prelu20(conv2d_output20)\n conv2d_output21 = self.conv2d21(prelu_output20)\n prelu_output21 = self.prelu21(conv2d_output21)\n conv2d_output22 = self.conv2d22(concatenate_output3)\n prelu_output22 = self.prelu22(conv2d_output22)\n prelu_output22 = self.asymmetric_pad(prelu_output22)\n averagepooling2d_output6 = self.averagepooling2d6(prelu_output22)\n conv2d_output23 = self.conv2d23(concatenate_output3)\n prelu_output23 = self.prelu23(conv2d_output23)\n conv2d_output24 = self.conv2d24(prelu_output23)\n prelu_output24 = self.prelu24(conv2d_output24)\n conv2d_output25 = self.conv2d25(concatenate_output3)\n prelu_output25 = self.prelu25(conv2d_output25)\n concatenate_output4 = torch.cat(\n (prelu_output25, prelu_output21, prelu_output24, averagepooling2d_output6),\n dim=1,\n )\n averagepooling2d_output7 = self.averagepooling2d7(concatenate_output4)\n conv2d_output26 = self.conv2d26(averagepooling2d_output7)\n prelu_output26 = self.prelu26(conv2d_output26)\n prelu_output26 = self.asymmetric_pad(prelu_output26)\n averagepooling2d_output8 = self.averagepooling2d8(prelu_output26)\n conv2d_output27 = self.conv2d27(averagepooling2d_output7)\n prelu_output27 = self.prelu27(conv2d_output27)\n conv2d_output28 = self.conv2d28(prelu_output27)\n prelu_output28 = self.prelu28(conv2d_output28)\n conv2d_output29 = self.conv2d29(averagepooling2d_output7)\n prelu_output29 = self.prelu29(conv2d_output29)\n concatenate_output5 = torch.cat(\n (prelu_output29, prelu_output28, averagepooling2d_output8), dim=1\n )\n flatten_output = torch.flatten(concatenate_output5)\n concatenate_output6 = torch.cat((flatten_output, ebv_output), dim=0)\n dense_output = self.dense(concatenate_output6)\n prelu_output30 = self.prelu30(dense_output)\n dense_output2 = self.dense2(prelu_output30)\n prelu_output31 = self.prelu31(dense_output2)\n dense_output3 = self.dense3(prelu_output31)\n\n return dense_output3\n\n\ndef main():\n # changed import call\n from modeci_mdf.execution_engine import EvaluableGraph\n\n # Create some test inputs for the model\n galaxy_images_output = torch.zeros((1, 5, 64, 64))\n ebv_output = torch.zeros((1,))\n\n # Seed the random number generator to get deterministic behavior for weight initialization\n torch.manual_seed(0)\n\n model = InceptionBlocks()\n\n # Turn on eval mode for model to get rid of any randomization due to things like BatchNorm or Dropout\n model.eval()\n\n # Run the model once to get some ground truth outpot (from PyTorch)\n output = model(galaxy_images_output, ebv_output).detach().numpy()\n\n # Convert to MDF\n mdf_model, params_dict = pytorch_to_mdf(\n model=model,\n args=(galaxy_images_output, ebv_output),\n example_outputs=output,\n trace=True,\n )\n\n # Get the graph\n mdf_graph = mdf_model.graphs[0]\n\n # Add inputs to the parameters dict so we can feed this to the EvaluableGraph for initialization of all\n # graph inputs.\n params_dict[\"input1\"] = galaxy_images_output.numpy()\n params_dict[\"input2\"] = ebv_output.numpy()\n\n # Evaluate the model via the MDF scheduler\n eg = EvaluableGraph(graph=mdf_graph, verbose=False)\n eg.evaluate(initializer=params_dict)\n\n # Make sure the results are the same betweeen PyTorch and MDF\n assert np.allclose(\n output,\n eg.enodes[\"Add_381\"].evaluable_outputs[\"_381\"].curr_value,\n )\n print(\"Passed all comparison tests!\")\n\n # Output the model to JSON\n mdf_model.to_json_file(\"inception.json\")\n\n import sys\n\n if \"-graph\" in sys.argv:\n mdf_model.to_graph_image(\n engine=\"dot\",\n output_format=\"png\",\n view_on_render=False,\n level=1,\n filename_root=\"inception\",\n only_warn_on_fail=True, # Makes sure test of this doesn't fail on Windows on GitHub Actions\n )\n\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"numpy.allclose",
"torch.zeros",
"torch.cat",
"torch.manual_seed",
"torch.nn.PReLU",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.AvgPool2d",
"torch.flatten",
"torch.nn.ZeroPad2d"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Izardo/myWork | [
"f2a6fd46f31f840589108963d6c0e9d7fdc9ddde"
] | [
"Topic_4_flow/guess2.py"
] | [
"# User guesses a randomly generated number, if \n# the guess is incorrect, the program gives hints\n# Author: Isabella Doyle\n\nfrom numpy import random\n\nnumberToGuess = random.randint(1, 100)\n\nguess = int(input(\"Guess a number: \"))\n\nwhile guess != numberToGuess:\n print(\"You guessed wrong\")\n if guess > numberToGuess:\n print(\"You need to guess lower\")\n elif guess < numberToGuess:\n print(\"You need to guess higher\")\n guess = int(input(\"Guess a number: \"))\n\nprint(\"Yay! {} is the correct guess!\".format(numberToGuess))\n"
] | [
[
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
junjungoal/mjrl | [
"3e21bb752a02c809a5d0be2c6268043c0d2f656c"
] | [
"mjrl/algos/behavior_cloning_2.py"
] | [
"import logging\nlogging.disable(logging.CRITICAL)\nimport numpy as np\nimport time as timer\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom mjrl.utils.logger import DataLog\nfrom tqdm import tqdm\n\nclass BC:\n def __init__(self, expert_paths,\n policy,\n epochs = 5,\n batch_size = 64,\n lr = 1e-3,\n optimizer = None):\n\n self.policy = policy\n self.expert_paths = expert_paths\n self.epochs = epochs\n self.mb_size = batch_size\n self.logger = DataLog()\n\n # get transformations\n observations = np.concatenate([path[\"observations\"] for path in expert_paths])\n actions = np.concatenate([path[\"actions\"] for path in expert_paths])\n in_shift, in_scale = np.mean(observations, axis=0), np.std(observations, axis=0)\n out_shift, out_scale = np.mean(actions, axis=0), np.std(actions, axis=0)\n\n # set scalings in the target policy\n self.policy.model.set_transformations(in_shift, in_scale, out_shift, out_scale)\n self.policy.old_model.set_transformations(in_shift, in_scale, out_shift, out_scale)\n\n # set the variance of gaussian policy based on out_scale\n params = self.policy.get_param_values()\n params[-self.policy.m:] = np.log(out_scale + 1e-12)\n self.policy.set_param_values(params)\n\n # construct optimizer\n self.optimizer = torch.optim.Adam(self.policy.model.parameters(), lr=lr) if optimizer is None else optimizer\n\n # loss criterion is MSE for maximum likelihood estimation\n self.loss_function = torch.nn.MSELoss()\n\n def loss(self, obs, act):\n obs_var = Variable(torch.from_numpy(obs).float(), requires_grad=False)\n act_var = Variable(torch.from_numpy(act).float(), requires_grad=False)\n act_hat = self.policy.model(obs_var)\n return self.loss_function(act_hat, act_var.detach())\n\n def train(self):\n observations = np.concatenate([path[\"observations\"] for path in self.expert_paths])\n actions = np.concatenate([path[\"actions\"] for path in self.expert_paths])\n\n params_before_opt = self.policy.get_param_values()\n ts = timer.time()\n num_samples = observations.shape[0]\n for ep in tqdm(range(self.epochs)):\n self.logger.log_kv('epoch', ep)\n loss_val = self.loss(observations, actions).data.numpy().ravel()[0]\n self.logger.log_kv('loss', loss_val)\n self.logger.log_kv('time', (timer.time()-ts))\n for mb in range(int(num_samples / self.mb_size)):\n rand_idx = np.random.choice(num_samples, size=self.mb_size)\n obs = observations[rand_idx]\n act = actions[rand_idx]\n self.optimizer.zero_grad()\n loss = self.loss(obs, act)\n loss.backward()\n self.optimizer.step()\n params_after_opt = self.policy.get_param_values()\n self.policy.set_param_values(params_after_opt, set_new=True, set_old=True)\n self.logger.log_kv('epoch', self.epochs)\n loss_val = self.loss(observations, actions).data.numpy().ravel()[0]\n self.logger.log_kv('loss', loss_val)\n self.logger.log_kv('time', (timer.time()-ts))\n"
] | [
[
"numpy.log",
"numpy.random.choice",
"torch.from_numpy",
"numpy.concatenate",
"numpy.std",
"numpy.mean",
"torch.nn.MSELoss"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bcorner/optics-topics-book | [
"664e7ea961d1bbd05e5dce1822e01939c053cf4d"
] | [
"optics_topics/_build/jupyter_execute/image-processing.py"
] | [
"#!/usr/bin/env python\n# coding: utf-8\n\n# # Image Processing\n# \n\n# ## Section table of contents\n# \n# ```{tableofcontents}\n# ```\n\n# ## Set up Environment\n# I suppose I better import some modules:\n# * scipy\n# * numpy\n# * matplotlib\n\n# In[1]:\n\n\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[2]:\n\n\nfrom scipy import ndimage, fft\n\n\n# In[3]:\n\n\nfrom PIL import Image \nimage = Image.open('../images/HNI_0079.JPG')\nimage\n\n\n# In[4]:\n\n\nprint(image.size)\n\n\n# In[5]:\n\n\nimarray = np.asarray(image)\ntint_imarray = imarray[:,:,0]\nplt.imshow( tint_imarray)\n\n\n# Hmmm, load\n\n# In[6]:\n\n\nim = image.load()\nim[0,0]\n\n\n# In[7]:\n\n\nimport matplotlib.image as mpimg\n\ngehry = mpimg.imread('../images/HNI_0079.JPG')\n#print(gehry)\nimgplt = plt.imshow(gehry)\n\n\n# Uh, let's make it gray, why not.\n\n# In[8]:\n\n\ngrayimage = image.convert(\"L\")\ngrayimage\n\n\n# In[9]:\n\n\nres = fft.fft2(grayimage)\n\n\n# In[10]:\n\n\nres.shape\n\n\n# In[11]:\n\n\nprint(res)\n\n\n# ## Image Data\n# \n\n# box of numbers\n# \n# \n# \n\n# ## Filters/Kernels\n# \n\n# ## Convolution\n\n# ## Fourier Transform\n\n# In[ ]:\n\n\n\n\n"
] | [
[
"numpy.asarray",
"matplotlib.image.imread",
"matplotlib.pyplot.imshow",
"scipy.fft.fft2"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.6",
"1.10",
"1.4",
"1.9",
"1.5",
"1.7",
"1.8"
],
"tensorflow": []
}
] |
henrystoldt/MAPLEAF | [
"af970d3e8200832f5e70d537b15ad38dd74fa551"
] | [
"MAPLEAF/Rocket/RocketComponents.py"
] | [
" # -*- coding: utf-8 -*-\n\"\"\"\nContains interface definitions (`RocketComponent`/`BodyComponent`) and Base classes for all RocketComponents (`FixedMass`), \nas well as some simple rocket component classes (`FixedForce`,`AeroForce`,`AeroDamping` etc.)\n\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import List, Union\n\nimport numpy as np\nfrom MAPLEAF.Motion import (AeroParameters, ForceMomentSystem, Inertia,\n NoNaNLinearNDInterpolator, RigidBodyState, Vector,\n linInterp)\n\nfrom . import AeroFunctions\n\n__all__ = [ \"RocketComponent\", \"BodyComponent\", \"PlanarInterface\", \"FixedMass\", \"FixedForce\", \"AeroForce\", \"AeroDamping\", \"TabulatedAeroForce\", \"TabulatedInertia\", \"FractionalJetDamping\" ]\n\nclass RocketComponent(ABC):\n ''' Interface definition for rocket components '''\n @abstractmethod\n def __init__(self, componentDictReader, rocket, stage):\n return\n\n @abstractmethod\n def getInertia(self, time, state) -> Inertia:\n return\n\n @abstractmethod\n def getAppliedForce(self, rocketState, time, environmentalConditions, rocketCG) -> ForceMomentSystem:\n return\n\n #### Other optional functions ####\n # def getExtraParametersToIntegrate(self):\n '''\n Override this method to make MAPLEAF integrate additional parameters (in addition to rigid body motion)\n Should return three lists\n - A list of (string) parameter names\n - The parameter will then be accessible under state.parameterName whenever the rocket state is available\n - A list of intial parameter values\n - Values can be scalars or vectors, or any other parameter that implements addition, subtraction and multiplication/division by scalars\n - A list of parameter derivative functions\n - Derivative functions should accept two parameters, the current time and the current state object and return the corresponding derivative of the value of that parameter\n '''\n\nclass BodyComponent(ABC):\n ''' \n Class that defines interface for axisymmetric body components.\n Contains logic for detecting adjacent body components & defining interfaces with them \n Examples: `MAPLEAF.Rocket.NoseCone`, `MAPLEAF.Rocket.Stage`\n '''\n # Override these attributes in child classes to change whether they can connect to components above/below them\n canConnectToComponentAbove = True\n canConnectToComponentBelow = True\n\n def getTopInterfaceLocation(self) -> Union[None, Vector]:\n ''' For planar cylindrical interfaces, returns the location of the center of the cylindrical interface '''\n if self.canConnectToComponentAbove:\n return self.position\n else:\n return None\n\n def getBottomInterfaceLocation(self) -> Union[None, Vector]:\n ''' For planar cylindrical interfaces, returns the location of the center of the cylindrical interface '''\n if self.canConnectToComponentBelow:\n baseZCoord = self.position.Z-self.length\n return Vector(self.position.X, self.position.Y, baseZCoord)\n else:\n return None\n\n def _getCenterOfPressure(self, *args) -> Vector:\n return self.CPLocation\n\n @abstractmethod\n def getMaxDiameter(self):\n ''' These functions used for determining rocket's current max diameter '''\n return\n\n @abstractmethod\n def getRadius(self, distanceFromTop: float) -> float:\n ''' Should return body component radius as a function of distance from the top of the component '''\n return\n\nclass PlanarInterface():\n def __init__(self, location: Vector, component1: RocketComponent, component2: RocketComponent, planeNormal=Vector(0,0,-1)):\n ''' \n Defines a planar interface between two components \n In the local frame, the normalVector is expected to point across the interface from component1 to component2 \n In a rocket, this means that (with the default normalVector pointing in the -'ve Z direction (towards the tail)), component1 is above component2 \n '''\n self.location = location\n self.component1 = component1\n self.component2 = component2\n self.normalVector = planeNormal\n\n @classmethod\n def createPlanarComponentInterfaces(cls, components):\n '''\n Expects components in the list to be sorted by z location (top to bottom)\n Tries to construct PlanarInterface objects connecting all of the BodyComponent object from top to bottom\n Returns a list of PlanarInterface objects, ordered from top to bottom\n '''\n return None\n # Ignore components that aren't of type 'BodyComponent'\n bodyComponents = []\n for comp in components:\n if isinstance(comp, BodyComponent):\n bodyComponents.append(comp)\n \n # Construct interfaces between components\n componentInterfaces = []\n interfaceLocationTolerance = 0.001 # m\n \n for i in range(len(bodyComponents)-1):\n topComponent = bodyComponents[i]\n bottomComponent = bodyComponents[i+1]\n topInterfaceLoc = topComponent.getBottomInterfaceLocation()\n bottomInterfaceLoc = bottomComponent.getTopInterfaceLocation()\n\n if (topInterfaceLoc - bottomInterfaceLoc).length() < interfaceLocationTolerance:\n interfaceLocation = (topInterfaceLoc + bottomInterfaceLoc) / 2 # Average location is where the interface will be\n componentInterfaces.append(PlanarInterface(interfaceLocation, topComponent, bottomComponent))\n else:\n raise ValueError(\"Body Component Location mismatch {} ({}) bottom interface at {} vs {} ({}) top interface at {}. Current interface tolerance = 0.001m\".format(\\\n topComponent.name, type(topComponent), topInterfaceLoc, bottomComponent.name, type(bottomComponent), bottomInterfaceLoc))\n\n return componentInterfaces\n\n @classmethod\n def sortByZLocation(cls, components, state) -> List[RocketComponent]:\n ''' \n Sort the components in order from top to bottom, component.position.Z\n This function could be relocated somewhere more suitable, at the time of writing, it is only being used to order components before creating interfaces b/w them\n '''\n def getZPosition(component):\n try:\n return component.position.Z\n except AttributeError:\n return component.getInertia(0, state).CG.Z\n\n components.sort(key=getZPosition, reverse=True)\n return components\n\nclass FixedMass(RocketComponent):\n '''\n Base class for all fixed-mass rocket components\n Implements functionality to read/store inertia and position info from sim definition file\n '''\n def __init__(self, componentDictReader, rocket, stage):\n self.rocket = rocket\n self.stage = stage\n self.componentDictReader = componentDictReader\n self.name = componentDictReader.getDictName()\n \n mass = componentDictReader.getFloat(\"mass\")\n\n # Position in simulation definition is relative to stage position\n self.position = componentDictReader.getVector(\"position\") + stage.position # Store position relative to nosecone here\n # CG in simulation definition is relative to component position\n cg = componentDictReader.getVector(\"cg\") + self.position # Store cg location relative to nosecone here\n\n try:\n MOI = componentDictReader.getVector(\"MOI\")\n except:\n MOI = Vector(mass*0.01, mass*0.01, mass*0.01) # Avoid having zero moments of inertia\n\n self.inertia = Inertia(MOI, cg, mass)\n self.zeroForce = ForceMomentSystem(Vector(0,0,0))\n\n def getInertia(self, time, state):\n return self.inertia\n\n def getMass(self, time):\n return self.inertia.mass\n\n def getCG(self, time):\n return self.inertia.CG\n\n def getAppliedForce(self, rocketState, time, environment, CG):\n return self.zeroForce\n\nclass FixedForce(RocketComponent):\n def __init__(self, componentDictReader, rocket, stage):\n ''' A Zero-inertia component that applies a constant ForceMomentSystem to the rocket '''\n self.componentDictReader = componentDictReader\n self.rocket = rocket\n self.stage = stage\n self.name = componentDictReader.getDictName()\n\n # Object is just a force, inertia is zero\n self.inertia = Inertia(Vector(0,0,0), Vector(0,0,0), 0)\n\n force = componentDictReader.getVector(\"force\")\n forceLocation = componentDictReader.getVector(\"position\")\n moment = componentDictReader.getVector(\"moment\")\n\n self.force = ForceMomentSystem(force, forceLocation, moment)\n \n def getInertia(self, time, state):\n return self.inertia\n\n def getAppliedForce(self, rocketState, time, environment, rocketCG):\n return self.force\n\nclass AeroForce(RocketComponent):\n ''' A zero-Inertia component with constant aerodynamic coefficients '''\n # Object is just a force, inertia is zero\n inertia = Inertia(Vector(0,0,0), Vector(0,0,0), 0)\n\n def __init__(self, componentDictReader, rocket, stage):\n self.componentDictReader = componentDictReader\n self.rocket = rocket\n self.stage = stage\n self.name = componentDictReader.getDictName()\n\n self.position = componentDictReader.getVector(\"position\")\n self.Aref = componentDictReader.getFloat(\"Aref\")\n self.Lref = componentDictReader.getFloat(\"Lref\")\n\n Cd = componentDictReader.getFloat(\"Cd\")\n Cl = componentDictReader.getFloat(\"Cl\")\n momentCoeffs = componentDictReader.getVector(\"momentCoeffs\")\n\n self.aeroCoeffs = [ Cd, Cl, *momentCoeffs ]\n\n def getInertia(self, time, state):\n return self.inertia\n\n def getAppliedForce(self, state, time, environment, rocketCG):\n return AeroFunctions.forceFromCoefficients(state, environment, *self.aeroCoeffs, self.position, self.Aref, self.Lref)\n\nclass AeroDamping(AeroForce):\n ''' A zero-inertia component with constant aerodynamic damping coefficients '''\n\n position = Vector(0,0,0)\n\n def __init__(self, componentDictReader, rocket, stage):\n self.componentDictReader = componentDictReader\n self.rocket = rocket\n self.stage = stage\n self.name = componentDictReader.getDictName()\n\n self.Aref = componentDictReader.getFloat(\"Aref\")\n self.Lref = componentDictReader.getFloat(\"Lref\")\n\n self.zDampingCoeffs = componentDictReader.getVector(\"zDampingCoeffs\")\n self.yDampingCoeffs = componentDictReader.getVector(\"yDampingCoeffs\")\n self.xDampingCoeffs = componentDictReader.getVector(\"xDampingCoeffs\")\n \n def getAppliedForce(self, state, time, environment, rocketCG):\n airspeed = max(AeroParameters.getLocalFrameAirVel(state, environment).length(), 0.0000001)\n redimConst = self.Lref / (2*airspeed)\n # Calculate moment coefficients from damping coefficients\n localFrameAngularVelocity = Vector(*state.angularVelocity)\n zMomentCoeff = self.zDampingCoeffs * localFrameAngularVelocity * redimConst\n yMomentCoeff = self.yDampingCoeffs * localFrameAngularVelocity * redimConst\n xMomentCoeff = self.xDampingCoeffs * localFrameAngularVelocity * redimConst\n momentCoeffs = [ xMomentCoeff, yMomentCoeff, zMomentCoeff ]\n\n return AeroFunctions.forceFromCoefficients(state, environment, 0, 0, *momentCoeffs, self.position, self.Aref, self.Lref)\n\nclass TabulatedAeroForce(AeroForce):\n ''' A zero-inertia component with aerodynamic coefficients that are tabulated according to one or more parameters (ex. AOA) '''\n\n def __init__(self, componentDictReader, rocket, stage):\n self.componentDictReader = componentDictReader\n self.rocket = rocket\n self.stage = stage\n self.name = componentDictReader.getDictName()\n\n self.position = componentDictReader.getVector(\"position\")\n self.Aref = componentDictReader.getFloat(\"Aref\")\n self.Lref = componentDictReader.getFloat(\"Lref\")\n\n coefficientTableFilePath = componentDictReader.getString(\"filePath\")\n self._loadCoefficients(coefficientTableFilePath)\n\n def _loadCoefficients(self, filePath):\n # Load first row to figure out what the columns mean\n with open(filePath) as f:\n columnNames = f.readline().strip().split(',')\n\n # Get functions that calculate the parameters used for interpolation\n # All these 'key'/parameter columns are expected to come before 'value' columns to be interpolated over\n self.parameterFunctions = []\n i = 0\n while i < len(columnNames):\n col = columnNames[i]\n if col in AeroParameters.stringToAeroFunctionMap:\n self.parameterFunctions.append(AeroParameters.stringToAeroFunctionMap[col])\n else:\n break\n i += 1\n\n # Continue parsing column names - aero coefficient names now \n # This is the ordering expected by AeroFunctions.forceFromCoefficients\n aeroCoeffStrings = [ \"CD\", \"CL\", \"CMx\", \"CMy\", \"CMz\" ]\n self.aeroCoeffIndices = [] # Provides mapping between value column position in interpolation table & position in output aero coefficient list (ordered like aeroCoeffStrings above)\n while i < len(columnNames):\n coeff = columnNames[i]\n\n if coeff in aeroCoeffStrings:\n self.aeroCoeffIndices.append(aeroCoeffStrings.index(coeff))\n \n else:\n raise ValueError(\"ERROR: One of the following columns: {} did not match any of the expected columns names: Keys: {}, values: {}. \\\n Or was in the wrong order. All key columns must come BEFORE value columns.\".format(columnNames, AeroParameters.stringToAeroFunctionMap.keys(), aeroCoeffStrings))\n i += 1\n\n # Load the data table to be interpolated\n dataTable = np.loadtxt(filePath, delimiter=',', skiprows=1)\n\n nKeyCols = len(self.parameterFunctions)\n keys = dataTable[:, 0:nKeyCols]\n aeroCoefficients = dataTable[:, nKeyCols:]\n\n if nKeyCols > 1:\n # Create n-dimensional interpolation function for aero coefficients\n self._interpAeroCoefficients = NoNaNLinearNDInterpolator(keys, aeroCoefficients, filePath)\n else:\n # Save to use with MAPLEAF.Motion.linInterp\n self.keys = [ key[0] for key in keys ]\n self.values = aeroCoefficients\n\n def _getAeroCoefficients(self, state, environment):\n keys = AeroParameters.getAeroPropertiesList(self.parameterFunctions, state, environment)\n\n if len(keys) > 1:\n # Multi-dimensional linear interpolation\n interpolatedCoefficients = self._interpAeroCoefficients(keys)[0]\n else:\n # 1D linear interpolation\n interpolatedCoefficients = linInterp(self.keys, self.values, keys[0])\n\n aeroCoefficients = [0.0] * 5\n for i in range(len(interpolatedCoefficients)):\n indexInCoeffArray = self.aeroCoeffIndices[i]\n aeroCoefficients[indexInCoeffArray] = interpolatedCoefficients[i]\n\n return aeroCoefficients\n\n def getAppliedForce(self, state, time, environment, rocketCG):\n aeroCoefficients = self._getAeroCoefficients(state, environment)\n return AeroFunctions.forceFromCoefficients(state, environment, *aeroCoefficients, self.position, self.Aref, self.Lref)\n\nclass TabulatedInertia(RocketComponent):\n ''' A zero-force component with time-varying tabulated inertia '''\n def __init__(self, componentDictReader, rocket, stage):\n self.rocket = rocket\n self.stage = stage\n self.componentDictReader = componentDictReader\n self.name = componentDictReader.getDictName()\n\n self.zeroForce = ForceMomentSystem(Vector(0,0,0))\n\n inertiaTableFilePath = componentDictReader.getString(\"filePath\")\n self._parseInertiaTable(inertiaTableFilePath)\n\n def _parseInertiaTable(self, filePath):\n data = np.loadtxt(filePath, skiprows=1, delimiter=',')\n self.times = data[:, 0]\n self.inertiaData = data[:, 1:]\n\n # Check that the right number of columns is present\n if data.shape[1] != 8:\n raise ValueError(\"Wrong number of columns in inertia table: {}. Expecting 8 columns: \\\n Time, Mass, CGx, CGy, CGz, MOIx, MOIy, MOIz\")\n\n def getInertia(self, time, state):\n inertiaData = linInterp(self.times, self.inertiaData, time)\n # MOI is last three columns, CG is the three before that, and mass is column 0\n return Inertia(Vector(*inertiaData[-3:]), Vector(*inertiaData[1:4]), inertiaData[0])\n \n def getAppliedForce(self, rocketState, time, environment, CG):\n return self.zeroForce\n\nclass FractionalJetDamping(RocketComponent):\n ''' A component to model Jet damping as per NASA's Two Stage to Orbit verification case '''\n\n # Object is just a force, inertia is zero\n inertia = Inertia(Vector(0,0,0), Vector(0,0,0), 0)\n\n def __init__(self, componentDictReader, rocket, stage):\n self.rocket = rocket\n self.stage = stage\n self.componentDictReader = componentDictReader\n self.name = componentDictReader.getDictName()\n \n self.dampingFraction = componentDictReader.getFloat(\"fraction\")\n\n def getAppliedForce(self, rocketState, time, environmentalConditions, rocketCG):\n # Only apply damping force if current stage's engine is firing\n # (Other stage's motors will have different exit planes)\n if time > self.stage.motor.ignitionTime and time < self.stage.engineShutOffTime:\n currentRocketInertia = self.rocket.getInertia(time, rocketState)\n \n # Differentiate rate of MOI change\n dt = 0.001\n nextRocketInertia = self.rocket.getInertia(time+dt, rocketState) \n MOIChangeRate = (currentRocketInertia.MOI.X - nextRocketInertia.MOI.X) / dt\n\n dampingFactor = MOIChangeRate * self.dampingFraction\n \n angVel = rocketState.angularVelocity\n dampingMoment = Vector(-angVel.X*dampingFactor, -angVel.Y*dampingFactor, 0)\n\n return ForceMomentSystem(Vector(0,0,0), moment=dampingMoment)\n else:\n return ForceMomentSystem(Vector(0,0,0))\n\n def getInertia(self, time, state):\n return self.inertia\n"
] | [
[
"numpy.loadtxt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
samadeusfp/prescriptiveProcessMonitoring | [
"7b39c9b3cb20208d409e733e91cb91fb69dbf238"
] | [
"get_accuracy_dataset.py"
] | [
"import EncoderFactory\nfrom DatasetManager import DatasetManager\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.metrics import roc_auc_score, precision_recall_fscore_support, confusion_matrix\nfrom sklearn.pipeline import FeatureUnion\n\nimport time\nimport os\nimport sys\nimport csv\nfrom sys import argv\nimport pickle\n\ndataset_name = argv[1]\npredictions_dir = argv[2]\nresults_dir = argv[3]\n\n# create results directory\nif not os.path.exists(os.path.join(results_dir)):\n os.makedirs(os.path.join(results_dir))\n\n# load predictions\ndt_preds = pd.read_csv(os.path.join(predictions_dir, \"preds_train_%s.csv\" % dataset_name), sep=\";\")\n\n# write results to file\nout_filename = os.path.join(results_dir, \"accuracy_%s_fixedconfs.csv\" % (dataset_name))\nwith open(out_filename, 'w') as fout:\n writer = csv.writer(fout, delimiter=';', quotechar='', quoting=csv.QUOTE_NONE)\n writer.writerow([\"dataset\", \"prefix\", \"accuracy\"])\n\n conf_threshold = 0.5\n for nr_event in range(1, dt_preds.prefix_nr.max() + 1):\n # trigger alarms according to conf_threshold\n dt_final = pd.DataFrame()\n unprocessed_case_ids = set(dt_preds.case_id.unique())\n tmp = dt_preds[(dt_preds.case_id.isin(unprocessed_case_ids)) & (dt_preds.prefix_nr == nr_event)]\n tmp = tmp[tmp.predicted_proba >= conf_threshold]\n tmp[\"prediction\"] = 1\n dt_final = pd.concat([dt_final, tmp], axis=0)\n unprocessed_case_ids = unprocessed_case_ids.difference(tmp.case_id)\n tmp = dt_preds[(dt_preds.case_id.isin(unprocessed_case_ids)) & (dt_preds.prefix_nr == 1)]\n tmp[\"prediction\"] = 0\n dt_final = pd.concat([dt_final, tmp], axis=0)\n\n case_lengths = dt_preds.groupby(\"case_id\").prefix_nr.max().reset_index()\n case_lengths.columns = [\"case_id\", \"case_length\"]\n dt_final = dt_final.merge(case_lengths)\n\n # calculate precision, recall etc. independent of the costs\n tn, fp, fn, tp = confusion_matrix(dt_final.actual, dt_final.prediction).ravel()\n\n accuracy = (tn+tp)/(tn+fp+fn+tp)\n writer.writerow([dataset_name, str(nr_event), str(accuracy)])\n\n"
] | [
[
"pandas.concat",
"sklearn.metrics.confusion_matrix",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
andylolu2/Alpha-Reversi | [
"226ddb8e794a892674209be75ea5e4af69b9a4df"
] | [
"apple_chess.py"
] | [
"from queue import Queue\nimport numpy as np\nimport random\nimport copy\nfrom multiprocessing import Manager, Pipe\nfrom constants import BOARD_DIM, C_PUCT, C_VIRTUAL_LOSS, HISTORY_LEN, MCTS_BATCH_SIZE, SAMPLES_PER_POS\nfrom helper_methods import dihedral_trans\n\nclass Board:\n '''\n Class Board implements game rules and game tree traversal\n '''\n def __init__(self, board=None, turn=None, train_random=None, deploy=False, get_edges=False, history=None, move_num=0):\n self.move_num = move_num\n self.N = 0\n self.W = 0\n self.Q = 0\n self.P = 0\n self.VIRTUAL_LOSS = 1\n if board is None:\n self.board = []\n for i in range(BOARD_DIM[0]):\n self.board.append([])\n for _ in range(BOARD_DIM[1]):\n self.board[i].append([0])\n self.board = np.array(self.board, dtype=np.float32)\n self.reset()\n else:\n self.board = np.copy(board)\n \n if history is None:\n self.history = [np.zeros((8, 8, 1), dtype=np.float32) for _ in range(HISTORY_LEN-1)]\n self.history.append(np.copy(self.board))\n else:\n self.history = history[:]\n \n if turn is None:\n self.turn = 1\n else:\n self.turn = turn\n \n if train_random is None:\n self.train_random = True\n else:\n self.train_random = train_random\n\n self.deploy = deploy\n\n self.parent = None\n\n self.edges = None\n if get_edges:\n self.edges = self.get_edges()\n\n def __copy__(self):\n return Board(board=self.board, turn=self.turn,\n train_random=self.train_random, deploy=self.deploy,\n move_num=self.move_num, history=self.history)\n \n def __repr__(self) -> str:\n return repr(self.board.reshape(BOARD_DIM))\n\n def _add(self, color, x, y):\n if x < 0 or x >= BOARD_DIM[0] or y < 0 or y >= BOARD_DIM[1]:\n print(\"That is outside of the grid\")\n elif self.board[x][y][0] == 0:\n if self.possible(color, x, y):\n self.board[x][y][0] = color\n self.flip_and_find_all_direction(color, x, y)\n self.turn *= -1\n self.move_num += 1\n self.history.append(np.copy(self.board))\n self.history.pop(0)\n if len(self.possible_moves(self.turn)) == 0:\n self.turn *= -1\n else:\n print(\"Move is invalid\")\n else:\n print(\"Position already occupied\")\n\n def reset(self):\n for i in range(BOARD_DIM[0]):\n for j in range(BOARD_DIM[1]):\n self.board[i][j] = [0]\n self.board[int(BOARD_DIM[0] / 2)][int(BOARD_DIM[1] / 2)] = [1]\n self.board[int(BOARD_DIM[0] / 2) - 1][int(BOARD_DIM[1] / 2)] = [-1]\n self.board[int(BOARD_DIM[0] / 2)][int(BOARD_DIM[1] / 2) - 1] = [-1]\n self.board[int(BOARD_DIM[0] / 2) - 1][int(BOARD_DIM[1] / 2) - 1] = [1] \n\n def traverse(self, x, y):\n '''\n Traverses the game tree\n '''\n self.edges = self.get_edges()\n if (x, y) in self.edges:\n child = self.edges[(x, y)]\n child.parent = None\n return child\n else:\n raise KeyError('The move is not valid')\n\n\n def get_edges(self):\n if self.edges is not None:\n return self.edges\n children = {}\n possible_moves = self.possible_moves(self.turn)\n for move in possible_moves:\n child = copy.copy(self)\n child._add(child.turn, move[0], move[1])\n child.parent = self\n children[move] = child\n return children\n \n def get_temperature(self):\n if self.train_random and self.move_num <= 10:\n return 1\n return 1e-1\n\n def possible(self, color, x, y):\n if x < 0 or x >= BOARD_DIM[0] or y < 0 or y >= BOARD_DIM[1]:\n return False\n elif self.board[x][y][0] == 0:\n self.board[x][y][0] = color\n temp = np.copy(self.board)\n self.flip_and_find_all_direction(color, x, y)\n if np.all(temp == self.board):\n self.board = temp\n self.board[x][y][0] = 0\n return False\n else:\n self.board = temp\n self.board[x][y][0] = 0\n return True\n else: # already occupied\n return False\n\n def possible_moves(self, color):\n possible_moves = []\n for i in range(BOARD_DIM[0]):\n for j in range(BOARD_DIM[1]):\n if self.board[i][j] != 0:\n for x_dir in range(-1, 2):\n for y_dir in range(-1, 2):\n if not (x_dir == 0 and y_dir == 0):\n if self.possible(color, i + x_dir, j + y_dir):\n if (i + x_dir, j + y_dir) not in possible_moves:\n possible_moves.append((i + x_dir, j + y_dir))\n return possible_moves\n\n def flip_and_find_direction(self, color, x, y, direction):\n next_x = x + direction[0]\n next_y = y + direction[1]\n if next_x < 0 or next_x >= BOARD_DIM[0] or next_y < 0 or next_y >= BOARD_DIM[1]:\n return False\n else:\n next_item = self.board[next_x][next_y][0]\n if next_item == 0:\n return False\n elif next_item == color:\n return True\n elif next_item == -color:\n next_exist = self.flip_and_find_direction(color, next_x, next_y, direction)\n if next_exist:\n self.board[next_x][next_y][0] = color\n return next_exist\n else:\n print(\"Error in find_next_dir\")\n\n def flip_and_find_all_direction(self, color, x, y):\n for x_dir in range(-1, 2):\n for y_dir in range(-1, 2):\n if not (x_dir == 0 and y_dir == 0):\n self.flip_and_find_direction(color, x, y, (x_dir, y_dir))\n\n def is_terminal(self):\n if len(self.possible_moves(1)) == 0 and len(self.possible_moves(-1)) == 0:\n return True\n else:\n return False\n\n def winner(self):\n if self.is_terminal():\n whites, blacks = self.black_and_white_num()\n if blacks > whites:\n return -1\n elif whites > blacks:\n return 1\n elif whites == blacks:\n return 0\n else:\n print(\"Error: Game hasn't completed\")\n\n def black_and_white_num(self):\n whites = 0\n blacks = 0\n for row in self.board:\n for col in row:\n if col[0] == 1:\n whites += 1\n if col[0] == -1:\n blacks += 1\n return whites, blacks\n\n def as_nn_input(self):\n '''\n Output: an tuple of a {board_dim_0 * board_dim_1 * (HISTORY_LEN * 2 + 1) array} and an int representing the transformation\n (HISTORY_LEN * 2 + 1) comes from HISTORY_LEN layers for blacks, \n HISTORY_LEN layers for whites and 1 layer to indicate player color\n '''\n # Separate black and white pieces\n black_history = []\n white_history = []\n for history in self.history:\n white_history.append(np.where(history == 1, history, 0))\n black_history.append(np.where(history == -1, history, 0))\n \n nn_input = np.concatenate(black_history + white_history, axis=2) * self.turn\n nn_input = nn_input.reshape(BOARD_DIM + (HISTORY_LEN * 2,))\n\n # Layer to indicate color\n color = 1 if self.turn == 1 else 0\n color = np.full(BOARD_DIM + (1,), color, dtype=np.float32)\n\n choice, transforamtion = dihedral_trans(nn_input)\n return (np.concatenate((choice, color), axis=2), transforamtion)\n\n def evaluate(self, nn):\n nn_inputs, transformations = tuple(zip(*[self.as_nn_input()]))\n nn_inputs = np.array(nn_inputs)\n outputs = nn(nn_inputs)\n values = []\n for _policy, _value, transformation in zip(outputs[0].numpy(), outputs[1].numpy(), transformations):\n _real_policy = dihedral_trans(_policy.reshape(BOARD_DIM), transformation=transformation, inverse=True)\n values.append(_value)\n value = sum(values) / len(values)\n return value\n\n def alpha_beta_value(self, nn, depth, a=-1e3, b=1e3, epsilon=0.05):\n if self.train_random and random.random() <= epsilon:\n return (None, random.choice(self.possible_moves(self.turn)))\n else:\n if depth == 0 or self.is_terminal():\n value = self.evaluate(nn)\n return (value, None)\n elif self.turn == 1:\n self.edges = self.get_edges()\n value = -1e9\n best_move = next(iter(self.edges.keys()))\n for move, child in self.edges.items():\n children_value, _ = child.alpha_beta_value(nn, depth - 1, a=a, b=b, epsilon=0)\n if children_value > value:\n value = children_value\n best_move = move\n a = max(a, value)\n if a >= b:\n break\n return (value, best_move)\n elif self.turn == -1:\n self.edges = self.get_edges()\n value = 1e9\n best_move = next(iter(self.edges.keys()))\n for move, child in self.edges.items():\n children_value, _ = child.alpha_beta_value(nn, depth - 1, a=a, b=b, epsilon=0)\n if children_value < value:\n value = children_value\n best_move = move\n b = min(b, value)\n if a >= b:\n break\n return (value, best_move)\n\n def mcts_select(self, cpuct=C_PUCT):\n node = self\n while True:\n if node.edges is None: # first visit\n break\n elif node.edges == {}: # terminal node\n break\n else:\n best_score = -1e3\n best_move = None\n for move, edge in node.edges.items():\n U = cpuct * edge.P * ((node.N - 1) ** 0.5) / (1 + edge.N)\n score = (edge.Q + U) * edge.VIRTUAL_LOSS\n if score > best_score:\n best_score = score\n best_move = move\n node = node.edges[best_move]\n node.VIRTUAL_LOSS *= C_VIRTUAL_LOSS\n return node\n\n def mcts(self, nn, iter=24, cpuct=C_PUCT, executor=None, verbose=False, depth_weight=1):\n '''\n Monte Carlo Tree Search algorithm\n Args:\n nn: the neural network used to evaluate the board state and returns a policy and value\n iter: number of monte carlo searches\n \n Returns: policy (BOARD_DIM[0] * BOARD_DIM[1] dimentional vector)\n '''\n if self.is_terminal():\n return np.zeros(BOARD_DIM, dtype=np.float32)\n \n nodes = []\n max_depth = 0\n for i in range(iter):\n # Select\n if executor:\n # Search in thread\n nodes.append(executor.submit(self.mcts_select, cpuct=cpuct))\n else:\n nodes.append(self.mcts_select(cpuct=cpuct))\n \n if i % MCTS_BATCH_SIZE == 0 or i == iter-1:\n if executor:\n # Get results from threads\n nodes = [future.result() for future in nodes]\n else:\n nodes = list(set(nodes))\n \n # Evaluate\n nn_inputs, transformations = tuple(zip(*[node.as_nn_input() for node in nodes]))\n nn_inputs = np.array(nn_inputs)\n outputs = nn(nn_inputs)\n for node, _policy, _value, transformation in zip(nodes, outputs[0].numpy(), outputs[1].numpy(), transformations):\n _real_policy, _ = dihedral_trans(_policy.reshape(BOARD_DIM), transformation=transformation, inverse=True)\n # Expand\n node.edges = node.get_edges()\n for move, edge in node.edges.items():\n # N, W, Q values are implicitly 0\n edge.P = _real_policy[move]\n \n # Backup\n current_node = node\n node_turn = node.turn\n depth = 0\n value_to_prop = _value[0]\n while True:\n if current_node.parent is None:\n break\n current_node.N += 1\n current_node.W += value_to_prop * node_turn * current_node.parent.turn # Add if parent turn same as node turn else subtract\n current_node.Q = current_node.W / current_node.N\n current_node.VIRTUAL_LOSS = 1\n current_node = current_node.parent\n value_to_prop *= depth_weight\n depth += 1\n \n if depth > max_depth: max_depth = depth\n\n nodes = []\n \n # Calculate policy based on visit counts\n policy = np.zeros(BOARD_DIM, dtype=np.float32)\n temperature = self.get_temperature()\n visit_sum = 0\n for move, edge in self.edges.items():\n visit_score = edge.N ** (1 / temperature)\n policy[move] = visit_score\n visit_sum += visit_score\n policy /= visit_sum\n policy = policy.reshape(BOARD_DIM[0] * BOARD_DIM[1])\n\n if verbose: print(f\"Maximum search depth: {max_depth}\")\n\n return policy\n \n def get_mcts_move(self, policy):\n '''\n policy: 2D np array\n returns: move, tuple of (x, y)\n '''\n if not self.train_random and self.deploy:\n (x, y) = np.unravel_index(policy.argmax(), BOARD_DIM)\n else:\n move = np.random.choice(np.arange(BOARD_DIM[0] * BOARD_DIM[1]), p=policy)\n x = int(move / BOARD_DIM[0])\n y = move % BOARD_DIM[0]\n return (x, y)"
] | [
[
"numpy.arange",
"numpy.full",
"numpy.concatenate",
"numpy.all",
"numpy.copy",
"numpy.array",
"numpy.zeros",
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rmw83/molecool | [
"7646661be5e141b6f5cbd857a2042c72b6285bce"
] | [
"molecool/tests/test_measure.py"
] | [
"\"\"\"\nUnit Testing for Measure Module.\n\"\"\"\n\nimport numpy as np\nimport molecool\nimport pytest\n\ndef test_calculate_distance():\n \n Atom_A = np.array([0.0, 0.0, 0.0])\n Atom_B = np.array([1.0, 0.0, 0.0])\n\n expected_distance = 1.0\n\n calculated_distance = molecool.calculate_distance(Atom_A, Atom_B)\n\n assert expected_distance == calculated_distance\n\ndef test_calculate_angle():\n\n rA = np.array([0.0, 0.0, -1.0])\n rB = np.array([0.0, 0.0, 0.0])\n rC = np.array([1.0, 0.0, 0.0])\n\n expected_angle = 90\n\n calculated_angle = molecool.calculate_angle(rA, rB, rC, degrees=True)\n\n assert expected_angle == calculated_angle\n\[email protected](\"p1, p2, p3, expected_angle\", [\n (np.array([np.sqrt(2)/2, np.sqrt(2)/2, 0]), np.array([0, 0, 0]), np.array([1, 0, 0]), 45),\n (np.array([0, 0, -1]), np.array([0, 1, 0]), np.array([1, 0, 0]), 60),\n (np.array([np.sqrt(3)/2, 1/2, 0]), np.array([0, 0, 0]), np.array([1, 0, 0]), 30)\n ])\ndef test_calculated_angle_many(p1, p2, p3, expected_angle):\n\n calculated_angle = molecool.calculate_angle(p1, p2, p3, degrees=True)\n\n assert calculated_angle == expected_angle\n\n"
] | [
[
"numpy.array",
"numpy.sqrt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Navjeet-AIT/CHAT-SENTIMENT-ANALYSIS | [
"f49682c7d973c4a966093ed6517fd28b5ce79bc2"
] | [
"Text/tests/examples/score_texts_emojis.py"
] | [
"# -*- coding: utf-8 -*-\n\n\"\"\" Use Text to score texts for emoji distribution.\n\nThe resulting emoji ids (0-63) correspond to the mapping\nin emoji_overview.png file at the root of the Text repo.\n\nWrites the result to a csv file.\n\"\"\"\nfrom __future__ import print_function, division\nimport example_helper\nimport json\nimport csv\nimport numpy as np\nfrom deepmoji.sentence_tokenizer import SentenceTokenizer\nfrom deepmoji.model_def import deepmoji_emojis\nfrom deepmoji.global_variables import PRETRAINED_PATH, VOCAB_PATH\n\nOUTPUT_PATH = 'test_sentences.csv'\n\nTEST_SENTENCES = [u'I love mom\\'s cooking',\n u'I love how you never reply back..',\n u'I love cruising with my homies',\n u'I love messing with yo mind!!',\n u'I love you and now you\\'re just gone..',\n u'This is shit',\n u'This is the shit']\n\ndef top_elements(array, k):\n ind = np.argpartition(array, -k)[-k:]\n return ind[np.argsort(array[ind])][::-1]\n\nmaxlen = 30\nbatch_size = 32\n\nprint('Tokenizing using dictionary from {}'.format(VOCAB_PATH))\nwith open(VOCAB_PATH, 'r') as f:\n vocabulary = json.load(f)\nst = SentenceTokenizer(vocabulary, maxlen)\ntokenized, _, _ = st.tokenize_sentences(TEST_SENTENCES)\n\nprint('Loading model from {}.'.format(PRETRAINED_PATH))\nmodel = deepmoji_emojis(maxlen, PRETRAINED_PATH)\nmodel.summary()\n\nprint('Running predictions.')\nprob = model.predict(tokenized)\n\n# Find top emojis for each sentence. Emoji ids (0-63)\n# correspond to the mapping in emoji_overview.png \n# at the root of the Text repo.\nprint('Writing results to {}'.format(OUTPUT_PATH))\nscores = []\nfor i, t in enumerate(TEST_SENTENCES):\n t_tokens = tokenized[i]\n t_score = [t]\n t_prob = prob[i]\n ind_top = top_elements(t_prob, 5)\n t_score.append(sum(t_prob[ind_top]))\n t_score.extend(ind_top)\n t_score.extend([t_prob[ind] for ind in ind_top])\n scores.append(t_score)\n print(t_score)\n\nwith open(OUTPUT_PATH, 'w') as csvfile:\n writer = csv.writer(csvfile, delimiter=',', lineterminator='\\n')\n writer.writerow(['Text', 'Top5%',\n 'Emoji_1', 'Emoji_2', 'Emoji_3', 'Emoji_4', 'Emoji_5',\n 'Pct_1', 'Pct_2', 'Pct_3', 'Pct_4', 'Pct_5'])\n for i, row in enumerate(scores):\n try:\n writer.writerow(row)\n except:\n print(\"Exception at row {}!\".format(i))\n"
] | [
[
"numpy.argsort",
"numpy.argpartition"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Pandinosaurus/midair-dataset | [
"df55d456d2a8f6370c4a0bc597a55b0e47e6b6f0"
] | [
"tools/IMU-data_generator.py"
] | [
"import h5py\nimport numpy as np\nfrom pyquaternion import Quaternion\nimport argparse\nimport os\nimport sys\n\nparser = argparse.ArgumentParser(description='Generate new IMU measurements for all trajectories in the given hdf5 file')\nparser.add_argument('--hdf5_path', type=str, help='path to hdf5 file',required=True)\n\nargs = parser.parse_args()\n\nif __name__ == '__main__':\n\n answer = str(input(\"Warning: this script will overwrite IMU measurements stored in the given hdf5 dataset. \\n\"+ \\\n \"Do you want to proceed? (y/n): \"))\n if not(answer==\"y\" or answer==\"Y\"):\n sys.exit(0)\n\n database = h5py.File(args.hdf5_path, \"a\")\n db_path = os.path.dirname(args.hdf5_path)\n\n # IMU noise parameters chosen randomly in a range of values encountered in real devices\n noise_acc = 2 * np.power(10., -np.random.uniform(low=1., high=3., size=(1, 3)))\n noise_gyr = np.power(10., -np.random.uniform(low=1., high=3., size=(1, 3)))\n imu_bias_acc_rw = 2 * np.power(10., -np.random.uniform(low=3., high=6., size=(1, 3)))\n imu_bias_gyr_rw = np.power(10., -np.random.uniform(low=4., high=6., size=(1, 3)))\n\n for dataset in database:\n print(\"Currently processing : %s\" % dataset)\n gt_group = database[dataset][\"groundtruth\"]\n gt_attitude = gt_group[\"attitude\"]\n gt_angular_vel = gt_group[\"angular_velocity\"]\n gt_accelerations = gt_group[\"acceleration\"]\n\n imu_group = database[dataset][\"imu\"]\n\n # Set init parameters\n imu_accelerometer = np.zeros(gt_attitude.shape, dtype=float)\n imu_gyroscope = np.zeros(gt_attitude.shape, dtype=float)\n\n imu_bias_acc = np.random.normal([0., 0., 0.], imu_bias_acc_rw)\n imu_bias_gyr = np.random.normal([0., 0., 0.], imu_bias_gyr_rw)\n\n init_bias_est_acc = imu_bias_acc + np.random.normal([0., 0., 0.], noise_acc / 50)\n init_bias_est_gyr = imu_bias_gyr + np.random.normal([0., 0., 0.], noise_gyr / 50)\n \n imu_group[\"accelerometer\"].attrs[\"init_bias_est\"] = init_bias_est_acc\n imu_group[\"gyroscope\"].attrs[\"init_bias_est\"] = init_bias_est_gyr\n\n # Pass over trajectory to generate simulated sensor measurements\n for i in range(gt_attitude.shape[0]):\n attitude = Quaternion(gt_attitude[i, :])\n imu_accelerometer = attitude.conjugate.rotate(gt_accelerations[i, :] + np.array([0., 0., -9.81])) \\\n + imu_bias_acc + np.random.normal([0., 0., 0.], noise_acc)\n imu_gyroscope = gt_angular_vel[i, :] + imu_bias_gyr + np.random.normal([0., 0., 0.], noise_gyr)\n imu_bias_acc += np.random.normal([0., 0., 0.], imu_bias_acc_rw)\n imu_bias_gyr += np.random.normal([0., 0., 0.], imu_bias_gyr_rw)\n imu_group[\"accelerometer\"][i] = imu_accelerometer\n imu_group[\"gyroscope\"][i] = imu_gyroscope\n\ndatabase.close()\n"
] | [
[
"numpy.random.uniform",
"numpy.random.normal",
"numpy.array",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
benoitbonnet/pytorch-CycleGAN-and-pix2pix | [
"348e97e4603a29e287c4ff1aa29cffe2999d0a4f"
] | [
"models/template_model.py"
] | [
"\"\"\"Model class template\n\nThis module provides a template for users to implement custom models.\nYou can specify '--model template' to use this model.\nThe class name should be consistent with both the filename and its model option.\nThe filename should be <model>_dataset.py\nThe class name should be <Model>Dataset.py\nIt implements a simple image-to-image translation baseline based on regression loss.\nGiven input-output pairs (data_A, data_B), it learns a network netG that can minimize the following L1 loss:\n min_<netG> ||netG(data_A) - data_B||_1\nYou need to implement the following functions:\n <modify_commandline_options>: Add model-specific options and rewrite default values for existing options.\n <__init__>: Initialize this model class.\n <set_input>: Unpack input data and perform data pre-processing.\n <forward>: Run forward pass. This will be called by both <optimize_parameters> and <test>.\n <optimize_parameters>: Update network weights; it will be called in every training iteration.\n\"\"\"\nimport torch\nfrom .base_model import BaseModel\nfrom . import networks\n\n\nclass TemplateModel(BaseModel):\n @staticmethod\n def modify_commandline_options(parser, is_train=True):\n \"\"\"Add new model-specific options and rewrite default values for existing options.\n\n Parameters:\n parser -- the option parser\n is_train -- if it is training phase or test phase. You can use this flag to add training-specific or test-specific options.\n\n Returns:\n the modified parser.\n \"\"\"\n parser.set_defaults(dataset_mode='aligned') # You can rewrite default values for this model. For example, this model usually uses aligned dataset as its dataset.\n if is_train:\n parser.add_argument('--lambda_regression', type=float, default=1.0, help='weight for the regression loss') # You can define new arguments for this model.\n\n return parser\n\n def __init__(self, opt):\n \"\"\"Initialize this model class.\n\n Parameters:\n opt -- training/test options\n\n A few things can be done here.\n - (required) call the initialization function of BaseModel\n - define loss function, visualization images, model names, and optimizers\n \"\"\"\n BaseModel.__init__(self, opt) # call the initialization method of BaseModel\n # specify the training losses you want to print out. The program will call base_model.get_current_losses to plot the losses to the console and save them to the disk.\n self.loss_names = ['loss_G']\n # specify the images you want to save and display. The program will call base_model.get_current_visuals to save and display these images.\n self.visual_names = ['data_A', 'data_B', 'output']\n # specify the models you want to save to the disk. The program will call base_model.save_networks and base_model.load_networks to save and load networks.\n # you can use opt.isTrain to specify different behaviors for training and test. For example, some networks will not be used during test, and you don't need to load them.\n self.model_names = ['G']\n # define networks; again, you can use opt.isTrain to specify different behaviors for training and test.\n self.netG = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG, gpu_ids=self.gpu_ids)\n if self.isTrain: # only defined during training time\n # define your loss functions. You can use losses provided by torch.nn such as torch.nn.L1Loss.\n # We also provide a GANLoss class \"networks.GANLoss\". self.criterionGAN = networks.GANLoss().to(self.device)\n self.criterionLoss = torch.nn.L1Loss()\n # define and initialize optimizers. You can define one optimizer for each network.\n # If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an example.\n self.optimizers = []\n self.optimizer = torch.optim.Adam(self.netG.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))\n self.optimizers = [self.optimizer]\n\n # Our program will automatically call <model.setup> to define schedulers, load networks, and print networks\n\n def set_input(self, input):\n \"\"\"Unpack input data from the dataloader and perform necessary pre-processing steps.\n\n Parameters:\n input: a dictionary that contains the data itself and its metadata information.\n \"\"\"\n AtoB = self.opt.direction == 'AtoB' # use <direction> to swap data_A and data_B\n self.data_A = input['A' if AtoB else 'B'].to(self.device) # get image data A\n self.data_B = input['B' if AtoB else 'A'].to(self.device) # get image data B\n self.image_paths = input['A_paths' if AtoB else 'B_paths'] # get image paths\n\n def forward(self):\n \"\"\"Run forward pass. This will be called by both functions <optimize_parameters> and <test>.\"\"\"\n self.output = self.netG(self.data_A) # generate output image given the input data_A\n\n def backward(self):\n \"\"\"calculate gradients for network weights.\"\"\"\n # caculate the intermediate results if necessary; here self.output has been computed during function <forward>\n # calculate loss given the input and intermediate results\n self.loss_G = self.criterionLoss(self.output, self.data_B) * self.opt.lambda_regression\n self.loss_G.backward() # calculate gradients of network G w.r.t. loss_G\n\n def optimize_parameters(self):\n \"\"\"Update network weights; it will be called in every training iteration.\"\"\"\n self.forward() # first call forward to calculate intermediate results\n self.optimizer.zero_grad() # clear network G's existing gradients\n self.backward() # calculate gradients for network G\n self.optimizer.step() # update gradients for network G\n"
] | [
[
"torch.nn.L1Loss"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
E-tanok/ReinforcementLearning_starcraft_2_pysc2 | [
"7587b1c7f269a1b533b4d33caa8f80319d11a5f3"
] | [
"parameters_custom.py"
] | [
"import pickle\nimport tensorflow as tf\n\n#Environment parameters :\nstep_mul = 10\nn_workers = 1\n\n#Workers parameters :\ngamma = 0.99\nrollout_size = 40\nwith_random_policy = False\ndict_worker_params = {'gamma':gamma, 'rollout_size':rollout_size, 'with_random_policy':with_random_policy}\n\n#Networks parameters :\nresolution = 32\nminimap_spectrum = ['height_map','visibility_map','creep','camera','player_id','player_relative','selected']\nscreen_spectrum = ['height_map','visibility_map','creep','power','player_id','player_relative','unit_type','selected',\n'unit_hit_points','unit_hit_points_ratio','unit_energy','unit_energy_ratio','unit_shields',\n'unit_shields_ratio','unit_density','unit_density_aa','effects']\noptimizer = tf.train.RMSPropOptimizer(learning_rate=1e-4, decay=0.99, epsilon=1e-5)\nbeta = 0.001\n\nreduce_units_dim = True\nunits_dim_reduction = 49\nfilter_actions = True\ndict_actions_spectrums = {'move':[331],\n'nothing':[0],\n'move_and_nothing':[0, 331],\n'blizzard_minigames':[0, 1, 2, 3, 4, 6, 7, 12, 13, 140, 168, 261, 274, 331, 332, 333, 334, 451, 452, 453],\n'blizzard_minigames_and_stimpack':[0, 1, 2, 3, 4, 6, 7, 12, 13, 140, 168, 234, 235, 236, 237, 238, 261, 274, 331, 332, 333, 334, 451, 452, 453],\n'try_marines_hit_and_run':[0, 12, 234, 331],\n'full':list(range(541))\n}\nactions_spectrum = dict_actions_spectrums['move']\n\ndict_activation_functions = {'None':None, 'relu':tf.nn.relu}\ndict_policy_losses = {'based_on_logits':'logits','based_on_softmax':'softmax'}\npolicy_loss = dict_policy_losses['based_on_logits']\nconv_activation = dict_activation_functions['None']\ndense_activation = dict_activation_functions['None']\n\n\ndict_network_params = {'resolution':resolution, 'minimap_spectrum':minimap_spectrum, 'screen_spectrum':screen_spectrum,\n'optimizer':optimizer, 'beta':beta,'filter_actions':filter_actions, 'actions_spectrum':actions_spectrum,\n'reduce_units_dim':reduce_units_dim, 'units_dim_reduction':units_dim_reduction, 'convolution_activation':conv_activation, 'dense_activation':dense_activation ,'policy_loss':policy_loss}\n\ndict_custom_params = {'resolution':resolution, 'n_workers':n_workers, 'step_mul':step_mul, 'worker_params':dict_worker_params, 'network_params':dict_network_params}\n"
] | [
[
"tensorflow.train.RMSPropOptimizer"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
JeyesHan/DeFRCN_Custom | [
"6a536408a61bb10a5ef84ce6683b6278e6e01f43"
] | [
"defrcn/modeling/roi_heads/roi_heads.py"
] | [
"import torch\nimport logging\nimport numpy as np\nfrom torch import nn\nfrom typing import Dict\nfrom detectron2.layers import ShapeSpec\nfrom detectron2.utils.registry import Registry\nfrom detectron2.modeling.matcher import Matcher\nfrom detectron2.modeling.poolers import ROIPooler\nfrom detectron2.utils.events import get_event_storage\nfrom detectron2.modeling.sampling import subsample_labels\nfrom detectron2.modeling.box_regression import Box2BoxTransform\nfrom detectron2.structures import Boxes, Instances, pairwise_iou\nfrom detectron2.modeling.backbone.resnet import BottleneckBlock, make_stage\nfrom detectron2.modeling.proposal_generator.proposal_utils import add_ground_truth_to_proposals\nfrom .box_head import build_box_head\nfrom .fast_rcnn import ROI_HEADS_OUTPUT_REGISTRY, FastRCNNOutputLayers, FastRCNNOutputs\n\nROI_HEADS_REGISTRY = Registry(\"ROI_HEADS\")\nROI_HEADS_REGISTRY.__doc__ = \"\"\"\nRegistry for ROI heads in a generalized R-CNN model.\nROIHeads take feature maps and region proposals, and\nperform per-region computation.\n\nThe registered object will be called with `obj(cfg, input_shape)`.\nThe call is expected to return an :class:`ROIHeads`.\n\"\"\"\n\nlogger = logging.getLogger(__name__)\n\n\ndef build_roi_heads(cfg, input_shape):\n \"\"\"\n Build ROIHeads defined by `cfg.MODEL.ROI_HEADS.NAME`.\n \"\"\"\n name = cfg.MODEL.ROI_HEADS.NAME\n return ROI_HEADS_REGISTRY.get(name)(cfg, input_shape)\n\n\ndef select_foreground_proposals(proposals, bg_label):\n \"\"\"\n Given a list of N Instances (for N images), each containing a `gt_classes` field,\n return a list of Instances that contain only instances with `gt_classes != -1 &&\n gt_classes != bg_label`.\n\n Args:\n proposals (list[Instances]): A list of N Instances, where N is the number of\n images in the batch.\n bg_label: label index of background class.\n\n Returns:\n list[Instances]: N Instances, each contains only the selected foreground instances.\n list[Tensor]: N boolean vector, correspond to the selection mask of\n each Instances object. True for selected instances.\n \"\"\"\n assert isinstance(proposals, (list, tuple))\n assert isinstance(proposals[0], Instances)\n assert proposals[0].has(\"gt_classes\")\n fg_proposals = []\n fg_selection_masks = []\n for proposals_per_image in proposals:\n gt_classes = proposals_per_image.gt_classes\n fg_selection_mask = (gt_classes != -1) & (gt_classes != bg_label)\n fg_idxs = fg_selection_mask.nonzero().squeeze(1)\n fg_proposals.append(proposals_per_image[fg_idxs])\n fg_selection_masks.append(fg_selection_mask)\n return fg_proposals, fg_selection_masks\n\n\nclass ROIHeads(torch.nn.Module):\n \"\"\"\n ROIHeads perform all per-region computation in an R-CNN.\n\n It contains logic of cropping the regions, extract per-region features,\n and make per-region predictions.\n\n It can have many variants, implemented as subclasses of this class.\n \"\"\"\n\n def __init__(self, cfg, input_shape: Dict[str, ShapeSpec]):\n super(ROIHeads, self).__init__()\n\n # fmt: off\n self.batch_size_per_image = cfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE\n self.positive_sample_fraction = cfg.MODEL.ROI_HEADS.POSITIVE_FRACTION\n self.test_score_thresh = cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST\n self.test_nms_thresh = cfg.MODEL.ROI_HEADS.NMS_THRESH_TEST\n self.test_detections_per_img = cfg.TEST.DETECTIONS_PER_IMAGE\n self.in_features = cfg.MODEL.ROI_HEADS.IN_FEATURES\n self.num_classes = cfg.MODEL.ROI_HEADS.NUM_CLASSES\n self.proposal_append_gt = cfg.MODEL.ROI_HEADS.PROPOSAL_APPEND_GT\n self.feature_strides = {k: v.stride for k, v in input_shape.items()}\n self.feature_channels = {k: v.channels for k, v in input_shape.items()}\n self.cls_agnostic_bbox_reg = cfg.MODEL.ROI_BOX_HEAD.CLS_AGNOSTIC_BBOX_REG\n self.smooth_l1_beta = cfg.MODEL.ROI_BOX_HEAD.SMOOTH_L1_BETA\n # fmt: on\n\n # Matcher to assign box proposals to gt boxes\n self.proposal_matcher = Matcher(\n cfg.MODEL.ROI_HEADS.IOU_THRESHOLDS,\n cfg.MODEL.ROI_HEADS.IOU_LABELS,\n allow_low_quality_matches=False,\n )\n\n # Box2BoxTransform for bounding box regression\n self.box2box_transform = Box2BoxTransform(\n weights=cfg.MODEL.ROI_BOX_HEAD.BBOX_REG_WEIGHTS\n )\n\n def _sample_proposals(self, matched_idxs, matched_labels, gt_classes):\n \"\"\"\n Based on the matching between N proposals and M groundtruth,\n sample the proposals and set their classification labels.\n\n Args:\n matched_idxs (Tensor): a vector of length N, each is the best-matched\n gt index in [0, M) for each proposal.\n matched_labels (Tensor): a vector of length N, the matcher's label\n (one of cfg.MODEL.ROI_HEADS.IOU_LABELS) for each proposal.\n gt_classes (Tensor): a vector of length M.\n\n Returns:\n Tensor: a vector of indices of sampled proposals. Each is in [0, N).\n Tensor: a vector of the same length, the classification label for\n each sampled proposal. Each sample is labeled as either a category in\n [0, num_classes) or the background (num_classes).\n \"\"\"\n has_gt = gt_classes.numel() > 0\n # Get the corresponding GT for each proposal\n if has_gt:\n gt_classes = gt_classes[matched_idxs]\n # Label unmatched proposals (0 label from matcher) as background (label=num_classes)\n gt_classes[matched_labels == 0] = self.num_classes\n # Label ignore proposals (-1 label)\n gt_classes[matched_labels == -1] = -1\n else:\n gt_classes = torch.zeros_like(matched_idxs) + self.num_classes\n\n sampled_fg_idxs, sampled_bg_idxs = subsample_labels(\n gt_classes,\n self.batch_size_per_image,\n self.positive_sample_fraction,\n self.num_classes,\n )\n\n sampled_idxs = torch.cat([sampled_fg_idxs, sampled_bg_idxs], dim=0)\n return sampled_idxs, gt_classes[sampled_idxs]\n\n @torch.no_grad()\n def label_and_sample_proposals(self, proposals, targets):\n \"\"\"\n Prepare some proposals to be used to train the ROI heads.\n It performs box matching between `proposals` and `targets`, and assigns\n training labels to the proposals.\n It returns `self.batch_size_per_image` random samples from proposals and groundtruth boxes,\n with a fraction of positives that is no larger than `self.positive_sample_fraction.\n\n Args:\n See :meth:`ROIHeads.forward`\n\n Returns:\n list[Instances]:\n length `N` list of `Instances`s containing the proposals\n sampled for training. Each `Instances` has the following fields:\n - proposal_boxes: the proposal boxes\n - gt_boxes: the ground-truth box that the proposal is assigned to\n (this is only meaningful if the proposal has a label > 0; if label = 0\n then the ground-truth box is random)\n Other fields such as \"gt_classes\" that's included in `targets`.\n \"\"\"\n gt_boxes = [x.gt_boxes for x in targets]\n # Augment proposals with ground-truth boxes.\n # In the case of learned proposals (e.g., RPN), when training starts\n # the proposals will be low quality due to random initialization.\n # It's possible that none of these initial\n # proposals have high enough overlap with the gt objects to be used\n # as positive examples for the second stage components (box head,\n # cls head). Adding the gt boxes to the set of proposals\n # ensures that the second stage components will have some positive\n # examples from the start of training. For RPN, this augmentation improves\n # convergence and empirically improves box AP on COCO by about 0.5\n # points (under one tested configuration).\n if self.proposal_append_gt:\n proposals = add_ground_truth_to_proposals(gt_boxes, proposals)\n\n proposals_with_gt = []\n\n num_fg_samples = []\n num_bg_samples = []\n for proposals_per_image, targets_per_image in zip(proposals, targets):\n has_gt = len(targets_per_image) > 0\n match_quality_matrix = pairwise_iou(\n targets_per_image.gt_boxes, proposals_per_image.proposal_boxes\n )\n matched_idxs, matched_labels = self.proposal_matcher(\n match_quality_matrix\n )\n sampled_idxs, gt_classes = self._sample_proposals(\n matched_idxs, matched_labels, targets_per_image.gt_classes\n )\n\n # Set target attributes of the sampled proposals:\n proposals_per_image = proposals_per_image[sampled_idxs]\n proposals_per_image.gt_classes = gt_classes\n\n # We index all the attributes of targets that start with \"gt_\"\n # and have not been added to proposals yet (=\"gt_classes\").\n if has_gt:\n sampled_targets = matched_idxs[sampled_idxs]\n # NOTE: here the indexing waste some compute, because heads\n # will filter the proposals again (by foreground/background,\n # etc), so we essentially index the data twice.\n for (\n trg_name,\n trg_value,\n ) in targets_per_image.get_fields().items():\n if trg_name.startswith(\n \"gt_\"\n ) and not proposals_per_image.has(trg_name):\n proposals_per_image.set(\n trg_name, trg_value[sampled_targets]\n )\n else:\n gt_boxes = Boxes(\n targets_per_image.gt_boxes.tensor.new_zeros(\n (len(sampled_idxs), 4)\n )\n )\n proposals_per_image.gt_boxes = gt_boxes\n\n num_bg_samples.append(\n (gt_classes == self.num_classes).sum().item()\n )\n num_fg_samples.append(gt_classes.numel() - num_bg_samples[-1])\n proposals_with_gt.append(proposals_per_image)\n\n # Log the number of fg/bg samples that are selected for training ROI heads\n storage = get_event_storage()\n storage.put_scalar(\"roi_head/num_fg_samples\", np.mean(num_fg_samples))\n storage.put_scalar(\"roi_head/num_bg_samples\", np.mean(num_bg_samples))\n\n return proposals_with_gt\n\n def forward(self, images, features, proposals, targets=None):\n \"\"\"\n Args:\n images (ImageList):\n features (dict[str: Tensor]): input data as a mapping from feature\n map name to tensor. Axis 0 represents the number of images `N` in\n the input data; axes 1-3 are channels, height, and width, which may\n vary between feature maps (e.g., if a feature pyramid is used).\n proposals (list[Instances]): length `N` list of `Instances`s. The i-th\n `Instances` contains object proposals for the i-th input image,\n with fields \"proposal_boxes\" and \"objectness_logits\".\n targets (list[Instances], optional): length `N` list of `Instances`s. The i-th\n `Instances` contains the ground-truth per-instance annotations\n for the i-th input image. Specify `targets` during training only.\n It may have the following fields:\n - gt_boxes: the bounding box of each instance.\n - gt_classes: the label for each instance with a category ranging in [0, #class].\n\n Returns:\n results (list[Instances]): length `N` list of `Instances`s containing the\n detected instances. Returned during inference only; may be []\n during training.\n losses (dict[str: Tensor]): mapping from a named loss to a tensor\n storing the loss. Used during training only.\n \"\"\"\n raise NotImplementedError()\n\n\n@ROI_HEADS_REGISTRY.register()\nclass Res5ROIHeads(ROIHeads):\n \"\"\"\n The ROIHeads in a typical \"C4\" R-CNN model, where the heads share the\n cropping and the per-region feature computation by a Res5 block.\n \"\"\"\n\n def __init__(self, cfg, input_shape):\n super().__init__(cfg, input_shape)\n\n assert len(self.in_features) == 1\n\n # fmt: off\n pooler_resolution = cfg.MODEL.ROI_BOX_HEAD.POOLER_RESOLUTION\n pooler_type = cfg.MODEL.ROI_BOX_HEAD.POOLER_TYPE\n pooler_scales = (1.0 / self.feature_strides[self.in_features[0]], )\n sampling_ratio = cfg.MODEL.ROI_BOX_HEAD.POOLER_SAMPLING_RATIO\n # fmt: on\n assert not cfg.MODEL.KEYPOINT_ON\n\n self.pooler = ROIPooler(\n output_size=pooler_resolution,\n scales=pooler_scales,\n sampling_ratio=sampling_ratio,\n pooler_type=pooler_type,\n )\n\n self.res5, out_channels = self._build_res5_block(cfg)\n output_layer = cfg.MODEL.ROI_HEADS.OUTPUT_LAYER\n self.box_predictor = ROI_HEADS_OUTPUT_REGISTRY.get(output_layer)(\n cfg, out_channels, self.num_classes, self.cls_agnostic_bbox_reg\n )\n\n def _build_res5_block(self, cfg):\n # fmt: off\n stage_channel_factor = 2 ** 3 # res5 is 8x res2\n num_groups = cfg.MODEL.RESNETS.NUM_GROUPS\n width_per_group = cfg.MODEL.RESNETS.WIDTH_PER_GROUP\n bottleneck_channels = num_groups * width_per_group * stage_channel_factor\n out_channels = cfg.MODEL.RESNETS.RES2_OUT_CHANNELS * stage_channel_factor\n stride_in_1x1 = cfg.MODEL.RESNETS.STRIDE_IN_1X1\n norm = cfg.MODEL.RESNETS.NORM\n assert not cfg.MODEL.RESNETS.DEFORM_ON_PER_STAGE[-1], \\\n \"Deformable conv is not yet supported in res5 head.\"\n # fmt: on\n\n blocks = make_stage(\n BottleneckBlock,\n 3,\n first_stride=2,\n in_channels=out_channels // 2,\n bottleneck_channels=bottleneck_channels,\n out_channels=out_channels,\n num_groups=num_groups,\n norm=norm,\n stride_in_1x1=stride_in_1x1,\n )\n return nn.Sequential(*blocks), out_channels\n\n def _shared_roi_transform(self, features, boxes):\n x = self.pooler(features, boxes)\n # print('pooler:', x.size())\n x = self.res5(x)\n # print('res5:', x.size())\n return x\n\n def forward(self, images, features, proposals, targets=None):\n \"\"\"\n See :class:`ROIHeads.forward`.\n \"\"\"\n del images\n\n if self.training:\n proposals = self.label_and_sample_proposals(proposals, targets)\n del targets\n\n proposal_boxes = [x.proposal_boxes for x in proposals]\n box_features = self._shared_roi_transform(\n [features[f] for f in self.in_features], proposal_boxes\n )\n feature_pooled = box_features.mean(dim=[2, 3]) # pooled to 1x1\n pred_class_logits, pred_proposal_deltas = self.box_predictor(\n feature_pooled\n )\n del feature_pooled\n\n outputs = FastRCNNOutputs(\n self.box2box_transform,\n pred_class_logits,\n pred_proposal_deltas,\n proposals,\n self.smooth_l1_beta,\n )\n\n if self.training:\n del features\n losses = outputs.losses()\n return [], losses\n else:\n pred_instances, _ = outputs.inference(\n self.test_score_thresh,\n self.test_nms_thresh,\n self.test_detections_per_img,\n )\n return pred_instances, {}\n\n\n@ROI_HEADS_REGISTRY.register()\nclass StandardROIHeads(ROIHeads):\n \"\"\"\n It's \"standard\" in a sense that there is no ROI transform sharing\n or feature sharing between tasks.\n The cropped rois go to separate branches directly.\n This way, it is easier to make separate abstractions for different branches.\n\n This class is used by most models, such as FPN and C5.\n To implement more models, you can subclass it and implement a different\n :meth:`forward()` or a head.\n \"\"\"\n\n def __init__(self, cfg, input_shape):\n super(StandardROIHeads, self).__init__(cfg, input_shape)\n self._init_box_head(cfg)\n\n def _init_box_head(self, cfg):\n # fmt: off\n pooler_resolution = cfg.MODEL.ROI_BOX_HEAD.POOLER_RESOLUTION\n pooler_scales = tuple(1.0 / self.feature_strides[k] for k in self.in_features)\n sampling_ratio = cfg.MODEL.ROI_BOX_HEAD.POOLER_SAMPLING_RATIO\n pooler_type = cfg.MODEL.ROI_BOX_HEAD.POOLER_TYPE\n # fmt: on\n\n # If StandardROIHeads is applied on multiple feature maps (as in FPN),\n # then we share the same predictors and therefore the channel counts must be the same\n in_channels = [self.feature_channels[f] for f in self.in_features]\n # Check all channel counts are equal\n assert len(set(in_channels)) == 1, in_channels\n in_channels = in_channels[0]\n\n self.box_pooler = ROIPooler(\n output_size=pooler_resolution,\n scales=pooler_scales,\n sampling_ratio=sampling_ratio,\n pooler_type=pooler_type,\n )\n # Here we split \"box head\" and \"box predictor\", which is mainly due to historical reasons.\n # They are used together so the \"box predictor\" layers should be part of the \"box head\".\n # New subclasses of ROIHeads do not need \"box predictor\"s.\n self.box_head = build_box_head(\n cfg,\n ShapeSpec(\n channels=in_channels,\n height=pooler_resolution,\n width=pooler_resolution,\n ),\n )\n\n self.cls_head = build_box_head(\n cfg,\n ShapeSpec(\n channels=in_channels,\n height=pooler_resolution,\n width=pooler_resolution,\n ),\n )\n\n output_layer = cfg.MODEL.ROI_HEADS.OUTPUT_LAYER\n self.box_predictor = ROI_HEADS_OUTPUT_REGISTRY.get(output_layer)(\n cfg,\n self.box_head.output_size,\n self.num_classes,\n self.cls_agnostic_bbox_reg,\n )\n\n self.cls_predictor = ROI_HEADS_OUTPUT_REGISTRY.get(output_layer)(\n cfg,\n self.box_head.output_size,\n self.num_classes,\n self.cls_agnostic_bbox_reg,\n )\n\n def forward(self, images, features, proposals, targets=None):\n \"\"\"\n See :class:`ROIHeads.forward`.\n \"\"\"\n del images\n if self.training:\n proposals = self.label_and_sample_proposals(proposals, targets)\n del targets\n\n features_list = [features[f] for f in self.in_features]\n\n if self.training:\n losses = self._forward_box(features_list, proposals)\n return proposals, losses\n else:\n pred_instances = self._forward_box(features_list, proposals)\n return pred_instances, {}\n\n def _forward_box(self, features, proposals):\n \"\"\"\n Forward logic of the box prediction branch.\n\n Args:\n features (list[Tensor]): #level input features for box prediction\n proposals (list[Instances]): the per-image object proposals with\n their matching ground truth.\n Each has fields \"proposal_boxes\", and \"objectness_logits\",\n \"gt_classes\", \"gt_boxes\".\n\n Returns:\n In training, a dict of losses.\n In inference, a list of `Instances`, the predicted instances.\n \"\"\"\n box_features = self.box_pooler(\n features, [x.proposal_boxes for x in proposals]\n )\n\n cls_features = self.cls_head(box_features)\n pred_class_logits, _ = self.cls_predictor(\n cls_features\n )\n\n box_features = self.box_head(box_features)\n _, pred_proposal_deltas = self.box_predictor(\n box_features\n )\n del box_features\n\n outputs = FastRCNNOutputs(\n self.box2box_transform,\n pred_class_logits,\n pred_proposal_deltas,\n proposals,\n self.smooth_l1_beta,\n )\n if self.training:\n return outputs.losses()\n else:\n pred_instances, _ = outputs.inference(\n self.test_score_thresh,\n self.test_nms_thresh,\n self.test_detections_per_img,\n )\n return pred_instances\n"
] | [
[
"torch.nn.Sequential",
"torch.cat",
"torch.zeros_like",
"torch.no_grad",
"numpy.mean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
shenlong95/zoofs | [
"8cac2ba00342e4c02d6004414871b34cbc5f3c38"
] | [
"zoofs/harrishawkoptimization.py"
] | [
"from zoofs.baseoptimizationalgorithm import BaseOptimizationAlgorithm\nimport numpy as np\nimport pandas as pd\nimport logging as log\nimport time\nimport plotly.graph_objects as go\nimport scipy\nimport warnings\nimport math\n\nclass HarrisHawkOptimization(BaseOptimizationAlgorithm):\n def __init__(self,\n objective_function,\n n_iteration: int = 1000,\n timeout: int = None,\n population_size=50,\n minimize=True,\n beta=0.5):\n \"\"\" \n Parameters\n ----------\n objective_function: user made function of the signature 'func(model,X_train,y_train,X_test,y_test)'\n User defined function that returns the objective value \n\n population_size: int, default=50\n Total size of the population , default=50\n\n n_iteration: int, default=1000\n Number of time the Particle Swarm Optimization algorithm will run\n\n timeout: int = None\n Stop operation after the given number of second(s).\n If this argument is set to None, the operation is executed without time limitation and n_iteration is followed\n\n minimize : bool, default=True\n Defines if the objective value is to be maximized or minimized\n\n beta: float, default=0.5\n beta value for random levy walk\n \n Attributes\n ----------\n best_feature_list : ndarray of shape (n_features)\n list of features with the best result of the entire run\n \"\"\"\n super().__init__(objective_function, n_iteration, timeout, population_size, minimize)\n self.beta=beta\n\n def _exploration_phase(self):\n\n q=np.random.random(len(self.exploration_individuals_indexes))\n\n q_lesser_indexes=self.exploration_individuals_indexes[np.where(q<0.5)[0]]\n q_lesser_individuals=self.individuals[q_lesser_indexes]\n\n r3=np.random.random(q_lesser_individuals.shape)\n r4=np.random.random(q_lesser_individuals.shape) \n\n self.X_m=self.individuals.mean(axis=0)\n X_sub=self.sigmoid((self.best_dim-self.X_m)-r3*(0+r4*(1-0)))\n self.individuals[q_lesser_indexes]=np.where(np.random.random(q_lesser_individuals.shape)<X_sub,1,0)\n\n q_greater_indexes=self.exploration_individuals_indexes[np.where(q>=0.5)[0]]\n q_greater_individuals=self.individuals[q_greater_indexes]\n\n X_rand=self.individuals[np.random.choice(np.arange(0,self.individuals.shape[0]),size=len(q_greater_indexes))]\n r1=np.random.random(q_greater_individuals.shape)\n r2=np.random.random(q_greater_individuals.shape) \n\n X_update=self.sigmoid(X_rand-r1*np.abs(X_rand-2*r2*q_greater_individuals))\n self.individuals[q_greater_indexes]=np.where(np.random.random(q_greater_individuals.shape)<X_update,1,0)\n\n def _temporary_evaluate_fitness(self, model, x_train, y_train, x_valid, y_valid,target_individuals):\n _temp=self.individuals\n self.individuals=target_individuals\n res=super()._evaluate_fitness(model, x_train, y_train, x_valid, y_valid,0,0)\n self.individuals=_temp\n return res\n\n def _levy_walk(self,soft_besiege_with_dives_indexes):\n nume = math.gamma(1 + self.beta) * np.sin(np.pi * self.beta / 2)\n deno = math.gamma((1 + self.beta) / 2) * self.beta * (2**((self.beta - 1) / 2))\n sigma = (nume / deno)**(1 / self.beta)\n u = np.random.random((len(soft_besiege_with_dives_indexes),self.individuals.shape[1])) * sigma \n v = np.random.random((len(soft_besiege_with_dives_indexes),self.individuals.shape[1]))\n step = u / (np.abs(v)**(1 / self.beta))\n LF = 0.01 * step\n return LF\n\n\n def _repeat(self,fitness,individuals):\n return np.repeat(fitness,individuals.shape[1],axis=0).reshape(individuals.shape)\n\n def _soft_besiege(self):\n soft_beseige_indexes=self.exploitation_individuals_indexes[np.where( (np.abs(self.exploitation_energy)>=0.5) & (self.r>=0.5) )[0]]\n J = 2*(1-np.random.random(len(soft_beseige_indexes))).reshape(-1,1)\n delta_X=self.best_dim-self.individuals[soft_beseige_indexes]\n soft_beseige_res=delta_X - np.repeat(self.e[soft_beseige_indexes],self.individuals.shape[1]).reshape(len(soft_beseige_indexes),self.individuals.shape[1])*\\\n np.abs(J*np.repeat(self.best_dim.reshape(1,-1), len(soft_beseige_indexes),axis=0)-self.individuals[soft_beseige_indexes])\n soft_beseige_res=self.sigmoid(soft_beseige_res)\n self.individuals[soft_beseige_indexes]=np.where(np.random.random(self.individuals[soft_beseige_indexes].shape)<soft_beseige_res,1,0)\n\n def _hard_besiege(self):\n hard_besiege_indexes=self.exploitation_individuals_indexes[np.where( (np.abs(self.exploitation_energy)<0.5) & (self.r>=0.5) )[0]] \n hard_besiege_res=self.best_dim-self.e[hard_besiege_indexes].reshape(-1,1)*np.abs(self.best_dim-self.individuals[hard_besiege_indexes])\n hard_besiege_res=self.sigmoid(hard_besiege_res)\n self.individuals[hard_besiege_indexes]=np.where(np.random.random(self.individuals[hard_besiege_indexes].shape)<hard_besiege_res,1,0)\n\n def _soft_besiege_with_dives(self,model, X_train, y_train, X_valid, y_valid):\n soft_besiege_with_dives_indexes=self.exploitation_individuals_indexes[np.where( (np.abs(self.exploitation_energy)>=0.5) & (self.r<0.5) )[0]] \n soft_besiege_individuals=self.individuals[soft_besiege_with_dives_indexes]\n\n LF=self._levy_walk(soft_besiege_with_dives_indexes)\n J = 2*(1-np.random.random(len(soft_besiege_with_dives_indexes))).reshape(-1,1)\n soft_besiege_with_dives_res=self.best_dim - np.repeat(self.e[soft_besiege_with_dives_indexes],self.individuals.shape[1]).reshape(len(soft_besiege_with_dives_indexes),self.individuals.shape[1])*\\\n np.abs(J*np.repeat(self.best_dim.reshape(1,-1), len(soft_besiege_with_dives_indexes),axis=0)-self.individuals[soft_besiege_with_dives_indexes])\n \n Y_soft_besiege_with_dives_res=self.sigmoid(soft_besiege_with_dives_res)\n Z_soft_besiege_with_dives_res=Y_soft_besiege_with_dives_res + np.random.random(Y_soft_besiege_with_dives_res.shape)*LF\n\n Y_soft_besiege_with_dives_res=np.where(np.random.random(Y_soft_besiege_with_dives_res.shape)<Y_soft_besiege_with_dives_res,1,0)\n Z_soft_besiege_with_dives_res=np.where(np.random.random(Z_soft_besiege_with_dives_res.shape)<Z_soft_besiege_with_dives_res,1,0)\n\n ind_fitness=self._temporary_evaluate_fitness(model, X_train, y_train, X_valid, y_valid,soft_besiege_individuals)\n Y_fitness=self._temporary_evaluate_fitness(model, X_train, y_train, X_valid, y_valid,Y_soft_besiege_with_dives_res)\n Z_fitness=self._temporary_evaluate_fitness(model, X_train, y_train, X_valid, y_valid,Z_soft_besiege_with_dives_res)\n\n self.individuals[soft_besiege_with_dives_indexes]=np.where(self._repeat(Y_fitness,Y_soft_besiege_with_dives_res)<self._repeat(Z_fitness,Z_soft_besiege_with_dives_res),\\\n np.where(self._repeat(Y_fitness,Y_soft_besiege_with_dives_res)<self._repeat(ind_fitness,soft_besiege_individuals),Y_soft_besiege_with_dives_res,soft_besiege_individuals),\n np.where(self._repeat(Z_fitness,Z_soft_besiege_with_dives_res)<self._repeat(ind_fitness,soft_besiege_individuals),Z_soft_besiege_with_dives_res,soft_besiege_individuals))\n\n def _hard_besiege_with_dives(self,model, X_train, y_train, X_valid, y_valid):\n hard_besiege_with_dives_indexes=self.exploitation_individuals_indexes[np.where( (np.abs(self.exploitation_energy)<0.5) & (self.r<0.5) )[0]] \n hard_besiege_individuals=self.individuals[hard_besiege_with_dives_indexes]\n\n LF=self._levy_walk(hard_besiege_with_dives_indexes)\n J = 2*(1-np.random.random(len(hard_besiege_with_dives_indexes))).reshape(-1,1)\n self.X_m=self.individuals.mean(axis=0)\n\n hard_besiege_with_dives_res=self.best_dim - np.repeat(self.e[hard_besiege_with_dives_indexes],self.individuals.shape[1]).reshape(len(hard_besiege_with_dives_indexes),self.individuals.shape[1])*\\\n np.abs(J*np.repeat(self.best_dim.reshape(1,-1), len(hard_besiege_with_dives_indexes),axis=0)-\n np.repeat(self.X_m.reshape(1,-1), len(hard_besiege_with_dives_indexes),axis=0))\n \n Y_hard_besiege_with_dives_res=self.sigmoid(hard_besiege_with_dives_res)\n Z_hard_besiege_with_dives_res=Y_hard_besiege_with_dives_res + np.random.random(Y_hard_besiege_with_dives_res.shape)*LF\n\n Y_hard_besiege_with_dives_res=np.where(np.random.random(Y_hard_besiege_with_dives_res.shape)<Y_hard_besiege_with_dives_res,1,0)\n Z_hard_besiege_with_dives_res=np.where(np.random.random(Z_hard_besiege_with_dives_res.shape)<Z_hard_besiege_with_dives_res,1,0)\n\n ind_fitness=self._temporary_evaluate_fitness(model, X_train, y_train, X_valid, y_valid,hard_besiege_individuals)\n Y_fitness=self._temporary_evaluate_fitness(model, X_train, y_train, X_valid, y_valid,Y_hard_besiege_with_dives_res)\n Z_fitness=self._temporary_evaluate_fitness(model, X_train, y_train, X_valid, y_valid,Z_hard_besiege_with_dives_res)\n\n self.individuals[hard_besiege_with_dives_indexes]=np.where(self._repeat(Y_fitness,Y_hard_besiege_with_dives_res)<self._repeat(Z_fitness,Z_hard_besiege_with_dives_res),\\\n np.where(self._repeat(Y_fitness,Y_hard_besiege_with_dives_res)<self._repeat(ind_fitness,hard_besiege_individuals),Y_hard_besiege_with_dives_res,hard_besiege_individuals),\n np.where(self._repeat(Z_fitness,Z_hard_besiege_with_dives_res)<self._repeat(ind_fitness,hard_besiege_individuals),Z_hard_besiege_with_dives_res,hard_besiege_individuals))\n\n\n def fit(self, model, X_train, y_train, X_valid, y_valid, verbose=True):\n \"\"\"\n Parameters\n ---------- \n model: machine learning model's object\n The object to be used for fitting on train data\n\n X_train: pandas.core.frame.DataFrame of shape (n_samples, n_features)\n Training input samples to be used for machine learning model\n\n y_train: pandas.core.frame.DataFrame or pandas.core.series.Series of shape (n_samples)\n The target values (class labels in classification, real numbers in\n regression).\n\n X_valid: pandas.core.frame.DataFrame of shape (n_samples, n_features)\n Validation input samples\n\n y_valid: pandas.core.frame.DataFrame or pandas.core.series.Series of shape (n_samples)\n The target values (class labels in classification, real numbers in\n regression).\n\n verbose : bool,default=True\n Print results for iterations\n\n \"\"\"\n self._check_params(model, X_train, y_train, X_valid, y_valid)\n\n self.feature_score_hash = {}\n self.feature_list = np.array(list(X_train.columns))\n self.best_results_per_iteration = {}\n self.best_score = np.inf\n self.best_dim = np.ones(X_train.shape[1])\n\n self.initialize_population(X_train)\n\n if (self.timeout is not None):\n timeout_upper_limit = time.time() + self.timeout\n else:\n timeout_upper_limit = time.time()\n\n for i in range(self.n_iteration):\n\n if (self.timeout is not None) & (time.time() > timeout_upper_limit):\n warnings.warn(\"Timeout occured\")\n break\n\n # Logging warning if any entity in the population ends up having zero selected features\n self._check_individuals()\n\n self.fitness_scores = self._evaluate_fitness(\n model, X_train, y_train, X_valid, y_valid)\n\n self.gbest_individual = self.best_dim\n\n self.iteration_objective_score_monitor(i)\n\n self.e_0 = -1 + 2 * np.random.random(size=(self.population_size))\n self.e = 2 * self.e_0 * (1 - ((i+1) / self.n_iteration))\n\n self.exploration_individuals_indexes=np.where(np.abs(self.e)>=1)[0]\n self._exploration_phase()\n\n self.exploitation_individuals_indexes=np.where(np.abs(self.e)<1)[0] \n self.r=np.random.random(len(self.exploitation_individuals_indexes))\n self.exploitation_energy=self.e[self.exploitation_individuals_indexes]\n\n self._soft_besiege()\n \n self._hard_besiege()\n \n self._soft_besiege_with_dives(model, X_train, y_train, X_valid, y_valid)\n\n self._hard_besiege_with_dives(model, X_train, y_train, X_valid, y_valid)\n\n self.verbose_results(verbose, i)\n \n self.best_feature_list = list(\n self.feature_list[np.where(self.best_dim)[0]])\n return self.best_feature_list\n"
] | [
[
"numpy.random.random",
"numpy.abs",
"numpy.arange",
"numpy.sin",
"numpy.ones",
"numpy.repeat",
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
LiwenxuanNJU/TVpgGLM | [
"d07f81cf3a404474b640777a3ab01b0a79ad9187"
] | [
"plot/Plotfun1.py"
] | [
"import sys\n\nsys.path.append(\"/Users/Roger/Dropbox/pyglm-master/pyglm/\")\nsys.path.append(\"/Users/Roger/Dropbox/pyglm-master/pyglm/utils/\")\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pickle\nfrom hips.plotting.colormaps import harvard_colors\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport seaborn as sns\n\nsns.set_style(\"white\")\npaper_rc = {'lines.linewidth': 2.5, 'lines.markersize': 10, 'font.size': 15,\n 'axes.labelsize':15, 'axes.titlesize':15, 'xtick.labelsize': 15, 'ytick.labelsize': 15}\nsns.set_context(\"paper\", rc = paper_rc)\nplt.ion()\n\n# plot: sythetic_true_location\nwith open('TVpgGLM/results/sythetic_true_location1.pickle', 'rb') as f:\n lps, W_true, W_smpls, A_smpls, L_true, L_smples = pickle.load(f)\n\nN = 10\nN_samples = 2000\nk = 0\nfig = plt.figure()\nhandles = []\n\n## True weighted adjacency matrix\nax0 = fig.add_subplot(131, aspect=\"equal\")\nim0 = ax0.imshow(W_true[:,:,0],vmin=-3, vmax=3, cmap=\"RdBu_r\", interpolation=\"nearest\")\nax0.set_yticks([])\nax0.set_xticks([])\nax0.set_xlabel('Post')\nax0.set_ylabel('Pre')\nax0.set_title(r'True $A \\odot W$')\n\n# Colorbar\ndivider = make_axes_locatable(ax0)\ncbax = divider.new_horizontal(size=\"5%\", pad=0.05)\nfig.add_axes(cbax)\nplt.colorbar(im0, cax=cbax)\nhandles.append(im0)\n\n## Est weighted adjacency matrix\nax1 = fig.add_subplot(132, aspect=\"equal\")\nW_mean = W_smpls[N_samples // 2:].mean(0)\nim1 = ax1.imshow(W_mean[:,:,0],vmin=-3, vmax=3, cmap=\"RdBu_r\", interpolation=\"nearest\")\nax1.set_yticks([])\nax1.set_xticks([])\nax1.set_xlabel('Post')\nax1.set_ylabel('Pre')\nax1.set_title(r'MCMC $\\mathbb{E}[A \\odot W]$')\n\n# Colorbar\ndivider = make_axes_locatable(ax1)\ncbax = divider.new_horizontal(size=\"5%\", pad=0.05)\nfig.add_axes(cbax)\nplt.colorbar(im1, cax=cbax)\nhandles.append(im1)\n\n## Latent location\ncolor = harvard_colors()[0:10]\nax2 = fig.add_subplot(133, aspect=\"equal\")\n\nfor i in range(N):\n ax2.scatter(L_smples[-500:, i, 0],\n L_smples[-500:, i, 1], alpha=0.1, s=50, c=color[k])\n k += 1\n\nax2.scatter(L_true[:, 0], L_true[:, 1], s=150, c=color, edgecolor='0',\n lw=1, marker=(5, 1))\n\nb = np.amax(abs(L_true)) + L_true[:].std() / 2.0\n\n# Plot grids for origin\nax2.plot([0, 0], [-b, b], ':k', lw=0.2)\nax2.plot([-b, b], [0, 0], ':k', lw=0.2)\n\n# Set the limits\nax2.set_xlim([-b, b])\nax2.set_ylim([-b, b])\n\n# Labels\nax2.set_xlabel(r'$\\ell_{1}$[a.u.]',labelpad=0.2)\nax2.set_ylabel(r'$\\ell_{2}$[a.u.]',labelpad=0.2)\nax2.set_title('True & Inferred Locations')\n\nfig.subplots_adjust(left=None, bottom=None, right=None, top=None,\n wspace=0.5, hspace=None)\n# Save the figure\nfig.savefig(\"TVpgGLM/fig/plot1.pdf\")\n"
] | [
[
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.ion",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
knowledgevis/rms_infer_web | [
"53382762ffc6ec12ac635e2938661008cd87cae8"
] | [
"girder_worker_tasks/arbor_nova_tasks/arbor_tasks/fnlcr/myod1.py"
] | [
"# added for girder interaction as plugin arbor task\nfrom girder_worker.app import app\nfrom girder_worker.utils import girder_job\nfrom tempfile import NamedTemporaryFile\n\nimport billiard as multiprocessing\nfrom billiard import Queue, Process \nimport json\nimport sys\n\n#---------\n\nimport torch\nfrom torch.utils.data import Dataset as BaseDataset\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport torch.nn.functional as F\nfrom torch.autograd import Function\nfrom torchvision import datasets, models, transforms\nimport torchnet.meter.confusionmeter as cm\n\nfrom sklearn.preprocessing import label_binarize\nfrom sklearn.metrics import roc_auc_score, roc_curve\nfrom sklearn.metrics import auc as calc_auc\n\nimport openslide as op\nimport argparse\nimport numpy as np\nimport torchvision\nimport cv2\nimport time\nfrom skimage.io import imread\nfrom tifffile import imsave\nimport matplotlib.pyplot as plt\nimport time\nimport random\nimport os, glob\nimport copy\nimport pandas as pd\nimport albumentations as albu\nfrom albumentations import Resize\nimport gc\nimport timm\nfrom radam import RAdam\n\nfrom PIL import Image\n\nImage.MAX_IMAGE_PIXELS = None\n\nREPORTING_INTERVAL = 10\n\nIMAGE_SIZE = 224\nPRINT_FREQ = 20\nclass_names = ['Neg', 'Pos']\nnum_classes = len(class_names)\n\n## MYOD1 heatmap will be saved in the inference_path folder\n#inference_output = './For_Curtis/Inferenced/'\n\n## MYOD1 WSIs tiff to inference location\n#inference_input_tiff = './For_Curtis/20x/'\n\n## MYOD1 WSIs svs to inference location\n#inference_input_svs = './For_Curtis/svs/'\n\n\n#-------------------------------------------\n# girder job definition to enable execution by girder_worker\n\n@girder_job(title='myod1')\[email protected](bind=True)\ndef myod1(self,image_file, segment_image_file,**kwargs):\n\n print(\" input image filename = {}\".format(image_file))\n\n # setup the GPU environment for pytorch\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n DEVICE = 'cuda'\n print('perform forward inferencing')\n\n # set the UI to 0% progress initially. stdout is parsed by the ui\n print(f'progress: {0}')\n\n # find and run all models in the models directory. Return the average value of the models\n # as the final result\n resultArray = []\n models = glob.glob('./models/myod1*')\n totalFolds = len(models)\n print('found ',totalFolds,'models to average')\n for fold,model in enumerate(models):\n print('**** running with model',model)\n print('****') \n predict_values = start_inferencing(image_file,segment_image_file,model,fold,totalFolds)\n resultArray.append(predict_values)\n print('completed all folds')\n\n # find the average of the model results\n predict_values = sum(resultArray) / len(resultArray)\n\n # new output of classification statistics in a string\n statistics = generateStatsString(predict_values)\n # generate unique names for multiple runs. Add extension so it is easier to use\n statoutname = NamedTemporaryFile(delete=False).name+'.json'\n open(statoutname,\"w\").write(statistics)\n\n # return the name of the output file\n return statoutname\n\n\n# calculate the statistics for the image by converting to numpy and comparing masks against\n# the tissue classes. create masks for each class and count the number of pixels\n\ndef generateStatsString(predict_values):\n # any number of statistics can be returned in a JSON object. Derived \n # stats can be calculated here and included as other keys in the dict object\n statsDict = {'Positive Score': predict_values[0] }\n # convert dict to json string\n print('statsdict:',statsDict)\n statsString = json.dumps(statsDict)\n return statsString\n\n\n#-------------------------------------------\n# from the MYOD1 script\n\ndef reset_seed(seed):\n \"\"\"\n ref: https://forums.fast.ai/t/accumulating-gradients/33219/28\n \"\"\"\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n\n\n# this code was adapted from a command line script that used argparse functionality to \n# set command line arguments with defaults. The following set of arguments includes the\n# defaults and suggested options. It is now initalized here and used in the algorithm \n# by referencing the \"args\" variable. The upperT=0.99 (upper threshold) is important to \n# match the results reported in the submitted manuscript. \n\nfrom argparse import Namespace\ndef parse():\n args = Namespace(alpha=0.1, batch_size=400, cth=0.9, data='./For_Curtis/', \\\n deterministic=False, epochs=90, evaluate=False, gnum=1, kfold=3, lowerT=0.75, \\\n lr=0.1, milweight=0.6, momentum=0.9, numgenes=3, pretrained=False, print_freq=10, \\\n prof=-1, resume='', start_epoch=0, sync_bn=False, tnum=1, upperT=0.99, \\\n weight_decay=0.0001, workers=128)\n\n return args\n\n\ndef convert_to_tensor(batch):\n num_images = batch.shape[0]\n tensor = torch.zeros((num_images, 3, IMAGE_SIZE, IMAGE_SIZE), dtype=torch.uint8).cuda(non_blocking=True)\n\n mean = torch.tensor([0.0, 0.0, 0.0]).cuda().view(1, 3, 1, 1)\n std = torch.tensor([255.0, 255.0, 255.0]).cuda().view(1, 3, 1, 1)\n\n for i, img in enumerate(batch):\n nump_array = np.asarray(img, dtype=np.uint8)\n if (nump_array.ndim < 3):\n nump_array = np.expand_dims(nump_array, axis=-1)\n nump_array = np.rollaxis(nump_array, 2)\n\n tensor[i] = torch.from_numpy(nump_array)\n\n tensor = tensor.float()\n tensor = tensor.sub_(mean).div_(std)\n return tensor\n\ndef load_best_model(model, path_to_model, best_prec1=0.0):\n if os.path.isfile(path_to_model):\n print(\"=> loading checkpoint '{}'\".format(path_to_model))\n checkpoint = torch.load(path_to_model, map_location=lambda storage, loc: storage)\n model.load_state_dict(checkpoint['state_dict'])\n print(\"=> loaded checkpoint '{}' (epoch {}), best_precision {}\"\n .format(path_to_model, checkpoint['epoch'], best_prec1))\n return model\n else:\n print(\"=> no checkpoint found at '{}'\".format(path_to_model))\n\n\nclass Classifier(nn.Module):\n def __init__(self, n_classes):\n super(Classifier, self).__init__()\n # self.effnet = timm.create_model('seresnet18', pretrained=True)\n self.effnet = timm.create_model('seresnet50', pretrained=True)\n in_features = 1000\n self.elu = nn.ELU()\n self.relu = nn.ReLU()\n self.dropout = nn.Dropout(0.25)\n self.alpha_dropout = nn.AlphaDropout(0.25)\n self.l0 = nn.Linear(in_features, 64, bias=True)\n self.l1 = nn.Linear(64, n_classes, bias=True)\n\n def forward(self, input):\n x = self.effnet(input)\n x = self.elu(x)\n x = self.alpha_dropout(x)\n x = self.l0(x)\n x = self.elu(x) # 64\n x = self.alpha_dropout(x)\n x = self.l1(x)\n return x\n\n\n\ndef start_inferencing(image_file,segmentation_mask,modelFilePath,foldCount,totalFolds):\n reset_seed(1)\n args = parse()\n torch.backends.cudnn.benchmark = True\n\n # Multiple different networks could be ensembled for the full model. To ensemble, a \n # loop would be added above this call to loop through all models and combine results\n\n #weight_path = './models/myod1_fold_01_model.pth.tar'\n weight_path = modelFilePath\n\n ## Model instantiation and load model weight.\n ## Currently, my default setup is using 4 GPUs and batch size is 400\n ## Verified with 1 GPU and with the same batch_size of 400\n model = Classifier(num_classes)\n model.eval()\n model = nn.DataParallel(model)\n model = model.cuda()\n model = load_best_model(model, weight_path, 0.)\n print('Loading model is finished!!!!!!!')\n\n ## inference test svs image and calculate area under the curve\n prediction = test_auc_svs(model, image_file, segmentation_mask, foldCount,totalFolds,args)\n return prediction\n\n\ndef test_auc_svs(model, inference_input, segment_input, foldCount, totalFolds,args):\n model.eval()\n\n ml = nn.Softmax(dim=1)\n\n ## Set IMAGE_SIZE as 224\n IMAGE_SIZE = 224\n\n \n ## Read input WSIs to be inferenced\n test_ids = [inference_input]\n print(len(test_ids))\n\n ## Patient, labels variables\n patients = np.zeros(len(test_ids))\n other_index = 0\n\n ## Variables to calculate final outcome value\n correct_count = np.zeros(2)\n correct_probs = np.zeros(2)\n\n for i in range(len(test_ids)):\n file_path = test_ids[i]\n\n ## imgFile_id => WSI file path's basename\n imgFile_id = os.path.splitext(os.path.basename(file_path))[0]\n\n ## WSI's segmentation mask (extract patches only from cancerous regions)\n label_path = segment_input\n\n ## Read WSI\n wholeslide = op.OpenSlide(file_path)\n\n ## Level 0 optical magnification\n ## If it is 40.0, extract larger patches (IMAGE_SIZE*2) and downsize\n ## If it is 20.0, extract IMAGE_SIZE patch\n\n objective = float(wholeslide.properties[op.PROPERTY_NAME_OBJECTIVE_POWER])\n print(imgFile_id + ' Objective is: ', objective)\n assert objective >= 20.0, \"Level 0 Objective should be greater than 20x\"\n\n ## Extract WSI height and width\n sizes = wholeslide.level_dimensions[0]\n image_height = sizes[1]\n image_width = sizes[0]\n\n ## Resize WSI's segmentation mask to WSI's size\n label_org = imread(label_path)\n aug = Resize(p=1.0, height=image_height, width=image_width)\n augmented = aug(image=label_org, mask=label_org)\n label = augmented['mask']\n\n # decide how long this will take and prepare to give status updates in the log file\n iteration_count = 10\n report_interval = 1\n report_count = 0\n # report current state\n # start with the fold count expression because this might be called multiple times\n percent_complete = 100 * foldCount / totalFolds\n\n ## If the Level 0 objective is 40.0\n if objective==40.0:\n ## Retrieve patches from WSI by batch_size but extract no more than 4000 patches\n for k in range(4000 // args.batch_size):\n image_width_start = 0\n image_width_end = image_width - IMAGE_SIZE*2 - 1\n\n image_height_start = 0\n image_height_end = image_height - IMAGE_SIZE*2 - 1\n\n x_coord = 0\n y_coord = 0\n\n patch_index = 0\n image_batch = np.zeros((args.batch_size, IMAGE_SIZE, IMAGE_SIZE, 3), np.uint8)\n\n ## Extract batch_size patches from WSI within cancerous regions\n for j in range(args.batch_size):\n picked = False\n\n while (picked == False):\n ## Pick random locations withint segmentation masks first\n x_coord = random.sample(range(image_width_start, image_width_end), 1)[0]\n y_coord = random.sample(range(image_height_start, image_height_end), 1)[0]\n label_patch = label[y_coord:y_coord + IMAGE_SIZE*2, x_coord:x_coord + IMAGE_SIZE*2]\n\n ## Examine whether the random coordinates are within cancerous regions\n ## If the coordinates are containing enough cancerous region 'picked = True' and If not 'picked=False'\n if (np.sum(label_patch // 255) > int(IMAGE_SIZE*2 * IMAGE_SIZE*2 * 0.50)) and (\n np.sum(label_patch == 127) == 0):\n picked = True\n else:\n picked = False\n\n ## Using the picked coordinates, extract corresponding WSI patch\n ## Store patches in the image_batch so that it can be later inferenced at once\n read_region = wholeslide.read_region((x_coord, y_coord), 0, (IMAGE_SIZE*2, IMAGE_SIZE*2))\n large_image_patch = np.asarray(read_region)[:, :, :3]\n image_aug = Resize(p=1.0, height=IMAGE_SIZE, width=IMAGE_SIZE)\n image_augmented = image_aug(image=large_image_patch)\n image_patch = image_augmented['image']\n image_batch[patch_index, :, :, :] = image_patch\n patch_index += 1\n\n with torch.no_grad():\n ## Convert image_batch to pytorch tensor\n image_tensor = convert_to_tensor(image_batch)\n\n ## Inference the image_tensor (as a batch)\n inst_logits = model(image_tensor)\n\n ## Model's outcome are logit values for each patch\n ## Need to conver them into probabilities of being MYOD1+\n probs = ml(inst_logits)\n\n ## Each patch produces two outcomes, MYOD1- and MYOD1+\n ## Larger value's index will be the prediction for the patch (0, MYOD1-) (1, MYOD1+)\n _, preds = torch.max(inst_logits, 1)\n cbatch_size = len(image_tensor)\n\n ## Examine all the patch's probability values\n ## If predicted outcome's probability is greater than args.upperT, use them in the final calculation\n ## Which means, if the model's outcome is not confident enough, we do not use them in our final calculation\n for l in range(cbatch_size):\n ## preds contains each patch's prediction (either 0 or 1)\n ## index 0 means MYOD1- and index 1 means MYOD1+\n index = preds[l].item()\n\n ## Check the probability of the prediction\n ## if it is greater than the threshold, it will be counted\n ## correct_count: (2, ) shape\n ## correct_count[0] contains total number of patches that are predicted as MYOD1- and has probability >= threshold\n ## correct_count[1] contains total number of patches that are predicted as MYOD1+ and has probability >= threshold\n if probs.data[l, index].item() >= args.upperT:\n correct_count[index] += 1\n correct_probs[index] += probs.data[l, index].item()\n\n # check that it is time to report progress. If so, print it and flush I/O to make sure it comes \n # out right after it is printed \n report_count += 1\n if (report_count > report_interval):\n percent_complete += (REPORTING_INTERVAL / totalFolds)\n print(f'progress: {percent_complete}')\n sys.stdout.flush()\n report_count = 0\n\n ## When it arrives at the last iteration\n if k == ((4000 // args.batch_size) - 1):\n\n ## If there are no predictions that are made with high conviction, decision is not made\n if (np.sum(correct_count) == 0):\n patients[other_index] = np.nan\n\n ## If there are predictions that are made with high conviction, decision is made\n ## Probability of WSI being predicted as MYOD1+ is as below\n ## (# high conviction MYOD1+ predictions)/(# total number of high convictions)\n else:\n patients[other_index] = 1.0 * correct_count[1] / (correct_count[0] + correct_count[1])\n\n other_index += 1\n correct_count[:] = 0.\n correct_probs[:] = 0.\n\n ## If the Level 0 objective is 40.0\n if objective == 20.0:\n ## Retrieve patches from WSI by batch_size but extract no more than 4000 patches\n for k in range(4000 // args.batch_size):\n image_width_start = 0\n image_width_end = image_width - IMAGE_SIZE - 1\n\n image_height_start = 0\n image_height_end = image_height - IMAGE_SIZE - 1\n\n x_coord = 0\n y_coord = 0\n\n patch_index = 0\n image_batch = np.zeros((args.batch_size, IMAGE_SIZE, IMAGE_SIZE, 3), np.uint8)\n\n ## Extract batch_size patches from WSI within cancerous regions\n for j in range(args.batch_size):\n picked = False\n\n while (picked == False):\n ## Pick random locations withint segmentation masks first\n x_coord = random.sample(range(image_width_start, image_width_end), 1)[0]\n y_coord = random.sample(range(image_height_start, image_height_end), 1)[0]\n label_patch = label[y_coord:y_coord + IMAGE_SIZE, x_coord:x_coord + IMAGE_SIZE]\n\n ## Examine whether the random coordinates are within cancerous regions\n ## If the coordinates are containing enough cancerous region 'picked = True' and If not 'picked=False'\n if (np.sum(label_patch // 255) > int(IMAGE_SIZE * IMAGE_SIZE * 0.50)) and (\n np.sum(label_patch == 127) == 0):\n picked = True\n else:\n picked = False\n\n ## Using the picked coordinates, extract corresponding WSI patch\n ## Store patches in the image_batch so that it can be later inferenced at once\n read_region = wholeslide.read_region((x_coord, y_coord), 0,\n (IMAGE_SIZE, IMAGE_SIZE))\n image_patch = np.asarray(read_region)[:, :, :3]\n image_batch[patch_index, :, :, :] = image_patch\n patch_index += 1\n\n with torch.no_grad():\n ## Convert image_batch to pytorch tensor\n image_tensor = convert_to_tensor(image_batch)\n\n ## Inference the image_tensor (as a batch)\n inst_logits = model(image_tensor)\n\n ## Model's outcome are logit values for each patch\n ## Need to conver them into probabilities of being MYOD1+\n probs = ml(inst_logits)\n\n ## Each patch produces two outcomes, MYOD1- and MYOD1+\n ## Larger value's index will be the prediction for the patch (0, MYOD1-) (1, MYOD1+)\n _, preds = torch.max(inst_logits, 1)\n cbatch_size = len(image_tensor)\n\n ## Examine all the patch's probability values\n ## If predicted outcome's probability is greater than args.upperT, use them in the final calculation\n ## Which means, if the model's outcome is not confident enough, we do not use them in our final calculation\n for l in range(cbatch_size):\n ## preds contains each patch's prediction (either 0 or 1)\n ## index 0 means MYOD1- and index 1 means MYOD1+\n index = preds[l].item()\n\n ## Check the probability of the prediction\n ## if it is greater than the threshold, it will be counted\n ## correct_count: (2, ) shape\n ## correct_count[0] contains total number of patches that are predicted as MYOD1- and has probability >= threshold\n ## correct_count[1] contains total number of patches that are predicted as MYOD1+ and has probability >= threshold\n if probs.data[l, index].item() >= args.upperT:\n correct_count[index] += 1\n correct_probs[index] += probs.data[l, index].item()\n\n # check that it is time to report progress. If so, print it and flush I/O to make sure it comes \n # out right after it is printed \n report_count += 1\n if (report_count > report_interval):\n percent_complete += (REPORTING_INTERVAL / totalFolds)\n print(f'progress: {percent_complete}')\n sys.stdout.flush()\n report_count = 0\n\n ## When it arrives at the last iteration\n if k == ((4000 // args.batch_size) - 1):\n\n ## If there are no predictions that are made with high conviction, decision is not made\n if (np.sum(correct_count) == 0):\n patients[other_index] = np.nan\n\n ## If there are predictions that are made with high conviction, decision is made\n ## Probability of WSI being predicted as MYOD1+ is as below\n ## (# high conviction MYOD1+ predictions)/(# total number of high convictions)\n else:\n patients[other_index] = 1.0 * correct_count[1] / (correct_count[0] + correct_count[1])\n\n \n other_index += 1\n correct_count[:] = 0.\n correct_probs[:] = 0.\n\n # force python garbage collection to free buffers\n gc.collect()\n print('MYOD1 inferencing complete')\n # return the array of processed patient results\n print('patients:',patients)\n return patients\n\n# end of MYOD1 script code\n#--------------------------------\n"
] | [
[
"numpy.rollaxis",
"torch.nn.Softmax",
"numpy.expand_dims",
"torch.max",
"torch.load",
"numpy.asarray",
"torch.zeros",
"torch.nn.ELU",
"torch.no_grad",
"torch.nn.Dropout",
"torch.from_numpy",
"torch.tensor",
"numpy.zeros",
"torch.nn.AlphaDropout",
"torch.nn.Linear",
"torch.nn.DataParallel",
"numpy.sum",
"torch.cuda.manual_seed",
"numpy.random.seed",
"torch.manual_seed",
"torch.nn.ReLU"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Said6289/SPlisHSPlasH | [
"fe0a37b05e25fa9d61bb7bd7372d1f26543d4e35"
] | [
"pySPlisHSPlasH/examples/plot.py"
] | [
"# Note that for this example you have to install matplotlib by:\n# pip install matplotlib\n \nimport pysplishsplash as sph\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ncounter = 0\nvelocities = []\ntimes = []\n\ndef time_step_callback():\n\tglobal counter\n\tsim = sph.Simulation.getCurrent()\n\ttm = sph.TimeManager.getCurrent()\n\tfluid = sim.getFluidModel(0)\n\t\n\t# plot the norm of the velocity of particle 0\n\tv = np.array(fluid.getVelocity(0))\n\tvn = np.linalg.norm(v)\n\tvelocities.append(vn)\n\ttimes.append(tm.getTime())\n\t\n\tif counter % 20 == 0:\n\t\tplt.plot(times, velocities, 'b')\n\t\tplt.draw()\n\t\tplt.pause(0.001)\n\tcounter += 1\n\ndef main():\n\tplt.xlabel('time (s)')\n\tplt.ylabel('velocity (m/s)')\n\tplt.title('Example plot')\n\tplt.grid(True)\n\tplt.ion()\n\tplt.plot([0.0], [0.0], 'b')\n\tplt.draw()\n\tplt.pause(0.001)\n\tplt.show()\n\n\tbase = sph.Exec.SimulatorBase()\n\tbase.init()\n\tgui = sph.GUI.Simulator_GUI_imgui(base)\n\tbase.setGui(gui)\n\t\n\tbase.setTimeStepCB(time_step_callback)\n\t\n\t# init the simulation\n\tbase.initSimulation()\n\t\n\tsim = sph.Simulation.getCurrent()\n\tsim.setValueBool(sim.ENABLE_Z_SORT, False)\t\n\t\n\tbase.runSimulation()\n\tbase.cleanup()\n\nif __name__ == \"__main__\":\n\tmain()\n"
] | [
[
"matplotlib.pyplot.title",
"numpy.linalg.norm",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ion",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.24",
"1.13",
"1.16",
"1.9",
"1.18",
"1.23",
"1.21",
"1.22",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AdrianLangseth/TDT4173_Anomaly_Detection | [
"7b8f511f3d24427ba52331afb7d0979666151440"
] | [
"src/ffnn/hyp_opt.py"
] | [
"import numpy as np\nimport tensorflow.keras.layers as KL\nimport tensorflow.keras.optimizers as opt\nimport tensorflow.python.keras.models as KM\nfrom data_load import load_MNIST\nfrom hyperas import optim\nfrom hyperas.distributions import uniform, choice\nfrom hyperopt import Trials, STATUS_OK, tpe\n\n\ndef create_model(x_train, y_train, x_test, y_test):\n inputs = KL.Input(shape=(28, 28))\n l = KL.Flatten()(inputs)\n l = KL.Dropout(0)(l) # Dropout on Visible layer\n l = KL.Dense(512, activation={{choice([\"relu\", \"sigmoid\", \"elu\"])}})(l) #\n l = KL.Dropout({{uniform(0, 0.5)}})(l) # Dropout on hidden layer\n outputs = KL.Dense(10, activation=\"softmax\")(l) #\n\n model = KM.Model(inputs, outputs)\n\n model.compile(optimizer=opt.Adam(learning_rate={{uniform(0.0005, 0.02)}}), loss=\"sparse_categorical_crossentropy\",\n metrics=[\"accuracy\"]) # choice([\"sgd\", \"adam\", \"RMSprop\"])}}\n result = model.fit(x_train, y_train,\n epochs={{choice([3, 5, 10])}},\n batch_size={{choice([16, 32, 64, 128])}},\n verbose=0,\n validation_split=(10000 / len(x_train)))\n\n highest_val_accuracy = np.amax(result.history['val_accuracy'])\n print('Highest validation accuracy of epoch:', highest_val_accuracy)\n return {'loss': -highest_val_accuracy, 'status': STATUS_OK, 'model': model}\n\n\nif __name__ == '__main__':\n best_run, best_model = optim.minimize(model=create_model,\n data=load_MNIST,\n algo=tpe.suggest,\n max_evals=5,\n trials=Trials())\n X_train, Y_train, X_test, Y_test = load_MNIST()\n print(\"Evalutation of best performing model:\")\n print(best_model.evaluate(X_test, Y_test))\n print(\"Best performing model chosen hyper-parameters:\")\n print(best_run)\n"
] | [
[
"numpy.amax",
"tensorflow.keras.layers.Dense",
"tensorflow.python.keras.models.Model",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.layers.Input"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
pi-kappa-devel/rad | [
"a8595c4991ad5ff27b1e70d1ff9a85d9234adca8"
] | [
"prad/rad.py"
] | [
"\"\"\"@package rad\nPython radial attention model classes.\n\nThe file contains three basic classes; namely a grid, a variable and a model\nclass. These classes provide are used as a bridge between the c applications\nand the Python Jupyter notebook. The c applications solve the radial attention\nmodel, generate solution approximation data and store them in the file system.\nThese classes load the data and provide an interface for them to be used in a\nPython Jupyter notebook. The notebook functionality creates the tables and the\nfigures that are used in the article.\n\"\"\"\n\nimport glob\nimport os.path\nimport struct\nfrom string import Template\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport plotly.graph_objs as go\nimport plotly.offline as py\nimport rad_conf\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom scipy.ndimage.filters import gaussian_filter1d\n\n\nclass Grid:\n \"\"\"Grid wrapper class.\n\n Loads and holds the binary data created by the c grid_t structure.\n\n Attributes:\n datafile (str): The filename of the binary grid data file.\n data (ndarray): The grid data.\n weight (double): The grid point weighting.\n \"\"\"\n\n datafile = None\n data = None\n weight = None\n\n def __init__(self, datafile):\n \"\"\"Constructor.\n\n Args:\n datafile (str): The filename of the binary grid data file.\n \"\"\"\n\n self.datafile = datafile\n with open(datafile, \"rb\") as file_handle:\n byte = file_handle.read(2)\n self.data = np.zeros(int.from_bytes(byte, byteorder=\"little\"))\n byte = file_handle.read(8)\n self.weight = struct.unpack(\"d\", byte)[0]\n for i in range(0, self.data.size):\n byte = file_handle.read(8)\n self.data[i] = struct.unpack(\"d\", byte)[0]\n\n def __str__(self):\n \"\"\"String representation of the grid object.\n\n Returns:\n A string representation of the object.\n \"\"\"\n return \"{}={{.n={}, .m={}, .M={}, .weight={}}}\".format(\n self.datafile, self.data.size, self.data[0], self.data[-1], self.weight,\n )\n\n def eqpart(self, size):\n \"\"\"Get indices approximating equi-partition.\n\n The function returns a set of indices, the values of which approximate\n a grid's equipartition. The function calculates the values of an\n equipartition of the passed size for the continuous domain of the grid.\n For each calculated value, it locates the index that corresponds to the\n lowest upper bound of this value in the discretized grid's domain. The\n set of these indices are returned.\n\n Args:\n size (int): The number of points in the partition.\n\n Returns:\n An array with the indices approximating the partition points.\n \"\"\"\n\n idc = np.zeros(size, dtype=np.int)\n idc[-1] = len(self.data) - 1\n step = (self.data[-1] - self.data[0]) / (size - 1)\n for k in range(1, size - 1):\n idc[k] = np.min(np.where(self.data > k * step))\n return idc\n\n def lower_bound_index(self, values):\n \"\"\"Get the index of the lower bracket value.\n\n For each element of the passed values, it finds and returns the minimum\n among the indices with values that are greater than the value.\n\n Args:\n values (ndarray): Array with values the lower bound indices of\n which are to be located.\n\n Returns:\n An array with the indices of the discretized grid's lower bound.\n \"\"\"\n\n out = np.zeros(len(values), dtype=int)\n for idx, val in enumerate(values):\n valid_idx = np.where(self.data >= val)[0]\n out[idx] = valid_idx[self.data[valid_idx].argmin()]\n return out\n\n\nclass Variable:\n \"\"\"Variable class.\n\n Loads and holds the binary data that approximate the optimal controls and\n the value functions generated by the c applications.\n\n Attributes:\n datafile (str): The filename of the binary variable data file.\n x_grid (Grid): The wealth grid data.\n r_grid (Grid): The radius grid data.\n data (ndarray): The variable data.\n \"\"\"\n\n datafile = None\n x_grid = None\n r_grid = None\n data = None\n\n def __init__(self, xgrid, rgrid, datafile=None, zvar=None):\n \"\"\"Constructor.\n\n Args:\n xgrid (Grid): The wealth grid data.\n rgrid (Grid): The radius grid data.\n\n Kwargs:\n datafile (str): The filename of the binary variable data file.\n zvar (ndarray): Variable data array.\n \"\"\"\n\n self.x_grid = xgrid\n self.r_grid = rgrid\n if datafile is not None:\n self.datafile = datafile\n with open(datafile, \"rb\") as file_handle:\n byte = file_handle.read(2)\n x_size = int.from_bytes(byte, byteorder=\"little\")\n if x_size != self.x_grid.data.size:\n raise \"Invalid 1st dimension size\"\n byte = file_handle.read(2)\n r_size = int.from_bytes(byte, byteorder=\"little\")\n if r_size != self.r_grid.data.size:\n raise \"Invalid 2nd dimension size\"\n self.data = np.zeros((x_size, r_size))\n for i in range(0, x_size):\n for j in range(0, r_size):\n byte = file_handle.read(8)\n self.data[j, i] = struct.unpack(\"d\", byte)[0]\n elif zvar is not None:\n if zvar.shape != (self.x_grid.data.size, self.r_grid.data.size):\n raise \"Invalid shape\"\n self.data = zvar\n # print(self)\n\n def __str__(self):\n \"\"\"String representation of the variable object.\n\n Returns:\n A string representation of the object.\n \"\"\"\n return \"{}={{.d1={}, .d2={}, .shape={}}}\".format(\n self.datafile, self.x_grid, self.r_grid, self.data.shape\n )\n\n def surf_visual(self):\n \"\"\"Interactive surface visualization for Python Jupyter notebook.\"\"\"\n\n surface = go.Surface(x=self.x_grid.data, y=self.r_grid.data, z=self.data)\n data = [surface]\n\n layout = go.Layout(\n title=self.datafile.split(\"/\")[-1],\n scene=dict(\n xaxis=dict(\n title=\"x\",\n gridcolor=\"rgb(255, 255, 255)\",\n zerolinecolor=\"rgb(255, 255, 255)\",\n showbackground=True,\n backgroundcolor=\"rgb(230, 230,230)\",\n ),\n yaxis=dict(\n title=\"r\",\n gridcolor=\"rgb(255, 255, 255)\",\n zerolinecolor=\"rgb(255, 255, 255)\",\n showbackground=True,\n backgroundcolor=\"rgb(230, 230,230)\",\n ),\n zaxis=dict(\n gridcolor=\"rgb(255, 255, 255)\",\n zerolinecolor=\"rgb(255, 255, 255)\",\n showbackground=True,\n backgroundcolor=\"rgb(230, 230,230)\",\n ),\n ),\n )\n\n fig = go.Figure(data=data, layout=layout)\n py.iplot(fig, filename=\"datafile\")\n\n def save_figs(self, fig_data):\n \"\"\"Create, show and save in png format a variable surface, its wealth\n and radius sections.\n\n Args:\n fig_data (dict): Figure data. Allowed keys are {angle, prefix,\n zlabel, rsections, rsections_points,\n xsections, xsections_points}\n \"\"\"\n\n fig = plt.figure()\n axes = fig.gca(projection=Axes3D.name)\n axes.set_zlabel(fig_data[\"zlabel\"])\n x_mesh, r_mesh = np.meshgrid(self.x_grid.data, self.r_grid.data)\n axes.set_xlabel(\"x\")\n axes.set_ylabel(\"r\")\n axes.plot_surface(\n x_mesh,\n r_mesh,\n self.data,\n cmap=rad_conf.RAD_FIG_CM,\n linewidth=0,\n antialiased=False,\n )\n axes.view_init(30, fig_data[\"angle\"])\n fig.savefig(\n rad_conf.RAD_TEMP_DIR + \"/\" + fig_data[\"prefix\"] + \"_surf.png\",\n **rad_conf.RAD_FIG_PROPERTIES,\n )\n\n if \"rsections\" not in fig_data:\n fig_data[\"rsections\"] = self.r_grid.eqpart(4)\n else:\n fig_data[\"rsections\"] = self.r_grid.lower_bound_index(fig_data[\"rsections\"])\n\n fig = plt.figure()\n axes = fig.gca()\n axes.set_prop_cycle(rad_conf.RAD_FIG_CYCLE)\n axes.set_ylabel(fig_data[\"zlabel\"])\n axes.set_xlabel(\"x\")\n for r_idx, r_val in enumerate(fig_data[\"rsections\"]):\n smoothed = gaussian_filter1d(self.data[r_val, :], sigma=1)\n axes.plot(\n self.x_grid.data,\n smoothed,\n label=\"$r_{}={:.2f}$\".format(r_idx, self.r_grid.data[r_val]),\n )\n if \"rsections_points\" in fig_data:\n plt.plot(\n fig_data[\"rsections_points\"][r_idx][1][0],\n fig_data[\"rsections_points\"][r_idx][1][1],\n linestyle=\"None\",\n marker=\".\",\n color=\"black\",\n markersize=5,\n )\n axes.annotate(\n fig_data[\"rsections_points\"][r_idx][0],\n fig_data[\"rsections_points\"][r_idx][1],\n xytext=(-18, 12),\n va=\"top\",\n textcoords=\"offset points\",\n )\n plt.legend(**rad_conf.RAD_LEGEND_PROPERTIES)\n fig.savefig(\n rad_conf.RAD_TEMP_DIR + \"/\" + fig_data[\"prefix\"] + \"_rsections.png\",\n **rad_conf.RAD_FIG_PROPERTIES,\n )\n\n if \"xsections\" not in fig_data:\n fig_data[\"xsections\"] = self.x_grid.eqpart(4)\n else:\n fig_data[\"xsections\"] = self.x_grid.lower_bound_index(fig_data[\"xsections\"])\n\n fig = plt.figure()\n axes = fig.gca()\n axes.set_prop_cycle(rad_conf.RAD_FIG_CYCLE)\n axes.set_ylabel(fig_data[\"zlabel\"])\n axes.set_xlabel(\"r\")\n for x_idx, x_val in enumerate(fig_data[\"xsections\"]):\n smoothed = gaussian_filter1d(self.data[:, x_val], sigma=1)\n axes.plot(\n self.r_grid.data,\n smoothed,\n label=\"$x_{}={:.2f}$\".format(x_idx, self.x_grid.data[x_val]),\n )\n if \"xsections_points\" in fig_data:\n plt.plot(\n fig_data[\"xsections_points\"][x_idx][1][0],\n fig_data[\"xsections_points\"][x_idx][1][1],\n linestyle=\"None\",\n marker=\".\",\n color=\"black\",\n markersize=5,\n )\n axes.annotate(\n fig_data[\"xsections_points\"][x_idx][0],\n fig_data[\"xsections_points\"][x_idx][1],\n xytext=(-10, 12),\n va=\"top\",\n textcoords=\"offset points\",\n )\n plt.legend(**rad_conf.RAD_LEGEND_PROPERTIES)\n fig.savefig(\n rad_conf.RAD_TEMP_DIR + \"/\" + fig_data[\"prefix\"] + \"_xsections.png\",\n **rad_conf.RAD_FIG_PROPERTIES,\n )\n\n\nclass RadialAttentionModel:\n \"\"\"Radial attention Model class.\n\n Loads binary data of the c setup structure. The format of the binary data\n is specified in the documentation of the c applications.\n\n Attributes:\n __ltbl_prototype__ (str): Latex table template string.\n\n data_path (str): Model setup save directory\n\n parameters (dict): Model's parameters.\n specification (dict): Model's functional specification.\n grids (dict): Model's grids.\n variables (dict): Model's variables.\n \"\"\"\n\n __ltbl_prototype__ = r\"\"\"\\begin{subtable}[t]{.53\\textwidth}\n\\centering\n\\footnotesize\n\\begin{tabularx}{\\textwidth}[t]{Xllll}\\toprule\n\\multicolumn{5}{c}{\\textbf{Grid Parameterization}} \\\\\\midrule\n\\textbf{Grid} & \\textbf{Points} & \\textbf{Min} & \\textbf{Max} & \\textbf{Weight} \\\\\\midrule\nwealth & $x_size & $xmin & $xmax & $xc \\\\\\hdashline\nradius & $r_size & $rmin & $rmax & $rc \\\\\\hdashline\n\\multirow{ 2}{*}{quantity} & \\multirow{ 2}{*}{$qn} & \\multirow{ 2}{*}{$qmin} & $qmax &\n \\multirow{2}{*}{$qc} \\\\\n& & & (120000) & \\\\\\hdashline\n\\multirow{ 2}{*}{effort} & \\multirow{ 2}{*}{$sn} & \\multirow{ 2}{*}{$smin} & $smax &\n \\multirow{2}{*}{$sc} \\\\\n& & & (1.0) & \\\\\\bottomrule\\bottomrule\n\\end{tabularx}\n\\end{subtable}\\hfill\n\\begin{subtable}[t]{.45\\textwidth}\n\\centering\n\\footnotesize\n\\begin{tabularx}{\\textwidth}[t]{Xl}\\toprule\n\\multicolumn{2}{c}{\\textbf{Model Parameterization}} \\\\\\midrule\n\\textbf{Parameter} & \\textbf{Value} \\\\\\midrule\ndiscount factor ($$\\beta$$) & $beta \\\\\\hdashline\nradius persistence ($$\\delta$$) & $delta \\\\\\hdashline\nattentional costs ($$\\alpha$$) & $alpha \\\\\\hdashline\ncomplementarities factor ($$\\gamma$$) & $gamma \\\\\\hdashline\nreturns ($$R$$) & $$\\frac{1}{\\beta}$$ \\\\\\bottomrule\\bottomrule\n\\end{tabularx}\n\\end{subtable}\"\"\"\n\n data_path = None\n\n parameters = {}\n specification = {}\n grids = {}\n variables = {}\n\n def __parse_fnc__(self, spec):\n \"\"\"Prepare functional specification string.\"\"\"\n\n output_str = spec.split(\"=\")[1]\n output_str = output_str.replace(\n \"v->m->alpha\", \"{}\".format(self.parameters[\"alpha\"])\n )\n output_str = output_str.replace(\n \"v->m->gamma\", \"{}\".format(self.parameters[\"gamma\"])\n )\n output_str = output_str.replace(\n \"v->m->delta\", \"{}\".format(self.parameters[\"delta\"])\n )\n output_str = output_str.replace(\"v->m->R\", \"{}\".format(self.parameters[\"R\"]))\n output_str = output_str.replace(\"exp\", \"np.exp\")\n output_str = output_str.replace(\"v->q\", \"q\")\n output_str = output_str.replace(\"v->r\", \"r\")\n output_str = output_str.replace(\"v->s\", \"s\")\n output_str = output_str.replace(\"v->x\", \"x\")\n return output_str.strip()\n\n def __init__(self, save_dir):\n \"\"\"Constructor.\n\n Args:\n save_dir (str): Model setup save directory.\n \"\"\"\n\n self.data_path = rad_conf.RAD_DATA_DIR + \"/\" + save_dir\n\n def construct_if_data_exist(data_path):\n if os.path.isfile(data_path):\n return Grid(data_path)\n else:\n raise RuntimeError(\n \"Data path '{}' does not exist. Consider executing 'rad_msol'.\".format(\n data_path\n )\n )\n\n self.grids[\"x\"] = construct_if_data_exist(self.data_path + \"/xg\")\n self.grids[\"r\"] = construct_if_data_exist(self.data_path + \"/rg\")\n self.grids[\"q\"] = construct_if_data_exist(self.data_path + \"/qg\")\n self.grids[\"s\"] = construct_if_data_exist(self.data_path + \"/sg\")\n\n self.variables[\"v0\"] = Variable(\n self.grids[\"x\"], self.grids[\"r\"], datafile=self.data_path + \"/v0\"\n )\n self.variables[\"v1\"] = Variable(\n self.grids[\"x\"], self.grids[\"r\"], datafile=self.data_path + \"/v1\"\n )\n self.variables[\"s\"] = Variable(\n self.grids[\"x\"], self.grids[\"r\"], datafile=self.data_path + \"/spol\"\n )\n self.variables[\"q\"] = Variable(\n self.grids[\"x\"], self.grids[\"r\"], datafile=self.data_path + \"/qpol\"\n )\n\n with open(self.data_path + \"/model\", \"rb\") as file_handle:\n self.parameters[\"alpha\"] = struct.unpack(\"d\", file_handle.read(8))[0]\n self.parameters[\"beta\"] = struct.unpack(\"d\", file_handle.read(8))[0]\n self.parameters[\"delta\"] = struct.unpack(\"d\", file_handle.read(8))[0]\n self.parameters[\"gamma\"] = struct.unpack(\"d\", file_handle.read(8))[0]\n self.parameters[\"R\"] = struct.unpack(\"d\", file_handle.read(8))[0]\n\n with open(self.data_path + \"/fncs\", \"r\") as file_handle:\n while True:\n line = file_handle.readline()\n if not line:\n break\n if line.startswith(\"util\"):\n self.specification[\"util\"] = {\"str\": self.__parse_fnc__(line[:-1])}\n self.specification[\"util\"][\"fnc\"] = eval(\n \"lambda q, r, s: \" + self.specification[\"util\"][\"str\"]\n )\n elif line.startswith(\"cost\"):\n self.specification[\"cost\"] = {\"str\": self.__parse_fnc__(line[:-1])}\n self.specification[\"cost\"][\"fnc\"] = eval(\n \"lambda r, s: \" + self.specification[\"cost\"][\"str\"]\n )\n elif line.startswith(\"radt\"):\n self.specification[\"radt\"] = {\"str\": self.__parse_fnc__(line[:-1])}\n self.specification[\"radt\"][\"fnc\"] = eval(\n \"lambda r, s: \" + self.specification[\"radt\"][\"str\"]\n )\n elif line.startswith(\"wltt\"):\n self.specification[\"wltt\"] = {\"str\": self.__parse_fnc__(line[:-1])}\n self.specification[\"wltt\"][\"fnc\"] = eval(\n \"lambda q, r, s, x: \" + self.specification[\"wltt\"][\"str\"]\n )\n\n def model_string(self):\n \"\"\"Get a brace-nested, string description of the model object.\"\"\"\n\n mask = \"\"\"model={{\n .alpha={}, .beta={}, .delta={}, .gamma={}, .R={}, .util={}, .cost={},\n .radt={}, .wltt={}}}\"\"\"\n return mask.format(\n self.parameters[\"alpha\"],\n self.parameters[\"beta\"],\n self.parameters[\"delta\"],\n self.parameters[\"gamma\"],\n self.parameters[\"R\"],\n self.specification[\"util\"][\"str\"],\n self.specification[\"cost\"][\"str\"],\n self.specification[\"radt\"][\"str\"],\n self.specification[\"wltt\"][\"str\"],\n )\n\n def get_radius_dynamics(self):\n \"\"\"Calculate the radius transition and return it as a Variable object.\"\"\"\n\n radt = np.zeros((self.grids[\"x\"].data.size, self.grids[\"r\"].data.size))\n for x_idx in range(0, len(self.grids[\"x\"].data)):\n for r_idx, r_val in enumerate(self.grids[\"r\"].data):\n radt[r_idx, x_idx] = self.specification[\"radt\"][\"fnc\"](\n r_val, self.variables[\"s\"].data[r_idx, x_idx]\n )\n return Variable(self.grids[\"x\"], self.grids[\"r\"], zvar=radt)\n\n def get_wealth_dynamics(self):\n \"\"\"Calculate the wealth transition and return it as a Variable object.\"\"\"\n\n wltt = np.zeros((self.grids[\"x\"].data.size, self.grids[\"r\"].data.size))\n for x_idx, x_val in enumerate(self.grids[\"x\"].data):\n for r_idx, r_val in enumerate(self.grids[\"r\"].data):\n wltt[r_idx, x_idx] = self.specification[\"wltt\"][\"fnc\"](\n self.variables[\"q\"].data[r_idx, x_idx],\n r_val,\n self.variables[\"s\"].data[r_idx, x_idx],\n x_val,\n )\n return Variable(self.grids[\"x\"], self.grids[\"r\"], zvar=wltt)\n\n def save_latex_table(self, filename):\n \"\"\"Create and save a latex table with the model and solution's parameterizations.\"\"\"\n\n with open(rad_conf.RAD_TEMP_DIR + \"/\" + filename, \"w\") as file_handle:\n file_handle.write(\n Template(self.__ltbl_prototype__).substitute(\n x_size=len(self.grids[\"x\"].data),\n xmin=\"{:g}\".format(self.grids[\"x\"].data[0]),\n xmax=\"{:g}\".format(self.grids[\"x\"].data[-1]),\n xc=\"{:g}\".format(self.grids[\"x\"].weight),\n r_size=len(self.grids[\"r\"].data),\n rmin=\"{:g}\".format(self.grids[\"r\"].data[0]),\n rmax=\"{:g}\".format(self.grids[\"r\"].data[-1]),\n rc=\"{:g}\".format(self.grids[\"r\"].weight),\n qn=len(self.grids[\"q\"].data),\n qmin=\"{:g}\".format(self.grids[\"q\"].data[0]),\n qmax=\"{:g}\".format(self.grids[\"q\"].data[-1]),\n qc=\"{:g}\".format(self.grids[\"q\"].weight),\n sn=len(self.grids[\"s\"].data),\n smin=\"{:g}\".format(self.grids[\"s\"].data[0]),\n smax=\"{:g}\".format(self.grids[\"s\"].data[-1]),\n sc=\"{:g}\".format(self.grids[\"s\"].weight),\n beta=self.parameters[\"beta\"],\n delta=self.parameters[\"delta\"],\n alpha=self.parameters[\"alpha\"],\n gamma=self.parameters[\"gamma\"],\n )\n )\n\n def save_learning_rsections(self, rsections=None):\n \"\"\"Create plot and save as png the learning dynamics' r sections.\"\"\"\n\n if rsections is None:\n rsections = np.linspace(0, 1, num=5)\n sdom = np.linspace(0, 3, num=100)\n\n fig = plt.figure()\n axes = fig.gca()\n axes.set_prop_cycle(rad_conf.RAD_FIG_CYCLE)\n axes.plot(sdom, np.ones(100), linestyle=\":\", color=\"black\", linewidth=1)\n for r_idx, r_val in enumerate(rsections):\n axes.plot(\n sdom,\n self.specification[\"radt\"][\"fnc\"](r_val, sdom),\n label=\"$r_{}={:.2f}$\".format(r_idx, r_val),\n )\n plt.legend(**rad_conf.RAD_LEGEND_PROPERTIES)\n axes.set_xlabel(\"s\")\n axes.set_ylabel(\"r'\")\n filename = rad_conf.RAD_TEMP_DIR + \"/l_rsections.png\"\n fig.savefig(filename, **rad_conf.RAD_FIG_PROPERTIES)\n\n return filename\n\n def save_cost_rsections(self, rsections=None):\n \"\"\"Create plot and save as png the cost functions' r sections.\"\"\"\n\n if rsections is None:\n rsections = np.linspace(0, 1, num=5)\n sdom = np.linspace(0, 3, num=100)\n\n fig = plt.figure()\n axes = fig.gca()\n axes.set_prop_cycle(rad_conf.RAD_FIG_CYCLE)\n for r_idx, r_val in enumerate(rsections):\n axes.plot(\n sdom,\n self.specification[\"cost\"][\"fnc\"](r_val, sdom),\n label=\"$r_{}={:.2f}$\".format(r_idx, r_val),\n )\n plt.legend(**rad_conf.RAD_LEGEND_PROPERTIES)\n axes.set_xlabel(\"s\")\n axes.set_ylabel(\"c\")\n filename = rad_conf.RAD_TEMP_DIR + \"/c_rsections.png\"\n fig.savefig(filename, **rad_conf.RAD_FIG_PROPERTIES)\n\n return filename\n\n\nclass ParameterDependence:\n \"\"\"Parameter dependence class.\n\n Comprises of functionality relevant for parameter dependence analysis of the radial attention\n model.\n\n Attributes:\n parameter_string (str): Parameter name.\n data_files (list): List of data filenames.\n \"\"\"\n\n parameter_string = None\n data_files = None\n\n def __init__(self, parameter_string):\n \"\"\"Constructor.\n\n Args:\n parameter_string (str): Parameter name.\n \"\"\"\n\n self.parameter_string = parameter_string\n\n self.data_files = [\n file.replace(rad_conf.RAD_DATA_DIR + \"/\", \"\")\n for file in glob.glob(\n rad_conf.RAD_DATA_DIR\n + \"/{}/{}*\".format(self.parameter_string, self.parameter_string)\n )\n ]\n self.data_files.sort()\n\n def save_fig(self, domain_data, ylab, yval):\n \"\"\"Create, show and save in png format the figures with the responses of the value function\n and the optimal controls on the particular parameter described by the passed the domain\n data.\n \"\"\"\n\n fig = plt.figure()\n axes = fig.gca()\n axes.set_prop_cycle(rad_conf.RAD_FIG_CYCLE)\n axes.set_xlabel(\"$\\\\{}$\".format(self.parameter_string))\n axes.set_ylabel(ylab[0])\n for r_idx in range(0, len(domain_data[\"r_indices\"])):\n for x_idx in range(0, len(domain_data[\"x_indices\"])):\n g_idx = r_idx * len(domain_data[\"x_indices\"]) + x_idx\n smoothed = gaussian_filter1d(yval[g_idx, :], sigma=1)\n axes.plot(\n domain_data[\"param_grid\"],\n smoothed,\n label=\"$r_{}={:.2f},x_{}={:.2f}$\".format(\n r_idx,\n domain_data[\"r_points\"][g_idx],\n x_idx,\n domain_data[\"x_points\"][g_idx],\n ),\n )\n plt.legend(**rad_conf.RAD_LEGEND_PROPERTIES)\n fig.savefig(\n rad_conf.RAD_TEMP_DIR + \"/{}_on_{}.png\".format(self.parameter_string, ylab),\n **rad_conf.RAD_FIG_PROPERTIES,\n )\n\n def save_figs(self, r_indices=None, x_indices=None):\n \"\"\"Create, show and save in png format the figures with the responses of the value function\n and the optimal controls on value changes of each parameter.\n \"\"\"\n\n if r_indices is None or x_indices is None:\n model = RadialAttentionModel(self.data_files[0])\n if r_indices is None:\n r_indices = model.grids[\"r\"].eqpart(4)[1:3]\n if x_indices is None:\n x_indices = model.grids[\"x\"].eqpart(4)[1:3]\n\n index_count = len(r_indices) * len(x_indices)\n point_count = len(self.data_files)\n\n domain_data = {\n \"param_grid\": np.zeros(point_count),\n \"r_indices\": r_indices,\n \"r_points\": np.zeros(index_count),\n \"x_indices\": x_indices,\n \"x_points\": np.zeros(index_count),\n }\n range_data = {\n \"spol\": np.zeros((index_count, point_count)),\n \"qpol\": np.zeros((index_count, point_count)),\n \"v\": np.zeros((index_count, point_count)),\n }\n\n for p_idx, p_val in enumerate(self.data_files):\n model = RadialAttentionModel(p_val)\n domain_data[\"param_grid\"][p_idx] = model.parameters[self.parameter_string]\n for r_idx, r_val in enumerate(r_indices):\n for x_idx, x_val in enumerate(x_indices):\n g_idx = r_idx * len(x_indices) + x_idx\n domain_data[\"r_points\"][g_idx] = model.grids[\"r\"].data[r_val]\n domain_data[\"x_points\"][g_idx] = model.grids[\"x\"].data[x_val]\n range_data[\"spol\"][g_idx, p_idx] = model.variables[\"s\"].data[\n r_val, x_val\n ]\n range_data[\"qpol\"][g_idx, p_idx] = model.variables[\"q\"].data[\n r_val, x_val\n ]\n range_data[\"v\"][g_idx, p_idx] = model.variables[\"v0\"].data[\n r_val, x_val\n ]\n\n for key, value in range_data.items():\n self.save_fig(domain_data, key, value)\n"
] | [
[
"matplotlib.pyplot.legend",
"numpy.linspace",
"numpy.ones",
"matplotlib.pyplot.plot",
"scipy.ndimage.filters.gaussian_filter1d",
"numpy.meshgrid",
"numpy.zeros",
"numpy.where",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"0.15",
"1.4",
"0.16",
"1.0",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"0.10",
"0.17",
"1.3"
],
"tensorflow": []
}
] |
Nitin-Mane/SARS-CoV-2-xDNN-Classifier | [
"abb6a82b8ee89a041b0e26e14ec1e416c4561266"
] | [
"modules/server.py"
] | [
"#!/usr/bin/env python\n###################################################################################\n##\n## Project: COVID -19 xDNN Classifier 2020\n## Version: 1.0.0\n## Module: Server\n## Desription: The COVID -19 xDNN Classifier 2020 server.\n## License: MIT\n## Copyright: 2021, Asociacion De Investigacion En Inteligencia Artificial Para\n## La Leucemia Peter Moss.\n## Author: Nitin Mane\n## Maintainer: Nitin Mane\n##\n## Modified: 2021-2-19\n##\n###################################################################################\n##\n## Permission is hereby granted, free of charge, to any person obtaining a copy\n## of this software and associated documentation files(the \"Software\"), to deal\n## in the Software without restriction, including without limitation the rights\n## to use, copy, modify, merge, publish, distribute, sublicense, and / or sell\n## copies of the Software, and to permit persons to whom the Software is\n## furnished to do so, subject to the following conditions:\n##\n## The above copyright notice and this permission notice shall be included in all\n## copies or substantial portions of the Software.\n##\n## THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n## SOFTWARE.\n##\n###################################################################################\n\nimport cv2\nimport json\nimport jsonpickle\nimport os\nimport requests\nimport time\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom modules.AbstractServer import AbstractServer\n\nfrom flask import Flask, request, Response\nfrom io import BytesIO\nfrom PIL import Image\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications.vgg16 import preprocess_input\n\n\nclass server(AbstractServer):\n\t\"\"\" COVID 19 xDNN Classifier 2020 Server.\n\n\tThis object represents the COVID 19 xDNN Classifier 2020 Server.\n\t\"\"\"\n\n\tdef predict(self, req):\n\t\t\"\"\" Classifies an image sent via HTTP. \"\"\"\n\n\t\tif len(req.files) != 0:\n\t\t\timg = Image.open(req.files['file'].stream).convert('RGB')\n\t\telse:\n\t\t\timg = Image.open(BytesIO(req.data)).convert('RGB')\n\n\t\timg = img.resize((224, 224), Image.ANTIALIAS)\n\t\tnp_img = tf.keras.preprocessing.image.img_to_array(img)\n\t\tnp_img.transpose(1, 2, 0)\n\t\t#img = keras.preprocessing.image.img_to_array(img)\n\t\t#img = np.array([img]) # Convert single image to a batch.\n\t\timg = np.expand_dims(np_img, axis=0)\n\t\timg = preprocess_input(img)\n\t\t#prediction = self.predict(img)\n\n\t\t#img = img.resize((224, 224), Image.ANTIALIAS)\n\t\t#img = image.img_to_array(img)\n\t\t#img = np.expand_dims(img, axis=0)\n\t\t#img = preprocess_input(img)\n\t\t#img = img.reshape((1,224,224,3))\n\n\t\treturn self.model.predict(img)\n\n\tdef request(self, img_path):\n\t\t\"\"\" Sends image to the inference API endpoint. \"\"\"\n\n\t\tself.helpers.logger.info(\"Sending request for: \" + img_path)\n\n\t\t_, img_encoded = cv2.imencode('.png', cv2.imread(img_path))\n\t\tresponse = requests.post(\n\t\t\tself.addr, data=img_encoded.tostring(), headers=self.headers)\n\t\tresponse = json.loads(response.text)\n\n\t\treturn response\n\n\tdef start(self):\n\t\t\"\"\" Starts the server. \"\"\"\n\n\t\tapp = Flask(self.helpers.credentials[\"iotJumpWay\"][\"name\"])\n\n\t\[email protected]('/Inference', methods=['POST'])\n\t\tdef Inference():\n\t\t\t\"\"\" Responds to HTTP POST requests. \"\"\"\n\n\t\t\tself.mqtt.publish(\"States\", {\n\t\t\t\t\"Type\": \"Prediction\",\n\t\t\t\t\"Name\": self.helpers.credentials[\"iotJumpWay\"][\"name\"],\n\t\t\t\t\"State\": \"Processing\",\n\t\t\t\t\"Message\": \"Processing data\"\n\t\t\t})\n\n\t\t\tmessage = \"\"\n\t\t\tprediction = self.predict(request)\n\t\t\tprint(prediction)\n\n\t\t\tif prediction == 1:\n\t\t\t\tmessage = \"Acute Lymphoblastic Leukemia detected!\"\n\t\t\t\tdiagnosis = \"Positive\"\n\t\t\telif prediction == 0:\n\t\t\t\tmessage = \"Acute Lymphoblastic Leukemia not detected!\"\n\t\t\t\tdiagnosis = \"Negative\"\n\n\t\t\tself.mqtt.publish(\"States\", {\n\t\t\t\t\"Type\": \"Prediction\",\n\t\t\t\t\"Name\": self.helpers.credentials[\"iotJumpWay\"][\"name\"],\n\t\t\t\t\"State\": diagnosis,\n\t\t\t\t\"Message\": message\n\t\t\t})\n\n\t\t\tresp = jsonpickle.encode({\n\t\t\t\t'Response': 'OK',\n\t\t\t\t'Message': message,\n\t\t\t\t'Diagnosis': diagnosis\n\t\t\t})\n\n\t\t\treturn Response(response=resp, status=200, mimetype=\"application/json\")\n\n\t\tapp.run(host=self.helpers.credentials[\"server\"][\"ip\"],\n\t\t\t\tport=self.helpers.credentials[\"server\"][\"port\"])\n\n\tdef test(self):\n\t\t\"\"\" Tests the trained model via HTTP. \"\"\"\n\n\t\ttotaltime = 0\n\t\tfiles = 0\n\n\t\ttp = 0\n\t\tfp = 0\n\t\ttn = 0\n\t\tfn = 0\n\n\t\tself.addr = \"http://\" + self.helpers.credentials[\"server\"][\"ip\"] + \\\n\t\t\t':'+str(self.helpers.credentials[\"server\"][\"port\"]) + '/Inference'\n\t\tself.headers = {'content-type': 'image/jpeg'}\n\n\t\tfor testFile in os.listdir(self.model.testing_dir):\n\t\t\tif os.path.splitext(testFile)[1] in self.model.valid:\n\n\t\t\t\tstart = time.time()\n\t\t\t\tprediction = self.request(self.model.testing_dir + \"/\" + testFile)\n\t\t\t\tprint(prediction)\n\t\t\t\tend = time.time()\n\t\t\t\tbenchmark = end - start\n\t\t\t\ttotaltime += benchmark\n\n\t\t\t\tmsg = \"\"\n\t\t\t\tstatus = \"\"\n\t\t\t\toutcome = \"\"\n\n\t\t\t\tif prediction[\"Diagnosis\"] == \"Positive\" and \"Non-Covid\" in testFile:\n\t\t\t\t\tfp += 1\n\t\t\t\t\tstatus = \"incorrectly\"\n\t\t\t\t\toutcome = \"(False Positive)\"\n\t\t\t\telif prediction[\"Diagnosis\"] == \"Negative\" and \"Non-Covid\" in testFile:\n\t\t\t\t\ttn += 1\n\t\t\t\t\tstatus = \"correctly\"\n\t\t\t\t\toutcome = \"(True Negative)\"\n\t\t\t\telif prediction[\"Diagnosis\"] == \"Positive\" and \"Covid\" in testFile:\n\t\t\t\t\ttp += 1\n\t\t\t\t\tstatus = \"correctly\"\n\t\t\t\t\toutcome = \"(True Positive)\"\n\t\t\t\telif prediction[\"Diagnosis\"] == \"Negative\" and \"Covid\" in testFile:\n\t\t\t\t\tfn += 1\n\t\t\t\t\tstatus = \"incorrectly\"\n\t\t\t\t\toutcome = \"(False Negative)\"\n\n\t\t\t\tfiles += 1\n\t\t\t\tself.helpers.logger.info(\"COVID-19 xDNN Classifier \" + status +\n\t\t\t\t\t\t\t\t\t\" detected \" + outcome + \" in \" + str(benchmark) + \" seconds.\")\n\n\t\tself.helpers.logger.info(\"Images Classified: \" + str(files))\n\t\tself.helpers.logger.info(\"True Positives: \" + str(tp))\n\t\tself.helpers.logger.info(\"False Positives: \" + str(fp))\n\t\tself.helpers.logger.info(\"True Negatives: \" + str(tn))\n\t\tself.helpers.logger.info(\"False Negatives: \" + str(fn))\n\t\tself.helpers.logger.info(\"Total Time Taken: \" + str(totaltime))\n"
] | [
[
"numpy.expand_dims",
"tensorflow.keras.preprocessing.image.img_to_array",
"tensorflow.keras.applications.vgg16.preprocess_input"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
zgulde/zgulde-python | [
"0dd89962b4ca2141ebe4335ef0200b0595d06d4d"
] | [
"misc/scatter_lowess.py"
] | [
"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom statsmodels.nonparametric.smoothers_lowess import lowess\nplt.ion()\n\n\ndef scatter_lowess(\n df: pd.DataFrame, x: str, y: str, g=None, ax=None, scatter_kwargs={}, plot_kwargs={}\n):\n if ax is None:\n ax = plt.gca()\n if g is not None:\n for group, subset in df.groupby(g):\n ax.scatter(subset[x], subset[y], label=group, **scatter_kwargs)\n ax.plot(\n *by_col(lowess(subset[y], subset[x], return_sorted=True)), **plot_kwargs\n )\n ax.legend(title=g)\n else:\n ax.scatter(df[x], df[y], **scatter_kwargs)\n ax.plot(\n *by_col(lowess(df[y], df[x], return_sorted=True)),\n **{\"c\": \"black\", **plot_kwargs}\n )\n return ax\n\n\ndef by_col(m):\n for i in range(m.shape[1]):\n yield m[:, i]\n\nimport pydataset\n\nmpg = pydataset.data(\"mpg\")\ntips = pydataset.data('tips')\n\nfig, axs = plt.subplots(1, 2, sharey=True, sharex=True)\nfor ax, (sex, subset) in zip(axs, tips.groupby(\"sex\")):\n scatter_lowess(\n subset,\n \"total_bill\",\n \"tip\",\n \"smoker\",\n scatter_kwargs={\"ec\": \"black\", \"alpha\": 0.6},\n ax=ax,\n )\n ax.set(title=sex)\n\ntips.groupby(['size', 'sex']).size().rename('count')\n"
] | [
[
"matplotlib.pyplot.gca",
"matplotlib.pyplot.ion",
"matplotlib.pyplot.subplots"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jcoheur/pybitup | [
"6b31cbea7ae871a09aad154829eb85e599ce9214"
] | [
"pybitup/post_process.py"
] | [
"import matplotlib.pyplot as plt\nfrom matplotlib import colors \nimport pickle\nimport pandas as pd \nimport pathlib\nimport json\nfrom jsmin import jsmin\nimport numpy as np\nfrom scipy import stats\nimport seaborn as sns\n\nfrom tikzplotlib import save as tikz_save\n\n\ndef post_process_data(input_file_name):\n \n # Colors\n lineColor = [['C0'], ['C1'], ['C2'], [\n 'C3'], ['C4'], ['C5'], ['C6'], ['C7']]\n\n # -------------------------\n # Open and read input file \n # -------------------------\n\n # First, remove comments from the file with jsmin because json doesn't allow it\n with open(f\"{input_file_name}\") as js_file:\n minified = jsmin(js_file.read())\n user_inputs = json.loads(minified)\n\n if (user_inputs.get(\"PostProcess\") is not None):\n inputFields = user_inputs[\"PostProcess\"] \n else: \n raise ValueError('Ask for post processing data but no inputs were provided')\n\n out_folder = pathlib.Path(\"output\")\n out_data_file = pathlib.Path(out_folder, \"output.txt\")\n model_eval_folder = pathlib.Path(out_folder, \"model_eval\") \n\n with open(out_data_file, 'r') as file_param:\n\n for ind, line in enumerate(file_param):\n if ind == 1:\n # Get random variable names \n c_chain = line.strip()\n unpar_name=c_chain.split()\n\n elif ind == 3: \n # Get number of iterations \n c_chain = line.strip()\n n_iterations = int(c_chain)\n\n n_unpar = len(unpar_name)\n n_samples = n_iterations + 1\n\n unpar_name_list = {}\n for i, name_param in enumerate(unpar_name):\n unpar_name_list[name_param] = i\n\n num_fig = 0\n\n # -------------------------------------------\n # --------- Plot experimental data ----------\n # -------------------------------------------\n\n # if (inputFields.get(\"Data\") is not None):\n # # Load experimental data\n # with open('output/data', 'rb') as file_data_exp:\n # pickler_data_exp = pickle.Unpickler(file_data_exp)\n # data_exp = pickler_data_exp.load()\n\n # if inputFields[\"Data\"][\"display\"] == \"yes\":\n # for i in range(data_exp.n_data_set):\n\n # ind_1 = data_exp.index_data_set[i, 0]\n # ind_2 = data_exp.index_data_set[i, 1]\n\n # plt.figure(inputFields[\"Data\"][\"num_plot\"])\n # plt.plot(data_exp.x[ind_1:ind_2+1], data_exp.y[ind_1:ind_2+1],\n # 'o', color=lineColor[i][0], mfc='none')\n\n # error_bar (data_exp.x[ind_1:ind_2+1], data_exp.y[ind_1:ind_2+1], \n # data_exp.std_y[ind_1:ind_2+1], lineColor[i][0])\n\n # #, edgecolors='r'\n\n if (inputFields.get(\"Data\") is not None):\n # Load experimental data\n data_file = pathlib.Path(out_folder, \"data.bin\")\n with open(data_file, 'rb') as file_data_exp:\n pickler_data_exp = pickle.Unpickler(file_data_exp)\n data_exp = pickler_data_exp.load()\n\n if inputFields[\"Data\"][\"display\"] == \"yes\":\n num_plot = inputFields[\"Data\"][\"num_plot\"]\n for num_data_set, data_id in enumerate(data_exp.keys()):\n n_x = len(data_exp[data_id].x)\n n_data_set = int(len(data_exp[data_id].y[0])/n_x)\n \n for i in range(n_data_set): \n plt.figure(num_plot[num_data_set])\n plt.figure(i)\n\n if data_exp[data_id].n_runs > 1:\n plt.plot(data_exp[data_id].x, data_exp[data_id].mean_y[i*n_x:(i+1)*n_x],\n 'o', color=lineColor[num_data_set][0], mfc='none')\n\n for j in range(data_exp[data_id].n_runs):\n plt.plot(data_exp[data_id].x, data_exp[data_id].y[j][i*n_x:i*n_x+n_x],'o', color=lineColor[num_data_set][0], mfc='none', label=\"Exp. data\")\n\n plt.xlabel(user_inputs[\"Sampling\"][\"BayesianPosterior\"][\"Data\"][num_data_set][\"xField\"][0])\n plt.ylabel(user_inputs[\"Sampling\"][\"BayesianPosterior\"][\"Data\"][num_data_set][\"yField\"][0])\n\n\n # error_bar (data_exp[data_id].x, data_exp[data_id].y[j][i*n_x:i*n_x+n_x]\n # data_exp[data_id].std_y[i*n_x:i*n_x+n_x], lineColor[num_data_set][0])\n error_bar (data_exp[data_id].x, data_exp[data_id].y[j][i*n_x:i*n_x+n_x],\n data_exp[data_id].std_y[i*n_x:i*n_x+n_x], lineColor[num_data_set][0])\n\n #, edgecolors='r'\n plt.legend()\n\n\n # -------------------------------------------\n # --------- Plot initial guess --------------\n # -------------------------------------------\n\n if (inputFields.get(\"InitialGuess\") is not None):\n if inputFields[\"InitialGuess\"][\"display\"] == \"yes\":\n\n for num_data_set, data_id in enumerate(data_exp.keys()):\n init_model_eval_file = pathlib.Path(model_eval_folder, f\"{data_id}_fun_eval-{0}.npy\") \n data_init = np.load(init_model_eval_file)\n\n n_x = len(data_exp[data_id].x)\n n_data_set = int(len(data_exp[data_id].y[0])/n_x)\n\n\n for i in range(n_data_set): \n\n plt.figure(num_plot[num_data_set])\n plt.figure(i)\n\n plt.plot(data_exp[data_id].x,\n data_init[i*n_x:(i+1)*n_x], '--', color=lineColor[num_data_set][0], label=\"Init. guess\")\n\n plt.legend()\n\n if (inputFields.get(\"MarkovChain\") is not None) or (inputFields.get(\"Posterior\") is not None) or (inputFields.get(\"Propagation\") is not None):\n\n\n reader = pd.read_csv('output/mcmc_chain.csv', header=None)\n param_value_raw = reader.values\n n_samples = len(param_value_raw[:, 0]) # + 1\n\n # # Load the samples of the distribution \n # param_value_raw = np.zeros((n_samples, n_unpar))\n # with open('output/mcmc_chain.dat', 'r') as file_param:\n # i = 0\n # for line in file_param:\n # c_chain = line.strip()\n # param_value_raw[i, :] = np.fromstring(\n # c_chain[1:len(c_chain)-1], sep=' ')\n # i += 1\n # -------------------------------------------\n # --------- Plot markov chains --------------\n # -------------------------------------------\n\n if inputFields.get(\"MarkovChain\") is not None and inputFields[\"MarkovChain\"][\"display\"] == \"yes\":\n num_fig = 100\n vec_std = np.zeros(n_unpar)\n for i in range(n_unpar):\n plt.figure(num_fig+i)\n plt.plot(range(n_samples), param_value_raw[:, i])\n plt.xlabel(\"Number of iterations\")\n plt.ylabel(unpar_name[i])\n\n #saveToTikz('markov_chain_'+unpar_name[i]+'.tex')\n\n c_mean_val = np.mean(param_value_raw[:, i])\n c_std_val = np.std(param_value_raw[:, i])\n vec_std[i] = c_std_val\n cv = c_std_val / c_mean_val\n Q1 = np.percentile(param_value_raw[:, i], 25, axis=0)\n Q3 = np.percentile(param_value_raw[:, i], 75, axis=0)\n cqv = (Q3 - Q1)/(Q3 + Q1)\n\n print(\"{}: mean value = {}; standard dev. = {}; cv = {}; cqv = {}\".format(unpar_name[i], c_mean_val, c_std_val, cv, cqv))\n\n\n if inputFields[\"MarkovChain\"].get(\"check_convergence\") is not None and inputFields[\"MarkovChain\"][\"check_convergence\"] == \"yes\":\n\n # Computing convergence criteria and graphs for each chains \n # From Gelman et al., Bayesian Data Analysis, 2014. \n mean_it = np.zeros(n_samples-1)\n plt.figure(1000+i)\n for it in range(n_samples-1): \n mean_it[it] = np.mean(param_value_raw[0:it+1, i])\n\n plt.plot(range(n_samples-1), mean_it)\n\n \"\"\"\n cov_c = np.cov(param_value_raw, rowvar=False)\n print(\"Final chain covariance matrix:\")\n print(cov_c)\n\n corr_c = cov_c \n for i in range(n_unpar):\n corr_c[i][i] = cov_c[i][i] / (vec_std[i] * vec_std[i])\n for j in range(i+1, n_unpar):\n corr_c[i][j] = cov_c[i][j] / (vec_std[i] * vec_std[j])\n corr_c[j][i] = corr_c[i][j]\n\n print(\"Final chain correlation matrix:\")\n print(corr_c)\n\n fig = plt.figure(400, figsize=(16, 12))\n ax = sns.heatmap(\n corr_c, \n vmin=-1, vmax=1, center=0,\n cmap=sns.diverging_palette(20, 220, n=200),\n square=True, \n \n )\n ax.set_xticklabels(\n ax.get_xticklabels(),\n rotation=45,\n horizontalalignment='right'\n )\n\n # From https://towardsdatascience.com/better-heatmaps-and-correlation-matrix-plots-in-python-41445d0f2bec\n def heatmap(x, y, size):\n plot_grid = plt.GridSpec(1, 15, hspace=0.2, wspace=0.1) # Setup a 1x15 grid\n ax = plt.subplot(plot_grid[:,:-1]) # Use the leftmost 14 columns of the grid for the main plot\n\n \n # Mapping from column names to integer coordinates\n x_labels = x\n y_labels = y\n\n x_to_num = []\n y_to_num=[]\n for i, name in enumerate(x_labels):\n for j, name in enumerate(x_labels):\n x_to_num.append(j)\n y_to_num.append(i)\n\n size_scale = 500\n m = np.abs(size.flatten())\n\n n_colors = 256 # Use 256 colors for the diverging color palette\n palette = sns.diverging_palette(20, 220, n=n_colors) # Create the palette\n color_min, color_max = [-1, 1] # Range of values that will be mapped to the palette, i.e. min and max possible correlation\n\n def value_to_color(val):\n val_position = float((val - color_min)) / (color_max - color_min) # position of value in the input range, relative to the length of the input range\n ind = int(val_position * (n_colors - 1)) # target index in the color palette\n return palette[ind]\n\n color_vec = []\n for i, val in enumerate(size.flatten()):\n color_vec.append(value_to_color(val))\n #print(color_vec)\n\n ax.scatter(\n x=x_to_num, # Use mapping for x\n y=y_to_num, # Use mapping for y\n s=m*size_scale, # Vector of square sizes, proportional to size parameter\n c=color_vec, \n marker='s' # Use square as scatterplot marker\n )\n \n # Show column labels on the axes\n ax.set_xticks([v for v in range(len(x_labels))])\n ax.set_xticklabels(x_labels, rotation=45, horizontalalignment='right', fontsize=20)\n ax.set_yticks([v for v in range(len(x_labels))])\n ax.set_yticklabels(y_labels, fontsize=20)\n\n ax.grid(False, 'major')\n ax.grid(True, 'minor')\n ax.set_xticks([t + 0.5 for t in ax.get_xticks()], minor=True)\n ax.set_yticks([t + 0.5 for t in ax.get_yticks()], minor=True)\n\n # ax.set_xlim([-0.5, max([v for v in x_to_num.values()]) + 0.5]) \n # ax.set_ylim([-0.5, max([v for v in y_to_num.values()]) + 0.5])\n\n\n\n\n # Add color legend on the right side of the plot\n ax = plt.subplot(plot_grid[:,-1]) # Use the rightmost column of the plot\n\n col_x = [0]*len(palette) # Fixed x coordinate for the bars\n bar_y=np.linspace(color_min, color_max, n_colors) # y coordinates for each of the n_colors bars\n\n bar_height = bar_y[1] - bar_y[0]\n ax.barh(\n y=bar_y,\n width=[5]*len(palette), # Make bars 5 units wide\n left=col_x, # Make bars start at 0\n height=bar_height,\n color=palette,\n linewidth=0.0, \n )\n ax.set_xlim(1, 2) # Bars are going from 0 to 5, so lets crop the plot somewhere in the middle\n ax.grid(False) # Hide grid\n ax.set_facecolor('white') # Make background white\n ax.set_xticks([]) # Remove horizontal ticks\n ax.tick_params(axis=\"y\", labelsize=20)\n ax.set_yticks(np.linspace(min(bar_y), max(bar_y), 3)) # Show vertical ticks for min, middle and max\n ax.yaxis.tick_right() # Show vertical ticks on the right \n\n\n\n unpar_name_real = [\"$\\\\log_{10} (\\\\mathcal{A}_{1,1})$\", \"$\\\\log_{10} (\\\\mathcal{A}_{1,2})$\", \"$\\\\log_{10} (\\\\mathcal{A}_{2,1})$\", \"$\\\\log_{10} (\\\\mathcal{A}_{3,1})$\", \n \"$\\\\mathcal{E}_{1,1}$\", \"$\\\\mathcal{E}_{1,2}$\", \"$\\\\mathcal{E}_{2,1}$\", \"$\\\\mathcal{E}_{3,1}$\", \n \"$\\\\gamma_{2,1,5}$\", \"$\\\\gamma_{3,1,7}$\"]\n heatmap(\n x=unpar_name_real,\n y=unpar_name_real,\n size=corr_c\n )\n\n fig.savefig('correlation_matrix.pdf')\n # Savetotikz not good for this \n # saveToTikz('correlation_matrix.tex')\n \"\"\"\n\n \n \"\"\" \n # 2D MCMC iterations\n #---------------\n\n num_fig = 500\n for i in range(n_unpar):\n for j in range(i+1, n_unpar):\n plt.figure(num_fig+i)\n plt.plot(param_value_raw[:, i], param_value_raw[:, j])\n plt.xlabel(unpar_name[i])\n plt.ylabel(unpar_name[j])\n\n num_fig += 1 \n \"\"\"\n \n\n\n\n\n\n\n\n\n # -------------------------------------------\n # -------- Posterior distribution -----------\n # -------------------------------------------\n \n if inputFields.get(\"Posterior\") is not None and inputFields[\"Posterior\"][\"display\"] == \"yes\":\n\n burnin_it = inputFields[\"Posterior\"][\"burnin\"]\n param_value = param_value_raw[range(burnin_it, n_samples), :]\n\n num_fig = 200\n\n if inputFields[\"Posterior\"][\"distribution\"] == \"marginal\":\n\n if \"ksdensity\" in inputFields[\"Posterior\"][\"estimation\"]:\n for i in range(n_unpar):\n\n # Estimate marginal pdf using gaussian kde\n data_i = param_value[:, i]\n kde = stats.gaussian_kde(data_i)\n x = np.linspace(data_i.min(), data_i.max(), 100)\n p = kde(x)\n\n # Plot \n plt.figure(num_fig+i)\n plt.plot(x, p)\n plt.xlabel(unpar_name[i])\n plt.ylabel(\"Probability density\")\n\n # Find and plot the mode\n plt.plot(x[np.argmax(p)], p.max(), 'r*')\n\n if inputFields[\"Posterior\"][\"distribution\"] == \"yes\":\n saveToTikz(\"marginal_pdf_param_\"+i+\".tex\")\n\n if \"hist\" in inputFields[\"Posterior\"][\"estimation\"]:\n for i in range(n_unpar):\n\n data_i = param_value[:, i]\n\n plt.figure(num_fig+i)\n plt.hist(data_i, bins='auto', density=True)\n \n for i in range(n_unpar): \n plt.figure(num_fig+i)\n #saveToTikz('marginal_pdf_'+inputFields[\"Posterior\"][\"estimation\"]+'_'+unpar_name[i]+'.tex')\n\n if inputFields[\"Posterior\"][\"distribution\"] == \"bivariate\":\n # Compute bivariate marginal pdf \n\n if \"scatter\" in inputFields[\"Posterior\"][\"estimation\"]: \n for i in range(n_unpar):\n range_data = range(1,len(param_value[:,i]), 10)\n data_i = param_value[range_data, i]\n\n for j in range(i+1, n_unpar):\n data_j = param_value[range_data, j]\n\n plt.figure(num_fig)\n plt.scatter(data_j, data_i, c=['C2'], s=10)\n num_fig += 1 \n\n if \"contour\" in inputFields [\"Posterior\"][\"estimation\"]:\n\n for i, var_name in enumerate(unpar_name):\n\n # Get first coordinate param values\n x = param_value[:, i]\n xmin = np.min(x) \n xmax = np.max(x) \n\n # Get second coordinatee param values\n for var_name_2 in unpar_name[i+1:len(unpar_name)]:\n # Number of the corresponding parameter name \n k = unpar_name_list[var_name_2]\n\n y = param_value[:, k]\n ymax = np.max(y)\n ymin = np.min(y)\n\n # Peform the kernel density estimate\n xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]\n \n positions = np.vstack([xx.ravel(), yy.ravel()])\n values = np.vstack([x, y])\n\n kernel = stats.gaussian_kde(values)\n f = np.reshape(kernel(positions).T, xx.shape)\n\n fig = plt.figure(num_fig)\n ax = fig.gca()\n\n ax.set_xlim(xmin, xmax)\n ax.set_ylim(ymin, ymax)\n # Contourf plot\n cfset = ax.contourf(xx, yy, f, cmap='Blues')\n ## Or kernel density estimate plot instead of the contourf plot\n #ax.imshow(np.rot90(f), cmap='Blues', extent=[xmin, xmax, ymin, ymax])\n # Contour plot\n cset = ax.contour(xx, yy, f, colors='k')\n # Label plot\n ax.clabel(cset, inline=1, fontsize=10)\n plt.xlabel(var_name)\n plt.ylabel(var_name_2)\n\n num_fig = num_fig + 1\n\n #saveToTikz('bivariate_contour_'+var_name+'_'+var_name_2+'.tex')\n\n # plt.figure(num_fig)\n # plt.scatter(np.log(x), np.log(y), c=['C2'], s=10)\n # plt.xlabel(var_name)\n # plt.ylabel(var_name_2)\n\n # num_fig = num_fig + 1\n \n\n #saveToTikz('no_reparam.tex')\n\n\n # ----- Bivariate probability distribution functions ----- \n # --------------------------------------------------------\n\n # OLD MATLAB IMPLEMENTATIL\n # figNum=1;\n # %param_values=inputParams.Parametrization(param_values);\n # if strcmp(bivariatePDF.plot, 'yes')\n # for i = 1 : nParam_uncertain\n # param_i = param_values(samplesPlot,i);\n # for j = i+1 : nParam_uncertain\n # param_j = param_values(samplesPlot,j);\n # if strcmp(bivariatePDF.plotHist, 'yes')\n # figure\n # hist3([param_i param_j], bivariatePDF.binHist);\n # set(get(gca,'child'),'FaceColor','interp','CDataMode','auto');\n # %ylim([1.2 1.5].*1e5); xlim([0 0.5].*1e6) \n # end\n # if strcmp(bivariatePDF.plotContourFilled, 'yes')\n # figure; hold on\n # [n,c] = hist3([param_i param_j], bivariatePDF.binHist);\n # [~,h]=contourf(c{1}, c{2}, n.', 80);\n # set(h,'LineColor','none')\n # end\n # if strcmp(bivariatePDF.plotContour, 'yes')\n # figure(figNum); hold on\n # [n,c] = hist3([param_i param_j], bivariatePDF.binHist);\n # [~,h]=contour(c{1}, c{2}, n.', 10);\n # set(h,'LineColor',matlab_default_colors(1,:))\n # end\n # if strcmp(bivariatePDF.scatterPlot, 'yes')\n # figure(figNum); hold on\n\n # scatter(param_j, param_i, 15, matlab_default_colors(2,:), 'filled')\n # end\n # figNum=figNum+1;\n # xlabel(paramNames(j)); \n # ylabel(paramNames(i)); \n # run('plot_dimensions'); box off\n \n # if strcmp(bivariatePDF.saveImg, 'yes')\n # matlab2tikz(['2Dpdf_' num2str(i) '_' num2str(j) '.tex'])\n # end\n \n # end\n # end\n # end\n\n\n\n # -------------------------------------------\n # ------ Posterior predictive check ---------\n # -------------------------------------------\n\n if (inputFields.get(\"PosteriorPredictiveCheck\") is not None):\n if inputFields[\"PosteriorPredictiveCheck\"][\"display\"] == \"yes\":\n\n # By default, we have saved 100 function evaluations\n n_fun_eval = n_samples # 100\n delta_it = int(n_samples/n_fun_eval)\n delta_it = 10\n\n start_val = int(inputFields[\"PosteriorPredictiveCheck\"][\"burnin\"]*delta_it)\n\n # By default, the last function evaluation to be plotted is equal to the number of iterations\n end_val = int(n_samples)\n\n # Num of fun eval after discarding burn in samples\n n_fun_eval_est = int((n_samples - start_val)/delta_it)\n #for i in range(data_exp.n_data_set):\n for num_data_set, data_id in enumerate(data_exp.keys()):\n n_x = len(data_exp[data_id].x)\n n_data_set = int(len(data_exp[data_id].y[0])/n_x)\n \n for i in range(n_data_set): \n plt.figure(num_plot[num_data_set])\n plt.figure(i)\n\n # Initialise bounds\n init_model_eval_file = pathlib.Path(model_eval_folder, f\"{data_id}_fun_eval-{0}.npy\") \n data_ij = np.load(init_model_eval_file)\n data_ij_max = data_ij\n data_ij_min = data_ij\n data_ij_mean = np.zeros(n_x)\n data_ij_var = np.zeros(n_x)\n\n ind_1 = i*n_x\n ind_2 =(i+1)*n_x\n\n # Histogram \n data_hist = np.zeros([n_fun_eval_est, n_x])\n\n for c_eval, j in enumerate(range(start_val+delta_it, end_val, delta_it)):\n # Load current data\n model_eval_j_file = pathlib.Path(model_eval_folder, f\"{data_id}_fun_eval-{j}.npy\") \n data_ij = np.load(model_eval_j_file)\n data_set_n = data_ij[ind_1:ind_2]\n \n # Update bounds\n for k in range(n_x):\n if data_ij_max[k] < data_set_n[k]:\n data_ij_max[k] = data_set_n[k]\n elif data_ij_min[k] > data_set_n[k]:\n data_ij_min[k] = data_set_n[k]\n\n data_hist[c_eval, :] = data_set_n[:] \n\n # Update mean \n data_ij_mean[:] = data_ij_mean[:] + data_set_n[:]\n\n # Plot all realisation (modify alpha value to see something)\n # plt.plot(data_exp[data_id].x, data_set_n[:], alpha=0.5)\n\n # Compute mean \n data_ij_mean = data_ij_mean[:]/n_fun_eval_est\n\n # Identical loop to compute the variance \n for j in range(start_val+delta_it, end_val, delta_it):\n\n # Load current data\n model_eval_j_file = pathlib.Path(model_eval_folder, f\"{data_id}_fun_eval-{j}.npy\") \n data_ij = np.load(model_eval_j_file)\n data_set_n = data_ij[ind_1:ind_2]\n\n # Compute variance\n data_ij_var = data_ij_var[:] + (data_set_n[:] - data_ij_mean[:])**2\n\n data_ij_var = data_ij_var[:]/(n_fun_eval_est - 1) \n \n # # Plot median and all results from propagation\n # plt.plot(data_exp.x[ind_1:ind_2+1], (data_ij_min +\n # data_ij_max)/2, color=lineColor[i][0], alpha=0.5)\n # plt.fill_between(data_exp.x[ind_1:ind_2+1], data_ij_min[:],\n # data_ij_max[:], facecolor=lineColor[i][0], alpha=0.1)\n\n # Plot mean and 95% confidence interval for the mean \n # CI_lowerbound = data_ij_mean - 1.96*np.sqrt(data_ij_var/n_fun_eval)\n # CI_upperbound = data_ij_mean + 1.96*np.sqrt(data_ij_var/n_fun_eval)\n # plt.plot(data_exp.x[ind_1:ind_2+1], data_ij_mean, color=lineColor[i][0], alpha=0.5)\n # plt.fill_between(data_exp.x[ind_1:ind_2+1], CI_lowerbound, CI_upperbound, facecolor=lineColor[i][0], alpha=0.1)\n\n # Plot mean \n # ---------\n plt.plot(data_exp[data_id].x, data_ij_mean, color=lineColor[num_data_set][0], alpha=0.5, label=\"Mean prop.\")\n\n # Plot 95% credible interval\n # ---------------------------\n if inputFields[\"PosteriorPredictiveCheck\"][\"cred_int\"] == \"yes\":\n low_cred_int = np.percentile(data_hist, 2.5, axis=0)\n high_cred_int = np.percentile(data_hist, 97.5, axis=0)\n plt.fill_between(data_exp[data_id].x, low_cred_int, high_cred_int, facecolor=lineColor[num_data_set][0], alpha=0.3, label=\"95\\% cred. int.\")\n \n # Plot 95% prediction interval\n # -----------------------------\n # For the prediction interval, we add the std to the result\n # Thus, the value of the sigma in the likelihood must be present in a csv file \n if inputFields[\"PosteriorPredictiveCheck\"][\"pred_int\"] == \"yes\":\n\n path_to_est_sigma = pathlib.Path(out_folder, \"estimated_sigma.csv\") \n if path_to_est_sigma.exists(): # Sigma was estimated \n print(\"Prediction interval computed using the estimated the standard deviations.\")\n reader = pd.read_csv(path_to_est_sigma)\n sigma_values = reader['model_id'].values\n else: # Values from the data \n print(\"Prediction interval computed using the standard deviations from the data.\")\n sigma_values = data_exp[data_id].std_y[i*n_x:i*n_x+n_x]\n\n plt.fill_between(data_exp[data_id].x, low_cred_int-sigma_values, \n high_cred_int+sigma_values, facecolor=lineColor[num_data_set][0], alpha=0.1, label=\"95\\% pred. int.\")\n\n #plt.fill_between(data_exp[data_id].x, low_cred_int-data_exp[data_id].std_y[ind_1:ind_2], \n # high_cred_int+data_exp[data_id].std_y[ind_1:ind_2], facecolor=lineColor[num_data_set][0], alpha=0.1)\n\n plt.legend()\n\n # Values are saved in csv format using Panda dataframe \n df = pd.DataFrame({\"x\": data_exp[data_id].x,\n \"mean\" : data_ij_mean, \n \"lower_bound\": data_ij_min, \n \"upper_bound\": data_ij_max})\n path_to_predCheckInt_file = pathlib.Path(out_folder, f\"{data_id}_posterior_pred_check_interval.csv\") \n df.to_csv(path_to_predCheckInt_file, index=None)\n\n df_CI = pd.DataFrame({\"x\": data_exp[data_id].x, \n \"CI_lb\": low_cred_int, \n \"CI_ub\": high_cred_int})\n path_to_predCheckCI_file = pathlib.Path(out_folder, f\"{data_id}_posterior_pred_check_CI.csv\") \n df_CI.to_csv(path_to_predCheckCI_file, index=None) \n\n del data_ij_max, data_ij_min, data_set_n\n\n\n\n # -------------------------------------------\n # ------------ Propagation ------------------\n # -------------------------------------------\n\n\n if (inputFields.get(\"Propagation\") is not None):\n if inputFields[\"Propagation\"][\"display\"] == \"yes\":\n\n num_plot = inputFields[\"Propagation\"][\"num_plot\"]\n\n for num_model_id, model_id in enumerate(inputFields[\"Propagation\"][\"model_id\"]):\n\n results_prop_CI = pd.read_csv('output/'+model_id+'_CI.csv') \n results_prop_intervals = pd.read_csv('output/'+model_id+'_interval.csv') \n\n # Plot graphs\n plt.figure(num_plot)\n\n plt.plot(results_prop_intervals[\"x\"], results_prop_intervals['mean'], color=lineColor[i][0], alpha=0.5)\n plt.fill_between(results_prop_intervals[\"x\"], results_prop_CI[\"CI_lb\"], results_prop_CI[\"CI_ub\"], facecolor=lineColor[i][0], alpha=0.1)\n\n # Prediction interval \n #plt.fill_between(data_exp[data_id].x, (results_prop_CI[\"CI_lb\"]-data_exp['std_rho']), (results_prop_CI[\"CI_ub\"]+data_exp['std_rho']), facecolor=lineColor[i][0], alpha=0.1)\n\n\n # -------------------------------------------\n # --------- Sensitivity analysis ------------\n # -------------------------------------------\n\n if (inputFields.get(\"SensitivityAnalysis\") is not None):\n if inputFields[\"SensitivityAnalysis\"][\"display\"] == \"yes\":\n num_plot = inputFields[\"SensitivityAnalysis\"][\"num_plot\"]\n\n # There should be data corresponding to \"function evaluations\" for the abscissa\n with open(data_file, 'rb') as file_data_exp:\n pickler_data_exp = pickle.Unpickler(file_data_exp)\n data_exp = pickler_data_exp.load()\n\n for num_data_set, data_id in enumerate(data_exp.keys()):\n\n # Read sensitivity values \n V_i = pd.read_csv('output/sensitivity_values.csv')\n\n\n if user_inputs[\"SensitivityAnalysis\"][\"Method\"] == \"MC\":\n # With MC method, we have also computed expecations\n\n\n plt.figure(num_plot)\n plt.plot(data_exp[data_id].x, V_i['V_tot'], color=\"black\", label=\"V_tot\") \n plt.ylabel(\"Expectation\")\n plt.xlabel(\"x\")\n\n plt.figure(num_plot+1)\n plt.plot(data_exp[data_id].x, V_i['E_tot'], 'C0')\n plt.ylabel(\"Variance\")\n plt.xlabel(\"x\")\n\n for i, name in enumerate(V_i.columns): \n\n if name == \"E_tot\" or name == \"V_tot\": \n continue\n\n plt.figure(num_plot+1)\n plt.plot(data_exp[data_id].x, V_i['E_tot'] + np.sqrt(V_i[name]), color=lineColor[i][0], label=name)\n plt.plot(data_exp[data_id].x, V_i['E_tot'] - np.sqrt(V_i[name]), color=lineColor[i][0])\n\n plt.figure(num_plot)\n plt.plot(data_exp[data_id].x, V_i[name], color=lineColor[i][0], label=name)\n\n\n\n\n elif user_inputs[\"SensitivityAnalysis\"][\"Method\"] == \"Kernel\": \n plt.figure(num_plot)\n plt.ylabel(\"Variance\")\n plt.xlabel(\"x\")\n\n for i, name in enumerate(V_i.columns): \n plt.plot(data_exp[data_id].x, V_i[name], color=lineColor[i][0], label=name)\n\n plt.legend()\n\n\n\n\n\n # Show plot \n #saveToTikz('propagation.tex')\n plt.show()\n\n\ndef saveToTikz(nameTikzFile):\n\n plt.grid(True)\n\t#tikzplotlib.clean_figure()\n tikz_save(nameTikzFile, axis_height='\\\\figureheight', axis_width='\\\\figurewidth',\n extra_axis_parameters=['/pgf/number format/.cd, 1000 sep={}', 'title=\\\\figuretitle', 'xlabel=\\\\figurexlabel', 'ylabel=\\\\figureylabel'])\n\n\t\t\t \ndef error_bar (x_data, y_data, error, col, line_width=1): \n\n yp_data_error = y_data + error \n ym_data_error = y_data - error\n\n Dx = x_data[-1] - x_data[0]\n dx = Dx/150\n\n ld = len(x_data)\n # Might be problematic if ld is too large (takes too much time)\n for i in range(0, ld): \n plt.plot([x_data[i], x_data[i]], [ym_data_error[i], yp_data_error[i]], color=col)\n plt.plot([x_data[i]-dx, x_data[i]+dx], [yp_data_error[i], yp_data_error[i]], color=col)\n plt.plot([x_data[i]-dx, x_data[i]+dx], [ym_data_error[i], ym_data_error[i]], color=col)\n\n"
] | [
[
"matplotlib.pyplot.legend",
"numpy.sqrt",
"pandas.DataFrame",
"matplotlib.pyplot.plot",
"numpy.max",
"scipy.stats.gaussian_kde",
"numpy.mean",
"pandas.read_csv",
"numpy.std",
"numpy.argmax",
"numpy.load",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.min",
"matplotlib.pyplot.fill_between",
"matplotlib.pyplot.show",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.scatter",
"numpy.percentile",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
cadurosar/laplacian_networks | [
"27f6f2d7145426b38f578e9c1beecae3e7392f1b"
] | [
"imagenet32/models/preact_parseval.py"
] | [
"'''Pre-activation ResNet in PyTorch.\n\nReference:\n[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun\n Identity Mappings in Deep Residual Networks. arXiv:1603.05027\n'''\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport math\nimport os\n\nfrom torch.autograd import Variable\n\nclass Parseval_Conv2d(nn.Conv2d):\n\n def forward(self, input):\n new_weight = self.weight/np.sqrt(2*self.kernel_size[0]*self.kernel_size[1]+1)\n return F.conv2d(input, new_weight, self.bias, self.stride,\n self.padding, self.dilation, self.groups)\n\n\nclass PreActBlock(nn.Module):\n '''Pre-activation version of the BasicBlock.'''\n expansion = 1\n\n def __init__(self, in_planes, planes, stride=1):\n super(PreActBlock, self).__init__()\n self.conv1 = Parseval_Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n self.conv2 = Parseval_Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(in_planes)\n self.bn2 = nn.BatchNorm2d(planes)\n\n if stride != 1 or in_planes != self.expansion*planes:\n self.shortcut = nn.Sequential(\n Parseval_Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False)\n )\n\n def forward(self, x):\n out = x\n out = self.bn1(out)\n relu1 = F.relu(out)\n shortcut = self.shortcut(relu1) if hasattr(self, 'shortcut') else x\n out = self.conv1(relu1)\n out = self.bn2(out)\n relu2 = F.relu(out)\n out = self.conv2(relu2)\n out = 0.5*out + 0.5*shortcut\n return relu1, relu2, out\n\n\nclass PreActResNetParseval(nn.Module):\n def __init__(self, block, num_classes=1000,initial_planes=16):\n super(PreActResNetParseval, self).__init__()\n self.in_planes = initial_planes\n self.output_relus\n self.classes = num_classes\n wide = 5\n\n self.conv1 = Parseval_Conv2d(3, self.in_planes, kernel_size=3, stride=1, padding=1, bias=False)\n\n self.layer1 = block(self.in_planes, self.in_planes*wide, 1)\n self.layer2 = block(self.in_planes*wide, self.in_planes*wide, 1)\n self.layer3 = block(self.in_planes*wide, self.in_planes*wide, 1)\n self.layer4 = block(self.in_planes*wide, self.in_planes*wide, 1)\n\n self.layer5 = block(self.in_planes*wide, self.in_planes*wide*2, 2)\n self.layer6 = block(self.in_planes*wide*2, self.in_planes*wide*2, 1)\n self.layer7 = block(self.in_planes*wide*2, self.in_planes*wide*2, 1)\n self.layer8 = block(self.in_planes*wide*2, self.in_planes*wide*2, 1)\n\n self.layer9 = block(self.in_planes*wide*2, self.in_planes*wide*4, 2)\n self.layer10 = block(self.in_planes*wide*4, self.in_planes*wide*4, 1)\n self.layer11 = block(self.in_planes*wide*4, self.in_planes*wide*4, 1)\n self.layer12 = block(self.in_planes*wide*4, self.in_planes*wide*4, 1)\n \n self.linear = nn.Linear(self.in_planes*20*block.expansion, self.classes)\n\n \n def forward(self, x, save=False, epoch=0,normalize=False):\n relus = list()\n if normalize:\n mean = torch.cuda.FloatTensor([0.481, 0.457, 0.407]).view(1, 3, 1, 1)\n std = torch.cuda.FloatTensor([0.260, 0.253, 0.268 ]).view(1, 3, 1, 1)\n x2 = x-torch.autograd.Variable(mean)\n x3 = x2/torch.autograd.Variable(std)\n out = self.conv1(x3)\n else:\n out = self.conv1(x)\n out = self.layer1(out)\n relus.extend(out[:2]) \n out = self.layer2(out[2]) \n relus.extend(out[:2]) \n\n out = self.layer3(out[2])\n relus.extend(out[:2])\n\n out = self.layer4(out[2])\n relus.extend(out[:2]) \n\n out = self.layer5(out[2])\n relus.extend(out[:2]) \n\n out = self.layer6(out[2])\n relus.extend(out[:2])\n\n out = self.layer7(out[2])\n relus.extend(out[:2])\n\n out = self.layer8(out[2])\n relus.extend(out[:2])\n\n out = self.layer9(out[2])\n relus.extend(out[:2])\n\n out = self.layer10(out[2])\n relus.extend(out[:2])\n\n out = self.layer11(out[2])\n relus.extend(out[:2])\n\n out = self.layer12(out[2])\n relus.extend(out[:2])\n \n final_out = F.relu(out[2]) \n relus.append(final_out) \n out = final_out\n out = out.view(out.size(0), out.size(1), -1)\n out = torch.mean(out,2)\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n if self.output_relus:\n return relus,out\n else:\n return out\n\ndef PreActResNet18Parseval(initial_planes=16,num_classes=1000): # Chamada na hora de criar a net\n return PreActResNetParseval(PreActBlock,initial_planes=initial_planes,num_classes=num_classes)\n"
] | [
[
"torch.mean",
"numpy.sqrt",
"torch.nn.functional.conv2d",
"torch.cuda.FloatTensor",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.nn.BatchNorm2d",
"torch.autograd.Variable"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
reyjul/alphafold | [
"d422d5f024c9ac40a389b51704c0560d9152103c"
] | [
"run_alphafold.py"
] | [
"# Copyright 2021 DeepMind Technologies Limited\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Full AlphaFold protein structure prediction script.\"\"\"\nimport json\nimport os\nimport pathlib\nimport pickle\nimport random\nimport shutil\nimport sys\nimport time\nfrom typing import Dict, Union, Optional\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nfrom alphafold.common import protein\nfrom alphafold.common import residue_constants\nfrom alphafold.data import pipeline\nfrom alphafold.data import pipeline_multimer\nfrom alphafold.data import templates\nfrom alphafold.data.tools import hhsearch\nfrom alphafold.data.tools import hmmsearch\nfrom alphafold.model import config\nfrom alphafold.model import model\nfrom alphafold.relax import relax\nimport numpy as np\n\nfrom alphafold.model import data\n# Internal import (7716).\n\nlogging.set_verbosity(logging.INFO)\n\nflags.DEFINE_list(\n 'fasta_paths', None, 'Paths to FASTA files, each containing a prediction '\n 'target that will be folded one after another. If a FASTA file contains '\n 'multiple sequences, then it will be folded as a multimer. Paths should be '\n 'separated by commas. All FASTA paths must have a unique basename as the '\n 'basename is used to name the output directories for each prediction.')\nflags.DEFINE_list(\n 'is_prokaryote_list', None, 'Optional for multimer system, not used by the '\n 'single chain system. This list should contain a boolean for each fasta '\n 'specifying true where the target complex is from a prokaryote, and false '\n 'where it is not, or where the origin is unknown. These values determine '\n 'the pairing method for the MSA.')\n\nflags.DEFINE_string('data_dir', None, 'Path to directory of supporting data.')\nflags.DEFINE_string('output_dir', None, 'Path to a directory that will '\n 'store the results.')\nflags.DEFINE_string('jackhmmer_binary_path', shutil.which('jackhmmer'),\n 'Path to the JackHMMER executable.')\nflags.DEFINE_string('hhblits_binary_path', shutil.which('hhblits'),\n 'Path to the HHblits executable.')\nflags.DEFINE_string('hhsearch_binary_path', shutil.which('hhsearch'),\n 'Path to the HHsearch executable.')\nflags.DEFINE_string('hmmsearch_binary_path', shutil.which('hmmsearch'),\n 'Path to the hmmsearch executable.')\nflags.DEFINE_string('hmmbuild_binary_path', shutil.which('hmmbuild'),\n 'Path to the hmmbuild executable.')\nflags.DEFINE_string('kalign_binary_path', shutil.which('kalign'),\n 'Path to the Kalign executable.')\nflags.DEFINE_string('uniref90_database_path', None, 'Path to the Uniref90 '\n 'database for use by JackHMMER.')\nflags.DEFINE_string('mgnify_database_path', None, 'Path to the MGnify '\n 'database for use by JackHMMER.')\nflags.DEFINE_string('bfd_database_path', None, 'Path to the BFD '\n 'database for use by HHblits.')\nflags.DEFINE_string('small_bfd_database_path', None, 'Path to the small '\n 'version of BFD used with the \"reduced_dbs\" preset.')\nflags.DEFINE_string('uniclust30_database_path', None, 'Path to the Uniclust30 '\n 'database for use by HHblits.')\nflags.DEFINE_string('uniprot_database_path', None, 'Path to the Uniprot '\n 'database for use by JackHMMer.')\nflags.DEFINE_string('pdb70_database_path', None, 'Path to the PDB70 '\n 'database for use by HHsearch.')\nflags.DEFINE_string('pdb_seqres_database_path', None, 'Path to the PDB '\n 'seqres database for use by hmmsearch.')\nflags.DEFINE_string('template_mmcif_dir', None, 'Path to a directory with '\n 'template mmCIF structures, each named <pdb_id>.cif')\nflags.DEFINE_string('max_template_date', None, 'Maximum template release date '\n 'to consider. Important if folding historical test sets.')\nflags.DEFINE_string('obsolete_pdbs_path', None, 'Path to file containing a '\n 'mapping from obsolete PDB IDs to the PDB IDs of their '\n 'replacements.')\nflags.DEFINE_enum('db_preset', 'full_dbs',\n ['full_dbs', 'reduced_dbs'],\n 'Choose preset MSA database configuration - '\n 'smaller genetic database config (reduced_dbs) or '\n 'full genetic database config (full_dbs)')\nflags.DEFINE_enum('model_preset', 'monomer',\n ['monomer', 'monomer_casp14', 'monomer_ptm', 'multimer'],\n 'Choose preset model configuration - the monomer model, '\n 'the monomer model with extra ensembling, monomer model with '\n 'pTM head, or multimer model')\nflags.DEFINE_boolean('benchmark', False, 'Run multiple JAX model evaluations '\n 'to obtain a timing that excludes the compilation time, '\n 'which should be more indicative of the time required for '\n 'inferencing many proteins.')\nflags.DEFINE_integer('random_seed', None, 'The random seed for the data '\n 'pipeline. By default, this is randomly generated. Note '\n 'that even if this is set, Alphafold may still not be '\n 'deterministic, because processes like GPU inference are '\n 'nondeterministic.')\nflags.DEFINE_boolean('use_templates', True,\n 'Whether to search for template structures.')\nflags.DEFINE_boolean('use_precomputed_msas', False, 'Whether to read MSAs that '\n 'have been written to disk. WARNING: This will not check '\n 'if the sequence, database or configuration have changed.')\nflags.DEFINE_boolean('amber', True,\n 'Whether to do an Amber relaxation of the models.')\nflags.DEFINE_boolean('only_msas', False, 'Whether to only build MSAs, and not '\n 'do any prediction.')\nFLAGS = flags.FLAGS\n\nMAX_TEMPLATE_HITS = 20\nRELAX_MAX_ITERATIONS = 0\nRELAX_ENERGY_TOLERANCE = 2.39\nRELAX_STIFFNESS = 10.0\nRELAX_EXCLUDE_RESIDUES = []\nRELAX_MAX_OUTER_ITERATIONS = 3\n\n\ndef _check_flag(flag_name: str,\n other_flag_name: str,\n should_be_set: bool):\n if should_be_set != bool(FLAGS[flag_name].value):\n verb = 'be' if should_be_set else 'not be'\n raise ValueError(f'{flag_name} must {verb} set when running with '\n f'\"--{other_flag_name}={FLAGS[other_flag_name].value}\".')\n\n\ndef predict_structure(\n fasta_path: str,\n fasta_name: str,\n output_dir_base: str,\n data_pipeline: Union[pipeline.DataPipeline, pipeline_multimer.DataPipeline],\n model_runners: Dict[str, model.RunModel],\n amber_relaxer: Optional[relax.AmberRelaxation],\n benchmark: bool,\n random_seed: int,\n is_prokaryote: Optional[bool] = None,\n only_msas: Optional[bool] = False):\n \"\"\"Predicts structure using AlphaFold for the given sequence.\"\"\"\n logging.info('Predicting %s', fasta_name)\n timings = {}\n output_dir = os.path.join(output_dir_base, fasta_name)\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n msa_output_dir = os.path.join(output_dir, 'msas')\n if not os.path.exists(msa_output_dir):\n os.makedirs(msa_output_dir)\n\n # Get features.\n t_0 = time.time()\n if is_prokaryote is None:\n feature_dict = data_pipeline.process(\n input_fasta_path=fasta_path,\n msa_output_dir=msa_output_dir)\n else:\n feature_dict = data_pipeline.process(\n input_fasta_path=fasta_path,\n msa_output_dir=msa_output_dir,\n is_prokaryote=is_prokaryote)\n timings['features'] = time.time() - t_0\n\n # Write out features as a pickled dictionary.\n features_output_path = os.path.join(output_dir, 'features.pkl')\n with open(features_output_path, 'wb') as f:\n pickle.dump(feature_dict, f, protocol=4)\n\n if not only_msas:\n unrelaxed_pdbs = {}\n relaxed_pdbs = {}\n ranking_confidences = {}\n\n # Run the models.\n num_models = len(model_runners)\n for model_index, (model_name, model_runner) in enumerate(\n model_runners.items()):\n logging.info('Running model %s on %s', model_name, fasta_name)\n t_0 = time.time()\n model_random_seed = model_index + random_seed * num_models\n processed_feature_dict = model_runner.process_features(\n feature_dict, random_seed=model_random_seed)\n timings[f'process_features_{model_name}'] = time.time() - t_0\n\n t_0 = time.time()\n prediction_result = model_runner.predict(processed_feature_dict,\n random_seed=model_random_seed)\n t_diff = time.time() - t_0\n timings[f'predict_and_compile_{model_name}'] = t_diff\n logging.info(\n 'Total JAX model %s on %s predict time (includes compilation time, see --benchmark): %.1fs',\n model_name, fasta_name, t_diff)\n\n if benchmark:\n t_0 = time.time()\n model_runner.predict(processed_feature_dict,\n random_seed=model_random_seed)\n t_diff = time.time() - t_0\n timings[f'predict_benchmark_{model_name}'] = t_diff\n logging.info(\n 'Total JAX model %s on %s predict time (excludes compilation time): %.1fs',\n model_name, fasta_name, t_diff)\n\n plddt = prediction_result['plddt']\n ranking_confidences[model_name] = prediction_result['ranking_confidence']\n\n # Save the model outputs.\n result_output_path = os.path.join(output_dir, f'result_{model_name}.pkl')\n with open(result_output_path, 'wb') as f:\n pickle.dump(prediction_result, f, protocol=4)\n\n # Add the predicted LDDT in the b-factor column.\n # Note that higher predicted LDDT value means higher model confidence.\n plddt_b_factors = np.repeat(\n plddt[:, None], residue_constants.atom_type_num, axis=-1)\n unrelaxed_protein = protein.from_prediction(\n features=processed_feature_dict,\n result=prediction_result,\n b_factors=plddt_b_factors,\n remove_leading_feature_dimension=not model_runner.multimer_mode)\n\n unrelaxed_pdbs[model_name] = protein.to_pdb(unrelaxed_protein)\n unrelaxed_pdb_path = os.path.join(output_dir, f'unrelaxed_{model_name}.pdb')\n with open(unrelaxed_pdb_path, 'w') as f:\n f.write(unrelaxed_pdbs[model_name])\n\n if amber_relaxer:\n # Relax the prediction.\n t_0 = time.time()\n relaxed_pdb_str, _, _ = amber_relaxer.process(prot=unrelaxed_protein)\n timings[f'relax_{model_name}'] = time.time() - t_0\n\n relaxed_pdbs[model_name] = relaxed_pdb_str\n\n # Save the relaxed PDB.\n relaxed_output_path = os.path.join(\n output_dir, f'relaxed_{model_name}.pdb')\n with open(relaxed_output_path, 'w') as f:\n f.write(relaxed_pdb_str)\n\n # Rank by model confidence and write out relaxed PDBs in rank order.\n ranked_order = []\n for idx, (model_name, _) in enumerate(\n sorted(ranking_confidences.items(), key=lambda x: x[1], reverse=True)):\n ranked_order.append(model_name)\n ranked_output_path = os.path.join(output_dir, f'ranked_{idx}.pdb')\n with open(ranked_output_path, 'w') as f:\n if amber_relaxer:\n f.write(relaxed_pdbs[model_name])\n else:\n f.write(unrelaxed_pdbs[model_name])\n\n ranking_output_path = os.path.join(output_dir, 'ranking_debug.json')\n with open(ranking_output_path, 'w') as f:\n label = 'iptm+ptm' if 'iptm' in prediction_result else 'plddts'\n f.write(json.dumps(\n {label: ranking_confidences, 'order': ranked_order}, indent=4))\n\n logging.info('Final timings for %s: %s', fasta_name, timings)\n\n timings_output_path = os.path.join(output_dir, 'timings.json')\n with open(timings_output_path, 'w') as f:\n f.write(json.dumps(timings, indent=4))\n\n\ndef main(argv):\n if len(argv) > 1:\n raise app.UsageError('Too many command-line arguments.')\n\n run_multimer_system = 'multimer' in FLAGS.model_preset\n use_small_bfd = FLAGS.db_preset == 'reduced_dbs'\n\n require_all_databases = True\n if FLAGS.use_precomputed_msas and not FLAGS.use_templates \\\n and not FLAGS.only_msas:\n require_all_databases = False\n\n if require_all_databases:\n for flag_name in (\n 'uniref90_database_path',\n 'mgnify_database_path',\n 'template_mmcif_dir',\n 'obsolete_pdbs_path'):\n if getattr(FLAGS, flag_name) is None:\n raise ValueError(f'Flag --{flag_name} must have a value other than None')\n\n for tool_name in (\n 'jackhmmer', 'hhblits', 'hhsearch', 'hmmsearch', 'hmmbuild', 'kalign'):\n if not FLAGS[f'{tool_name}_binary_path'].value:\n raise ValueError(f'Could not find path to the \"{tool_name}\" binary. Make '\n 'sure it is installed on your system.')\n \n _check_flag('small_bfd_database_path', 'db_preset',\n should_be_set=use_small_bfd)\n _check_flag('bfd_database_path', 'db_preset',\n should_be_set=not use_small_bfd)\n _check_flag('uniclust30_database_path', 'db_preset',\n should_be_set=not use_small_bfd)\n\n _check_flag('pdb70_database_path', 'model_preset',\n should_be_set=not run_multimer_system)\n _check_flag('pdb_seqres_database_path', 'model_preset',\n should_be_set=run_multimer_system)\n _check_flag('uniprot_database_path', 'model_preset',\n should_be_set=run_multimer_system)\n\n if FLAGS.model_preset == 'monomer_casp14':\n num_ensemble = 8\n else:\n num_ensemble = 1\n\n # Check for duplicate FASTA file names.\n fasta_names = [pathlib.Path(p).stem for p in FLAGS.fasta_paths]\n if len(fasta_names) != len(set(fasta_names)):\n raise ValueError('All FASTA paths must have a unique basename.')\n\n # Check that is_prokaryote_list has same number of elements as fasta_paths,\n # and convert to bool.\n if FLAGS.is_prokaryote_list:\n if len(FLAGS.is_prokaryote_list) != len(FLAGS.fasta_paths):\n raise ValueError('--is_prokaryote_list must either be omitted or match '\n 'length of --fasta_paths.')\n is_prokaryote_list = []\n for s in FLAGS.is_prokaryote_list:\n if s in ('true', 'false'):\n is_prokaryote_list.append(s == 'true')\n else:\n raise ValueError('--is_prokaryote_list must contain comma separated '\n 'true or false values.')\n else: # Default is_prokaryote to False.\n is_prokaryote_list = [False] * len(fasta_names)\n\n template_searcher = None\n template_featurizer = None\n if FLAGS.use_templates:\n if run_multimer_system:\n template_searcher = hmmsearch.Hmmsearch(\n binary_path=FLAGS.hmmsearch_binary_path,\n hmmbuild_binary_path=FLAGS.hmmbuild_binary_path,\n database_path=FLAGS.pdb_seqres_database_path)\n template_featurizer = templates.HmmsearchHitFeaturizer(\n mmcif_dir=FLAGS.template_mmcif_dir,\n max_template_date=FLAGS.max_template_date,\n max_hits=MAX_TEMPLATE_HITS,\n kalign_binary_path=FLAGS.kalign_binary_path,\n release_dates_path=None,\n obsolete_pdbs_path=FLAGS.obsolete_pdbs_path)\n else:\n template_searcher = hhsearch.HHSearch(\n binary_path=FLAGS.hhsearch_binary_path,\n databases=[FLAGS.pdb70_database_path])\n template_featurizer = templates.HhsearchHitFeaturizer(\n mmcif_dir=FLAGS.template_mmcif_dir,\n max_template_date=FLAGS.max_template_date,\n max_hits=MAX_TEMPLATE_HITS,\n kalign_binary_path=FLAGS.kalign_binary_path,\n release_dates_path=None,\n obsolete_pdbs_path=FLAGS.obsolete_pdbs_path)\n\n monomer_data_pipeline = pipeline.DataPipeline(\n jackhmmer_binary_path=FLAGS.jackhmmer_binary_path,\n hhblits_binary_path=FLAGS.hhblits_binary_path,\n uniref90_database_path=FLAGS.uniref90_database_path,\n mgnify_database_path=FLAGS.mgnify_database_path,\n bfd_database_path=FLAGS.bfd_database_path,\n uniclust30_database_path=FLAGS.uniclust30_database_path,\n small_bfd_database_path=FLAGS.small_bfd_database_path,\n template_searcher=template_searcher,\n template_featurizer=template_featurizer,\n use_small_bfd=use_small_bfd,\n use_precomputed_msas=FLAGS.use_precomputed_msas,\n use_templates=FLAGS.use_templates)\n\n if run_multimer_system:\n data_pipeline = pipeline_multimer.DataPipeline(\n monomer_data_pipeline=monomer_data_pipeline,\n jackhmmer_binary_path=FLAGS.jackhmmer_binary_path,\n uniprot_database_path=FLAGS.uniprot_database_path,\n use_precomputed_msas=FLAGS.use_precomputed_msas)\n else:\n data_pipeline = monomer_data_pipeline\n\n model_runners = {}\n model_names = config.MODEL_PRESETS[FLAGS.model_preset]\n for model_name in model_names:\n model_config = config.model_config(model_name)\n if run_multimer_system:\n model_config.model.num_ensemble_eval = num_ensemble\n else:\n model_config.data.eval.num_ensemble = num_ensemble\n model_params = data.get_model_haiku_params(\n model_name=model_name, data_dir=FLAGS.data_dir)\n model_runner = model.RunModel(model_config, model_params)\n model_runners[model_name] = model_runner\n\n logging.info('Have %d models: %s', len(model_runners),\n list(model_runners.keys()))\n\n amber_relaxer = None\n if FLAGS.amber:\n amber_relaxer = relax.AmberRelaxation(\n max_iterations=RELAX_MAX_ITERATIONS,\n tolerance=RELAX_ENERGY_TOLERANCE,\n stiffness=RELAX_STIFFNESS,\n exclude_residues=RELAX_EXCLUDE_RESIDUES,\n max_outer_iterations=RELAX_MAX_OUTER_ITERATIONS)\n\n random_seed = FLAGS.random_seed\n if random_seed is None:\n random_seed = random.randrange(sys.maxsize // len(model_names))\n logging.info('Using random seed %d for the data pipeline', random_seed)\n\n # Predict structure for each of the sequences.\n for i, fasta_path in enumerate(FLAGS.fasta_paths):\n is_prokaryote = is_prokaryote_list[i] if run_multimer_system else None\n fasta_name = fasta_names[i]\n predict_structure(\n fasta_path=fasta_path,\n fasta_name=fasta_name,\n output_dir_base=FLAGS.output_dir,\n data_pipeline=data_pipeline,\n model_runners=model_runners,\n amber_relaxer=amber_relaxer,\n benchmark=FLAGS.benchmark,\n random_seed=random_seed,\n is_prokaryote=is_prokaryote,\n only_msas=FLAGS.only_msas)\n\n\nif __name__ == '__main__':\n flags.mark_flags_as_required([\n 'fasta_paths',\n 'output_dir',\n 'data_dir',\n\n ])\n\n app.run(main)\n"
] | [
[
"numpy.repeat"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
goldenbili/Bert_Test2 | [
"35aa7505010d738a1e2b614d53f78707077157dd",
"35aa7505010d738a1e2b614d53f78707077157dd"
] | [
"run_squad_ColabTCPTrans_201910151851.py",
"run_squad_coding.py"
] | [
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team 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\"\"\"Run BERT on SQuAD 1.1 and SQuAD 2.0.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport json\nimport math\nimport os, types\nimport random\nimport modeling\nimport optimization\nimport tokenization\nimport six\nimport copy\nimport tensorflow as tf\nimport numpy as np\nimport scipy.sparse as sp\n\n# do excel\nfrom openpyxl import Workbook\n\n\nimport uuid\n\n# do \nimport code\nimport prettytable\n\nfrom decimal import *\nimport decimal\ngetcontext().prec = 50\n\n#Willy Define\nexample_in_set_eval_examples = 0\nexample_in_write_predictions = 0\npredict_result_index = 0\ncheckState_in_AtenResult = 0\ncheckState_in_AtenResult2 = 0\ncheckState_in_GetAnswer = 0\ncheckState_add_retriever = 0\nwilly_check_code = \"willy test on 201910151924\"\n\nfrom drqa import retriever\n\nDOC2IDX = None\ndocuments = []\n#db_class = retriever.get_class('sqlite')\n\n\n\nflags = tf.flags\n\nFLAGS = flags.FLAGS\n\n## Required parameters\nflags.DEFINE_string(\n \"bert_config_file\", None,\n \"The config json file corresponding to the pre-trained BERT model. \"\n \"This specifies the model architecture.\")\n\nflags.DEFINE_string(\"vocab_file\", None,\n \"The vocabulary file that the BERT model was trained on.\")\n\nflags.DEFINE_string(\n \"output_dir\", None,\n \"The output directory where the model checkpoints will be written.\")\n\n## Other parameters\nflags.DEFINE_string(\"train_file\", None,\n \"SQuAD json for training. E.g., train-v1.1.json\")\n\nflags.DEFINE_string(\n \"predict_file\", None,\n \"SQuAD json for predictions. E.g., dev-v1.1.json or test-v1.1.json\")\n\nflags.DEFINE_string(\n \"init_checkpoint\", None,\n \"Initial checkpoint (usually from a pre-trained BERT model).\")\n\nflags.DEFINE_bool(\n \"do_lower_case\", True,\n \"Whether to lower case the input text. Should be True for uncased \"\n \"models and False for cased models.\")\n\nflags.DEFINE_integer(\n \"max_seq_length\", 384,\n \"The maximum total input sequence length after WordPido_interactiveece tokenization. \"\n \"Sequences longer than this will be truncated, and sequences shorter \"\n \"than this will be padded.\")\n\nflags.DEFINE_integer(\n \"doc_stride\", 128,\n \"When splitting up a long document into chunks, how much stride to \"\n \"take between chunks.\")\n\nflags.DEFINE_integer(\n \"max_query_length\", 64,\n \"The maximum number of tokens for the question. Questions longer than \"\n \"this will be truncated to this length.\")\n\nflags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\")\n\nflags.DEFINE_bool(\"do_predict\", False, \"Whether to run eval on the dev set.\")\n\nflags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\")\n\nflags.DEFINE_integer(\"predict_batch_size\", 8,\n \"Total batch size for predictions.\")\n\nflags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for Adam.\")\n\nflags.DEFINE_float(\"num_train_epochs\", 3.0,\n \"Total number of training epochs to perform.\")\n\nflags.DEFINE_float(\n \"warmup_proportion\", 0.1,\n \"Proportion of training to perform linear learning rate warmup for. \"\n \"E.g., 0.1 = 10% of training.\")\n\nflags.DEFINE_integer(\"save_checkpoints_steps\", 1000,\n \"How often to save the model checkpoint.\")\n\nflags.DEFINE_integer(\"iterations_per_loop\", 1000,\n \"How many steps to make in each estimator call.\")\n\nflags.DEFINE_integer(\n \"n_best_size\", 20,\n \"The total number of n-best predictions to generate in the \"\n \"nbest_predictions.json output file.\")\n\nflags.DEFINE_integer(\n \"max_answer_length\", 30,\n \"The maximum length of an answer that can be generated. This is needed \"\n \"because the start and end predictions are not conditioned on one another.\")\n\nflags.DEFINE_bool(\"use_tpu\", False, \"Whether to use TPU or GPU/CPU.\")\n\ntf.flags.DEFINE_string(\n \"tpu_name\", None,\n \"The Cloud TPU to use for training. This should be either the name \"\n \"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 \"\n \"url.\")\n\ntf.flags.DEFINE_string(\n \"tpu_zone\", None,\n \"[Optional] GCE zone where the Cloud TPU is located in. If not \"\n \"specified, we will attempt to automatically detect the GCE project from \"\n \"metadata.\")\n\ntf.flags.DEFINE_string(\n \"gcp_project\", None,\n \"[Optional] Project name for the Cloud TPU-enabled project. If not \"\n \"specified, we will attempt to automatically detect the GCE project from \"\n \"metadata.\")\n\ntf.flags.DEFINE_string(\"master\", None, \"[Optional] TensorFlow master URL.\")\n\nflags.DEFINE_integer(\n \"num_tpu_cores\", 8,\n \"Only used if `use_tpu` is True. Total number of TPU cores to use.\")\n\nflags.DEFINE_bool(\n \"verbose_logging\", False,\n \"If true, all of the warnings related to data processing will be printed. \"\n \"A number of warnings are expected for a normal SQuAD evaluation.\")\n\nflags.DEFINE_bool(\n \"version_2_with_negative\", False,\n \"If true, the SQuAD examples contain some that do not have an answer.\")\n\nflags.DEFINE_float(\n \"null_score_diff_threshold\", 0.0,\n \"If null_score - best_non_null is greater than the threshold predict null.\")\n\nflags.DEFINE_bool(\n \"do_retriever\", False,\n \"If True, use retriever to help reader to filte good doc - add by willy.\")\n\nflags.DEFINE_string(\n \"retriever_model\", None,\n \"retriever model path - add by willy.\")\n\nflags.DEFINE_float(\n \"retriever_weight\", 0.0,\n \"retriever weight - add by willy.\")\n\n\nflags.DEFINE_integer(\"retriever_ranker\", 1,\"Rank with retriever.\")\n\nflags.DEFINE_string(\"document_type\",\"SQuAD\", \"There are three document types: (1)paragraphs in SQuAD (2)SQlite (DataBase) (3) Text - add by willy.\" )\n\nflags.DEFINE_string(\"question_type\",\"SQuAD\", \"There are three question types: (1) SQuAD (2)one_question (3) interactive.\" )\n\nflags.DEFINE_string(\"question\", None, \"give question to predict - Willy Test.\")\n\nflags.DEFINE_string(\"db_file\", None, \"give path with data base file to set SQlite State - Willy Test.\")\n\nflags.DEFINE_string(\"question_table\", None, \"set table path - Willy Test.\")\n\nflags.DEFINE_string(\"excel_name\", None ,\"set excel name -Willy Test.\")\n\nflags.DEFINE_integer(\"show_all_choice\", 0, \"show all choice-Willy Test.\")\n\nflags.DEFINE_float(\n \"choice_score\", 0.15,\n \"choice score. - add by willy.\")\n\nflags.DEFINE_float(\n \"threshold_prob_ans_merge\", 0.5,\n \"threshold prob ans_merge - add by willy.\")\n\nflags.DEFINE_string(\"Host_TCPServer\", '127.0.0.1' ,\"Set TCP Host-Willy Test.\")\n\nflags.DEFINE_integer(\"PORT_TCPServer\", 1234, \"Set TCP Port-Willy Test.\")\n\n\nranker = None\n\nclass DecimalEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, decimal.Decimal):\n return float(obj)\n return super(DecimalEncoder, self).default(obj)\n\n\nclass SquadExample(object):\n \"\"\"A single training/test example for simple sequence classification.\n For examples without an answer, the start and end position are -1.\n \"\"\"\n\n def __init__(self,\n qas_id,\n question_text,\n doc_id, #willy add\n doc_tokens,\n orig_answer_text=None,\n start_position=None,\n end_position=None,\n is_impossible=False):\n self.qas_id = qas_id\n self.question_text = question_text\n self.doc_id = doc_id #willy add\n self.doc_tokens = doc_tokens\n self.orig_answer_text = orig_answer_text\n self.start_position = start_position\n self.end_position = end_position\n self.is_impossible = is_impossible\n\n def __str__(self):\n return self.__repr__()\n\n def __repr__(self):\n s = \"\"\n s += \"qas_id: %s\" % (tokenization.printable_text(self.qas_id))\n s += \", question_text: %s\" % (\n tokenization.printable_text(self.question_text))\n s += \", doc_id:[%s]\" % (tokenization.printable_text(self.doc_id)) #willy add\n s += \", doc_tokens: [%s]\" % (\" \".join(self.doc_tokens))\n if self.start_position:\n s += \", start_position: %d\" % (self.start_position)\n if self.start_position:\n s += \", end_position: %d\" % (self.end_position)\n if self.start_position:\n s += \", is_impossible: %r\" % (self.is_impossible)\n return s\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self,\n unique_id,\n example_index,\n doc_span_index,\n tokens,\n token_to_orig_map,\n token_is_max_context,\n input_ids,\n input_mask,\n segment_ids,\n start_position=None,\n end_position=None,\n is_impossible=None):\n self.unique_id = unique_id\n self.example_index = example_index\n self.doc_span_index = doc_span_index\n self.tokens = tokens\n self.token_to_orig_map = token_to_orig_map\n self.token_is_max_context = token_is_max_context\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.start_position = start_position\n self.end_position = end_position\n self.is_impossible = is_impossible\n\ndef TakeThird(val):\n return val[2]\n \n \ndef set_squad_examples(input_file,question):\n\n \"\"\"Read a SQuAD json file into a list of SquadExample.\"\"\"\n with tf.gfile.Open(input_file, \"r\") as reader:\n input_data = json.load(reader)[\"data\"]\n def is_whitespace(c):\n if c == \" \" or c == \"\\t\" or c == \"\\r\" or c == \"\\n\" or ord(c) == 0x202F:\n return True\n return False\n \n examples = []\n file = open(\"Output1.txt\", \"r\")\n document = file.read()\n file.close()\n paragraphs = document.split('\\n')\n paragraphs = list(filter(None, paragraphs))\n #-----------------------------------------------\n doc_tokensList = []\n for i , paragraph_text in enumerate(paragraphs):\n # paragraph_text = paragraph[\"context\"]\n doc_tokens = []\n char_to_word_offset = []\n prev_is_whitespace = True\n for c in paragraph_text:\n if is_whitespace(c):\n prev_is_whitespace = True\n else:\n if prev_is_whitespace:\n doc_tokens.append(c)\n else:\n doc_tokens[-1] += c\n prev_is_whitespace = False\n char_to_word_offset.append(len(doc_tokens) - 1)\n doc_tokensList.append(doc_tokens)\n #-----------------------------------------------\n start_position = -1\n end_position = -1\n orig_answer_text = \"\"\n is_impossible = False\n for i, doc_tokens in enumerate(doc_tokensList):\n example = SquadExample(\n qas_id=str(uuid.uuid1()),\n question_text=question,\n doc_id=DOC2IDX[i],\n doc_tokens=doc_tokens,\n orig_answer_text=orig_answer_text,\n start_position=start_position,\n end_position=end_position,\n is_impossible=is_impossible)\n examples.append(example)\n \n ''' \n for entry in input_data:\n for paragraph in entry[\"paragraphs\"]:\n for qa in paragraph[\"qas\"]:\n #qas_id = qa[\"id\"]\n # uuid reset by willy in 20190313\n qas_id = str(uuid.uuid1())\n question_text = qa[\"question\"]\n start_position = -1\n end_position = -1\n orig_answer_text = \"\"\n is_impossible = False\n for doc_tokens in doc_tokensList:\n example = SquadExample(\n qas_id=qas_id,\n question_text=question_text,\n doc_tokens=doc_tokens,\n orig_answer_text=orig_answer_text,\n start_position=start_position,\n end_position=end_position,\n is_impossible=is_impossible)\n print(example)\n examples.append(example)\n ''' \n #-----------------------------------------------\n return examples \n \ndef read_squad_examples(input_file, is_training):\n \"\"\"Read a SQuAD json file into a list of SquadExample.\"\"\"\n with tf.gfile.Open(input_file, \"r\") as reader:\n input_data = json.load(reader)[\"data\"]\n\n def is_whitespace(c):\n if c == \" \" or c == \"\\t\" or c == \"\\r\" or c == \"\\n\" or ord(c) == 0x202F:\n return True\n return False\n\n examples = []\n for entry in input_data:\n for paragraph in entry[\"paragraphs\"]:\n paragraph_text = paragraph[\"context\"]\n doc_tokens = []\n char_to_word_offset = []\n prev_is_whitespace = True\n for c in paragraph_text:\n if is_whitespace(c):\n prev_is_whitespace = True\n else:\n if prev_is_whitespace:\n doc_tokens.append(c)\n else:\n doc_tokens[-1] += c\n prev_is_whitespace = False\n char_to_word_offset.append(len(doc_tokens) - 1)\n\n for qa in paragraph[\"qas\"]:\n qas_id = qa[\"id\"]\n question_text = qa[\"question\"]\n start_position = None\n end_position = None\n orig_answer_text = None\n is_impossible = False\n if is_training:\n\n if FLAGS.version_2_with_negative:\n is_impossible = qa[\"is_impossible\"]\n if (len(qa[\"answers\"]) != 1) and (not is_impossible):\n raise ValueError(\n \"For training, each question should have exactly 1 answer.\")\n if not is_impossible:\n answer = qa[\"answers\"][0]\n orig_answer_text = answer[\"text\"]\n answer_offset = answer[\"answer_start\"]\n answer_length = len(orig_answer_text)\n start_position = char_to_word_offset[answer_offset]\n end_position = char_to_word_offset[answer_offset + answer_length -\n 1]\n # Only add answers where the text can be exactly recovered from the\n # document. If this CAN'T happen it's likely due to weird Unicode\n # stuff so we will just skip the example.\n #\n # Note that this means for training mode, every example is NOT\n # guaranteed to be preserved.\n actual_text = \" \".join(\n doc_tokens[start_position:(end_position + 1)])\n cleaned_answer_text = \" \".join(\n tokenization.whitespace_tokenize(orig_answer_text))\n if actual_text.find(cleaned_answer_text) == -1:\n tf.logging.warning(\"Could not find answer: '%s' vs. '%s'\",\n actual_text, cleaned_answer_text)\n continue\n else:\n start_position = -1\n end_position = -1\n orig_answer_text = \"\"\n\n example = SquadExample(\n qas_id=qas_id,\n question_text=question_text,\n doc_tokens=doc_tokens,\n orig_answer_text=orig_answer_text,\n start_position=start_position,\n end_position=end_position,\n is_impossible=is_impossible)\n examples.append(example)\n\n return examples\n\ndef convert_examples_to_features(examples, tokenizer, max_seq_length,\n doc_stride, max_query_length, is_training,\n output_fn):\n \"\"\"Loads a data file into a list of `InputBatch`s.\"\"\"\n\n unique_id = 1000000000\n\n for (example_index, example) in enumerate(examples):\n query_tokens = tokenizer.tokenize(example.question_text)\n\n\n if len(query_tokens) > max_query_length:\n query_tokens = query_tokens[0:max_query_length]\n\n tok_to_orig_index = []\n orig_to_tok_index = []\n all_doc_tokens = []\n for (i, token) in enumerate(example.doc_tokens):\n orig_to_tok_index.append(len(all_doc_tokens))\n sub_tokens = tokenizer.tokenize(token)\n for sub_token in sub_tokens:\n tok_to_orig_index.append(i)\n all_doc_tokens.append(sub_token)\n\n tok_start_position = None\n tok_end_position = None\n if is_training and example.is_impossible:\n tok_start_position = -1\n tok_end_position = -1\n if is_training and not example.is_impossible:\n tok_start_position = orig_to_tok_index[example.start_position]\n if example.end_position < len(example.doc_tokens) - 1:\n tok_end_position = orig_to_tok_index[example.end_position + 1] - 1\n else:\n tok_end_position = len(all_doc_tokens) - 1\n (tok_start_position, tok_end_position) = _improve_answer_span(\n all_doc_tokens, tok_start_position, tok_end_position, tokenizer,\n example.orig_answer_text)\n\n # The -3 accounts for [CLS], [SEP] and [SEP]\n max_tokens_for_doc = max_seq_length - len(query_tokens) - 3\n\n # We can have documents that are longer than the maximum sequence length.\n # To deal with this we do a sliding window approach, where we take chunks\n # of the up to our max length with a stride of `doc_stride`.\n _DocSpan = collections.namedtuple( # pylint: disable=invalid-name\n \"DocSpan\", [\"start\", \"length\"])\n doc_spans = []\n start_offset = 0\n while start_offset < len(all_doc_tokens):\n length = len(all_doc_tokens) - start_offset\n if length > max_tokens_for_doc:\n length = max_tokens_for_doc\n doc_spans.append(_DocSpan(start=start_offset, length=length))\n if start_offset + length == len(all_doc_tokens):\n break\n start_offset += min(length, doc_stride)\n\n for (doc_span_index, doc_span) in enumerate(doc_spans):\n tokens = []\n token_to_orig_map = {}\n token_is_max_context = {}\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in query_tokens:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n for i in range(doc_span.length):\n split_token_index = doc_span.start + i\n token_to_orig_map[len(tokens)] = tok_to_orig_index[split_token_index]\n\n is_max_context = _check_is_max_context(doc_spans, doc_span_index,\n split_token_index)\n token_is_max_context[len(tokens)] = is_max_context\n tokens.append(all_doc_tokens[split_token_index])\n segment_ids.append(1)\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n start_position = None\n end_position = None\n if is_training and not example.is_impossible:\n # For training, if our document chunk does not contain an annotation\n # we throw it out, since there is nothing to predict.\n doc_start = doc_span.start\n doc_end = doc_span.start + doc_span.length - 1\n out_of_span = False\n if not (tok_start_position >= doc_start and\n tok_end_position <= doc_end):\n out_of_span = True\n if out_of_span:\n start_position = 0\n end_position = 0\n else:\n doc_offset = len(query_tokens) + 2\n start_position = tok_start_position - doc_start + doc_offset\n end_position = tok_end_position - doc_start + doc_offset\n\n if is_training and example.is_impossible:\n start_position = 0\n end_position = 0\n ''' \n if example_index < 10:\n tf.logging.info(\"*** Example ***\")\n tf.logging.info(\"unique_id: %s\" % (unique_id))\n tf.logging.info(\"example_index: %s\" % (example_index))\n tf.logging.info(\"doc_span_index: %s\" % (doc_span_index))\n tf.logging.info(\"tokens: %s\" % \" \".join(\n [tokenization.printable_text(x) for x in tokens]))\n tf.logging.info(\"token_to_orig_map: %s\" % \" \".join(\n [\"%d:%d\" % (x, y) for (x, y) in six.iteritems(token_to_orig_map)]))\n tf.logging.info(\"token_is_max_context: %s\" % \" \".join([\n \"%d:%s\" % (x, y) for (x, y) in six.iteritems(token_is_max_context)\n ]))\n tf.logging.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n tf.logging.info(\n \"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n tf.logging.info(\n \"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\n if is_training and example.is_impossible:\n tf.logging.info(\"impossible example\")\n if is_training and not example.is_impossible:\n answer_text = \" \".join(tokens[start_position:(end_position + 1)])\n tf.logging.info(\"start_position: %d\" % (start_position))\n tf.logging.info(\"end_position: %d\" % (end_position))\n tf.logging.info(\n \"answer: %s\" % (tokenization.printable_text(answer_text)))\n '''\n\n feature = InputFeatures(\n unique_id=unique_id,\n example_index=example_index,\n doc_span_index=doc_span_index,\n tokens=tokens,\n token_to_orig_map=token_to_orig_map,\n token_is_max_context=token_is_max_context,\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n start_position=start_position,\n end_position=end_position,\n is_impossible=example.is_impossible)\n\n # Run callback\n output_fn(feature)\n\n unique_id += 1\n\n\ndef _improve_answer_span(doc_tokens, input_start, input_end, tokenizer,\n orig_answer_text):\n \"\"\"Returns tokenized answer spans that better match the annotated answer.\"\"\"\n\n # The SQuAD annotations are character based. We first project them to\n # whitespace-tokenized words. But then after WordPiece tokenization, we can\n # often find a \"better match\". For example:\n #\n # Question: What year was John Smith born?\n # Context: The leader was John Smith (1895-1943).\n # Answer: 1895\n #\n # The original whitespace-tokenized answer will be \"(1895-1943).\". However\n # after tokenization, our tokens will be \"( 1895 - 1943 ) .\". So we can match\n # the exact answer, 1895.\n #\n # However, this is not always possible. Consider the following:\n #\n # Question: What country is the top exporter of electornics?\n # Context: The Japanese electronics industry is the lagest in the world.\n # Answer: Japan\n #\n # In this case, the annotator chose \"Japan\" as a character sub-span of\n # the word \"Japanese\". Since our WordPiece tokenizer does not split\n # \"Japanese\", we just use \"Japanese\" as the annotation. This is fairly rare\n # in SQuAD, but does happen.\n tok_answer_text = \" \".join(tokenizer.tokenize(orig_answer_text))\n\n for new_start in range(input_start, input_end + 1):\n for new_end in range(input_end, new_start - 1, -1):\n text_span = \" \".join(doc_tokens[new_start:(new_end + 1)])\n if text_span == tok_answer_text:\n return (new_start, new_end)\n\n return (input_start, input_end)\n\n\ndef _check_is_max_context(doc_spans, cur_span_index, position):\n \"\"\"Check if this is the 'max context' doc span for the token.\"\"\"\n\n # Because of the sliding window approach taken to scoring documents, a single\n # token can appear in multiple documents. E.g.\n # Doc: the man went to the store and bought a gallon of milk\n # Span A: the man went to the\n # Span B: to the store and bought\n # Span C: and bought a gallon of\n # ...\n #\n # Now the word 'bought' will have two scores from spans B and C. We only\n # want to consider the score with \"maximum context\", which we define as\n # the *minimum* of its left and right context (the *sum* of left and\n # right context will always be the same, of course).\n #\n # In the example the maximum context for 'bought' would be span C since\n # it has 1 left context and 3 right context, while span B has 4 left context\n # and 0 right context.\n best_score = None\n best_span_index = None\n for (span_index, doc_span) in enumerate(doc_spans):\n end = doc_span.start + doc_span.length - 1\n if position < doc_span.start:\n continue\n if position > end:\n continue\n num_left_context = position - doc_span.start\n num_right_context = end - position\n score = min(num_left_context, num_right_context) + 0.01 * doc_span.length\n if best_score is None or score > best_score:\n best_score = score\n best_span_index = span_index\n\n return cur_span_index == best_span_index\n\n\ndef create_model(bert_config, is_training, input_ids, input_mask, segment_ids,\n use_one_hot_embeddings):\n \"\"\"Creates a classification model.\"\"\"\n model = modeling.BertModel(\n config=bert_config,\n is_training=is_training,\n input_ids=input_ids,\n input_mask=input_mask,\n token_type_ids=segment_ids,\n use_one_hot_embeddings=use_one_hot_embeddings)\n\n final_hidden = model.get_sequence_output()\n\n final_hidden_shape = modeling.get_shape_list(final_hidden, expected_rank=3)\n batch_size = final_hidden_shape[0]\n seq_length = final_hidden_shape[1]\n hidden_size = final_hidden_shape[2]\n\n output_weights = tf.get_variable(\n \"cls/squad/output_weights\", [2, hidden_size],\n initializer=tf.truncated_normal_initializer(stddev=0.02))\n\n output_bias = tf.get_variable(\n \"cls/squad/output_bias\", [2], initializer=tf.zeros_initializer())\n\n final_hidden_matrix = tf.reshape(final_hidden,\n [batch_size * seq_length, hidden_size])\n logits = tf.matmul(final_hidden_matrix, output_weights, transpose_b=True)\n logits = tf.nn.bias_add(logits, output_bias)\n\n logits = tf.reshape(logits, [batch_size, seq_length, 2])\n logits = tf.transpose(logits, [2, 0, 1])\n\n unstacked_logits = tf.unstack(logits, axis=0)\n\n (start_logits, end_logits) = (unstacked_logits[0], unstacked_logits[1])\n\n return (start_logits, end_logits)\n\n\ndef model_fn_builder(bert_config, init_checkpoint, learning_rate,\n num_train_steps, num_warmup_steps, use_tpu,\n use_one_hot_embeddings):\n \"\"\"Returns `model_fn` closure for TPUEstimator.\"\"\"\n\n def model_fn(features, labels, mode, params): # pylint: disable=unused-argument\n \"\"\"The `model_fn` for TPUEstimator.\"\"\"\n\n\n unique_ids = features[\"unique_ids\"]\n input_ids = features[\"input_ids\"]\n input_mask = features[\"input_mask\"]\n segment_ids = features[\"segment_ids\"]\n\n is_training = (mode == tf.estimator.ModeKeys.TRAIN)\n\n (start_logits, end_logits) = create_model(\n bert_config=bert_config,\n is_training=is_training,\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n use_one_hot_embeddings=use_one_hot_embeddings)\n\n tvars = tf.trainable_variables()\n\n initialized_variable_names = {}\n scaffold_fn = None\n if init_checkpoint:\n (assignment_map, initialized_variable_names\n ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)\n if use_tpu:\n\n def tpu_scaffold():\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\n return tf.train.Scaffold()\n\n scaffold_fn = tpu_scaffold\n else:\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\n\n\n for var in tvars:\n init_string = \"\"\n if var.name in initialized_variable_names:\n init_string = \", *INIT_FROM_CKPT*\"\n\n\n output_spec = None\n if mode == tf.estimator.ModeKeys.TRAIN:\n seq_length = modeling.get_shape_list(input_ids)[1]\n\n def compute_loss(logits, positions):\n one_hot_positions = tf.one_hot(\n positions, depth=seq_length, dtype=tf.float32)\n log_probs = tf.nn.log_softmax(logits, axis=-1)\n loss = -tf.reduce_mean(\n tf.reduce_sum(one_hot_positions * log_probs, axis=-1))\n return loss\n\n start_positions = features[\"start_positions\"]\n end_positions = features[\"end_positions\"]\n\n start_loss = compute_loss(start_logits, start_positions)\n end_loss = compute_loss(end_logits, end_positions)\n\n total_loss = (start_loss + end_loss) / 2.0\n\n train_op = optimization.create_optimizer(\n total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)\n\n output_spec = tf.contrib.tpu.TPUEstimatorSpec(\n mode=mode,\n loss=total_loss,\n train_op=train_op,\n scaffold_fn=scaffold_fn)\n elif mode == tf.estimator.ModeKeys.PREDICT:\n predictions = {\n \"unique_ids\": unique_ids,\n \"start_logits\": start_logits,\n \"end_logits\": end_logits,\n }\n output_spec = tf.contrib.tpu.TPUEstimatorSpec(\n mode=mode, predictions=predictions, scaffold_fn=scaffold_fn)\n else:\n raise ValueError(\n \"Only TRAIN and PREDICT modes are supported: %s\" % (mode))\n\n return output_spec\n\n return model_fn\n\n\ndef input_fn_builder(input_file, seq_length, is_training, drop_remainder):\n \"\"\"Creates an `input_fn` closure to be passed to TPUEstimator.\"\"\"\n\n name_to_features = {\n \"unique_ids\": tf.FixedLenFeature([], tf.int64),\n \"input_ids\": tf.FixedLenFeature([seq_length], tf.int64),\n \"input_mask\": tf.FixedLenFeature([seq_length], tf.int64),\n \"segment_ids\": tf.FixedLenFeature([seq_length], tf.int64),\n }\n\n if is_training:\n name_to_features[\"start_positions\"] = tf.FixedLenFeature([], tf.int64)\n name_to_features[\"end_positions\"] = tf.FixedLenFeature([], tf.int64)\n\n def _decode_record(record, name_to_features):\n \"\"\"Decodes a record to a TensorFlow example.\"\"\"\n example = tf.parse_single_example(record, name_to_features)\n\n # tf.Example only supports tf.int64, but the TPU only supports tf.int32.\n # So cast all int64 to int32.\n for name in list(example.keys()):\n t = example[name]\n if t.dtype == tf.int64:\n t = tf.to_int32(t)\n example[name] = t\n\n return example\n\n def input_fn(params):\n \"\"\"The actual input function.\"\"\"\n batch_size = params[\"batch_size\"]\n\n # For training, we want a lot of parallel reading and shuffling.\n # For eval, we want no shuffling and parallel reading doesn't matter.\n d = tf.data.TFRecordDataset(input_file)\n if is_training:\n d = d.repeat()\n d = d.shuffle(buffer_size=100)\n\n d = d.apply(\n tf.data.experimental.map_and_batch(\n lambda record: _decode_record(record, name_to_features),\n batch_size=batch_size,\n drop_remainder=drop_remainder))\n\n return d\n\n return input_fn\n\n\nRawResult = collections.namedtuple(\"RawResult\",\n [\"unique_id\", \"start_logits\", \"end_logits\"])\n\n\ndef write_predictions(all_examples, all_features, all_results, n_best_size,\n max_answer_length, do_lower_case,client\n ):\n \"\"\"Write final predictions to the json file and log-odds of null if needed.\"\"\"\n global ranker\n '''\n tf.logging.info(\"Writing predictions to: %s\" % (output_prediction_file))\n tf.logging.info(\"Writing nbest to: %s\" % (output_nbest_file))\n tf.logging.info(\"Writing Aten predic to: %s\" % (output_Aten_predict_file)) \n '''\n\n example_index_to_features = collections.defaultdict(list)\n for feature in all_features:\n example_index_to_features[feature.example_index].append(feature)\n\n unique_id_to_result = {}\n tf.logging.info(\"length of all_results: %d\" % (len(all_results)))\n for result in all_results:\n unique_id_to_result[result.unique_id] = result\n\n _PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name\n \"PrelimPrediction\",\n [\"feature_index\", \"start_index\", \"end_index\", \"start_logit\", \"end_logit\"])\n\n\n # Willy Addd collections -> for results\n #------------------------------------------------------------------------------- \n _AllPredictions = collections.namedtuple( # pylint: disable=invalid-name\n \"AllPredictions\",\n [\"question\", \"PredictListOneQues\"]) \n\n _AllPredictResultsInOneQuestion = collections.namedtuple( # pylint: disable=invalid-name\n \"AllPredictResultsInOneQuestion\",\n [\"doc_text\", \"doc_id\", \"doc_score\", \"PredictListOneDoc\"])\n\n _AllPredictResultsInOneDocument = collections.namedtuple( # pylint: disable=invalid-name\n \"AllPredictResultsInOneDocument\",\n [\"answer\", \"prob\", \"start\", \"end\"]) \n\n \n \n _FinalResult = collections.namedtuple( # pylint: disable=invalid-name\n \"FinalResult\",\n [\"question\", \"text\", \"text_id\", \"ans\", \"prob\"])\n _FinalResult2 = collections.namedtuple( # pylint: disable=invalid-name\n \"FinalResult2\",\n [\"question\", \"text\", \"ans\", \"prob\"])\n _FinalResult3 = collections.namedtuple( # pylint: disable=invalid-name\n \"FinalResult3\",\n [\"question\", \"text\", \"ans\", \"ans_prob\", \"TFIDF\", \"Score\", \"choice\"]) \n _FinalResultAll = collections.namedtuple( # pylint: disable=invalid-name\n \"FinalResultAll\",\n [\"question\", \"text1\", \"ans1\", \"ans_prob1\", \"TFIDF1\", \"Score1\", \"text2\", \"ans2\", \"ans_prob2\", \"TFIDF2\", \"Score2\", \"choice\"]) \n\n _TempAllpredict_Layer1 = collections.namedtuple( # pylint: disable=invalid-name \n \"TempAllpredict_Layer1\",\n [\"question\" , \"TempAllpredictList_Layer2\"]) \n\n _TempAllpredict_Layer2 = collections.namedtuple( # pylint: disable=invalid-name \n \"TempAllpredict_Layer2\",\n [\"doc_id\",\"doc_text\",\"best_ans\",\"best_prob\"])\n #-------------------------------------------------------------------------------\n\n all_predictions = collections.OrderedDict()\n all_nbest_json = collections.OrderedDict()\n scores_diff_json = collections.OrderedDict()\n \n \n all_predicts = []\n all_predictsInOneQues = []\n quesList = []\n Aten_result_list = []\n Aten_result3_list = []\n TempAllpredictLayer1_list = []\n TempAllpredictLayer2_list = []\n best_answer=\"\"\n best_prob=0.0\n ans_is_null = True\n \n #ranker = retriever.get_class('tfidf')(tfidf_path=FLAGS.retriever_model)\n for (example_index, example) in enumerate(all_examples):\n features = example_index_to_features[example_index] \n \n if example_in_write_predictions == 1:\n print (\"example idx:%d\" %example_index)\n print(\"question in example from predict\")\n print(example.question_text)\n print(\"doc_tokens in example from predict\")\n print(example.doc_tokens)\n print('-'*60)\n print('\\n') \n \n \n doc_names, doc_scores = ranker.closest_docs( example.question_text, 10 ) \n \n prelim_predictions = [] \n \n # keep track of the minimum score of null start+end of position 0\n score_null = 1000000 # large and positive\n min_null_feature_index = 0 # the paragraph slice with min mull score\n null_start_logit = 0 # the start logit at the slice with min null score\n null_end_logit = 0 # the end logit at the slice with min null score\n for (feature_index, feature) in enumerate(features):\n \n result = unique_id_to_result[feature.unique_id]\n start_indexes = _get_best_indexes(result.start_logits, n_best_size)\n end_indexes = _get_best_indexes(result.end_logits, n_best_size)\n \n # if we could have irrelevant answers, get the min score of irrelevant\n if FLAGS.version_2_with_negative:\n feature_null_score = result.start_logits[0] + result.end_logits[0]\n if feature_null_score < score_null:\n score_null = feature_null_score\n min_null_feature_index = feature_index\n null_start_logit = result.start_logits[0]\n null_end_logit = result.end_logits[0]\n for start_index in start_indexes:\n for end_index in end_indexes:\n # We could hypothetically create invalid predictions, e.g., predict\n # that the start of the span is in the question. We throw out all\n # invalid predictions.\n if start_index >= len(feature.tokens):\n continue\n if end_index >= len(feature.tokens):\n continue\n if start_index not in feature.token_to_orig_map:\n continue\n if end_index not in feature.token_to_orig_map:\n continue\n if not feature.token_is_max_context.get(start_index, False):\n continue\n if end_index < start_index:\n continue\n length = end_index - start_index + 1\n if length > max_answer_length:\n continue\n prelim_predictions.append(\n _PrelimPrediction(\n feature_index=feature_index,\n start_index=start_index,\n end_index=end_index,\n start_logit=result.start_logits[start_index],\n end_logit=result.end_logits[end_index]))\n \n \n if FLAGS.version_2_with_negative:\n prelim_predictions.append(\n _PrelimPrediction(\n feature_index=min_null_feature_index,\n start_index=0,\n end_index=0,\n start_logit=null_start_logit,\n end_logit=null_end_logit)) \n \n \n prelim_predictions = sorted(\n prelim_predictions,\n key=lambda x: (x.start_logit + x.end_logit),\n reverse=True)\n\n _NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name\n \"NbestPrediction\", [\"text\", \"start_logit\", \"end_logit\"])\n \n\n seen_predictions = {}\n nbest = []\n \n for pred in prelim_predictions:\n if len(nbest) >= n_best_size:\n break\n feature = features[pred.feature_index]\n if pred.start_index > 0: # this is a non-null prediction\n tok_tokens = feature.tokens[pred.start_index:(pred.end_index + 1)]\n orig_doc_start = feature.token_to_orig_map[pred.start_index]\n orig_doc_end = feature.token_to_orig_map[pred.end_index]\n orig_tokens = example.doc_tokens[orig_doc_start:(orig_doc_end + 1)]\n tok_text = \" \".join(tok_tokens)\n\n # De-tokenize WordPieces that have been split off.\n tok_text = tok_text.replace(\" ##\", \"\")\n tok_text = tok_text.replace(\"##\", \"\")\n\n # Clean whitespace\n tok_text = tok_text.strip()\n tok_text = \" \".join(tok_text.split())\n orig_text = \" \".join(orig_tokens)\n\n final_text = get_final_text(tok_text, orig_text, do_lower_case)\n \n if final_text in seen_predictions:\n continue \n seen_predictions[final_text] = True \n \n else:\n final_text = \"\"\n seen_predictions[final_text] = True\n \n nbest.append(\n _NbestPrediction(\n text=final_text,\n start_logit=pred.start_logit,\n end_logit=pred.end_logit)) \n\n\n # if we didn't inlude the empty option in the n-best, inlcude it\n if FLAGS.version_2_with_negative:\n if \"\" not in seen_predictions:\n nbest.append(\n _NbestPrediction(\n text=\"\", start_logit=null_start_logit,\n end_logit=null_end_logit))\n \n # In very rare edge cases we could have no valid predictions. So we\n # just create a nonce prediction in this case to avoid failure.\n if not nbest:\n nbest.append(\n _NbestPrediction(text=\"empty\", start_logit=0.0, end_logit=0.0))\n\n assert len(nbest) >= 1\n \n total_scores = []\n best_non_null_entry = None\n for entry in nbest:\n total_scores.append(entry.start_logit + entry.end_logit)\n if not best_non_null_entry:\n if entry.text:\n best_non_null_entry = entry\n\n #參考\n probs = _compute_softmax(total_scores)\n \n nbest_json = []\n for i, entry in enumerate(nbest):\n output = collections.OrderedDict()\n output[\"text\"] = entry.text\n output[\"probability\"] = probs[i]\n output[\"start_logit\"] = entry.start_logit\n output[\"end_logit\"] = entry.end_logit\n nbest_json.append(output)\n\n\n #----------------------------------------------\n # presupposition : Question is in order\n #\"question\", \"PredictResults\"\n if example.question_text not in quesList :\n if len(quesList)!=0 :\n #1. Save to all predicts\n #print('all_predictsInOneQues-')\n #print(all_predictsInOneQues)\n temp = copy.deepcopy(all_predictsInOneQues)\n #print('temp')\n #print(temp)\n all_predicts.append(\n _AllPredictions(\n question=quesList[-1], \n PredictListOneQues=temp\n )\n ) \n #2.TODO : Find the result (move to outside)\n #3. reset all_predictsInOneQues\n all_predictsInOneQues.clear()\n \n #. Add to questList\n quesList.append(example.question_text)\n #---------------------------------------------- \n \n\n # save answer dataset\n #----------------------------------------------\n all_predictsInOneDoc = [] \n #print('go to (1)')\n for i, entry in enumerate(nbest):\n if predict_result_index == 1:\n print(entry)\n if i==2:\n if predict_result_index == 1:\n print('In state 2')\n break\n tp_answer = entry.text \n if i==0 :\n if tp_answer.isspace() or not tp_answer:\n if predict_result_index == 1:\n print('In state 0,tp_ans: %s' %tp_answer)\n continue\n if i == 1 and len(all_predictsInOneDoc)!=0:\n if predict_result_index == 1:\n print('In state 1,tp_ans: %s' %tp_answer)\n break\n if predict_result_index == 1:\n print('In state set pridict. tp_ans: %s' %tp_answer ) \n all_predictsInOneDoc.append(\n _AllPredictResultsInOneDocument(\n answer=entry.text, \n prob=Decimal(probs[i]),\n start = entry.start_logit,\n end = entry.end_logit\n )\n )\n \n #print('go to (2)') \n #----------------------------------------------\n # End of save answer dataset\n if predict_result_index == 1:\n for i, entry in enumerate(all_predictsInOneDoc): \n print('index:%d' %i)\n print(\"answer: %s\" %(entry.answer))\n print(\"prob: %s\" %(entry.prob))\n print(\"start: %s\" %(entry.start))\n print(\"end: %s\" %(entry.end))\n print('\\n')\n print('-'*15)\n print('\\n')\n # append predicts to OneQues\n #print('go to (3)')\n #----------------------------------------------\n tp_docscore = 0.0\n if example.doc_id in doc_names :\n tp_docindex = doc_names.index(example.doc_id)\n tp_docscore = doc_scores [tp_docindex]\n #print('go to (4)')\n \n #print('go to (5)') \n #print('all_predictsInOneQues-in set')\n #print(all_predictsInOneQues) \n all_predictsInOneQues.append(\n _AllPredictResultsInOneQuestion(\n doc_text=example.doc_tokens,\n doc_id=example.doc_id,\n doc_score=tp_docscore,\n PredictListOneDoc=all_predictsInOneDoc\n )\n )\n #print('go to (6)')\n \n #print('all_predictsInOneQues-in set')\n #print(all_predictsInOneQues)\n #---------------------------------------------- \n \n # if example is examples last data\n if example == all_examples[-1] :\n all_predicts.append(\n _AllPredictions(question=example.question_text,PredictListOneQues=all_predictsInOneQues)) \n #---------------------------------------------- \n \n assert len(nbest_json) >= 1\n if not FLAGS.version_2_with_negative:\n all_predictions[example.qas_id] = nbest_json[0][\"text\"]\n else:\n # predict \"\" iff the null score - the score of best non-null > threshold\n if best_non_null_entry == None :\n score_diff = FLAGS.null_score_diff_threshold + 1.0\n else:\n score_diff = score_null - best_non_null_entry.start_logit - (\n best_non_null_entry.end_logit)\n scores_diff_json[example.qas_id] = score_diff\n if score_diff > FLAGS.null_score_diff_threshold:\n all_predictions[example.qas_id] = \"\"\n else:\n all_predictions[example.qas_id] = best_non_null_entry.text\n \n \n all_nbest_json[example.qas_id] = nbest_json \n\n \n #TODO: Find the best answer from Aten collections\n #----------------------------------------------\n ''' \n const_AtenQuest_index = [3,3,3,3,3,3,3,3,3,3,\n 3,3,3,3,3,3,3,3,3,3,\n 4,3,6,5,5,4,5,5,5,4,\n 5,5,3,5,4,5,5,5,5,5,\n 1,1,1,1,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,1] \n const_AtenIntent_index = [1,1,1,0,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,0,1,1,\n 1,1,1,1,1,0,1,1,1,0,\n 1,1,1,1,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,1] \n \n excel_NOtGoodAns_index = [0,0,0,3,0,0,0,0,0,0,\n 0,0,0,0,0,0,0,3,0,0,\n 0,0,3,2,0,4,3,0,2,4,\n 0,0,2,0,3,1,0,2,0,4,\n 0,0,0,0,0,0,0,0,0,0,\n 0,0,0,0,0,0,0,0]\n \n \n excel_count = 0 \n excel_index = 1 \n excel_Answer_count = const_AtenQuest_index[excel_index-1]\n excel_Intent_count = const_AtenIntent_index[excel_index-1]\n excel_NOtGoodAns_count = excel_NOtGoodAns_index[excel_index-1]\n wb = Workbook()\n ws = wb.active\n '''\n retriever_weight = FLAGS.retriever_weight \n\n\n intent_count = 1 \n for i, entry_predicts in enumerate(all_predicts):\n tp_ques = entry_predicts.question \n QuesList = entry_predicts.PredictListOneQues \n #print(\"ques: %s\" %(tp_ques))\n\n # set score only with bert , TF-IDF used to be choice doc.\n #----------------------------------------------\n QuesList.sort(key=TakeThird, reverse=True) \n #print('len with QuesList:%d' %len(QuesList))\n\n tp_text1 = QuesList[0].doc_text\n text1=\"\" \n for word in tp_text1:\n text1= text1 + \" \" + word \n ans1=\"\"\n ans1_prob = 0.0\n TFIDF1 = QuesList[0].doc_score\n Score1 = 0.0 \n\n entry_OneDoc = QuesList [0].PredictListOneDoc\n if len(entry_OneDoc) != 0 :\n ans1 = entry_OneDoc[0].answer\n ans1_prob = entry_OneDoc[0].prob\n \n for k, entry_OneAns in enumerate(entry_OneDoc):\n #print('index:%d' %k)\n tp_ans1_prob = Decimal(entry_OneAns.prob)\n if tp_ans1_prob > ans1_prob: \n ans1_prob = tp_ans1_prob\n ans1 = entry_OneAns.answer\n #print('Ans_ans:%s' %(entry_OneAns.answer))\n #print('Ans_prob:%e , start:%e , end:%e' %(entry_OneAns.prob , entry_OneAns.start , entry_OneAns.end))\n Score1 = ans1_prob \n #---------------------------------------------- \n \n\n # set score with bert and TF-IDF\n #----------------------------------------------\n \n text2=\"\" \n ans2=\"\"\n ans2_prob = 0.0\n TFIDF2 = 0.0\n Score2 = 0.0 \n \n for j , entry_OneDoc in enumerate(QuesList):\n tp_TFIDF2 = entry_OneDoc.doc_score\n tp_text2=\"\"\n for word in entry_OneDoc.doc_text:\n tp_text2 = tp_text2 + \" \" + word\n \n DocList = []\n DocList = entry_OneDoc.PredictListOneDoc\n for k, entry_OneAns in enumerate(DocList):\n tp_ans2_prob = Decimal(entry_OneAns.prob)\n tp_Score2 = Decimal(retriever_weight)*Decimal(tp_TFIDF2) + Decimal(1.0-retriever_weight)*Decimal(tp_ans2_prob)\n if tp_Score2>Score2:\n text2=tp_text2\n ans2=entry_OneAns.answer\n ans2_prob=tp_ans2_prob\n TFIDF2=tp_TFIDF2\n Score2 =tp_Score2\n #----------------------------------------------\n \n\n \n fin_text = text1\n fin_ans = ans1\n fin_ans_prob = ans1_prob\n fin_TFIDF = TFIDF1\n fin_Score = Score1\n choice_value = 0\n if TFIDF1<FLAGS.choice_score:\n fin_text = text2\n fin_ans = ans2\n fin_ans_prob = ans2_prob\n fin_TFIDF = TFIDF2 \n fin_Score = Score2\n choice_value = 1\n elif ans2_prob>ans1_prob*2:\n if ans2_prob > FLAGS.threshold_prob_ans_merge:\n fin_text = text2\n fin_ans = ans2\n fin_ans_prob = ans2_prob\n fin_TFIDF = TFIDF2 \n fin_Score = Score2\n choice_value = 1\n elif not ans1:\n fin_text = text2\n fin_ans = ans2\n fin_ans_prob = ans2_prob\n fin_TFIDF = TFIDF2\n fin_Score = Score2\n choice_value = 1\n \n \n if FLAGS.show_all_choice == 0:\n Aten_result3_list.append(\n _FinalResult3(\n question = tp_ques,\n text = fin_text,\n ans = fin_ans,\n ans_prob = fin_ans_prob,\n TFIDF = fin_TFIDF,\n Score = fin_Score,\n choice = choice_value\n )\n )\n else :\n Aten_result3_list.append(\n _FinalResultAll(\n question = tp_ques,\n text1 = text1,\n ans1 = ans1,\n ans_prob1 = ans1_prob,\n TFIDF1 = TFIDF1,\n Score1 = Score1,\n text2 = text2,\n ans2 = ans2,\n ans_prob2 = ans2_prob,\n TFIDF2 = TFIDF2,\n Score2 = Score2,\n choice = choice_value \n )\n ) \n print('ques: %s' %tp_ques)\n \n if FLAGS.show_all_choice==1:\n print('-'*5) \n print('Only Bert (TF-IDF used to be choice document):') \n print('text: %s' %text1)\n print('ans: %s' %ans1)\n print('ans_prob: %s' %ans1_prob)\n print('TFIDF: %s' %TFIDF1)\n print('Score: %s' %Score1)\n print('')\n \n print('-'*5)\n print('Merge TF-IDF:')\n print('text: %s' %text2)\n print('ans: %s' %ans2)\n print('ans_prob: %s' %ans2_prob)\n print('TFIDF: %s' %TFIDF2)\n print('Score: %s' %Score2)\n \n print('-'*5)\n print('My Choice ans(%d):' %choice_value)\n print('text: %s' %fin_text)\n print('ans: %s' %fin_ans)\n print('ans_prob: %s' %fin_ans_prob)\n print('TFIDF: %s' %fin_TFIDF)\n print('Score: %s' %fin_Score)\n\n # ack message to Colab Client\n temp_answer = 'Dr_Answer' + fin_ans + 'Dr_QA' + fin_text + '<AtenEnd>'\n client.send(temp_answer.encode('utf8'))\n '''\n\n print('-'*5)\n \n if excel_Answer_count == excel_count+1 :\n print('-'*15)\n\n print('\\n') \n \n \n if excel_Answer_count == excel_count :\n ws['C' + str(excel_index)] = excel_Answer_count\n ws['D' + str(excel_index)] = excel_NOtGoodAns_count\n ws['F' + str(excel_index)] = excel_Intent_count\n \n excel_index = excel_index+1\n excel_Answer_count = const_AtenQuest_index[excel_index-1] \n excel_NOtGoodAns_count = excel_NOtGoodAns_index[excel_index-1]\n excel_Intent_count = const_AtenIntent_index[excel_index-1] \n excel_count = 0 \n \n if excel_index <= len(const_AtenQuest_index) :\n # print('Set my fin_Score with excel: %s' %fin_Score) \n index_str = chr(73+excel_count) + str(excel_index) \n ws[index_str] = fin_Score\n excel_count = excel_count + 1\n\n\n\n\n ws['A60'] = 'All'\n ws['A61'] = '40QA'\n \n ws['B59'] = 'Right answer'\n ws['B60'] = '=SUM(B1:B40)+SUM(A41:A58)'\n ws['B61'] = '=SUM(B1:B40)'\n\n ws['C59'] = 'All answer'\n ws['C60'] = '=SUM(C1:C58)-SUM(D1:D40)'\n ws['C61'] = '=SUM(C1:C40)-SUM(D1:D40)'\n \n ws['E59'] = 'Right Intent'\n ws['E60'] = '=SUM(E1:E40)+SUM(A41:A58)'\n ws['E61'] = '=SUM(E1:E40)' \n\n ws['F59'] = 'All intent'\n ws['F60'] = '=SUM(F1:F40)+SUM(C41:C58)'\n ws['F61'] = '=SUM(F1:F40)' \n \n \n ws['G59'] = 'answer prob'\n ws['G60'] = '=B60/C60'\n ws['G61'] = '=B61/C61' \n\n ws['H59'] = 'Intent prob'\n ws['H60'] = '=E60/F60'\n ws['H61'] = '=E61/F61' \n \n wb.save(FLAGS.excel_name + '.xlsx')\n print('\\n') \n \n\n \n \n with tf.gfile.GFile(output_Aten_predict_file, \"w\") as writer:\n writer.write(json.dumps(Aten_result3_list, indent=4,cls=DecimalEncoder) + \"\\n\")\n\n with tf.gfile.GFile(output_prediction_file, \"w\") as writer:\n writer.write(json.dumps(all_predictions, indent=4) + \"\\n\")\n\n with tf.gfile.GFile(output_nbest_file, \"w\") as writer:\n writer.write(json.dumps(all_nbest_json, indent=4) + \"\\n\")\n\n if FLAGS.version_2_with_negative:\n with tf.gfile.GFile(output_null_log_odds_file, \"w\") as writer:\n writer.write(json.dumps(scores_diff_json, indent=4) + \"\\n\")\n '''\n\n\ndef get_final_text(pred_text, orig_text, do_lower_case):\n \"\"\"Project the tokenized prediction back to the original text.\"\"\"\n\n # When we created the data, we kept track of the alignment between original\n # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So\n # now `orig_text` contains the span of our original text corresponding to the\n # span that we predicted.\n #\n # However, `orig_text` may contain extra characters that we don't want in\n # our prediction.\n #\n # For example, let's say:\n # pred_text = steve smith\n # orig_text = Steve Smith's\n #\n # We don't want to return `orig_text` because it contains the extra \"'s\".\n #\n # We don't want to return `pred_text` because it's already been normalized\n # (the SQuAD eval script also does punctuation stripping/lower casing but\n # our tokenizer does additional normalization like stripping accent\n # characters).\n #\n # What we really want to return is \"Steve Smith\".\n #\n # Therefore, we have to apply a semi-complicated alignment heruistic between\n # `pred_text` and `orig_text` to get a character-to-charcter alignment. This\n # can fail in certain cases in which case we just return `orig_text`.\n\n def _strip_spaces(text):\n ns_chars = []\n ns_to_s_map = collections.OrderedDict()\n for (i, c) in enumerate(text):\n if c == \" \":\n continue\n ns_to_s_map[len(ns_chars)] = i\n ns_chars.append(c)\n ns_text = \"\".join(ns_chars)\n return (ns_text, ns_to_s_map)\n\n # We first tokenize `orig_text`, strip whitespace from the result\n # and `pred_text`, and check if they are the same length. If they are\n # NOT the same length, the heuristic has failed. If they are the same\n # length, we assume the characters are one-to-one aligned.\n tokenizer = tokenization.BasicTokenizer(do_lower_case=do_lower_case)\n\n tok_text = \" \".join(tokenizer.tokenize(orig_text))\n\n start_position = tok_text.find(pred_text)\n if start_position == -1:\n if FLAGS.verbose_logging:\n tf.logging.info(\n \"Unable to find text: '%s' in '%s'\" % (pred_text, orig_text))\n return orig_text\n end_position = start_position + len(pred_text) - 1\n\n (orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text)\n (tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text)\n\n if len(orig_ns_text) != len(tok_ns_text):\n if FLAGS.verbose_logging:\n tf.logging.info(\"Length not equal after stripping spaces: '%s' vs '%s'\",\n orig_ns_text, tok_ns_text)\n return orig_text\n\n # We then project the characters in `pred_text` back to `orig_text` using\n # the character-to-character alignment.\n tok_s_to_ns_map = {}\n for (i, tok_index) in six.iteritems(tok_ns_to_s_map):\n tok_s_to_ns_map[tok_index] = i\n\n orig_start_position = None\n if start_position in tok_s_to_ns_map:\n ns_start_position = tok_s_to_ns_map[start_position]\n if ns_start_position in orig_ns_to_s_map:\n orig_start_position = orig_ns_to_s_map[ns_start_position]\n\n if orig_start_position is None:\n if FLAGS.verbose_logging:\n tf.logging.info(\"Couldn't map start position\")\n return orig_text\n\n orig_end_position = None\n if end_position in tok_s_to_ns_map:\n ns_end_position = tok_s_to_ns_map[end_position]\n if ns_end_position in orig_ns_to_s_map:\n orig_end_position = orig_ns_to_s_map[ns_end_position]\n\n if orig_end_position is None:\n if FLAGS.verbose_logging:\n tf.logging.info(\"Couldn't map end position\")\n return orig_text\n\n output_text = orig_text[orig_start_position:(orig_end_position + 1)]\n return output_text\n\n\ndef _get_best_indexes(logits, n_best_size):\n \"\"\"Get the n-best logits from a list.\"\"\"\n index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)\n\n best_indexes = []\n for i in range(len(index_and_score)):\n if i >= n_best_size:\n break\n best_indexes.append(index_and_score[i][0])\n return best_indexes\n\n\ndef _compute_softmax(scores):\n \"\"\"Compute softmax probability over raw logits.\"\"\"\n if not scores:\n return []\n\n max_score = None\n for score in scores:\n if max_score is None or score > max_score:\n max_score = score\n\n exp_scores = []\n total_sum = 0.0\n for score in scores:\n x = math.exp(score - max_score)\n exp_scores.append(x)\n total_sum += x\n\n probs = []\n for score in exp_scores:\n probs.append(score / total_sum)\n return probs\n\n\nclass FeatureWriter(object):\n \"\"\"Writes InputFeature to TF example file.\"\"\"\n\n def __init__(self, filename, is_training):\n self.filename = filename\n self.is_training = is_training\n self.num_features = 0\n self._writer = tf.python_io.TFRecordWriter(filename)\n\n def process_feature(self, feature):\n \"\"\"Write a InputFeature to the TFRecordWriter as a tf.train.Example.\"\"\"\n self.num_features += 1\n\n def create_int_feature(values):\n feature = tf.train.Feature(\n int64_list=tf.train.Int64List(value=list(values)))\n return feature\n\n features = collections.OrderedDict()\n features[\"unique_ids\"] = create_int_feature([feature.unique_id])\n features[\"input_ids\"] = create_int_feature(feature.input_ids)\n features[\"input_mask\"] = create_int_feature(feature.input_mask)\n features[\"segment_ids\"] = create_int_feature(feature.segment_ids)\n\n if self.is_training:\n features[\"start_positions\"] = create_int_feature([feature.start_position])\n features[\"end_positions\"] = create_int_feature([feature.end_position])\n impossible = 0\n if feature.is_impossible:\n impossible = 1\n features[\"is_impossible\"] = create_int_feature([impossible])\n\n tf_example = tf.train.Example(features=tf.train.Features(feature=features))\n #print(\"tf_example:\")\n #print(tf_example)\n self._writer.write(tf_example.SerializeToString())\n\n def close(self):\n self._writer.close()\n\n\ndef validate_flags_or_throw(bert_config):\n \"\"\"Validate the input FLAGS or throw an exception.\"\"\"\n tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,\n FLAGS.init_checkpoint)\n\n if not FLAGS.do_train and not FLAGS.do_predict:\n raise ValueError(\"At least one of `do_train` or `do_predict` must be True.\")\n\n if FLAGS.do_train:\n if not FLAGS.train_file:\n raise ValueError(\n \"If `do_train` is True, then `train_file` must be specified.\")\n if FLAGS.do_predict:\n if not FLAGS.predict_file:\n raise ValueError(\n \"If `do_predict` is True, then `predict_file` must be specified.\")\n\n if FLAGS.max_seq_length > bert_config.max_position_embeddings:\n raise ValueError(\n \"Cannot use sequence length %d because the BERT model \"\n \"was only trained up to sequence length %d\" %\n (FLAGS.max_seq_length, bert_config.max_position_embeddings))\n\n if FLAGS.max_seq_length <= FLAGS.max_query_length + 3:\n raise ValueError(\n \"The max_seq_length (%d) must be greater than max_query_length \"\n \"(%d) + 3\" % (FLAGS.max_seq_length, FLAGS.max_query_length))\n \n # Retriever - added by Willy \n if FLAGS.do_retriever:\n if not FLAGS.retriever_model:\n raise ValueError(\"You have to set retriever model(give the path) when you set do_retriever to Yes.\")\n if FLAGS.document_type != 'Sqlite' or FLAGS.db_file == None :\n raise ValueError(\"You have to set document_type to Sqlit and set the db_file when you set do_retriever to Yes.\")\n \n # TODO : think a mechanism to chek these key word\n '''\n if FLAGS.document_type is 'SQlite':\n # TODO: set database\n elif FLAGS.document_type is 'Text':\n # TODO: set text file\n elif FLAGS.document_type is 'SQuAD':\n # is original method\n else :\n raise ValueError(\n \"You have to set correct document_type: (1)'SQlite' (2)'Text' (3)SQuAD.\")\n'''\n\ndef read_squad_documents(input_file):\n \"\"\"Read a SQuAD json file into a list of SquadExample.\"\"\"\n \n with tf.gfile.Open(input_file, \"r\") as reader:\n input_data = json.load(reader)[\"data\"] \n documents = []\n for entry in input_data:\n for paragraph in entry[\"paragraphs\"]:\n documents.append(paragraph[\"context\"])\n \n return documents\n\n\ndef read_sqlite_documents(input_file):\n # TODO\n db_class = retriever.get_class('sqlite')\n with db_class(input_file) as doc_db:\n doc_ids = doc_db.get_doc_ids()\n for ids in doc_ids:\n documents.append(doc_db.get_doc_text(ids))\n doc_db.close()\n\n DOC2IDX = {doc_id: i for i, doc_id in enumerate(doc_ids)}\n return DOC2IDX, documents\n\n\ndef read_text_documents(input_file):\n examples = []\n file = open(input_file, \"r\")\n documents = file.read()\n file.close()\n documents_split = documents.split('\\n')\n documents_final = list(filter(None, documents))\n return documents_final\n\ndef read_squad_question(input_file):\n questions = []\n \"\"\"Read a SQuAD json file into a list of SquadExample.\"\"\"\n with tf.gfile.Open(input_file, \"r\") as reader: \n input_data = json.load(reader)[\"data\"] \n for entry in input_data:\n for paragraph in entry[\"paragraphs\"]:\n for qa in paragraph[\"qas\"]:\n questions.append(qa[\"question\"])\n return questions\n\ndef set_eval_examples(questions, DOC2IDX):\n def is_whitespace(c):\n if c == \" \" or c == \"\\t\" or c == \"\\r\" or c == \"\\n\" or ord(c) == 0x202F:\n return True\n return False\n\n eval_examples = []\n temp_list = []\n for i, DOCID in enumerate(DOC2IDX) :\n temp_list.append(DOCID)\n\n for question in questions:\n #-------------------------questions - Start---------------------------# \n question_text = question\n start_position = -1\n end_position = -1\n orig_answer_text = \"\"\n is_impossible = False\n\n #-------------documents - Start--------------#\n for i , paragraph_text in enumerate(documents):\n paragraph_text = paragraph_text\n #-------paragraphs - Start-------#\n doc_tokens = []\n char_to_word_offset = []\n prev_is_whitespace = True\n for c in paragraph_text:\n if is_whitespace(c):\n prev_is_whitespace = True\n else:\n if prev_is_whitespace:\n doc_tokens.append(c)\n else:\n doc_tokens[-1] += c\n prev_is_whitespace = False\n char_to_word_offset.append(len(doc_tokens) - 1)\n #-------paragraphs - End-------#\n qas_id = str(uuid.uuid1())\n example = SquadExample(\n qas_id=qas_id,\n question_text=question_text,\n doc_id = temp_list[i],\n doc_tokens=doc_tokens,\n orig_answer_text=orig_answer_text,\n start_position=start_position,\n end_position=end_position,\n is_impossible=is_impossible)\n eval_examples.append(example)\n #-------------documents - Start--------------#\n #-------------------------questions - End-----------------------------#\n\n if example_in_set_eval_examples == 1:\n print('len of eval_examples:%d' %len(eval_examples))\n for i, example in enumerate(eval_examples):\n print(i)\n print (example.question_text)\n '''\n for i, example in enumerate(eval_examples):\n print('idx:%d:%s' %(i,example.question_text))\n '''\n return eval_examples\n\n\n\n\nfrom socket import *\nimport sys\nimport threading\nimport time\nfrom time import localtime\n\nimport imp\n\nBUFSIZ = 4096\n\n\nif sys.version[0] == '2':\n imp.reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n\nclass TcpServer():\n def __init__(self,tokenizer,estimator,DOC2IDX):\n self.HOST = FLAGS.Host_TCPServer\n self.PORT = FLAGS.PORT_TCPServer\n self.tokenizer = tokenizer\n self.estimator = estimator\n self.ADDR = (self.HOST,self.PORT)\n\n self.DOC2IDX = DOC2IDX\n\n\n try:\n\n self.STOP_CHAT = False\n\n self.sock = socket(AF_INET, SOCK_STREAM)\n print('%d is open' %self.PORT)\n\n self.sock.bind(self.ADDR)\n self.sock.listen(5)\n # 设置退出条件\n\n # 所有监听的客户端\n self.clients = {}\n self.thrs = {}\n self.stops = []\n\n except Exception as e:\n print(\"%d is down\" %self.PORT)\n return None\n\n def listen_client(self):\n while not self.STOP_CHAT:\n print(u'等待接入,侦听端口:%d' %self.PORT)\n self.tcpClientSock, self.addr = self.sock.accept()\n print(u'接受连接,客户端地址:', self.addr)\n address = self.addr\n # 将建立的client socket链接放到列表self.clients中\n self.clients[address] = self.tcpClientSock\n # 分别将每个建立的链接放入进程中,接收且分发消息\n self.thrs[address] = threading.Thread(target=self.readmsg, args=[address])\n self.thrs[address].start()\n time.sleep(0.5)\n #self.tcpClientSock.send(b'you are connect...')\n print(u'系統結束')\n\n\n\n def readmsg(self, address):\n # 如果地址不存在,则返回False\n if address not in self.clients:\n return False\n # 得到发送消息的client socket\n client = self.clients[address]\n while True:\n try:\n # 获取到消息内容data\n data = client.recv(BUFSIZ)\n except:\n print(error)\n self.close_client(address)\n break\n try:\n temp = data.decode('utf8')\n except:\n print('data is not reasonable :%s' %(str(data)) )\n continue\n # python3使用bytes,所以要进行编码\n # s='%s发送给我的信息是:[%s] %s' %(addr[0],ctime(), data.decode('utf8'))\n # 对日期进行一下格式化\n ISOTIMEFORMAT = '%Y-%m-%d %X'\n stime = time.strftime(ISOTIMEFORMAT, localtime())\n print([address], '@',[stime],':', data.decode('utf8'))\n\n self.STOP_CHAT = (data.decode('utf8').upper() == \"QUIT\")\n\n if self.STOP_CHAT:\n print(\"quit\")\n self.close_client(address)\n print(\"already quit\")\n break\n\n tokenizer = self.tokenizer\n estimator = self.estimator\n DOC2IDX = self.DOC2IDX\n question = data.decode('utf8')\n #print('My question:',question)\n\n\n if FLAGS.do_predict:\n # define\n #---------------------------------------------------\n def append_feature(feature):\n eval_features.append(feature)\n eval_writer.process_feature(feature)\n # ---------------------------------------------------\n # print('WillyTest(1)...do Set question:%s' %(FLAGS.question_type))\n # ---------------------set question , changed by willy---------------------#\n questions = list()\n questions.append(question)\n\n #print('My questions:')\n #print(questions)\n #-------------------------------------------------------------------------#\n\n \n #print('WillyTest(2)...do Set eval_examples')\n eval_examples=set_eval_examples(questions,DOC2IDX)\n\n #print('WillyTest(2.1)...do FeatureWriter')\n eval_writer = FeatureWriter(\n filename=os.path.join(FLAGS.output_dir, \"eval.tf_record\"),\n is_training=False\n )\n eval_features = []\n\n #print('WillyTest(2.2)...do convert_examples_to_features')\n convert_examples_to_features(\n examples=eval_examples,\n tokenizer=tokenizer,\n max_seq_length=FLAGS.max_seq_length,\n doc_stride=FLAGS.doc_stride,\n max_query_length=FLAGS.max_query_length,\n is_training=False,\n output_fn=append_feature\n )\n eval_writer.close()\n tf.logging.info(\"***** Running predictions *****\")\n tf.logging.info(\" Num orig examples = %d\", len(eval_examples))\n tf.logging.info(\" Num split examples = %d\", len(eval_features))\n tf.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size)\n\n print('WillyTest(5)...before redict_input_fn = input_fn_builder: eval_writer.filename=%s, FLAGS.max_seq_length=%d' %(eval_writer.filename,FLAGS.max_seq_length))\n\n predict_input_fn = input_fn_builder(\n input_file=eval_writer.filename,\n seq_length=FLAGS.max_seq_length,\n is_training=False,\n drop_remainder=False\n )\n all_results = []\n print('WillyTest(6)...before estimator predict')\n for result in estimator.predict(predict_input_fn, yield_single_examples=True):\n if len(all_results) % 1000 == 0:\n tf.logging.info(\"Processing example: %d\" % (len(all_results)))\n unique_id = int(result[\"unique_ids\"])\n start_logits = [float(x) for x in result[\"start_logits\"].flat]\n end_logits = [float(x) for x in result[\"end_logits\"].flat]\n all_results.append(RawResult(unique_id=unique_id,start_logits=start_logits,end_logits=end_logits))\n\n\n print('WillyTest(8)...before write_predictions')\n write_predictions(\n eval_examples, eval_features, all_results,\n FLAGS.n_best_size, FLAGS.max_answer_length,\n FLAGS.do_lower_case,client\n )\n '''\n output_prediction_file = os.path.join(FLAGS.output_dir, \"predictions.json\")\n output_nbest_file = os.path.join(FLAGS.output_dir, \"nbest_predictions.json\")\n output_null_log_odds_file = os.path.join(FLAGS.output_dir, \"null_odds.json\")\n output_Aten_predict_file = os.path.join(FLAGS.output_dir, \"Aten_predicts.json\")\n\n print('WillyTest(8)...before write_predictions')\n write_predictions(\n eval_examples, eval_features, all_results,\n FLAGS.n_best_size, FLAGS.max_answer_length,\n FLAGS.do_lower_case, output_prediction_file,\n output_nbest_file, output_null_log_odds_file,\n output_Aten_predict_file,client\n )\n '''\n\n\n\n\n\n\n\n def close_client(self, address):\n try:\n '''\n print(u'try leave')\n client = self.clients.pop(address)\n print(u'try leave1')\n self.stops.append(address)\n print(u'try leave2')\n client.close()\n print(u'try leave3')\n '''\n for k in self.clients:\n print(u'try leave')\n print(u'try client1:', [self.clients[k]])\n print(u'try client2:', [self.clients[address]])\n print(u'try client3:', [k])\n print(u'try client4:', [address])\n client = self.clients.pop(k)\n #print(u'try leave1')\n #self.stops.append(k)\n print(u'try leave2')\n client.close()\n print(u'try leave3')\n '''\n print(u'try leave4:client:',[self.clients[k]])\n self.clients[k].send(str(address) + u\"已经离开了\")\n '''\n except:\n print(u'try fault')\n pass\n print(str(address) + u'已经退出')\n \n\n\n\ndef main(_):\n global ranker\n tf.logging.set_verbosity(tf.logging.INFO)\n print(willy_check_code)\n \n bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)\n\n validate_flags_or_throw(bert_config)\n\n tf.gfile.MakeDirs(FLAGS.output_dir)\n\n tokenizer = tokenization.FullTokenizer(\n vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)\n\n tpu_cluster_resolver = None\n if FLAGS.use_tpu and FLAGS.tpu_name:\n tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(\n FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)\n\n is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2\n run_config = tf.contrib.tpu.RunConfig(\n cluster=tpu_cluster_resolver,\n master=FLAGS.master,\n model_dir=FLAGS.output_dir,\n save_checkpoints_steps=FLAGS.save_checkpoints_steps,\n tpu_config=tf.contrib.tpu.TPUConfig(\n iterations_per_loop=FLAGS.iterations_per_loop,\n num_shards=FLAGS.num_tpu_cores,\n per_host_input_for_training=is_per_host))\n\n train_examples = None\n num_train_steps = None\n num_warmup_steps = None\n \n\n\n model_fn = model_fn_builder(\n bert_config=bert_config,\n init_checkpoint=FLAGS.init_checkpoint,\n learning_rate=FLAGS.learning_rate,\n num_train_steps=num_train_steps,\n num_warmup_steps=num_warmup_steps,\n use_tpu=FLAGS.use_tpu,\n use_one_hot_embeddings=FLAGS.use_tpu)\n\n if FLAGS.do_retriever:\n # Set Document\n # ------------------------------------------------------\n print('WillyTest...do SQlite')\n DOC2IDX, docments = read_sqlite_documents(input_file=FLAGS.db_file)\n # ------------------------------------------------------\n else:\n # Set Document\n tf.logging.info(\"my document_type is %s\", FLAGS.document_type)\n if FLAGS.document_type is 'Text':\n # TODO\n print('WillyTest...do Text')\n docments = read_text_documents(input_file=FLAGS.predict_file)\n\n elif FLAGS.document_type is 'SQuAD':\n # TODO\n print('WillyTest...do SQuAD')\n docments = read_squad_documents(input_file=FLAGS.predict_file)\n\n # else:\n # #raise ValueError(\"Your document_type: %s is undefined or wrong, please reset it.\" %(FLAGS.document_type))\n\n # If TPU is not available, this will fall back to normal Estimator on CPU\n # or GPU.\n estimator = tf.contrib.tpu.TPUEstimator(\n use_tpu=FLAGS.use_tpu,\n model_fn=model_fn,\n config=run_config,\n train_batch_size=FLAGS.train_batch_size,\n predict_batch_size=FLAGS.predict_batch_size)\n\n print(\"do tcp server\")\n ranker = retriever.get_class('tfidf')(tfidf_path=FLAGS.retriever_model)\n tserver = None\n tserver = TcpServer(tokenizer,estimator,DOC2IDX)\n while tserver == None:\n tserver = TcpServer( tokenizer,estimator,DOC2IDX)\n print(\"do tcp server-listen\")\n tserver.listen_client()\n \n\n\n\n\nif __name__ == \"__main__\":\n flags.mark_flag_as_required(\"vocab_file\")\n flags.mark_flag_as_required(\"bert_config_file\")\n flags.mark_flag_as_required(\"output_dir\")\n tf.app.run()\n",
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team 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\"\"\"Run BERT on SQuAD 1.1 and SQuAD 2.0.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport json\nimport math\nimport os, types\nimport random\nimport modeling\nimport optimization\nimport tokenization\nimport six\nimport copy\nimport tensorflow as tf\nimport numpy as np\nimport scipy.sparse as sp\n\n# do excel\nfrom openpyxl import Workbook\n\n\nimport uuid\n\n# do \nimport code\nimport prettytable\n\nfrom decimal import *\nimport decimal\ngetcontext().prec = 50\n\n#Willy Define\nexample_in_set_eval_examples = 0\nexample_in_write_predictions = 1\npredict_result_index = 0\ncheckState_in_AtenResult = 0\ncheckState_in_AtenResult2 = 0\ncheckState_in_GetAnswer = 0\ncheckState_add_retriever = 0\nwilly_check_code = \"willy test on 201907101548\"\n\nfrom drqa import retriever\n\nDOC2IDX = None\ndocuments = []\ndb_class = retriever.get_class('sqlite')\n\n\n\nflags = tf.flags\n\nFLAGS = flags.FLAGS\n\n## Required parameters\nflags.DEFINE_string(\n \"bert_config_file\", None,\n \"The config json file corresponding to the pre-trained BERT model. \"\n \"This specifies the model architecture.\")\n\nflags.DEFINE_string(\"vocab_file\", None,\n \"The vocabulary file that the BERT model was trained on.\")\n\nflags.DEFINE_string(\n \"output_dir\", None,\n \"The output directory where the model checkpoints will be written.\")\n\n## Other parameters\nflags.DEFINE_string(\"train_file\", None,\n \"SQuAD json for training. E.g., train-v1.1.json\")\n\nflags.DEFINE_string(\n \"predict_file\", None,\n \"SQuAD json for predictions. E.g., dev-v1.1.json or test-v1.1.json\")\n\nflags.DEFINE_string(\n \"init_checkpoint\", None,\n \"Initial checkpoint (usually from a pre-trained BERT model).\")\n\nflags.DEFINE_bool(\n \"do_lower_case\", True,\n \"Whether to lower case the input text. Should be True for uncased \"\n \"models and False for cased models.\")\n\nflags.DEFINE_integer(\n \"max_seq_length\", 384,\n \"The maximum total input sequence length after WordPido_interactiveece tokenization. \"\n \"Sequences longer than this will be truncated, and sequences shorter \"\n \"than this will be padded.\")\n\nflags.DEFINE_integer(\n \"doc_stride\", 128,\n \"When splitting up a long document into chunks, how much stride to \"\n \"take between chunks.\")\n\nflags.DEFINE_integer(\n \"max_query_length\", 64,\n \"The maximum number of tokens for the question. Questions longer than \"\n \"this will be truncated to this length.\")\n\nflags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\")\n\nflags.DEFINE_bool(\"do_predict\", False, \"Whether to run eval on the dev set.\")\n\nflags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\")\n\nflags.DEFINE_integer(\"predict_batch_size\", 8,\n \"Total batch size for predictions.\")\n\nflags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for Adam.\")\n\nflags.DEFINE_float(\"num_train_epochs\", 3.0,\n \"Total number of training epochs to perform.\")\n\nflags.DEFINE_float(\n \"warmup_proportion\", 0.1,\n \"Proportion of training to perform linear learning rate warmup for. \"\n \"E.g., 0.1 = 10% of training.\")\n\nflags.DEFINE_integer(\"save_checkpoints_steps\", 1000,\n \"How often to save the model checkpoint.\")\n\nflags.DEFINE_integer(\"iterations_per_loop\", 1000,\n \"How many steps to make in each estimator call.\")\n\nflags.DEFINE_integer(\n \"n_best_size\", 20,\n \"The total number of n-best predictions to generate in the \"\n \"nbest_predictions.json output file.\")\n\nflags.DEFINE_integer(\n \"max_answer_length\", 30,\n \"The maximum length of an answer that can be generated. This is needed \"\n \"because the start and end predictions are not conditioned on one another.\")\n\nflags.DEFINE_bool(\"use_tpu\", False, \"Whether to use TPU or GPU/CPU.\")\n\ntf.flags.DEFINE_string(\n \"tpu_name\", None,\n \"The Cloud TPU to use for training. This should be either the name \"\n \"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 \"\n \"url.\")\n\ntf.flags.DEFINE_string(\n \"tpu_zone\", None,\n \"[Optional] GCE zone where the Cloud TPU is located in. If not \"\n \"specified, we will attempt to automatically detect the GCE project from \"\n \"metadata.\")\n\ntf.flags.DEFINE_string(\n \"gcp_project\", None,\n \"[Optional] Project name for the Cloud TPU-enabled project. If not \"\n \"specified, we will attempt to automatically detect the GCE project from \"\n \"metadata.\")\n\ntf.flags.DEFINE_string(\"master\", None, \"[Optional] TensorFlow master URL.\")\n\nflags.DEFINE_integer(\n \"num_tpu_cores\", 8,\n \"Only used if `use_tpu` is True. Total number of TPU cores to use.\")\n\nflags.DEFINE_bool(\n \"verbose_logging\", False,\n \"If true, all of the warnings related to data processing will be printed. \"\n \"A number of warnings are expected for a normal SQuAD evaluation.\")\n\nflags.DEFINE_bool(\n \"version_2_with_negative\", False,\n \"If true, the SQuAD examples contain some that do not have an answer.\")\n\nflags.DEFINE_float(\n \"null_score_diff_threshold\", 0.0,\n \"If null_score - best_non_null is greater than the threshold predict null.\")\n\nflags.DEFINE_bool(\n \"do_retriever\", False,\n \"If True, use retriever to help reader to filte good doc - add by willy.\")\n\nflags.DEFINE_string(\n \"retriever_model\", None,\n \"retriever model path - add by willy.\")\n\nflags.DEFINE_float(\n \"retriever_weight\", 0.0,\n \"retriever weight - add by willy.\")\n\n\nflags.DEFINE_integer(\"retriever_ranker\", 1,\"Rank with retriever.\")\n\nflags.DEFINE_string(\"document_type\",\"SQuAD\", \"There are three document types: (1)paragraphs in SQuAD (2)SQlite (DataBase) (3) Text - add by willy.\" )\n\nflags.DEFINE_string(\"question_type\",\"SQuAD\", \"There are three question types: (1) SQuAD (2)one_question (3) interactive.\" )\n\nflags.DEFINE_string(\"question\", None, \"give question to predict - Willy Test.\")\n\nflags.DEFINE_string(\"db_file\", None, \"give path with data base file to set SQlite State - Willy Test.\")\n\nflags.DEFINE_string(\"question_table\", None, \"set table path - Willy Test.\")\n\nflags.DEFINE_string(\"excel_name\", None ,\"set excel name -Willy Test.\")\n\n\nclass DecimalEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, decimal.Decimal):\n return float(obj)\n return super(DecimalEncoder, self).default(obj)\n\n\nclass SquadExample(object):\n \"\"\"A single training/test example for simple sequence classification.\n\n For examples without an answer, the start and end position are -1.\n \"\"\"\n\n def __init__(self,\n qas_id,\n question_text,\n doc_id, #willy add\n doc_tokens,\n orig_answer_text=None,\n start_position=None,\n end_position=None,\n is_impossible=False):\n self.qas_id = qas_id\n self.question_text = question_text\n self.doc_id = doc_id #willy add\n self.doc_tokens = doc_tokens\n self.orig_answer_text = orig_answer_text\n self.start_position = start_position\n self.end_position = end_position\n self.is_impossible = is_impossible\n\n def __str__(self):\n return self.__repr__()\n\n def __repr__(self):\n s = \"\"\n s += \"qas_id: %s\" % (tokenization.printable_text(self.qas_id))\n s += \", question_text: %s\" % (\n tokenization.printable_text(self.question_text))\n s += \", doc_id:[%s]\" % (tokenization.printable_text(self.doc_id)) #willy add\n s += \", doc_tokens: [%s]\" % (\" \".join(self.doc_tokens))\n if self.start_position:\n s += \", start_position: %d\" % (self.start_position)\n if self.start_position:\n s += \", end_position: %d\" % (self.end_position)\n if self.start_position:\n s += \", is_impossible: %r\" % (self.is_impossible)\n return s\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self,\n unique_id,\n example_index,\n doc_span_index,\n tokens,\n token_to_orig_map,\n token_is_max_context,\n input_ids,\n input_mask,\n segment_ids,\n start_position=None,\n end_position=None,\n is_impossible=None):\n self.unique_id = unique_id\n self.example_index = example_index\n self.doc_span_index = doc_span_index\n self.tokens = tokens\n self.token_to_orig_map = token_to_orig_map\n self.token_is_max_context = token_is_max_context\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.start_position = start_position\n self.end_position = end_position\n self.is_impossible = is_impossible\n\ndef set_squad_examples(input_file,question):\n\n \"\"\"Read a SQuAD json file into a list of SquadExample.\"\"\"\n with tf.gfile.Open(input_file, \"r\") as reader:\n input_data = json.load(reader)[\"data\"]\n def is_whitespace(c):\n if c == \" \" or c == \"\\t\" or c == \"\\r\" or c == \"\\n\" or ord(c) == 0x202F:\n return True\n return False\n \n examples = []\n file = open(\"Output1.txt\", \"r\")\n document = file.read()\n file.close()\n paragraphs = document.split('\\n')\n paragraphs = list(filter(None, paragraphs))\n #-----------------------------------------------\n doc_tokensList = []\n for i , paragraph_text in enumerate(paragraphs):\n # paragraph_text = paragraph[\"context\"]\n doc_tokens = []\n char_to_word_offset = []\n prev_is_whitespace = True\n for c in paragraph_text:\n if is_whitespace(c):\n prev_is_whitespace = True\n else:\n if prev_is_whitespace:\n doc_tokens.append(c)\n else:\n doc_tokens[-1] += c\n prev_is_whitespace = False\n char_to_word_offset.append(len(doc_tokens) - 1)\n doc_tokensList.append(doc_tokens)\n #-----------------------------------------------\n start_position = -1\n end_position = -1\n orig_answer_text = \"\"\n is_impossible = False\n for i, doc_tokens in enumerate(doc_tokensList):\n example = SquadExample(\n qas_id=str(uuid.uuid1()),\n question_text=question,\n doc_id=DOC2IDX[i],\n doc_tokens=doc_tokens,\n orig_answer_text=orig_answer_text,\n start_position=start_position,\n end_position=end_position,\n is_impossible=is_impossible)\n examples.append(example)\n \n ''' \n for entry in input_data:\n for paragraph in entry[\"paragraphs\"]:\n for qa in paragraph[\"qas\"]:\n #qas_id = qa[\"id\"]\n # uuid reset by willy in 20190313\n qas_id = str(uuid.uuid1())\n question_text = qa[\"question\"]\n start_position = -1\n end_position = -1\n orig_answer_text = \"\"\n is_impossible = False\n\n for doc_tokens in doc_tokensList:\n example = SquadExample(\n qas_id=qas_id,\n question_text=question_text,\n doc_tokens=doc_tokens,\n orig_answer_text=orig_answer_text,\n start_position=start_position,\n end_position=end_position,\n is_impossible=is_impossible)\n\n print(example)\n examples.append(example)\n ''' \n #-----------------------------------------------\n return examples \n \ndef read_squad_examples(input_file, is_training):\n \"\"\"Read a SQuAD json file into a list of SquadExample.\"\"\"\n with tf.gfile.Open(input_file, \"r\") as reader:\n input_data = json.load(reader)[\"data\"]\n\n def is_whitespace(c):\n if c == \" \" or c == \"\\t\" or c == \"\\r\" or c == \"\\n\" or ord(c) == 0x202F:\n return True\n return False\n\n examples = []\n for entry in input_data:\n for paragraph in entry[\"paragraphs\"]:\n paragraph_text = paragraph[\"context\"]\n doc_tokens = []\n char_to_word_offset = []\n prev_is_whitespace = True\n for c in paragraph_text:\n if is_whitespace(c):\n prev_is_whitespace = True\n else:\n if prev_is_whitespace:\n doc_tokens.append(c)\n else:\n doc_tokens[-1] += c\n prev_is_whitespace = False\n char_to_word_offset.append(len(doc_tokens) - 1)\n\n for qa in paragraph[\"qas\"]:\n qas_id = qa[\"id\"]\n question_text = qa[\"question\"]\n start_position = None\n end_position = None\n orig_answer_text = None\n is_impossible = False\n if is_training:\n\n if FLAGS.version_2_with_negative:\n is_impossible = qa[\"is_impossible\"]\n if (len(qa[\"answers\"]) != 1) and (not is_impossible):\n raise ValueError(\n \"For training, each question should have exactly 1 answer.\")\n if not is_impossible:\n answer = qa[\"answers\"][0]\n orig_answer_text = answer[\"text\"]\n answer_offset = answer[\"answer_start\"]\n answer_length = len(orig_answer_text)\n start_position = char_to_word_offset[answer_offset]\n end_position = char_to_word_offset[answer_offset + answer_length -\n 1]\n # Only add answers where the text can be exactly recovered from the\n # document. If this CAN'T happen it's likely due to weird Unicode\n # stuff so we will just skip the example.\n #\n # Note that this means for training mode, every example is NOT\n # guaranteed to be preserved.\n actual_text = \" \".join(\n doc_tokens[start_position:(end_position + 1)])\n cleaned_answer_text = \" \".join(\n tokenization.whitespace_tokenize(orig_answer_text))\n if actual_text.find(cleaned_answer_text) == -1:\n tf.logging.warning(\"Could not find answer: '%s' vs. '%s'\",\n actual_text, cleaned_answer_text)\n continue\n else:\n start_position = -1\n end_position = -1\n orig_answer_text = \"\"\n\n example = SquadExample(\n qas_id=qas_id,\n question_text=question_text,\n doc_tokens=doc_tokens,\n orig_answer_text=orig_answer_text,\n start_position=start_position,\n end_position=end_position,\n is_impossible=is_impossible)\n examples.append(example)\n\n return examples\n\ndef convert_examples_to_features(examples, tokenizer, max_seq_length,\n doc_stride, max_query_length, is_training,\n output_fn):\n \"\"\"Loads a data file into a list of `InputBatch`s.\"\"\"\n\n unique_id = 1000000000\n\n for (example_index, example) in enumerate(examples):\n query_tokens = tokenizer.tokenize(example.question_text)\n\n\n if len(query_tokens) > max_query_length:\n query_tokens = query_tokens[0:max_query_length]\n\n tok_to_orig_index = []\n orig_to_tok_index = []\n all_doc_tokens = []\n for (i, token) in enumerate(example.doc_tokens):\n orig_to_tok_index.append(len(all_doc_tokens))\n sub_tokens = tokenizer.tokenize(token)\n for sub_token in sub_tokens:\n tok_to_orig_index.append(i)\n all_doc_tokens.append(sub_token)\n\n tok_start_position = None\n tok_end_position = None\n if is_training and example.is_impossible:\n tok_start_position = -1\n tok_end_position = -1\n if is_training and not example.is_impossible:\n tok_start_position = orig_to_tok_index[example.start_position]\n if example.end_position < len(example.doc_tokens) - 1:\n tok_end_position = orig_to_tok_index[example.end_position + 1] - 1\n else:\n tok_end_position = len(all_doc_tokens) - 1\n (tok_start_position, tok_end_position) = _improve_answer_span(\n all_doc_tokens, tok_start_position, tok_end_position, tokenizer,\n example.orig_answer_text)\n\n # The -3 accounts for [CLS], [SEP] and [SEP]\n max_tokens_for_doc = max_seq_length - len(query_tokens) - 3\n\n # We can have documents that are longer than the maximum sequence length.\n # To deal with this we do a sliding window approach, where we take chunks\n # of the up to our max length with a stride of `doc_stride`.\n _DocSpan = collections.namedtuple( # pylint: disable=invalid-name\n \"DocSpan\", [\"start\", \"length\"])\n doc_spans = []\n start_offset = 0\n while start_offset < len(all_doc_tokens):\n length = len(all_doc_tokens) - start_offset\n if length > max_tokens_for_doc:\n length = max_tokens_for_doc\n doc_spans.append(_DocSpan(start=start_offset, length=length))\n if start_offset + length == len(all_doc_tokens):\n break\n start_offset += min(length, doc_stride)\n\n for (doc_span_index, doc_span) in enumerate(doc_spans):\n tokens = []\n token_to_orig_map = {}\n token_is_max_context = {}\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in query_tokens:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n for i in range(doc_span.length):\n split_token_index = doc_span.start + i\n token_to_orig_map[len(tokens)] = tok_to_orig_index[split_token_index]\n\n is_max_context = _check_is_max_context(doc_spans, doc_span_index,\n split_token_index)\n token_is_max_context[len(tokens)] = is_max_context\n tokens.append(all_doc_tokens[split_token_index])\n segment_ids.append(1)\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n start_position = None\n end_position = None\n if is_training and not example.is_impossible:\n # For training, if our document chunk does not contain an annotation\n # we throw it out, since there is nothing to predict.\n doc_start = doc_span.start\n doc_end = doc_span.start + doc_span.length - 1\n out_of_span = False\n if not (tok_start_position >= doc_start and\n tok_end_position <= doc_end):\n out_of_span = True\n if out_of_span:\n start_position = 0\n end_position = 0\n else:\n doc_offset = len(query_tokens) + 2\n start_position = tok_start_position - doc_start + doc_offset\n end_position = tok_end_position - doc_start + doc_offset\n\n if is_training and example.is_impossible:\n start_position = 0\n end_position = 0\n\n if example_index < 10:\n tf.logging.info(\"*** Example ***\")\n tf.logging.info(\"unique_id: %s\" % (unique_id))\n tf.logging.info(\"example_index: %s\" % (example_index))\n tf.logging.info(\"doc_span_index: %s\" % (doc_span_index))\n tf.logging.info(\"tokens: %s\" % \" \".join(\n [tokenization.printable_text(x) for x in tokens]))\n tf.logging.info(\"token_to_orig_map: %s\" % \" \".join(\n [\"%d:%d\" % (x, y) for (x, y) in six.iteritems(token_to_orig_map)]))\n tf.logging.info(\"token_is_max_context: %s\" % \" \".join([\n \"%d:%s\" % (x, y) for (x, y) in six.iteritems(token_is_max_context)\n ]))\n tf.logging.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n tf.logging.info(\n \"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n tf.logging.info(\n \"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\n if is_training and example.is_impossible:\n tf.logging.info(\"impossible example\")\n if is_training and not example.is_impossible:\n answer_text = \" \".join(tokens[start_position:(end_position + 1)])\n tf.logging.info(\"start_position: %d\" % (start_position))\n tf.logging.info(\"end_position: %d\" % (end_position))\n tf.logging.info(\n \"answer: %s\" % (tokenization.printable_text(answer_text)))\n\n feature = InputFeatures(\n unique_id=unique_id,\n example_index=example_index,\n doc_span_index=doc_span_index,\n tokens=tokens,\n token_to_orig_map=token_to_orig_map,\n token_is_max_context=token_is_max_context,\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n start_position=start_position,\n end_position=end_position,\n is_impossible=example.is_impossible)\n\n # Run callback\n output_fn(feature)\n\n unique_id += 1\n\n\ndef _improve_answer_span(doc_tokens, input_start, input_end, tokenizer,\n orig_answer_text):\n \"\"\"Returns tokenized answer spans that better match the annotated answer.\"\"\"\n\n # The SQuAD annotations are character based. We first project them to\n # whitespace-tokenized words. But then after WordPiece tokenization, we can\n # often find a \"better match\". For example:\n #\n # Question: What year was John Smith born?\n # Context: The leader was John Smith (1895-1943).\n # Answer: 1895\n #\n # The original whitespace-tokenized answer will be \"(1895-1943).\". However\n # after tokenization, our tokens will be \"( 1895 - 1943 ) .\". So we can match\n # the exact answer, 1895.\n #\n # However, this is not always possible. Consider the following:\n #\n # Question: What country is the top exporter of electornics?\n # Context: The Japanese electronics industry is the lagest in the world.\n # Answer: Japan\n #\n # In this case, the annotator chose \"Japan\" as a character sub-span of\n # the word \"Japanese\". Since our WordPiece tokenizer does not split\n # \"Japanese\", we just use \"Japanese\" as the annotation. This is fairly rare\n # in SQuAD, but does happen.\n tok_answer_text = \" \".join(tokenizer.tokenize(orig_answer_text))\n\n for new_start in range(input_start, input_end + 1):\n for new_end in range(input_end, new_start - 1, -1):\n text_span = \" \".join(doc_tokens[new_start:(new_end + 1)])\n if text_span == tok_answer_text:\n return (new_start, new_end)\n\n return (input_start, input_end)\n\n\ndef _check_is_max_context(doc_spans, cur_span_index, position):\n \"\"\"Check if this is the 'max context' doc span for the token.\"\"\"\n\n # Because of the sliding window approach taken to scoring documents, a single\n # token can appear in multiple documents. E.g.\n # Doc: the man went to the store and bought a gallon of milk\n # Span A: the man went to the\n # Span B: to the store and bought\n # Span C: and bought a gallon of\n # ...\n #\n # Now the word 'bought' will have two scores from spans B and C. We only\n # want to consider the score with \"maximum context\", which we define as\n # the *minimum* of its left and right context (the *sum* of left and\n # right context will always be the same, of course).\n #\n # In the example the maximum context for 'bought' would be span C since\n # it has 1 left context and 3 right context, while span B has 4 left context\n # and 0 right context.\n best_score = None\n best_span_index = None\n for (span_index, doc_span) in enumerate(doc_spans):\n end = doc_span.start + doc_span.length - 1\n if position < doc_span.start:\n continue\n if position > end:\n continue\n num_left_context = position - doc_span.start\n num_right_context = end - position\n score = min(num_left_context, num_right_context) + 0.01 * doc_span.length\n if best_score is None or score > best_score:\n best_score = score\n best_span_index = span_index\n\n return cur_span_index == best_span_index\n\n\ndef create_model(bert_config, is_training, input_ids, input_mask, segment_ids,\n use_one_hot_embeddings):\n \"\"\"Creates a classification model.\"\"\"\n model = modeling.BertModel(\n config=bert_config,\n is_training=is_training,\n input_ids=input_ids,\n input_mask=input_mask,\n token_type_ids=segment_ids,\n use_one_hot_embeddings=use_one_hot_embeddings)\n\n final_hidden = model.get_sequence_output()\n\n final_hidden_shape = modeling.get_shape_list(final_hidden, expected_rank=3)\n batch_size = final_hidden_shape[0]\n seq_length = final_hidden_shape[1]\n hidden_size = final_hidden_shape[2]\n\n output_weights = tf.get_variable(\n \"cls/squad/output_weights\", [2, hidden_size],\n initializer=tf.truncated_normal_initializer(stddev=0.02))\n\n output_bias = tf.get_variable(\n \"cls/squad/output_bias\", [2], initializer=tf.zeros_initializer())\n\n final_hidden_matrix = tf.reshape(final_hidden,\n [batch_size * seq_length, hidden_size])\n logits = tf.matmul(final_hidden_matrix, output_weights, transpose_b=True)\n logits = tf.nn.bias_add(logits, output_bias)\n\n logits = tf.reshape(logits, [batch_size, seq_length, 2])\n logits = tf.transpose(logits, [2, 0, 1])\n\n unstacked_logits = tf.unstack(logits, axis=0)\n\n (start_logits, end_logits) = (unstacked_logits[0], unstacked_logits[1])\n\n return (start_logits, end_logits)\n\n\ndef model_fn_builder(bert_config, init_checkpoint, learning_rate,\n num_train_steps, num_warmup_steps, use_tpu,\n use_one_hot_embeddings):\n \"\"\"Returns `model_fn` closure for TPUEstimator.\"\"\"\n\n def model_fn(features, labels, mode, params): # pylint: disable=unused-argument\n \"\"\"The `model_fn` for TPUEstimator.\"\"\"\n\n tf.logging.info(\"*** Features ***\")\n for name in sorted(features.keys()):\n tf.logging.info(\" name = %s, shape = %s\" % (name, features[name].shape))\n\n unique_ids = features[\"unique_ids\"]\n input_ids = features[\"input_ids\"]\n input_mask = features[\"input_mask\"]\n segment_ids = features[\"segment_ids\"]\n\n is_training = (mode == tf.estimator.ModeKeys.TRAIN)\n\n (start_logits, end_logits) = create_model(\n bert_config=bert_config,\n is_training=is_training,\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n use_one_hot_embeddings=use_one_hot_embeddings)\n\n tvars = tf.trainable_variables()\n\n initialized_variable_names = {}\n scaffold_fn = None\n if init_checkpoint:\n (assignment_map, initialized_variable_names\n ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)\n if use_tpu:\n\n def tpu_scaffold():\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\n return tf.train.Scaffold()\n\n scaffold_fn = tpu_scaffold\n else:\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\n\n tf.logging.info(\"**** Trainable Variables ****\")\n for var in tvars:\n init_string = \"\"\n if var.name in initialized_variable_names:\n init_string = \", *INIT_FROM_CKPT*\"\n tf.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape,\n init_string)\n\n output_spec = None\n if mode == tf.estimator.ModeKeys.TRAIN:\n seq_length = modeling.get_shape_list(input_ids)[1]\n\n def compute_loss(logits, positions):\n one_hot_positions = tf.one_hot(\n positions, depth=seq_length, dtype=tf.float32)\n log_probs = tf.nn.log_softmax(logits, axis=-1)\n loss = -tf.reduce_mean(\n tf.reduce_sum(one_hot_positions * log_probs, axis=-1))\n return loss\n\n start_positions = features[\"start_positions\"]\n end_positions = features[\"end_positions\"]\n\n start_loss = compute_loss(start_logits, start_positions)\n end_loss = compute_loss(end_logits, end_positions)\n\n total_loss = (start_loss + end_loss) / 2.0\n\n train_op = optimization.create_optimizer(\n total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)\n\n output_spec = tf.contrib.tpu.TPUEstimatorSpec(\n mode=mode,\n loss=total_loss,\n train_op=train_op,\n scaffold_fn=scaffold_fn)\n elif mode == tf.estimator.ModeKeys.PREDICT:\n predictions = {\n \"unique_ids\": unique_ids,\n \"start_logits\": start_logits,\n \"end_logits\": end_logits,\n }\n output_spec = tf.contrib.tpu.TPUEstimatorSpec(\n mode=mode, predictions=predictions, scaffold_fn=scaffold_fn)\n else:\n raise ValueError(\n \"Only TRAIN and PREDICT modes are supported: %s\" % (mode))\n\n return output_spec\n\n return model_fn\n\n\ndef input_fn_builder(input_file, seq_length, is_training, drop_remainder):\n \"\"\"Creates an `input_fn` closure to be passed to TPUEstimator.\"\"\"\n\n name_to_features = {\n \"unique_ids\": tf.FixedLenFeature([], tf.int64),\n \"input_ids\": tf.FixedLenFeature([seq_length], tf.int64),\n \"input_mask\": tf.FixedLenFeature([seq_length], tf.int64),\n \"segment_ids\": tf.FixedLenFeature([seq_length], tf.int64),\n }\n\n if is_training:\n name_to_features[\"start_positions\"] = tf.FixedLenFeature([], tf.int64)\n name_to_features[\"end_positions\"] = tf.FixedLenFeature([], tf.int64)\n\n def _decode_record(record, name_to_features):\n \"\"\"Decodes a record to a TensorFlow example.\"\"\"\n example = tf.parse_single_example(record, name_to_features)\n\n # tf.Example only supports tf.int64, but the TPU only supports tf.int32.\n # So cast all int64 to int32.\n for name in list(example.keys()):\n t = example[name]\n if t.dtype == tf.int64:\n t = tf.to_int32(t)\n example[name] = t\n\n return example\n\n def input_fn(params):\n \"\"\"The actual input function.\"\"\"\n batch_size = params[\"batch_size\"]\n\n # For training, we want a lot of parallel reading and shuffling.\n # For eval, we want no shuffling and parallel reading doesn't matter.\n d = tf.data.TFRecordDataset(input_file)\n if is_training:\n d = d.repeat()\n d = d.shuffle(buffer_size=100)\n\n d = d.apply(\n tf.data.experimental.map_and_batch(\n lambda record: _decode_record(record, name_to_features),\n batch_size=batch_size,\n drop_remainder=drop_remainder))\n\n return d\n\n return input_fn\n\n\nRawResult = collections.namedtuple(\"RawResult\",\n [\"unique_id\", \"start_logits\", \"end_logits\"])\n\n\ndef write_predictions(all_examples, all_features, all_results, n_best_size,\n max_answer_length, do_lower_case, output_prediction_file,\n output_nbest_file, output_null_log_odds_file,\n output_Aten_predict_file\n ):\n \"\"\"Write final predictions to the json file and log-odds of null if needed.\"\"\"\n tf.logging.info(\"Writing predictions to: %s\" % (output_prediction_file))\n tf.logging.info(\"Writing nbest to: %s\" % (output_nbest_file))\n tf.logging.info(\"Writing nbest to: %s\" % (output_Aten_predict_file)) \n\n example_index_to_features = collections.defaultdict(list)\n for feature in all_features:\n example_index_to_features[feature.example_index].append(feature)\n\n unique_id_to_result = {}\n tf.logging.info(\"length of all_results: %d\" % (len(all_results)))\n for result in all_results:\n unique_id_to_result[result.unique_id] = result\n\n _PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name\n \"PrelimPrediction\",\n [\"feature_index\", \"start_index\", \"end_index\", \"start_logit\", \"end_logit\"])\n\n\n # Willy Addd collections -> for results\n #------------------------------------------------------------------------------- \n _AllPredictions = collections.namedtuple( # pylint: disable=invalid-name\n \"AllPredictions\",\n [\"question\", \"no_answer\", \"PredictListOneQues\"]) \n\n _AllPredictResultsInOneQuestion = collections.namedtuple( # pylint: disable=invalid-name\n \"AllPredictResultsInOneQuestion\",\n [\"doc_text\", \"doc_id\", \"PredictListOneDoc\"])\n\n _AllPredictResultsInOneDocument = collections.namedtuple( # pylint: disable=invalid-name\n \"AllPredictResultsInOneDocument\",\n [\"answer\", \"prob\"]) \n\n _FinalResult = collections.namedtuple( # pylint: disable=invalid-name\n \"FinalResult\",\n [\"question\", \"text\", \"text_id\", \"ans\", \"prob\"])\n _FinalResult2 = collections.namedtuple( # pylint: disable=invalid-name\n \"FinalResult2\",\n [\"question\", \"text\", \"ans\", \"prob\"])\n\n _TempAllpredict_Layer1 = collections.namedtuple( # pylint: disable=invalid-name \n \"TempAllpredict_Layer1\",\n [\"question\" , \"TempAllpredictList_Layer2\"]) \n\n _TempAllpredict_Layer2 = collections.namedtuple( # pylint: disable=invalid-name \n \"TempAllpredict_Layer2\",\n [\"doc_id\",\"doc_text\",\"best_ans\",\"best_prob\"])\n #-------------------------------------------------------------------------------\n\n all_predictions = collections.OrderedDict()\n all_nbest_json = collections.OrderedDict()\n scores_diff_json = collections.OrderedDict()\n \n \n all_predicts = []\n all_predictsInOneQues = []\n quesList = []\n Aten_result_list = []\n Aten_result2_list = []\n TempAllpredictLayer1_list = []\n TempAllpredictLayer2_list = []\n best_answer=\"\"\n best_prob=0.0\n ans_is_null = True\n \n for (example_index, example) in enumerate(all_examples):\n features = example_index_to_features[example_index] \n \n if example_in_write_predictions == 1:\n print (\"example idx:%d\" %example_index)\n print(\"question in example from predict\")\n print(example.question_text)\n print(\"doc_tokens in example from predict\")\n print(example.doc_tokens)\n print('-'*60)\n print('\\n') \n \n prelim_predictions = [] \n \n # keep track of the minimum score of null start+end of position 0\n score_null = 1000000 # large and positive\n min_null_feature_index = 0 # the paragraph slice with min mull score\n null_start_logit = 0 # the start logit at the slice with min null score\n null_end_logit = 0 # the end logit at the slice with min null score\n for (feature_index, feature) in enumerate(features):\n result = unique_id_to_result[feature.unique_id]\n start_indexes = _get_best_indexes(result.start_logits, n_best_size)\n end_indexes = _get_best_indexes(result.end_logits, n_best_size)\n \n\n \n # if we could have irrelevant answers, get the min score of irrelevant\n if FLAGS.version_2_with_negative:\n feature_null_score = result.start_logits[0] + result.end_logits[0]\n if feature_null_score < score_null:\n score_null = feature_null_score\n min_null_feature_index = feature_index\n null_start_logit = result.start_logits[0]\n null_end_logit = result.end_logits[0]\n for start_index in start_indexes:\n for end_index in end_indexes:\n # We could hypothetically create invalid predictions, e.g., predict\n # that the start of the span is in the question. We throw out all\n # invalid predictions.\n if start_index >= len(feature.tokens):\n continue\n if end_index >= len(feature.tokens):\n continue\n if start_index not in feature.token_to_orig_map:\n continue\n if end_index not in feature.token_to_orig_map:\n continue\n if not feature.token_is_max_context.get(start_index, False):\n continue\n if end_index < start_index:\n continue\n length = end_index - start_index + 1\n if length > max_answer_length:\n continue\n prelim_predictions.append(\n _PrelimPrediction(\n feature_index=feature_index,\n start_index=start_index,\n end_index=end_index,\n start_logit=result.start_logits[start_index],\n end_logit=result.end_logits[end_index]))\n \n \n if FLAGS.version_2_with_negative:\n prelim_predictions.append(\n _PrelimPrediction(\n feature_index=min_null_feature_index,\n start_index=0,\n end_index=0,\n start_logit=null_start_logit,\n end_logit=null_end_logit)) \n \n \n prelim_predictions = sorted(\n prelim_predictions,\n key=lambda x: (x.start_logit + x.end_logit),\n reverse=True)\n\n _NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name\n \"NbestPrediction\", [\"text\", \"start_logit\", \"end_logit\"])\n \n\n seen_predictions = {}\n nbest = []\n \n for pred in prelim_predictions:\n if len(nbest) >= n_best_size:\n break\n feature = features[pred.feature_index]\n if pred.start_index > 0: # this is a non-null prediction\n tok_tokens = feature.tokens[pred.start_index:(pred.end_index + 1)]\n orig_doc_start = feature.token_to_orig_map[pred.start_index]\n orig_doc_end = feature.token_to_orig_map[pred.end_index]\n orig_tokens = example.doc_tokens[orig_doc_start:(orig_doc_end + 1)]\n tok_text = \" \".join(tok_tokens)\n\n # De-tokenize WordPieces that have been split off.\n tok_text = tok_text.replace(\" ##\", \"\")\n tok_text = tok_text.replace(\"##\", \"\")\n\n # Clean whitespace\n tok_text = tok_text.strip()\n tok_text = \" \".join(tok_text.split())\n orig_text = \" \".join(orig_tokens)\n\n final_text = get_final_text(tok_text, orig_text, do_lower_case)\n \n if final_text in seen_predictions:\n continue \n seen_predictions[final_text] = True \n \n else:\n final_text = \"\"\n seen_predictions[final_text] = True\n\n nbest.append(\n _NbestPrediction(\n text=final_text,\n start_logit=pred.start_logit,\n end_logit=pred.end_logit)) \n\n\n # if we didn't inlude the empty option in the n-best, inlcude it\n if FLAGS.version_2_with_negative:\n if \"\" not in seen_predictions:\n nbest.append(\n _NbestPrediction(\n text=\"\", start_logit=null_start_logit,\n end_logit=null_end_logit))\n \n # In very rare edge cases we could have no valid predictions. So we\n # just create a nonce prediction in this case to avoid failure.\n if not nbest:\n nbest.append(\n _NbestPrediction(text=\"empty\", start_logit=0.0, end_logit=0.0))\n\n assert len(nbest) >= 1\n \n total_scores = []\n best_non_null_entry = None\n for entry in nbest:\n total_scores.append(entry.start_logit + entry.end_logit)\n if not best_non_null_entry:\n if entry.text:\n best_non_null_entry = entry\n\n #參考\n probs = _compute_softmax(total_scores)\n \n nbest_json = []\n for i, entry in enumerate(nbest):\n output = collections.OrderedDict()\n output[\"text\"] = entry.text\n output[\"probability\"] = probs[i]\n output[\"start_logit\"] = entry.start_logit\n output[\"end_logit\"] = entry.end_logit\n nbest_json.append(output)\n\n \n #----------------------------------------------\n # presupposition : Question is in order\n #\"question\", \"PredictResults\"\n if example.question_text not in quesList :\n if len(quesList)!=0 :\n #1. Save to all predicts\n temp = copy.deepcopy(all_predictsInOneQues)\n all_predicts.append(\n _AllPredictions(question=quesList[-1], no_answer=ans_is_null, PredictListOneQues=temp) ) \n if predict_result_index == 1:\n print(\"Set all predict1\")\n print(\"all_predicts:\")\n print(all_predicts)\n print('-'*60)\n print('\\n') \n #2.TODO : Find the result (move to outside)\n #3. reset all_predictsInOneQues\n all_predictsInOneQues.clear()\n ans_is_null = True \n \n #. Add to questList\n quesList.append(example.question_text)\n \n if predict_result_index == 1:\n print (\"renew question:\")\n print(\"question list:\")\n print (quesList)\n print('-'*30)\n print('\\n') \n print(\"all_predicts:\")\n print(all_predicts)\n print('-'*60)\n print('\\n') \n #---------------------------------------------- \n \n \n # save two dataset\n #----------------------------------------------\n all_predictsInOneDoc = [] \n for i, entry in enumerate(nbest):\n if i == 2:\n break\n all_predictsInOneDoc.append(\n _AllPredictResultsInOneDocument(answer=entry.text, prob=Decimal(probs[i]) ))\n if ans_is_null == True and entry.text!=\"\" and i==0 :\n ans_is_null = False\n #----------------------------------------------\n \n \n # append predicts to OneQues\n #----------------------------------------------\n all_predictsInOneQues.append\n (\n _AllPredictResultsInOneQuestion(\n doc_text=example.doc_tokens,\n doc_id=example.doc_id,\n PredictListOneDoc=all_predictsInOneDoc\n )\n )\n if predict_result_index == 1:\n print (\"all_predictsInOneQues\")\n print(all_predictsInOneQues)\n print('-'*15)\n print('\\n') \n #----------------------------------------------\n \n \n # if example is examples last data\n if example == all_examples[-1] :\n all_predicts.append(\n _AllPredictions(question=example.question_text,no_answer=ans_is_null,PredictListOneQues=all_predictsInOneQues)) \n #----------------------------------------------\n \n \n assert len(nbest_json) >= 1\n if not FLAGS.version_2_with_negative:\n all_predictions[example.qas_id] = nbest_json[0][\"text\"]\n else:\n # predict \"\" iff the null score - the score of best non-null > threshold\n if best_non_null_entry == None :\n score_diff = FLAGS.null_score_diff_threshold + 1.0\n else:\n score_diff = score_null - best_non_null_entry.start_logit - (\n best_non_null_entry.end_logit)\n scores_diff_json[example.qas_id] = score_diff\n if score_diff > FLAGS.null_score_diff_threshold:\n all_predictions[example.qas_id] = \"\"\n else:\n all_predictions[example.qas_id] = best_non_null_entry.text\n \n \n all_nbest_json[example.qas_id] = nbest_json\n \n\n \n #TODO: Find the best answer from Aten collections\n #---------------------------------------------- \n const_AtenQuest_index = [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,3,6,5,5,5,5,5,5,5,5,5,3,5,4,5,5,5,5,5,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] \n const_AtenIntent_index = [1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] \n excel_NOtGoodAns_index = [0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,4,2,0,5,3,0,2,5,0,0,2,0,3,1,0,2,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n \n \n excel_count = 0 \n excel_index = 1 \n excel_Answer_count = const_AtenQuest_index[excel_index-1]\n excel_Intent_count = const_AtenIntent_index[excel_index-1]\n excel_NOtGoodAns_count = excel_NOtGoodAns_index[excel_index-1]\n wb = Workbook()\n ws = wb.active \n retriever_weight = FLAGS.retriever_weight\n \n \n ranker = None\n if FLAGS.do_retriever: \n ranker = retriever.get_class('tfidf')(tfidf_path=FLAGS.retriever_model) \n \n\n if checkState_in_AtenResult2 == 1:\n print('len of all_predicts:%d' %len(all_predicts))\n \n # 1.choice article\n # destination: \n # way :\n\n #Start of question list\n #---------------------------------------#\n _DocList_BestAns = collections.namedtuple( \n \"DocList\",\n [\"doc_id\", \"best_answer\", \"PredictListOneQues\"])\n \n for i, entry_predicts in enumerate(all_predicts):\n tp_ques = entry_predicts.question \n QuesList = entry_predicts.PredictListOneQues\n \n \n # Start of document list\n #---------------------------------------# \n for j, entry_OneQues in enumerate(QuesList):\n tp_text = entry_OneQues.doc_text\n doc_id = entry_OneQues.doc_id\n DocList = entry_OneQues.PredictListOneDoc \n \n \n # Start of ansert list\n onedoc_answer = ''\n onedoc_prob = 0.0 \n #---------------------------------------# \n for k, entry_Doc in enumerate(DocList):\n tp_now_answer = entry_Doc.answer\n tp_now_prob = Decimal(entry_Doc.prob)\n # string is empty\n if tp_now_answer.isspace() or not tp_now_answer :\n continue\n \n # prob formula\n # now: orginal \n #-----------------------------------\n #TODO\n #-----------------------------------\n \n # prob comp \n if tp_now_prob < onedoc_prob:\n onedoc_answer = tp_now_prob\n onedoc_prob = 0.0\n \n #---------------------------------------# \n # End of ansert list\n \n # Now : get the best answer in one doc\n # Do : save it(best_ answer , best_prob, start_log, end_log, doc_id)\n # (onedoc_answer , onedoc_prob, \n \n #---------------------------------------#\n # End of document list\n \n \n # Start of database ranker\n #---------------------------------------# \n if ranker!=None:\n doc_names, doc_scores = ranker.closest_docs( tp_ques, len(QuesList) ) \n table = prettytable.PrettyTable(\n ['Rank', 'Doc Id', 'Doc Score']\n ) \n for i in range(len(doc_names)):\n table.add_row([i + 1, doc_names[i], '%.5g' % doc_scores[i]])\n #---------------------------------------#\n # End of database ranker \n \n \n # Now : get doc_list with best answer prob in each document \n # Do : find the best doc with one question , save it (ques , doc_id)\n \n #---------------------------------------# \n # End of question list \n \n \n \n # 2.choice best answer in one document\n # destination: \n # way : \n #---------------------------------------# \n '''\n for i, entry_predicts in enumerate(all_predicts):\n tp_ques = entry_predicts.question \n QuesList = entry_predicts.PredictListOneQues\n \n if checkState_in_AtenResult2 == 1:\n print(\"Ques:\")\n print(\"Ques_ID=%d, tp_ques=%s\" %(i,tp_ques) ) \n \n\n if ranker!= None : \n doc_names, doc_scores = ranker.closest_docs( tp_ques, len(QuesList) ) \n table = prettytable.PrettyTable(\n ['Rank', 'Doc Id', 'Doc Score']\n ) \n for i in range(len(doc_names)):\n table.add_row([i + 1, doc_names[i], '%.5g' % doc_scores[i]])\n \n tp_no_answer = entry_predicts.no_answer\n best_ans = \"\"\n best_prob = 0.0\n best_doc = \"\"\n best_Docidx = 0\n \n tp_no_answer_ori = entry_predicts.no_answer\n best_ans_ori = \"\"\n best_prob_ori = 0.0\n best_doc_ori = \"\"\n best_Docidx_ori = 0 \n \n if checkState_in_AtenResult2 == 1:\n print('len of QuesList:%d' %len(QuesList))\n \n\n for j, entry_OneQues in enumerate(QuesList):\n tp_text = entry_OneQues.doc_text\n doc_id = entry_OneQues.doc_id\n DocList = entry_OneQues.PredictListOneDoc\n # Doc score\n doc_score = 0.0\n if doc_id in doc_names:\n doc_score = doc_scores[doc_names.index(doc_id)]\n \n \n #check state\n #--------------------------------------------------------------------------\n if checkState_in_AtenResult2 == 1:\n print(\"DocIndex= %d \" %(j))\n \n print('DocID: %s' %(entry_OneQues.doc_id))\n \n print('DocText:')\n print(entry_OneQues.doc_text)\n\n \n #--------------------------------------------------------------------------\n \n\n \n if checkState_in_AtenResult2 == 1:\n print('len of DocList:%d' %len(DocList))\n #\n #---------------------------------------# \n for k, entry_Doc in enumerate(DocList):\n \n tp_now_prob = Decimal(entry_Doc.prob)\n tp_now_prob2 = Decimal(entry_Doc.prob)\n \n #print('retriever_weight:%f, tp_now_prob:%f, doc_score:%f' %(retriever_weight, tp_now_prob, doc_score))\n if FLAGS.do_retriever:\n tp_now_prob = Decimal(retriever_weight)*Decimal(doc_score) + Decimal(1.0-retriever_weight)*Decimal(tp_now_prob)\n \n if checkState_in_AtenResult2 == 1:\n print(\"Weight: Ans_id=%d, Answer=%s , prob=%e\" %(k, entry_Doc.answer , tp_now_prob))\n print(\"Original: Ans_id=%d, Answer=%s , prob=%e\" %(k, entry_Doc.answer , tp_now_prob2))\n #\n #-----------------------------------#\n if tp_no_answer == False and k == 0:\n #\n #-------------------------------#\n\n if checkState_in_AtenResult == 1:\n print(\"In Doc State 1, Weight: Ans_id=%d, Answer=%s , prob=%e\" %(k, entry_Doc.answer , tp_now_prob)) \n print(\"In Doc State 1, Original : Ans_id=%d, Answer=%s , prob=%e\" %(k, entry_Doc.answer , tp_now_prob2))\n # do weight:\n if entry_Doc.answer.strip() != \"\" and entry_Doc.answer.strip() != \" \" and tp_now_prob > best_prob:\n if checkState_in_AtenResult == 1:\n print(\"Reset answer:\")\n print(\"Weight: original data: best_ans: %s, best_prob=%e,best_Docidx=%d\" %(best_ans, best_prob,best_Docidx))\n \n best_ans = entry_Doc.answer\n best_prob = tp_now_prob\n best_doc = tp_text\n best_Docidx = j\n \n if checkState_in_AtenResult == 1:\n print(\"change data: best_ans: %s, best_prob=%e,best_Docidx=%d\" %(best_ans, best_prob,best_Docidx))\n \n # do original:\n if entry_Doc.answer.strip() != \"\" and entry_Doc.answer.strip() != \" \" and tp_now_prob2 > best_prob_ori:\n if checkState_in_AtenResult == 1:\n print(\"Reset answer:\")\n print(\"Orginal: original data: best_ans: %s, best_prob=%e,best_Docidx=%d\" %(best_ans_ori, best_prob_ori,best_Docidx_ori)) \n\n best_ans_ori = entry_Doc.answer\n best_prob_ori = tp_now_prob2\n best_doc_ori = tp_text\n best_Docidx_ori = j\n if checkState_in_AtenResult == 1:\n print(\"change data: best_ans: %s, best_prob=%e,best_Docidx=%d\" %(best_ans_ori, best_prob_ori,best_Docidx_ori))\n \n #-------------------------------# \n #\n #-----------------------------------#\n elif entry_Doc.answer.strip() != \"\" and entry_Doc.answer.strip() != \" \" and tp_no_answer == True and k == 1:\n #\n #-------------------------------#\n if checkState_in_AtenResult == 1:\n print(\"In Doc State 2, Weight: Ans_id=%d, Answer=%s , prob=%e\" %(k, entry_Doc.answer , tp_now_prob)) \n print(\"In Doc State 2, Original : Ans_id=%d, Answer=%s , prob=%e\" %(k, entry_Doc.answer , tp_now_prob2))\n \n if tp_now_prob > best_prob:\n if checkState_in_AtenResult == 1:\n print(\"Reset answer:\")\n print(\"original data: best_ans: %s, best_prob=%e, best_Docidx=%d\" %(best_ans_ori, best_prob, best_Docidx))\n\n best_ans = entry_Doc.answer\n best_prob = tp_now_prob\n best_doc = tp_text\n best_Docidx = j\n if checkState_in_AtenResult == 1:\n print(\"change data: best_ans: %s, best_prob=%e,best_Docidx=%d\" %(best_ans, best_prob,best_Docidx))\n if tp_now_prob2 > best_prob_ori:\n if checkState_in_AtenResult == 1:\n print(\"Reset answer:\")\n print(\"Orginal: original data: best_ans: %s, best_prob=%e,best_Docidx=%d\" %(best_ans_ori, best_prob_ori,best_Docidx_ori)) \n\n best_ans_ori = entry_Doc.answer\n best_prob_ori = tp_now_prob2\n best_doc_ori = tp_text\n best_Docidx_ori = j \n if checkState_in_AtenResult == 1:\n print(\"change data: best_ans: %s, best_prob=%e,best_Docidx=%d\" %(best_ans_ori, best_prob_ori,best_Docidx_ori))\n \n #-------------------------------#\n #-----------------------------------#\n else:\n if checkState_in_AtenResult==1:\n print(\" In Doc State 3, Weight: Ans_id=%d, Answer=%s , prob=%e\" %(k, entry_Doc.answer , tp_now_prob))\n print(\" In Doc State 3, Orginal: Ans_id=%d, Answer=%s , prob=%e\" %(k, entry_Doc.answer , tp_now_prob2))\n #-----------------------------------# end of for Doc_List\n \n TempAllpredictLayer2_list.append(\n _TempAllpredict_Layer2(\n doc_id = best_Docidx_ori ,\n doc_text = best_doc_ori ,\n best_ans = best_ans_ori ,\n best_prob = best_prob_ori\n )\n )\n TempAllpredictLayer1_list.append(\n _TempAllpredict_Layer1(\n question = tp_ques,\n TempAllpredictList_Layer2 = TempAllpredictLayer2_list\n )\n ) \n #---------------------------------------# end of for Ques_List\n str_result=\"\"\n for word in best_doc:\n str_result= str_result + \" \" + word\n \n Aten_result_list.append(\n _FinalResult(\n question = tp_ques,\n text_id = best_Docidx,\n text = str_result,\n ans = best_ans,\n prob = best_prob\n )\n )\n \n Aten_result2_list.append(\n _FinalResult2(\n question = tp_ques,\n text = str_result,\n ans = best_ans,\n prob = best_prob\n )\n )\n \n if excel_Answer_count == excel_count : \n ws['C' + str(excel_index)] = excel_Answer_count\n ws['D' + str(excel_index)] = excel_NOtGoodAns_count\n ws['F' + str(excel_index)] = excel_Intent_count\n excel_index = excel_index+1\n excel_Answer_count = const_AtenQuest_index[excel_index-1] \n excel_NOtGoodAns_count = excel_NOtGoodAns_index[excel_index-1]\n excel_Intent_count = const_AtenIntent_index[excel_index-1] \n excel_count = 0\n \n if excel_index <= len(const_AtenQuest_index) :\n index_str = chr(73+excel_count) + str(excel_index) \n ws[index_str] = best_prob\n excel_count = excel_count + 1\n \n if checkState_in_AtenResult == 1 :\n print (\"Aten_result_list\") \n print(\"question: %s\" %tp_ques)\n print(\"best_Docidx: %d\" %best_Docidx)\n print(\"best_ans: %s\" %best_ans)\n print(\"best_prob: %f\" %best_prob) \n\n #-------------------------------------------------# \n ''' \n\n ws['A60'] = 'All'\n ws['A61'] = '40QA'\n \n ws['B59'] = 'Right answer'\n ws['B60'] = '=SUM(B1:B40)+SUM(A41:A58)'\n ws['B61'] = '=SUM(B1:B40)'\n\n ws['C59'] = 'All answer'\n ws['C60'] = '=SUM(C1:C58)-SUM(D1:D40)'\n ws['C61'] = '=SUM(C1:C40)-SUM(D1:D40)'\n \n ws['E59'] = 'Right Intent'\n ws['E60'] = '=SUM(E1:E40)+SUM(A41:A58)'\n ws['E61'] = '=SUM(E1:E40)' \n\n ws['F59'] = 'All intent'\n ws['F60'] = '=SUM(F1:F40)+SUM(C41:C58)'\n ws['F61'] = '=SUM(F1:F40)' \n \n \n ws['G59'] = 'answer prob'\n ws['G60'] = '=B60/C60'\n ws['G61'] = '=B61/C61' \n\n ws['H59'] = 'Intent prob'\n ws['H60'] = '=E60/F60'\n ws['H61'] = '=E61/F61' \n \n wb.save(FLAGS.excel_name + '.xlsx')\n print('\\n') \n \n '''\n for i, entry in enumerate(TempAllpredictLayer1_list):\n print('question(%d) :%s' %(i, entry.question))\n list2 = entry.TempAllpredictList_Layer2\n print('len of list :%d' %len(list2))\n if i==0: \n for j, entry2 in enumerate(list2):\n print('index (%d)' %j)\n print('doc_id: %d' %entry2.doc_id)\n print('doc_text: %s' %entry2.doc_text)\n print('best_ans: %s' %entry2.best_ans)\n print('best_prob: %e' %entry2.best_prob)\n '''\n\n ''' \n for i, entry in enumerate(Aten_result_list):\n print(\"question :%s\" %entry.question)\n print(\"text_id:%d\" %entry.text_id)\n print(\"text:%s\" %entry.text)\n print(\"ans:%s\" %entry.ans)\n print(\"prob:%e\" %entry.prob)\n\n \n print('-'*30)\n print('\\n')\n ''' \n \n with tf.gfile.GFile(output_Aten_predict_file, \"w\") as writer:\n writer.write(json.dumps(Aten_result2_list, indent=4,cls=DecimalEncoder) + \"\\n\")\n # writer.write(json.dumps(Aten_result_list, indent=4,cls=DecimalEncoder) + \"\\n\")\n\n with tf.gfile.GFile(output_prediction_file, \"w\") as writer:\n writer.write(json.dumps(all_predictions, indent=4) + \"\\n\")\n\n with tf.gfile.GFile(output_nbest_file, \"w\") as writer:\n writer.write(json.dumps(all_nbest_json, indent=4) + \"\\n\")\n\n if FLAGS.version_2_with_negative:\n with tf.gfile.GFile(output_null_log_odds_file, \"w\") as writer:\n writer.write(json.dumps(scores_diff_json, indent=4) + \"\\n\")\n\n\ndef get_final_text(pred_text, orig_text, do_lower_case):\n \"\"\"Project the tokenized prediction back to the original text.\"\"\"\n\n # When we created the data, we kept track of the alignment between original\n # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So\n # now `orig_text` contains the span of our original text corresponding to the\n # span that we predicted.\n #\n # However, `orig_text` may contain extra characters that we don't want in\n # our prediction.\n #\n # For example, let's say:\n # pred_text = steve smith\n # orig_text = Steve Smith's\n #\n # We don't want to return `orig_text` because it contains the extra \"'s\".\n #\n # We don't want to return `pred_text` because it's already been normalized\n # (the SQuAD eval script also does punctuation stripping/lower casing but\n # our tokenizer does additional normalization like stripping accent\n # characters).\n #\n # What we really want to return is \"Steve Smith\".\n #\n # Therefore, we have to apply a semi-complicated alignment heruistic between\n # `pred_text` and `orig_text` to get a character-to-charcter alignment. This\n # can fail in certain cases in which case we just return `orig_text`.\n\n def _strip_spaces(text):\n ns_chars = []\n ns_to_s_map = collections.OrderedDict()\n for (i, c) in enumerate(text):\n if c == \" \":\n continue\n ns_to_s_map[len(ns_chars)] = i\n ns_chars.append(c)\n ns_text = \"\".join(ns_chars)\n return (ns_text, ns_to_s_map)\n\n # We first tokenize `orig_text`, strip whitespace from the result\n # and `pred_text`, and check if they are the same length. If they are\n # NOT the same length, the heuristic has failed. If they are the same\n # length, we assume the characters are one-to-one aligned.\n tokenizer = tokenization.BasicTokenizer(do_lower_case=do_lower_case)\n\n tok_text = \" \".join(tokenizer.tokenize(orig_text))\n\n start_position = tok_text.find(pred_text)\n if start_position == -1:\n if FLAGS.verbose_logging:\n tf.logging.info(\n \"Unable to find text: '%s' in '%s'\" % (pred_text, orig_text))\n return orig_text\n end_position = start_position + len(pred_text) - 1\n\n (orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text)\n (tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text)\n\n if len(orig_ns_text) != len(tok_ns_text):\n if FLAGS.verbose_logging:\n tf.logging.info(\"Length not equal after stripping spaces: '%s' vs '%s'\",\n orig_ns_text, tok_ns_text)\n return orig_text\n\n # We then project the characters in `pred_text` back to `orig_text` using\n # the character-to-character alignment.\n tok_s_to_ns_map = {}\n for (i, tok_index) in six.iteritems(tok_ns_to_s_map):\n tok_s_to_ns_map[tok_index] = i\n\n orig_start_position = None\n if start_position in tok_s_to_ns_map:\n ns_start_position = tok_s_to_ns_map[start_position]\n if ns_start_position in orig_ns_to_s_map:\n orig_start_position = orig_ns_to_s_map[ns_start_position]\n\n if orig_start_position is None:\n if FLAGS.verbose_logging:\n tf.logging.info(\"Couldn't map start position\")\n return orig_text\n\n orig_end_position = None\n if end_position in tok_s_to_ns_map:\n ns_end_position = tok_s_to_ns_map[end_position]\n if ns_end_position in orig_ns_to_s_map:\n orig_end_position = orig_ns_to_s_map[ns_end_position]\n\n if orig_end_position is None:\n if FLAGS.verbose_logging:\n tf.logging.info(\"Couldn't map end position\")\n return orig_text\n\n output_text = orig_text[orig_start_position:(orig_end_position + 1)]\n return output_text\n\n\ndef _get_best_indexes(logits, n_best_size):\n \"\"\"Get the n-best logits from a list.\"\"\"\n index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)\n\n best_indexes = []\n for i in range(len(index_and_score)):\n if i >= n_best_size:\n break\n best_indexes.append(index_and_score[i][0])\n return best_indexes\n\n\ndef _compute_softmax(scores):\n \"\"\"Compute softmax probability over raw logits.\"\"\"\n if not scores:\n return []\n\n max_score = None\n for score in scores:\n if max_score is None or score > max_score:\n max_score = score\n\n exp_scores = []\n total_sum = 0.0\n for score in scores:\n x = math.exp(score - max_score)\n exp_scores.append(x)\n total_sum += x\n\n probs = []\n for score in exp_scores:\n probs.append(score / total_sum)\n return probs\n\n\nclass FeatureWriter(object):\n \"\"\"Writes InputFeature to TF example file.\"\"\"\n\n def __init__(self, filename, is_training):\n self.filename = filename\n self.is_training = is_training\n self.num_features = 0\n self._writer = tf.python_io.TFRecordWriter(filename)\n\n def process_feature(self, feature):\n \"\"\"Write a InputFeature to the TFRecordWriter as a tf.train.Example.\"\"\"\n self.num_features += 1\n\n def create_int_feature(values):\n feature = tf.train.Feature(\n int64_list=tf.train.Int64List(value=list(values)))\n return feature\n\n features = collections.OrderedDict()\n features[\"unique_ids\"] = create_int_feature([feature.unique_id])\n features[\"input_ids\"] = create_int_feature(feature.input_ids)\n features[\"input_mask\"] = create_int_feature(feature.input_mask)\n features[\"segment_ids\"] = create_int_feature(feature.segment_ids)\n\n if self.is_training:\n features[\"start_positions\"] = create_int_feature([feature.start_position])\n features[\"end_positions\"] = create_int_feature([feature.end_position])\n impossible = 0\n if feature.is_impossible:\n impossible = 1\n features[\"is_impossible\"] = create_int_feature([impossible])\n\n tf_example = tf.train.Example(features=tf.train.Features(feature=features))\n #print(\"tf_example:\")\n #print(tf_example)\n self._writer.write(tf_example.SerializeToString())\n\n def close(self):\n self._writer.close()\n\n\ndef validate_flags_or_throw(bert_config):\n \"\"\"Validate the input FLAGS or throw an exception.\"\"\"\n tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,\n FLAGS.init_checkpoint)\n\n if not FLAGS.do_train and not FLAGS.do_predict:\n raise ValueError(\"At least one of `do_train` or `do_predict` must be True.\")\n\n if FLAGS.do_train:\n if not FLAGS.train_file:\n raise ValueError(\n \"If `do_train` is True, then `train_file` must be specified.\")\n if FLAGS.do_predict:\n if not FLAGS.predict_file:\n raise ValueError(\n \"If `do_predict` is True, then `predict_file` must be specified.\")\n\n if FLAGS.max_seq_length > bert_config.max_position_embeddings:\n raise ValueError(\n \"Cannot use sequence length %d because the BERT model \"\n \"was only trained up to sequence length %d\" %\n (FLAGS.max_seq_length, bert_config.max_position_embeddings))\n\n if FLAGS.max_seq_length <= FLAGS.max_query_length + 3:\n raise ValueError(\n \"The max_seq_length (%d) must be greater than max_query_length \"\n \"(%d) + 3\" % (FLAGS.max_seq_length, FLAGS.max_query_length))\n \n # Retriever - added by Willy \n if FLAGS.do_retriever:\n if not FLAGS.retriever_model:\n raise ValueError(\"You have to set retriever model(give the path) when you set do_retriever to Yes.\")\n if FLAGS.document_type != 'Sqlite' or FLAGS.db_file == None :\n raise ValueError(\"You have to set document_type to Sqlit and set the db_file when you set do_retriever to Yes.\")\n \n # TODO : think a mechanism to chek these key word\n '''\n if FLAGS.document_type is 'SQlite':\n # TODO: set database\n elif FLAGS.document_type is 'Text':\n # TODO: set text file\n elif FLAGS.document_type is 'SQuAD':\n # is original method\n else :\n raise ValueError(\n \"You have to set correct document_type: (1)'SQlite' (2)'Text' (3)SQuAD.\")\n'''\n\ndef read_squad_documents(input_file):\n \"\"\"Read a SQuAD json file into a list of SquadExample.\"\"\"\n with tf.gfile.Open(input_file, \"r\") as reader:\n input_data = json.load(reader)[\"data\"] \n documents = []\n for entry in input_data:\n for paragraph in entry[\"paragraphs\"]:\n documents.append(paragraph[\"context\"])\n \n return documents\n\n\ndef read_sqlite_documents(input_file):\n # TODO\n \n with db_class(input_file) as doc_db:\n doc_ids = doc_db.get_doc_ids()\n for ids in doc_ids:\n documents.append(doc_db.get_doc_text(ids))\n DOC2IDX = {doc_id: i for i, doc_id in enumerate(doc_ids)}\n return DOC2IDX, documents\n\n\ndef read_text_documents(input_file):\n examples = []\n file = open(input_file, \"r\")\n documents = file.read()\n file.close()\n documents_split = documents.split('\\n')\n documents_final = list(filter(None, documents))\n return documents_final\n\ndef read_squad_question(input_file):\n questions = []\n \"\"\"Read a SQuAD json file into a list of SquadExample.\"\"\"\n with tf.gfile.Open(input_file, \"r\") as reader: \n input_data = json.load(reader)[\"data\"] \n for entry in input_data:\n for paragraph in entry[\"paragraphs\"]:\n for qa in paragraph[\"qas\"]:\n questions.append(qa[\"question\"])\n return questions\n\ndef set_eval_examples(questions, DOC2IDX):\n def is_whitespace(c):\n if c == \" \" or c == \"\\t\" or c == \"\\r\" or c == \"\\n\" or ord(c) == 0x202F:\n return True\n return False\n\n eval_examples = []\n temp_list = []\n print ('Show 2 DOC2IDX, len=%d'%(len(DOC2IDX)))\n print (DOC2IDX)\n for i, DOCID in enumerate(DOC2IDX) :\n print('ID:%d ,doc:%s' %(i,DOCID))\n temp_list.append(DOCID)\n \n for question in questions:\n #-------------------------questions - Start---------------------------# \n question_text = question\n start_position = -1\n end_position = -1\n orig_answer_text = \"\"\n is_impossible = False\n\n #-------------documents - Start--------------#\n for i , paragraph_text in enumerate(documents):\n paragraph_text = paragraph_text\n #-------paragraphs - Start-------#\n doc_tokens = []\n char_to_word_offset = []\n prev_is_whitespace = True\n for c in paragraph_text:\n if is_whitespace(c):\n prev_is_whitespace = True\n else:\n if prev_is_whitespace:\n doc_tokens.append(c)\n else:\n doc_tokens[-1] += c\n prev_is_whitespace = False\n char_to_word_offset.append(len(doc_tokens) - 1)\n #-------paragraphs - End-------#\n qas_id = str(uuid.uuid1())\n example = SquadExample(\n qas_id=qas_id,\n question_text=question_text,\n doc_id = temp_list[i],\n doc_tokens=doc_tokens,\n orig_answer_text=orig_answer_text,\n start_position=start_position,\n end_position=end_position,\n is_impossible=is_impossible)\n eval_examples.append(example)\n #-------------documents - Start--------------#\n #-------------------------questions - End-----------------------------#\n if example_in_set_eval_examples == 1:\n print('len of eval_examples:%d' %len(eval_examples))\n for i, example in enumerate(eval_examples):\n print(i)\n print (example)\n return eval_examples\n\n\n\ndef main(_):\n tf.logging.set_verbosity(tf.logging.INFO)\n print(willy_check_code)\n \n bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)\n\n validate_flags_or_throw(bert_config)\n\n tf.gfile.MakeDirs(FLAGS.output_dir)\n\n tokenizer = tokenization.FullTokenizer(\n vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)\n\n tpu_cluster_resolver = None\n if FLAGS.use_tpu and FLAGS.tpu_name:\n tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(\n FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)\n\n is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2\n run_config = tf.contrib.tpu.RunConfig(\n cluster=tpu_cluster_resolver,\n master=FLAGS.master,\n model_dir=FLAGS.output_dir,\n save_checkpoints_steps=FLAGS.save_checkpoints_steps,\n tpu_config=tf.contrib.tpu.TPUConfig(\n iterations_per_loop=FLAGS.iterations_per_loop,\n num_shards=FLAGS.num_tpu_cores,\n per_host_input_for_training=is_per_host))\n\n train_examples = None\n num_train_steps = None\n num_warmup_steps = None\n \n ranker = None\n \n #------------------------do train(Start-(1))----------------------------#\n if FLAGS.do_train:\n train_examples = read_squad_examples(\n input_file=FLAGS.train_file, is_training=True)\n num_train_steps = int(\n len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)\n num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)\n\n # Pre-shuffle the input to avoid having to make a very large shuffle\n # buffer in in the `input_fn`.\n rng = random.Random(12345)\n rng.shuffle(train_examples)\n #--------------------------do train(End-(1))----------------------------#\n\n model_fn = model_fn_builder(\n bert_config=bert_config,\n init_checkpoint=FLAGS.init_checkpoint,\n learning_rate=FLAGS.learning_rate,\n num_train_steps=num_train_steps,\n num_warmup_steps=num_warmup_steps,\n use_tpu=FLAGS.use_tpu,\n use_one_hot_embeddings=FLAGS.use_tpu)\n\n # If TPU is not available, this will fall back to normal Estimator on CPU\n # or GPU.\n estimator = tf.contrib.tpu.TPUEstimator(\n use_tpu=FLAGS.use_tpu,\n model_fn=model_fn,\n config=run_config,\n train_batch_size=FLAGS.train_batch_size,\n predict_batch_size=FLAGS.predict_batch_size)\n\n if FLAGS.do_train:\n # We write to a temporary file to avoid storing very large constant tensors\n # in memory.\n train_writer = FeatureWriter(\n filename=os.path.join(FLAGS.output_dir, \"train.tf_record\"),\n is_training=True)\n convert_examples_to_features(\n examples=train_examples,\n tokenizer=tokenizer,\n max_seq_length=FLAGS.max_seq_length,\n doc_stride=FLAGS.doc_stride,\n max_query_length=FLAGS.max_query_length,\n is_training=True,\n output_fn=train_writer.process_feature)\n train_writer.close()\n\n tf.logging.info(\"***** Running training *****\")\n tf.logging.info(\" Num orig examples = %d\", len(train_examples))\n tf.logging.info(\" Num split examples = %d\", train_writer.num_features)\n tf.logging.info(\" Batch size = %d\", FLAGS.train_batch_size)\n tf.logging.info(\" Num steps = %d\", num_train_steps)\n del train_examples\n\n train_input_fn = input_fn_builder(\n input_file=train_writer.filename,\n seq_length=FLAGS.max_seq_length,\n is_training=True,\n drop_remainder=True)\n estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)\n\n if FLAGS.do_predict: \n \n \n #print('WillyTest(1)...do Set question:%s' %(FLAGS.question_type))\n #---------------------set question , changed by willy---------------------# \n questions = list()\n '''\n if FLAGS.question_type is 'SQuAD':\n questions = read_squad_question(input_file=FLAGS.predict_file)\n elif FLAGS.question_type is 'one_question':\n questions.append(FLAGS.question)\n elif FLAGS.question_type is 'interactive':\n #TODO : interactive mode\n questions.append(FLAGS.question)\n '''\n if FLAGS.question_type == 'one_question':\n questions.append(FLAGS.question)\n elif FLAGS.question_type == 'questionTable':\n file = open(FLAGS.question_table, \"r\")\n for line in file.readlines():\n line = line.strip()\n # print line\n questions.append(line)\n \n \n #questions.append(FLAGS.question)\n \n #-------------------------------------------------------------------------#\n \n \n #--------------------set document , changed by willy--------------------# \n if FLAGS.do_retriever:\n # Set Document\n #------------------------------------------------------\n\n print('WillyTest...do SQlite')\n DOC2IDX, docments = read_sqlite_documents(input_file=FLAGS.db_file)\n\n \n '''\n print('Show DOCIDX')\n print(DOC2IDX)\n for i, DOCID in enumerate(DOC2IDX) :\n print('ID:%d ,doc:%s' %(i,DOCID))\n '''\n #------------------------------------------------------\n \n else:\n # Set Document\n tf.logging.info(\"my document_type is %s\",FLAGS.document_type)\n if FLAGS.document_type is 'Text':\n #TODO\n print('WillyTest...do Text')\n docments = read_text_documents(input_file=FLAGS.predict_file)\n \n elif FLAGS.document_type is 'SQuAD':\n #TODO\n print('WillyTest...do SQuAD')\n docments = read_squad_documents(input_file=FLAGS.predict_file)\n #else:\n #raise ValueError(\"Your document_type: %s is undefined or wrong, please reset it.\" %(FLAGS.document_type)) \n\n #-------------------------------------------------------------------------#\n \n # define\n #---------------------------------------------------\n def append_feature(feature):\n eval_features.append(feature)\n eval_writer.process_feature(feature)\n # ---------------------------------------------------\n\n #print('WillyTest(2)...do Set eval_examples')\n eval_examples=set_eval_examples(questions,DOC2IDX)\n\n #print('WillyTest(2.1)...do FeatureWriter')\n eval_writer = FeatureWriter(\n filename=os.path.join(FLAGS.output_dir, \"eval.tf_record\"),\n is_training=False)\n eval_features = []\n\n #print('WillyTest(2.2)...do convert_examples_to_features')\n convert_examples_to_features(\n examples=eval_examples,\n tokenizer=tokenizer,\n max_seq_length=FLAGS.max_seq_length,\n doc_stride=FLAGS.doc_stride,\n max_query_length=FLAGS.max_query_length,\n is_training=False,\n output_fn=append_feature)\n eval_writer.close() \n \n \n \n '''\n eval_examples = read_squad_examples(\n input_file=FLAGS.predict_file, is_training=False)\n \n \n print('WillyTest(3)...do FeatureWriter')\n eval_writer = FeatureWriter(\n filename=os.path.join(FLAGS.output_dir, \"eval.tf_record\"),\n is_training=False)\n eval_features = []\n\n print('WillyTest(4)...do convert_examples_to_features')\n convert_examples_to_features(\n examples=eval_examples,\n tokenizer=tokenizer,\n max_seq_length=FLAGS.max_seq_length,\n doc_stride=FLAGS.doc_stride,\n max_query_length=FLAGS.max_query_length,\n is_training=False,\n output_fn=append_feature)\n eval_writer.close()\n '''\n\n tf.logging.info(\"***** Running predictions *****\")\n tf.logging.info(\" Num orig examples = %d\", len(eval_examples))\n tf.logging.info(\" Num split examples = %d\", len(eval_features))\n tf.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size)\n\n\n print('WillyTest(5)...before redict_input_fn = input_fn_builder: eval_writer.filename=%s, FLAGS.max_seq_length=%d' %(eval_writer.filename,FLAGS.max_seq_length))\n predict_input_fn = input_fn_builder(\n input_file=eval_writer.filename,\n seq_length=FLAGS.max_seq_length,\n is_training=False,\n drop_remainder=False)\n\n # If running eval on the TPU, you will need to specify the number of\n # steps.\n all_results = []\n for result in estimator.predict(predict_input_fn, yield_single_examples=True):\n if len(all_results) % 1000 == 0:\n tf.logging.info(\"Processing example: %d\" % (len(all_results)))\n unique_id = int(result[\"unique_ids\"])\n start_logits = [float(x) for x in result[\"start_logits\"].flat]\n end_logits = [float(x) for x in result[\"end_logits\"].flat]\n all_results.append(RawResult(unique_id=unique_id,start_logits=start_logits,end_logits=end_logits))\n\n output_prediction_file = os.path.join(FLAGS.output_dir, \"predictions.json\")\n output_nbest_file = os.path.join(FLAGS.output_dir, \"nbest_predictions.json\")\n output_null_log_odds_file = os.path.join(FLAGS.output_dir, \"null_odds.json\")\n output_Aten_predict_file = os.path.join(FLAGS.output_dir, \"Aten_predicts.json\")\n\n print('WillyTest(8)...before write_predictions') \n write_predictions(eval_examples, eval_features, all_results,\n FLAGS.n_best_size, FLAGS.max_answer_length,\n FLAGS.do_lower_case, output_prediction_file,\n output_nbest_file, output_null_log_odds_file,\n output_Aten_predict_file\n )\n\n\n\nif __name__ == \"__main__\":\n flags.mark_flag_as_required(\"vocab_file\")\n flags.mark_flag_as_required(\"bert_config_file\")\n flags.mark_flag_as_required(\"output_dir\")\n tf.app.run()\n"
] | [
[
"tensorflow.contrib.cluster_resolver.TPUClusterResolver",
"tensorflow.logging.warning",
"tensorflow.FixedLenFeature",
"tensorflow.nn.log_softmax",
"tensorflow.reduce_sum",
"tensorflow.train.init_from_checkpoint",
"tensorflow.gfile.MakeDirs",
"tensorflow.to_int32",
"tensorflow.contrib.tpu.TPUEstimatorSpec",
"tensorflow.contrib.tpu.TPUEstimator",
"tensorflow.data.TFRecordDataset",
"tensorflow.truncated_normal_initializer",
"tensorflow.python_io.TFRecordWriter",
"tensorflow.logging.set_verbosity",
"tensorflow.trainable_variables",
"tensorflow.parse_single_example",
"tensorflow.app.run",
"tensorflow.matmul",
"tensorflow.unstack",
"tensorflow.gfile.Open",
"tensorflow.zeros_initializer",
"tensorflow.logging.info",
"tensorflow.one_hot",
"tensorflow.contrib.tpu.TPUConfig",
"tensorflow.train.Features",
"tensorflow.nn.bias_add",
"tensorflow.train.Scaffold",
"tensorflow.transpose",
"tensorflow.flags.DEFINE_string",
"tensorflow.reshape"
],
[
"tensorflow.contrib.cluster_resolver.TPUClusterResolver",
"tensorflow.logging.warning",
"tensorflow.FixedLenFeature",
"tensorflow.nn.log_softmax",
"tensorflow.gfile.GFile",
"tensorflow.reduce_sum",
"tensorflow.train.init_from_checkpoint",
"tensorflow.gfile.MakeDirs",
"tensorflow.to_int32",
"tensorflow.contrib.tpu.TPUEstimatorSpec",
"tensorflow.contrib.tpu.TPUEstimator",
"tensorflow.data.TFRecordDataset",
"tensorflow.truncated_normal_initializer",
"tensorflow.python_io.TFRecordWriter",
"tensorflow.logging.set_verbosity",
"tensorflow.trainable_variables",
"tensorflow.parse_single_example",
"tensorflow.app.run",
"tensorflow.matmul",
"tensorflow.unstack",
"tensorflow.gfile.Open",
"tensorflow.zeros_initializer",
"tensorflow.logging.info",
"tensorflow.one_hot",
"tensorflow.contrib.tpu.TPUConfig",
"tensorflow.train.Features",
"tensorflow.nn.bias_add",
"tensorflow.train.Scaffold",
"tensorflow.transpose",
"tensorflow.flags.DEFINE_string",
"tensorflow.reshape"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"1.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.8",
"1.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"1.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.8",
"1.2",
"2.10"
]
}
] |
jjgoings/cclib | [
"56e34d48d0f6bb5e7a940873558b57bd3a59a7d8"
] | [
"cclib/parser/data.py"
] | [
"# -*- coding: utf-8 -*-\r\n#\r\n# Copyright (c) 2019, the cclib development team\r\n#\r\n# This file is part of cclib (http://cclib.github.io) and is distributed under\r\n# the terms of the BSD 3-Clause License.\r\n\r\n\"\"\"Classes and tools for storing and handling parsed data\"\"\"\r\n\r\nimport logging\r\nfrom collections import namedtuple\r\n\r\nimport numpy\r\n\r\nfrom cclib.method import Electrons\r\nfrom cclib.method import orbitals\r\n\r\n\r\nAttribute = namedtuple('Attribute', ['type', 'json_key', 'attribute_path'])\r\n\r\n\r\nclass ccData(object):\r\n \"\"\"Stores data extracted by cclib parsers\r\n\r\n Description of cclib attributes:\r\n aonames -- atomic orbital names (list of strings)\r\n aooverlaps -- atomic orbital overlap matrix (array[2])\r\n atombasis -- indices of atomic orbitals on each atom (list of lists)\r\n atomcharges -- atomic partial charges (dict of arrays[1])\r\n atomcoords -- atom coordinates (array[3], angstroms)\r\n atommasses -- atom masses (array[1], daltons)\r\n atomnos -- atomic numbers (array[1])\r\n atomspins -- atomic spin densities (dict of arrays[1])\r\n ccenergies -- molecular energies with Coupled-Cluster corrections (array[2], eV)\r\n charge -- net charge of the system (integer)\r\n coreelectrons -- number of core electrons in atom pseudopotentials (array[1])\r\n enthalpy -- sum of electronic and thermal enthalpies (float, hartree/particle)\r\n entropy -- entropy (float, hartree/particle)\r\n etenergies -- energies of electronic transitions (array[1], 1/cm)\r\n etoscs -- oscillator strengths of electronic transitions (array[1])\r\n etrotats -- rotatory strengths of electronic transitions (array[1], ??)\r\n etsecs -- singly-excited configurations for electronic transitions (list of lists)\r\n etsyms -- symmetries of electronic transitions (list of string)\r\n freeenergy -- sum of electronic and thermal free energies (float, hartree/particle)\r\n fonames -- fragment orbital names (list of strings)\r\n fooverlaps -- fragment orbital overlap matrix (array[2])\r\n fragnames -- names of fragments (list of strings)\r\n frags -- indices of atoms in a fragment (list of lists)\r\n gbasis -- coefficients and exponents of Gaussian basis functions (PyQuante format)\r\n geotargets -- targets for convergence of geometry optimization (array[1])\r\n geovalues -- current values for convergence of geometry optmization (array[1])\r\n grads -- current values of forces (gradients) in geometry optimization (array[3])\r\n hessian -- elements of the force constant matrix (array[1])\r\n homos -- molecular orbital indices of HOMO(s) (array[1])\r\n metadata -- various metadata about the package and computation (dict)\r\n mocoeffs -- molecular orbital coefficients (list of arrays[2])\r\n moenergies -- molecular orbital energies (list of arrays[1], eV)\r\n moments -- molecular multipole moments (list of arrays[], a.u.)\r\n mosyms -- orbital symmetries (list of lists)\r\n mpenergies -- molecular electronic energies with Møller-Plesset corrections (array[2], eV)\r\n mult -- multiplicity of the system (integer)\r\n natom -- number of atoms (integer)\r\n nbasis -- number of basis functions (integer)\r\n nmo -- number of molecular orbitals (integer)\r\n nocoeffs -- natural orbital coefficients (array[2])\r\n nooccnos -- natural orbital occupation numbers (array[1])\r\n nsocoeffs -- natural spin orbital coefficients (list of array[2])\r\n nsooccnos -- natural spin orbital occupation numbers (list of array[1])\r\n optdone -- flags whether an optimization has converged (Boolean)\r\n optstatus -- optimization status for each set of atomic coordinates (array[1])\r\n polarizabilities -- (dipole) polarizabilities, static or dynamic (list of arrays[2])\r\n pressure -- temperature used for Thermochemistry (float, atm)\r\n scancoords -- geometries of each scan step (array[3], angstroms)\r\n scanenergies -- energies of potential energy surface (list)\r\n scannames -- names of varaibles scanned (list of strings)\r\n scanparm -- values of parameters in potential energy surface (list of tuples)\r\n scfenergies -- molecular electronic energies after SCF (Hartree-Fock, DFT) (array[1], eV)\r\n scftargets -- targets for convergence of the SCF (array[2])\r\n scfvalues -- current values for convergence of the SCF (list of arrays[2])\r\n temperature -- temperature used for Thermochemistry (float, kelvin)\r\n time -- time in molecular dynamics and other trajectories (array[1], fs)\r\n transprop -- all absorption and emission spectra (dictionary {name:(etenergies, etoscs)})\n WARNING: this attribute is not standardized and is liable to change in cclib 2.0\n vibanharms -- vibrational anharmonicity constants (array[2], 1/cm)\r\n vibdisps -- cartesian displacement vectors (array[3], delta angstrom)\r\n vibfreqs -- vibrational frequencies (array[1], 1/cm)\r\n vibirs -- IR intensities (array[1], km/mol)\r\n vibmass -- Vibrational reduced mass (array[1], Da)\n vibramans -- Raman intensities (array[1], A^4/Da)\r\n vibsyms -- symmetries of vibrations (list of strings)\r\n (1) The term 'array' refers to a numpy array\r\n (2) The number of dimensions of an array is given in square brackets\r\n (3) Python indexes arrays/lists starting at zero, so if homos==[10], then\r\n the 11th molecular orbital is the HOMO\r\n \"\"\"\r\n\r\n # The expected types for all supported attributes.\r\n # The json_key is the key name used for attributes in the CJSON/JSON format\r\n # 'TBD' - To Be Decided are the key names of attributes which haven't been included in the cjson format\r\n _attributes = {\r\n \"aonames\": Attribute(list, 'names', 'atoms:orbitals'),\r\n \"aooverlaps\": Attribute(numpy.ndarray, 'overlaps', 'properties:orbitals'),\r\n \"atombasis\": Attribute(list, 'indices', 'atoms:orbitals'),\r\n \"atomcharges\": Attribute(dict, 'partial charges', 'properties'),\r\n \"atomcoords\": Attribute(numpy.ndarray, 'coords', 'atoms:coords:3d'),\r\n \"atommasses\": Attribute(numpy.ndarray, 'mass', 'atoms'),\r\n \"atomnos\": Attribute(numpy.ndarray, 'number', 'atoms:elements'),\r\n \"atomspins\": Attribute(dict, 'spins', 'atoms'),\r\n \"ccenergies\": Attribute(numpy.ndarray, 'coupled cluster', 'properties:energy'),\r\n \"charge\": Attribute(int, 'charge', 'properties'),\r\n \"coreelectrons\": Attribute(numpy.ndarray, 'core electrons', 'atoms'),\r\n \"enthalpy\": Attribute(float, 'enthalpy', 'properties'),\r\n \"entropy\": Attribute(float, 'entropy', 'properties'),\r\n \"etenergies\": Attribute(numpy.ndarray, 'electronic transitions', 'transitions'),\r\n \"etoscs\": Attribute(numpy.ndarray, 'oscillator strength', 'transitions'),\r\n \"etrotats\": Attribute(numpy.ndarray, 'rotatory strength', 'transitions'),\r\n \"etsecs\": Attribute(list, 'one excited config', 'transitions'),\r\n \"etsyms\": Attribute(list, 'symmetry', 'transitions'),\r\n \"freeenergy\": Attribute(float, 'free energy', 'properties:energy'),\r\n \"fonames\": Attribute(list, 'orbital names', 'fragments'),\r\n \"fooverlaps\": Attribute(numpy.ndarray, 'orbital overlap', 'fragments'),\r\n \"fragnames\": Attribute(list, 'fragment names', 'fragments'),\r\n \"frags\": Attribute(list, 'atom indices', 'fragments'),\r\n \"gbasis\": Attribute(list, 'basis functions', 'atoms:orbitals'),\r\n \"geotargets\": Attribute(numpy.ndarray, 'geometric targets', 'optimization'),\r\n \"geovalues\": Attribute(numpy.ndarray, 'geometric values', 'optimization'),\r\n \"grads\": Attribute(numpy.ndarray, 'TBD', 'N/A'),\r\n \"hessian\": Attribute(numpy.ndarray, 'hessian matrix', 'vibrations'),\r\n \"homos\": Attribute(numpy.ndarray, 'homos', 'properties:orbitals'),\r\n \"metadata\": Attribute(dict, 'TBD', 'N/A'),\r\n \"mocoeffs\": Attribute(list, 'coeffs', 'properties:orbitals'),\r\n \"moenergies\": Attribute(list, 'energies', 'properties:orbitals'),\r\n \"moments\": Attribute(list, 'total dipole moment', 'properties'),\r\n \"mosyms\": Attribute(list, 'molecular orbital symmetry', 'properties:orbitals'),\r\n \"mpenergies\": Attribute(numpy.ndarray, 'moller plesset', 'properties:energy'),\r\n \"mult\": Attribute(int, 'multiplicity', 'properties'),\r\n \"natom\": Attribute(int, 'number of atoms', 'properties'),\r\n \"nbasis\": Attribute(int, 'basis number', 'properties:orbitals'),\r\n \"nmo\": Attribute(int, 'MO number', 'properties:orbitals'),\r\n \"nocoeffs\": Attribute(numpy.ndarray, 'TBD', 'N/A'),\r\n \"nooccnos\": Attribute(numpy.ndarray, 'TBD', 'N/A'),\r\n \"nsocoeffs\": Attribute(list, 'TBD', 'N/A'),\r\n \"nsooccnos\": Attribute(list, 'TBD', 'N/A'),\r\n \"optdone\": Attribute(list, 'done', 'optimization'),\r\n \"optstatus\": Attribute(numpy.ndarray, 'status', 'optimization'),\r\n \"polarizabilities\": Attribute(list, 'polarizabilities', 'N/A'),\r\n \"pressure\": Attribute(float, 'pressure', 'properties'),\r\n \"scancoords\": Attribute(numpy.ndarray, 'step geometry', 'optimization:scan'),\r\n \"scanenergies\": Attribute(list, 'PES energies', 'optimization:scan'),\r\n \"scannames\": Attribute(list, 'variable names', 'optimization:scan'),\r\n \"scanparm\": Attribute(list, 'PES parameter values', 'optimization:scan'),\r\n \"scfenergies\": Attribute(numpy.ndarray, 'scf energies', 'optimization:scf'),\r\n \"scftargets\": Attribute(numpy.ndarray, 'targets', 'optimization:scf'),\r\n \"scfvalues\": Attribute(list, 'values', 'optimization:scf'),\r\n \"temperature\": Attribute(float, 'temperature', 'properties'),\r\n \"time\": Attribute(numpy.ndarray, 'time', 'N/A'),\r\n \"transprop\": Attribute(dict, 'electronic transitions', 'transitions'),\n \"vibanharms\": Attribute(numpy.ndarray, 'anharmonicity constants', 'vibrations'),\r\n \"vibdisps\": Attribute(numpy.ndarray, 'displacement', 'vibrations'),\r\n \"vibfreqs\": Attribute(numpy.ndarray, 'frequencies', 'vibrations'),\r\n \"vibirs\": Attribute(numpy.ndarray, 'IR', 'vibrations:intensities'),\r\n \"vibmass\": Attribute(numpy.ndarray, 'Reduced Mass', 'vibrations'),\n \"vibramans\": Attribute(numpy.ndarray, 'raman', 'vibrations:intensities'),\r\n \"vibsyms\": Attribute(list, 'vibration symmetry', 'vibrations')\r\n }\r\n\r\n # The name of all attributes can be generated from the dictionary above.\r\n _attrlist = sorted(_attributes.keys())\r\n\r\n # Arrays are double precision by default, but these will be integer arrays.\r\n _intarrays = ['atomnos', 'coreelectrons', 'homos', 'optstatus']\r\n\r\n # Attributes that should be lists of arrays (double precision).\r\n _listsofarrays = ['mocoeffs', 'moenergies', 'moments', 'polarizabilities', 'scfvalues']\r\n\r\n # Attributes that should be dictionaries of arrays (double precision).\r\n _dictsofarrays = [\"atomcharges\", \"atomspins\"]\r\n\r\n # Possible statuses for optimization steps.\r\n # OPT_UNKNOWN is the default and means optimization is in progress.\r\n # OPT_NEW is set for every new optimization (e.g. PES, IRCs, etc.)\r\n # OPT_DONE is set for the last step of an optimisation that converged.\r\n # OPT_UNCONVERGED is set for every unconverged step (e.g. should be mutually exclusive with OPT_DONE)\r\n # bit value notation allows coding for multiple states: OPT_NEW and OPT_UNCONVERGED or OPT_NEW and OPT_DONE.\r\n OPT_UNKNOWN = 0b000\r\n OPT_NEW = 0b001\r\n OPT_UNCONVERGED = 0b010\r\n OPT_DONE = 0b100\r\n\r\n def __init__(self, attributes={}):\r\n \"\"\"Initialize the cclibData object.\r\n\r\n Normally called in the parse() method of a Logfile subclass.\r\n\r\n Inputs:\r\n attributes - optional dictionary of attributes to load as data\r\n \"\"\"\r\n\r\n if attributes:\r\n self.setattributes(attributes)\r\n\r\n def listify(self):\r\n \"\"\"Converts all attributes that are arrays or lists/dicts of arrays to lists.\"\"\"\r\n\r\n attrlist = [k for k in self._attrlist if hasattr(self, k)]\r\n for k in attrlist:\r\n v = self._attributes[k].type\r\n if v == numpy.ndarray:\r\n setattr(self, k, getattr(self, k).tolist())\r\n elif v == list and k in self._listsofarrays:\r\n setattr(self, k, [x.tolist() for x in getattr(self, k)])\r\n elif v == dict and k in self._dictsofarrays:\r\n items = getattr(self, k).items()\r\n pairs = [(key, val.tolist()) for key, val in items]\r\n setattr(self, k, dict(pairs))\r\n\r\n def arrayify(self):\r\n \"\"\"Converts appropriate attributes to arrays or lists/dicts of arrays.\"\"\"\r\n\r\n attrlist = [k for k in self._attrlist if hasattr(self, k)]\r\n for k in attrlist:\r\n v = self._attributes[k].type\r\n precision = 'd'\r\n if k in self._intarrays:\r\n precision = 'i'\r\n if v == numpy.ndarray:\r\n setattr(self, k, numpy.array(getattr(self, k), precision))\r\n elif v == list and k in self._listsofarrays:\r\n setattr(self, k, [numpy.array(x, precision) for x in getattr(self, k)])\r\n elif v == dict and k in self._dictsofarrays:\r\n items = getattr(self, k).items()\r\n pairs = [(key, numpy.array(val, precision)) for key, val in items]\r\n setattr(self, k, dict(pairs))\r\n\r\n def getattributes(self, tolists=False):\r\n \"\"\"Returns a dictionary of existing data attributes.\r\n\r\n Inputs:\r\n tolists - flag to convert attributes to lists where applicable\r\n \"\"\"\r\n\r\n if tolists:\r\n self.listify()\r\n attributes = {}\r\n for attr in self._attrlist:\r\n if hasattr(self, attr):\r\n attributes[attr] = getattr(self, attr)\r\n if tolists:\r\n self.arrayify()\r\n return attributes\r\n\r\n def setattributes(self, attributes):\r\n \"\"\"Sets data attributes given in a dictionary.\r\n\r\n Inputs:\r\n attributes - dictionary of attributes to set\r\n Outputs:\r\n invalid - list of attributes names that were not set, which\r\n means they are not specified in self._attrlist\r\n \"\"\"\r\n\r\n if type(attributes) is not dict:\r\n raise TypeError(\"attributes must be in a dictionary\")\r\n\r\n valid = [a for a in attributes if a in self._attrlist]\r\n invalid = [a for a in attributes if a not in self._attrlist]\r\n\r\n for attr in valid:\r\n setattr(self, attr, attributes[attr])\r\n\r\n self.arrayify()\r\n self.typecheck()\r\n\r\n return invalid\r\n\r\n def typecheck(self):\r\n \"\"\"Check the types of all attributes.\r\n\r\n If an attribute does not match the expected type, then attempt to\r\n convert; if that fails, only then raise a TypeError.\r\n \"\"\"\r\n\r\n self.arrayify()\r\n for attr in [a for a in self._attrlist if hasattr(self, a)]:\r\n\r\n val = getattr(self, attr)\r\n if type(val) == self._attributes[attr].type:\r\n continue\r\n\r\n try:\r\n val = self._attributes[attr].type(val)\r\n except ValueError:\r\n args = (attr, type(val), self._attributes[attr].type)\r\n raise TypeError(\"attribute %s is %s instead of %s and could not be converted\" % args)\r\n\r\n def check_values(self, logger=logging):\r\n \"\"\"Perform custom checks on the values of attributes.\"\"\"\r\n if hasattr(self, \"etenergies\") and any(e < 0 for e in self.etenergies):\r\n negative_values = [e for e in self.etenergies if e < 0]\r\n msg = (\"At least one excitation energy is negative. \"\r\n \"\\nNegative values: %s\\nFull etenergies: %s\"\r\n % (negative_values, self.etenergies))\r\n logger.error(msg)\r\n\r\n def write(self, filename=None, indices=None, *args, **kwargs):\r\n \"\"\"Write parsed attributes to a file.\r\n\r\n Possible extensions:\r\n .cjson or .json - output a chemical JSON file\r\n .cml - output a chemical markup language (CML) file\r\n .xyz - output a Cartesian XYZ file of the last coordinates available\r\n \"\"\"\r\n\r\n from cclib.io import ccwrite\r\n outputstr = ccwrite(self, outputdest=filename, indices=indices,\n *args, **kwargs)\r\n return outputstr\r\n\r\n def writejson(self, filename=None, indices=None):\r\n \"\"\"Write parsed attributes to a JSON file.\"\"\"\r\n return self.write(filename=filename, indices=indices,\n outputtype='cjson')\r\n\r\n def writecml(self, filename=None, indices=None):\r\n \"\"\"Write parsed attributes to a CML file.\"\"\"\r\n return self.write(filename=filename, indices=indices,\n outputtype='cml')\r\n\r\n def writexyz(self, filename=None, indices=None):\r\n \"\"\"Write parsed attributes to an XML file.\"\"\"\r\n return self.write(filename=filename, indices=indices,\n outputtype='xyz')\r\n\r\n @property\r\n def converged_geometries(self):\r\n \"\"\"\r\n Return all converged geometries.\r\n\r\n An array containing only the converged geometries, e.g.:\r\n - For PES or IRCs, return all geometries for which optstatus matches OPT_DONE\r\n - The converged geometry for simple optimisations\r\n - The input geometry for single points\r\n \"\"\"\r\n if hasattr(self, 'optstatus'):\r\n converged_indexes = [x for x, y in enumerate(self.optstatus) if y & self.OPT_DONE > 0]\r\n return self.atomcoords[converged_indexes]\r\n else:\r\n return self.atomcoords\r\n\r\n @property\r\n def new_geometries(self):\r\n \"\"\"\r\n Return all starting geometries.\r\n\r\n An array containing only the starting geometries, e.g.:\r\n - For PES or IRCs, return all geometries for which optstatus matches OPT_NEW\r\n - The input geometry for simple optimisations or single points\r\n \"\"\"\r\n if hasattr(self, 'optstatus'):\r\n new_indexes = [x for x, y in enumerate(self.optstatus) if y & self.OPT_NEW > 0]\r\n return self.atomcoords[new_indexes]\r\n else:\r\n return self.atomcoords\r\n\r\n @property\r\n def unknown_geometries(self):\r\n \"\"\"\r\n Return all OPT_UNKNOWN geometries.\r\n\r\n An array containing only the starting geometries, e.g.:\r\n - For PES or IRCs, return all geometries for which optstatus matches OPT_UNKNOWN\r\n - The input geometry for simple optimisations or single points\r\n \"\"\"\r\n if hasattr(self, 'optstatus'):\r\n unknown_indexes = [x for x, y in enumerate(self.optstatus) if y == self.OPT_UNKNOWN]\r\n return self.atomcoords[unknown_indexes]\r\n else:\r\n return self.atomcoords\r\n\r\n @property\r\n def unconverged_geometries(self):\r\n \"\"\"\r\n Return all unconverged geometries.\r\n\r\n An array containing only the starting geometries, e.g.:\r\n - For PES or IRCs, return all geometries for which optstatus matches OPT_UNCONVERGED\r\n - The input geometry for simple optimisations or single points\r\n \"\"\"\r\n if hasattr(self, 'optstatus'):\r\n unconverged_indexes = [x for x, y in enumerate(self.optstatus) if y & self.OPT_UNCONVERGED > 0]\r\n return self.atomcoords[unconverged_indexes]\r\n else:\r\n return self.atomcoords\r\n\r\n @property\r\n def nelectrons(self):\r\n return Electrons(self).count()\r\n\r\n @property\r\n def closed_shell(self):\r\n return orbitals.Orbitals(self).closed_shell()\r\n\r\n\r\nclass ccData_optdone_bool(ccData):\r\n \"\"\"This is the version of ccData where optdone is a Boolean.\"\"\"\r\n\r\n def __init__(self, *args, **kwargs):\r\n\r\n super(ccData_optdone_bool, self).__init__(*args, **kwargs)\r\n self._attributes[\"optdone\"] = Attribute(bool, 'done', 'optimization')\r\n\r\n def setattributes(self, *args, **kwargs):\r\n invalid = super(ccData_optdone_bool, self).setattributes(*args, **kwargs)\r\n\r\n # Reduce optdone to a Boolean, because it will be parsed as a list. If this list has any element,\r\n # it means that there was an optimized structure and optdone should be True.\r\n if hasattr(self, 'optdone'):\r\n self.optdone = len(self.optdone) > 0\r\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ischtz/lighthouse-inventory | [
"fab4d47eb9fc3e74223814b7e8dfb955337aa5cc"
] | [
"lh_inventory.py"
] | [
"\"\"\"\nUtility to inventorize SteamVR (Lighthouse) tracked devices from \ntheir JSON config files. \n\"\"\"\n\nimport os\nimport glob\nimport json\nimport pprint\nimport argparse\n\nimport pandas as pd\n\nLH_PATH = os.environ['ProgramFiles(x86)'] + '\\\\Steam\\\\config\\\\lighthouse'\nSEP = ';'\n\nif __name__ == '__main__':\n\n # Parse command line arguments\n desc = 'Tool to create a list (CSV) of all tracked Lighthouse devices (e.g. HMD, controllers, Vive Trackers) known to SteamVR. '\n desc += 'Alternatively, compiles such a list from JSON config files downloaded from SteamVR devices using lighthouse_console.exe.'\n ap = argparse.ArgumentParser(description=desc)\n ap.add_argument('-j', '--json_files', default=None, help='JSON files or folders to convert, e.g. \"folder/*.json\"')\n ap.add_argument('-o', dest='output_file', default=None, metavar='output_file', help='Ouput file (default: steamvr_inventory.tsv)')\n ap.add_argument('-u', dest='update', action='store_true', default=False, help='Update output file instead of overwriting')\n ap.add_argument('-d', dest='debug', action='store_true', default=False, help='If set, print out JSON and MAT file structures')\n options = ap.parse_args()\n\n # Set default options\n if options.output_file is None:\n output_file = 'steamvr_inventory.csv'\n else:\n output_file = options.output_file \n if options.json_files is None:\n print('Reading local lighthouse config at {:s}...\\n'.format(LH_PATH))\n jfiles = glob.glob(LH_PATH + '\\\\**\\\\*.json', recursive=True)\n else:\n if os.path.isdir(options.json_files):\n print('Reading JSON config files from {:s}...\\n'.format(options.json_files))\n jfiles = glob.glob(os.path.join(options.json_files, '**\\\\*.json'), recursive=True)\n else:\n jfiles = glob.glob(options.json_files)\n\n df = []\n\n for j in jfiles:\n if os.path.split(j)[1] == 'lighthousedb.json':\n continue # Skip base station config db\n\n with open(j, 'rb') as f:\n data = json.load(f)\n basename = os.path.splitext(os.path.split(j)[-1])[0]\n if options.debug:\n print('JSON INPUT: {:s}'.format(j))\n pprint.pprint(data)\n print('\\n\\n')\n\n # Drop every key that doesn't contain a single value\n dropped = []\n for k in data.keys():\n if type(data[k]) in (dict, tuple, list):\n dropped.append(k)\n for k in dropped:\n del data[k]\n\n # Add file name for easy reference\n data['_input_file'] = basename\n try:\n print('{:s}: {:s}, {:s} ({:s})'.format(data['device_serial_number'],\n data['manufacturer'],\n data['model_number'],\n data['device_class']))\n except:\n print(' ') # don't break if one of above fields isn't defined\n \n df.append(data)\n\n df = pd.DataFrame(df)\n if options.update and os.path.isfile(output_file):\n df_old = pd.read_csv(output_file, sep=SEP, index_col=False)\n df = df.merge(df_old, how='outer')\n \n if options.debug:\n print(df)\n\n df.sort_values(['device_class']).to_csv(output_file, sep=SEP, index=False)\n print('\\nSaved {:d} devices to {:s}.'.format(df.shape[0], output_file))\n"
] | [
[
"pandas.read_csv",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.