repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
qf6101/preprocess_tabular_data | [
"8c2a2064d0be175b4d4ae68bd6c5b6874b009067"
]
| [
"auto_inspect/funcs.py"
]
| [
"import math\nfrom datetime import datetime\nimport numpy as np\nfrom typing import Tuple, Optional, List, Set, Dict\nfrom pandas import Series, DataFrame\nimport ruamel.yaml as yaml\n\n\ndef inspect_dtype(col: Series, predefined_dtype=None) -> Tuple[str, bool]:\n dtype = 'int'\n all_missing = False\n all_samevalue = False\n\n if predefined_dtype:\n dtype = predefined_dtype\n else:\n for v in col:\n if isinstance(v, str):\n dtype = 'str'\n break\n\n if isinstance(v, datetime):\n dtype = 'time'\n break\n\n if not np.isnan(v) and math.ceil(v) > v:\n dtype = 'float'\n break\n\n col2 = col.dropna()\n\n if dtype == 'int':\n col2 = [int(v) for v in col2]\n if all([(np.isnan(v) | (v == 0)) for v in col2]):\n all_missing = True\n\n if dtype == 'str':\n if len(set(col)) == 1:\n all_samevalue = True\n elif dtype == 'int' or dtype == 'float':\n col2 = np.array([float(v) for v in col2])\n if len(set(col2)) == 1:\n all_samevalue = True\n\n return dtype, all_missing | all_samevalue\n\n\ndef inspect_categorical(col: Series, dtype: str, min_distinct=5) -> Optional[Set]:\n if dtype == 'str':\n feature_candidates = set(col)\n if np.nan in feature_candidates:\n feature_candidates.remove(np.nan)\n return feature_candidates\n elif dtype == 'int':\n col2 = np.array(col)\n col2 = col2[col2 != 0]\n feature_candidates = set(col2)\n\n if 2 < len(feature_candidates) < min_distinct:\n return feature_candidates\n elif (len(feature_candidates) == 2) and (0 in feature_candidates):\n return feature_candidates\n\n return None\n\n\ndef inspect_buckets(col: Series) -> List:\n col2 = np.array(col)\n buckets = np.percentile(col2, range(10, 100, 10))\n buckets = sorted(list(set(buckets)))\n return buckets\n\n\ndef inspect_standardscale(col: Series, min_diff=1000) -> Tuple[str, float, float]:\n col2 = np.array([float(v) for v in col])\n col2 = col2[~(col2 == 0)]\n\n if max(col2) - min(col2) > min_diff:\n col2 = np.log1p(col2)\n log_op = 'ln'\n else:\n log_op = 'direct'\n\n return log_op, np.mean(col2), np.std(col2)\n\n\ndef inspect_column(col: Series, bucketize_int=True, categorical_min_distinct=5,\n standardscale_min_diff=1000, predefined_dtype=None) -> Dict[str, object]:\n dtype, useless = inspect_dtype(col, predefined_dtype)\n\n if not useless:\n kinds = inspect_categorical(col, dtype, categorical_min_distinct)\n\n if kinds:\n return {'btype': 'categorical', 'dtype': dtype, 'kinds': kinds}\n else:\n if bucketize_int and dtype == 'int':\n buckets = inspect_buckets(col)\n if (len(buckets) == 2 and 0 in set(buckets)) or (len(buckets) > 2):\n return {'btype': 'bucketizing', 'dtype': dtype, 'buckets': buckets}\n elif dtype == 'int' or dtype == 'float':\n standardscale = inspect_standardscale(col, standardscale_min_diff)\n return {'btype': 'realvalued', 'dtype': dtype, 'standardscale': standardscale}\n elif dtype == 'time':\n return {'btype': 'time', 'dtype': dtype}\n\n return {'btype': 'useless', 'dtype': dtype}\n\n\ndef inspect_dataframe(df: DataFrame, skip_cols=[], bucketize_int=True, categorical_min_distinct=5,\n standardscale_min_diff=1000, predefined_dtypes={}, skip_vals=[]) -> Dict[str, object]:\n outp = {}\n skip_cols = set(skip_cols)\n for c in df.columns:\n if c not in skip_cols:\n if c in predefined_dtypes:\n predefined_dtype = predefined_dtypes[c]\n else:\n predefined_dtype = None\n\n col = df[c]\n for sv in skip_vals:\n col = col.replace(to_replace=sv, value=np.nan)\n col = col.dropna()\n\n outp[c] = inspect_column(col, bucketize_int, categorical_min_distinct, standardscale_min_diff,\n predefined_dtype=predefined_dtype)\n return outp\n\n\ndef save_inspected(inspected: Dict[str, object], fname: str, skip_time=False) -> None:\n to_save = []\n\n for k, v in inspected.items():\n if v['btype'] == 'useless':\n continue\n elif skip_time and v['btype'] == 'time':\n continue\n else:\n dtype = v['dtype']\n\n if dtype == 'str':\n fill_missing = 'unknown'\n elif dtype == 'time':\n fill_missing = '-'\n else:\n fill_missing = -99998\n\n operations = [{'fill_missing': fill_missing}]\n\n if 'kinds' in v:\n if dtype == 'str':\n operations.append({'kinds': [str(i) for i in v['kinds']]})\n elif dtype == 'int':\n operations.append({'kinds': [int(i) for i in v['kinds']]})\n elif 'buckets' in v:\n operations.append({'buckets': [int(i) for i in v['buckets']]})\n elif 'standardscale' in v:\n if v['standardscale'][0] == 'ln':\n operations.append({'log': 'ln'})\n operations.append({'mean': float(v['standardscale'][1]), 'std': float(v['standardscale'][2])})\n\n to_save.append({'attribute':\n {'name': k, 'btype': v['btype'], 'dtype': v['dtype'], 'operations': operations}\n })\n\n with open(fname, 'w') as f:\n yaml.round_trip_dump(to_save, f, default_flow_style=False)\n"
]
| [
[
"numpy.array",
"numpy.isnan",
"numpy.mean",
"numpy.log1p",
"numpy.std"
]
]
|
empyriumz/QAS_RL | [
"1f44f46acd9e61a8ed501cc7f0462c7217f46316"
]
| [
"utils.py"
]
| [
"import configparser\nimport numpy as np\nfrom chemical_hamiltonians import (\n qiskit_LiH_chem,\n qiskit_H2_chem,\n paulis2matrices,\n)\nimport json\nfrom itertools import product\n\n\ndef gen_hamiltonian(num_qubits, conf, taper=True, exact_en=False):\n if conf[\"ham_type\"] == \"LiH\":\n paulis, paulis_qulacs, weights, energies, shift = qiskit_LiH_chem(\n conf[\"geometry\"], conf[\"taper\"], exact_en, conf[\"mapping\"]\n )\n\n # observable = Observable(num_qubits)\n # for i in range(len(paulis)):\n # observable.add_operator(weights[i], paulis_qulacs[i])\n ham = paulis2matrices(paulis)\n tmp = [weights[i] * ham[i] for i in range(len(paulis))]\n hamiltonian = np.sum(tmp, axis=0)\n\n return hamiltonian, energies, shift\n elif conf[\"ham_type\"] == \"H2\":\n assert num_qubits == 2, \"H2 molecule has 2 qubit Hamiltonian\"\n paulis, paulis_qulacs, w, shift = qiskit_H2_chem(conf[\"geometry\"])\n # observable = Observable(num_qubits)\n # for i in range(len(paulis)):\n # observable.add_operator(weights[i], paulis_qulacs[i])\n ham = paulis2matrices(paulis)\n tmp = [w[i] * ham[i] for i in range(len(paulis))]\n hamiltonian = np.sum(tmp, axis=0)\n eigvals, eigvecs = np.linalg.eig(hamiltonian)\n return hamiltonian, eigvals.real, shift\n\n\ndef get_config(config_name, experiment_name, path=\"configuration_files\", verbose=True):\n config_dict = {}\n Config = configparser.ConfigParser()\n Config.read(\"{}/{}{}\".format(path, config_name, experiment_name))\n for sections in Config:\n config_dict[sections] = {}\n for key, val in Config.items(sections):\n # config_dict[sections].update({key: json.loads(val)})\n try:\n config_dict[sections].update({key: int(val)})\n except ValueError:\n config_dict[sections].update({key: val})\n floats = [\n \"learning_rate\",\n \"dropout\",\n \"alpha\",\n \"beta\",\n \"beta_incr\",\n \"shift_threshold_ball\",\n \"succes_switch\",\n \"tolearance_to_thresh\",\n \"memory_reset_threshold\",\n \"fake_min_energy\",\n \"_true_en\",\n ]\n strings = [\n \"ham_type\",\n \"fn_type\",\n \"geometry\",\n \"method\",\n \"agent_type\",\n \"agent_class\",\n \"init_seed\",\n \"init_path\",\n \"init_thresh\",\n \"method\",\n \"mapping\",\n \"optim_alg\",\n \"curriculum_type\",\n ]\n lists = [\n \"episodes\",\n \"neurons\",\n \"accept_err\",\n \"epsilon_decay\",\n \"epsilon_min\",\n \"epsilon_decay\",\n \"final_gamma\",\n \"memory_clean\",\n \"update_target_net\",\n \"epsilon_restart\",\n \"thresholds\",\n \"switch_episodes\",\n ]\n if key in floats:\n config_dict[sections].update({key: float(val)})\n elif key in strings:\n config_dict[sections].update({key: str(val)})\n elif key in lists:\n config_dict[sections].update({key: json.loads(val)})\n del config_dict[\"DEFAULT\"]\n return config_dict\n\n\ndef dictionary_of_actions(num_qubits):\n \"\"\"\n Creates dictionary of actions for system which steers positions of gates,\n and axes of rotations.\n \"\"\"\n dictionary = dict()\n i = 0\n\n for c, x in product(range(num_qubits), range(1, num_qubits)):\n dictionary[i] = [c, x, num_qubits, 0]\n i += 1\n\n \"\"\"h denotes rotation axis. 1, 2, 3 --> X, Y, Z axes \"\"\"\n for r, h in product(range(num_qubits), range(1, 4)):\n dictionary[i] = [num_qubits, 0, r, h]\n i += 1\n return dictionary\n\n\ndef dict_of_actions_revert_q(num_qubits):\n \"\"\"\n Creates dictionary of actions for system which steers positions of gates,\n and axes of rotations. Systems have reverted order to above dictionary of actions.\n \"\"\"\n dictionary = dict()\n i = 0\n\n for c, x in product(range(num_qubits - 1, -1, -1), range(num_qubits - 1, 0, -1)):\n dictionary[i] = [c, x, num_qubits, 0]\n i += 1\n\n \"\"\"h denotes rotation axis. 1, 2, 3 --> X, Y, Z axes \"\"\"\n for r, h in product(range(num_qubits - 1, -1, -1), range(1, 4)):\n dictionary[i] = [num_qubits, 0, r, h]\n i += 1\n return dictionary\n\n\nif __name__ == \"__main__\":\n from dataclasses import dataclass\n\n @dataclass\n class Config:\n num_qubits = 4\n problem = {\n \"ham_type\": \"LiH\",\n \"geometry\": \"Li .0 .0 .0; H .0 .0 2.2\",\n \"taper\": 1,\n \"mapping\": \"parity\",\n }\n\n __ham = dict()\n\n __ham[\"hamiltonian\"], __ham[\"eigvals\"], __ham[\"energy_shift\"] = gen_hamiltonian(\n Config.num_qubits, Config.problem\n )\n __geometry = Config.problem[\"geometry\"].replace(\" \", \"_\")\n np.savez(\n f\"mol_data/LiH_{Config.num_qubits}q_geom_{__geometry}_{Config.problem['mapping']}\",\n **__ham,\n )\n"
]
| [
[
"numpy.sum",
"numpy.savez",
"numpy.linalg.eig"
]
]
|
artidoro/cnn-dailymail | [
"ab5b87e267e9a289cbcf2127753edeb8080a0380"
]
| [
"chain_extractor_xsum/process_labels.py"
]
| [
"import sys\nimport os\nimport hashlib\nimport struct\nimport subprocess\nimport collections\nimport tensorflow as tf\nfrom tensorflow.core.example import example_pb2\n\ndm_single_close_quote = '\\u2019' # unicode\ndm_double_close_quote = '\\u201d'\nEND_TOKENS = ['.', '!', '?', '...', \"'\", \"`\", '\"', dm_single_close_quote, dm_double_close_quote,\n \")\"] # acceptable ways to end a sentence\n\n# We use these to separate the summary sentences in the .bin datafiles\nSENTENCE_START = '<s>'\nSENTENCE_END = '</s>'\n\nall_train_urls = \"../url_lists/url_lists_reduced_1/bbc_ids_train.txt\"\nall_val_urls = \"../url_lists/url_lists_reduced_1/bbc_ids_val.txt\"\nall_test_urls = \"../url_lists/url_lists_reduced_1/bbc_ids_test.txt\"\n\n\n# These are the number of .story files we expect there to be in bbc_stories_dir\n# num_expected_stories = 226711\nnum_expected_stories = 12000\n\nVOCAB_SIZE = 200000\nCHUNK_SIZE = 1000 # num examples per chunk, for the chunked data\n\n\ndef chunk_file(set_name):\n in_file = finished_files_dir+'/%s.bin' % set_name\n reader = open(in_file, \"rb\")\n chunk = 0\n finished = False\n while not finished:\n chunk_fname = os.path.join(chunks_dir, '%s_%03d.bin' % (set_name, chunk)) # new chunk\n with open(chunk_fname, 'wb') as writer:\n for _ in range(CHUNK_SIZE):\n len_bytes = reader.read(8)\n if not len_bytes:\n finished = True\n break\n str_len = struct.unpack('q', len_bytes)[0]\n example_str = struct.unpack('%ds' % str_len, reader.read(str_len))[0]\n writer.write(struct.pack('q', str_len))\n writer.write(struct.pack('%ds' % str_len, example_str))\n chunk += 1\n\n\ndef chunk_all():\n # Make a dir to hold the chunks\n if not os.path.isdir(chunks_dir):\n os.mkdir(chunks_dir)\n # Chunk the data\n for set_name in ['train', 'val', 'test']:\n print(\"Splitting %s data into chunks...\" % set_name)\n chunk_file(set_name)\n print(\"Saved chunked data in %s\" % chunks_dir)\n\n\ndef tokenize_stories(stories_dir, tokenized_stories_dir):\n \"\"\"Maps a whole directory of .story files to a tokenized version using Stanford CoreNLP Tokenizer\"\"\"\n print(\"Preparing to tokenize %s to %s...\" % (stories_dir, tokenized_stories_dir))\n stories = os.listdir(stories_dir)\n # make IO list file\n print(\"Making list of files to tokenize...\")\n with open(\"mapping.txt\", \"w\") as f:\n for s in stories:\n f.write(\"%s \\t %s\\n\" % (os.path.join(stories_dir, s), os.path.join(tokenized_stories_dir, s)))\n command = ['java', 'edu.stanford.nlp.process.PTBTokenizer', '-ioFileList', '-preserveLines', 'mapping.txt']\n print(\"Tokenizing %i files in %s and saving in %s...\" % (len(stories), stories_dir, tokenized_stories_dir))\n subprocess.call(command)\n print(\"Stanford CoreNLP Tokenizer has finished.\")\n os.remove(\"mapping.txt\")\n\n # Check that the tokenized stories directory contains the same number of files as the original directory\n num_orig = len(os.listdir(stories_dir))\n num_tokenized = len(os.listdir(tokenized_stories_dir))\n if num_orig != num_tokenized:\n raise Exception(\n \"The tokenized stories directory %s contains %i files, but it should contain the same number as %s (which has %i files). Was there an error during tokenization?\" % (\n tokenized_stories_dir, num_tokenized, stories_dir, num_orig))\n print(\"Successfully finished tokenizing %s to %s.\\n\" % (stories_dir, tokenized_stories_dir))\n\n\ndef read_text_file(text_file):\n lines = []\n with open(text_file, \"r\") as f:\n for line in f:\n lines.append(line.strip())\n return lines\n\n\ndef hashhex(s):\n \"\"\"Returns a heximal formated SHA1 hash of the input string.\"\"\"\n h = hashlib.sha1()\n h.update(s.encode('utf-8'))\n return h.hexdigest()\n\n\ndef get_url_hashes(url_list):\n return [hashhex(url) for url in url_list]\n\n\ndef fix_missing_period(line):\n \"\"\"Adds a period to a line that is missing a period\"\"\"\n if \"@highlight\" in line: return line\n if line == \"\": return line\n if line[-1] in END_TOKENS: return line\n # print line[-1]\n return line + \" .\"\n\n\ndef get_art_abs_lbs(story_file, label_file, chains_file):\n article = open(story_file + \".article\", \"r\").read()\n abstract = open(story_file + \".abstract\", \"r\").read()\n\n article_lines = article.split('<split1>')\n\n labels = read_text_file(label_file)\n chains = open(chains_file, \"r\").read()\n\n if len(labels) == 0 and len(article_lines)==0:\n labels = \"\"\n elif len(labels) == 0 and len(article_lines)!=0:\n print(story_file)\n print(labels)\n print(article_lines)\n exit(0)\n else:\n labels = labels[0]\n # Make article into a single string\n article = ' <split1> '.join(article_lines)\n if len(article.split()) != len(labels.split()):\n print(story_file)\n print(\"Article and label mismatch, check labeling process\")\n print(len(article.split()))\n print(len(labels.split()))\n print(article)\n print(labels)\n a = article.split()\n b = labels.split()\n for i in range(len(article.split())):\n print(a[i],b[i])\n exit()\n\n return article, abstract, labels, chains\n\n\ndef write_to_bin(url_file, out_file, makevocab=False):\n \"\"\"Reads the tokenized .story files corresponding to the urls listed in the url_file and writes them to a out_file.\"\"\"\n print(\"Making bin file for URLs listed in %s...\" % url_file)\n story_fnames = read_text_file(url_file)\n # url_hashes = get_url_hashes(url_list)\n # story_fnames = [s + \".story\" for s in url_hashes]\n num_stories = len(story_fnames)\n\n if makevocab:\n vocab_counter = collections.Counter()\n\n with open(out_file, 'wb') as writer:\n for idx, s in enumerate(story_fnames):\n if idx % 1000 == 0:\n print(\"Writing story %i of %i; %.2f percent done\" % (\n idx, num_stories, float(idx) * 100.0 / float(num_stories)))\n\n # Look in the tokenized story dirs to find the .story file corresponding to this url\n if os.path.isfile(os.path.join(bbc_tokenized_stories_dir, s + '.article')) and os.path.isfile(os.path.join(bbc_tokenized_stories_dir, s + '.abstract')):\n story_file = os.path.join(bbc_tokenized_stories_dir, s)\n else:\n print(\n \"Error: Couldn't find tokenized story file %s in tokenized story directory %s. Was there an error during tokenization?\" % (\n s, bbc_tokenized_stories_dir))\n # Check again if tokenized stories directories contain correct number of files\n print(\"Checking that the tokenized stories directory %s contains correct number of files...\" % (\n bbc_tokenized_stories_dir))\n check_num_stories(bbc_tokenized_stories_dir, num_expected_stories * 2)\n raise Exception(\n \"Tokenized stories directory %s contains correct number of files but story file %s found in neither.\" % (\n bbc_tokenized_stories_dir, s))\n if os.path.isfile(os.path.join(bbc_label_dir, s)):\n label_file = os.path.join(bbc_label_dir, s)\n else:\n print(\n \"Error: Couldn't find label story file %s in either label directory %s. Was there an error during labeling?\" % (\n s, bbc_label_dir))\n\n if os.path.isfile(os.path.join(bbc_chains_dir, s)):\n chains_file = os.path.join(bbc_chains_dir, s)\n else:\n print(\n \"Error: Couldn't find chains story file %s in either label directory %s. Was there an error during labeling?\" % (\n s, bbc_chains_dir))\n print(\"processing: \"+s)\n # Get the strings to write to .bin file\n article, abstract, labels, chains = get_art_abs_lbs(story_file, label_file, chains_file)\n # Write to tf.Example\n tf_example = example_pb2.Example()\n tf_example.features.feature['article'].bytes_list.value.extend([str.encode(article)])\n tf_example.features.feature['abstract'].bytes_list.value.extend([str.encode(abstract)])\n tf_example.features.feature['labels'].bytes_list.value.extend([str.encode(labels)])\n tf_example.features.feature['links'].bytes_list.value.extend([str.encode(chains)])\n tf_example_str = tf_example.SerializeToString()\n str_len = len(tf_example_str)\n writer.write(struct.pack('q', str_len))\n writer.write(struct.pack('%ds' % str_len, tf_example_str))\n\n # Write the vocab to file, if applicable\n if makevocab:\n art_tokens = article.split(' ')\n abs_tokens = abstract.split(' ')\n abs_tokens = [t for t in abs_tokens if\n t not in [SENTENCE_START, SENTENCE_END]] # remove these tags from vocab\n tokens = art_tokens + abs_tokens\n tokens = [t.strip() for t in tokens] # strip\n tokens = [t for t in tokens if t != \"\"] # remove empty\n vocab_counter.update(tokens)\n\n print(\"Finished writing file %s\\n\" % out_file)\n\n # write vocab to file\n if makevocab:\n print(\"Writing vocab file...\")\n with open(os.path.join(finished_files_dir, \"vocab\"), 'w') as writer:\n for word, count in vocab_counter.most_common(VOCAB_SIZE):\n writer.write(word + ' ' + str(count) + '\\n')\n print(\"Finished writing vocab file\")\n\ndef check_num_stories(stories_dir, num_expected):\n num_stories = len(os.listdir(stories_dir))\n if num_stories != num_expected:\n raise Exception(\n \"stories directory %s contains %i files but should contain %i\" % (stories_dir, num_stories, num_expected))\n return\n\nif __name__ == '__main__':\n # Directory names for input and output directories.\n bbc_tokenized_stories_dir = '../bbc_stories_tokenized_reduced_1'\n bbc_label_dir = '../bbc_reduced_1_contsel_tags_labels'\n bbc_chains_dir = '../bbc_reduced_1_ner_coref_heuristic_chain_labels'\n finished_files_dir = \"../finished_files_wlabels_wner_wcoref_chains_reduced_1\"\n chunks_dir = os.path.join(finished_files_dir, \"chunked\")\n\n\n # Check the stories directories contain the correct number of .story files\n # May skip this for new dataset where we don't know num.\n check_num_stories(bbc_tokenized_stories_dir, num_expected_stories * 2) # One for the article and one for the abstract file\n check_num_stories(bbc_label_dir, num_expected_stories)\n check_num_stories(bbc_chains_dir, num_expected_stories)\n\n # # Create some new directories\n if not os.path.exists(finished_files_dir): os.makedirs(finished_files_dir)\n\n # Read the tokenized stories, do a little postprocessing then write to bin files\n write_to_bin(all_test_urls, os.path.join(finished_files_dir, \"test.bin\"))\n write_to_bin(all_val_urls, os.path.join(finished_files_dir, \"val.bin\"))\n write_to_bin(all_train_urls, os.path.join(finished_files_dir, \"train.bin\"), makevocab=True)\n\n # Chunk the data. This splits each of train.bin, val.bin and test.bin into smaller chunks, each containing e.g. 1000 examples, and saves them in finished_files/chunks\n chunk_all()\n"
]
| [
[
"tensorflow.core.example.example_pb2.Example"
]
]
|
matthew-viglione/py-wordle | [
"d786c8aa90bd11686bfa749e639253db25cba88c"
]
| [
"solver_and_stats.py"
]
| [
"\"\"\"Do some fun analytics on the wordle word sets\"\"\"\n\nimport string\nimport matplotlib.pyplot as plt\n\nfrom colorama import init\n\ninit()\n\n\nclass Colors:\n \"\"\"Colors class:reset all colors with colors.reset; two\n sub classes fg for foreground\n and bg for background; use as colors.subclass.colorname.\n i.e. colors.fg.red or colors.bg.greenalso, the generic bold, disable,\n underline, reverse, strike through,\n and invisible work with the main class i.e. colors.bold\"\"\"\n\n reset = \"\\033[0m\"\n bold = \"\\033[01m\"\n disable = \"\\033[02m\"\n underline = \"\\033[04m\"\n reverse = \"\\033[07m\"\n strikethrough = \"\\033[09m\"\n invisible = \"\\033[08m\"\n\n class fg:\n \"\"\"Valid foreround colors.\"\"\"\n\n BLACK = \"\\033[30m\"\n RED = \"\\033[31m\"\n GREEN = \"\\033[32m\"\n ORANGE = \"\\033[33m\"\n BLUE = \"\\033[34m\"\n PURPLE = \"\\033[35m\"\n CYAN = \"\\033[36m\"\n LIGHTGREY = \"\\033[37m\"\n DARKGREY = \"\\033[90m\"\n LIGHTRED = \"\\033[91m\"\n LIGHTGREEN = \"\\033[92m\"\n YELLOW = \"\\033[93m\"\n LIGHTBLUE = \"\\033[94m\"\n PINK = \"\\033[95m\"\n LIGHTCYAN = \"\\033[96m\"\n\n @classmethod\n def all(cls):\n \"\"\"Return a list containing all color name and color code pairs.\"\"\"\n return [(name, value) for name, value in vars(cls).items() if name.isupper()]\n\n def color_test(self):\n \"\"\"Print all colors to terminal.\n\n e.g.: Colors.fg().color_test()\n \"\"\"\n for c, v in self.all():\n print(f\"{v}{c}\\033[0m\")\n\n class bg:\n \"\"\"Valid background colors.\"\"\"\n\n BLACK = \"\\033[40m\"\n RED = \"\\033[41m\"\n GREEN = \"\\033[42m\"\n ORANGE = \"\\033[43m\"\n BLUE = \"\\033[44m\"\n PURPLE = \"\\033[45m\"\n CYAN = \"\\033[46m\"\n LIGHTGREY = \"\\033[47m\"\n\n @classmethod\n def all(cls):\n \"\"\"Return a list containing all color name and color code pairs.\"\"\"\n return [(name, value) for name, value in vars(cls).items() if name.isupper()]\n\n def color_test(self):\n \"\"\"Print all colors to terminal.\n\n e.g.: Colors.bg().color_test()\n \"\"\"\n for c, v in self.all():\n print(f\"{v}{c}\\033[0m\")\n\n\nvalid_guesses = \"wordlist_guesses.txt\"\nvalid_solutions = \"wordlist_solutions.txt\"\nfile_list = [valid_guesses, valid_solutions]\n\n\ndef get_size_of_wordlist(filename):\n \"\"\"Reuturn the number of lines in the file.\"\"\"\n return sum(1 for _ in open(filename))\n\n\ndef get_letter_counts(filename):\n \"\"\"Return a dictionary with letter -> count pairs from a wordlist.\"\"\"\n counts = dict.fromkeys(string.ascii_lowercase, 0)\n with open(filename) as file:\n for line in file:\n for char in line.rstrip():\n counts[char] += 1\n return counts\n\n\ndef get_letter_counts_by_position(filename):\n \"\"\"Return a dictionary with letter -> count pairs from a wordlist.\"\"\"\n counts = []\n for i in range(0, 5):\n counts.append(dict.fromkeys(string.ascii_lowercase, 0))\n with open(filename) as file:\n for line in file:\n for i, char in enumerate(line.rstrip()):\n counts[i][char] += 1\n return counts\n\n\ndef generate_bar_graph(d, data_name=\"\"):\n \"\"\"Plot a bar graph from a dict with keys on X axis and values on Y axis.\"\"\"\n plt.title(f\"Letter frequency for '{data_name}'\")\n plt.xlabel(\"Letter\")\n plt.ylabel(\"Frequency (Percent and count)\")\n plt.ylim([0, max(d.values()) * 1.3])\n plt.bar(range(len(d)), list(d.values()), align=\"center\")\n plt.xticks(range(len(d)), list(d.keys()))\n\n for i, v in enumerate(d.values()):\n percent = str(round(v / sum(d.values()) * 100, 2))\n label = \" \" + percent + \"% (\" + str(v) + \")\"\n plt.text(i + 0.075, v + 10, label, ha=\"center\", size=\"x-small\", rotation=90)\n fig_name = data_name.replace(\" \", \"_\").lower() + \".png\"\n # plt.savefig(fig_name)\n # plt.cla()\n plt.show()\n\n\ndef generate_bar_graph_by_position(filename):\n count_list = get_letter_counts_by_position(filename)\n for i, counts in enumerate(count_list):\n generate_bar_graph(counts, f\"position {i+1} in {filename}\")\n\n\ndef get_min_key(d):\n \"\"\"Return the key from the dict with the min value.\"\"\"\n return min(d, key=d.get)\n\n\ndef get_max_key(d):\n \"\"\"Return the key from the dict with the max value.\"\"\"\n return max(d, key=d.get)\n\n\ndef sort_dict(d, reverse=True):\n \"\"\"Return the dictionary sorted by value.\"\"\"\n return {k: v for k, v in sorted(d.items(), key=lambda item: item[1], reverse=reverse)}\n\n\ndef normalize_dict(d):\n \"\"\"Turn the dictionary values into percentages\"\"\"\n total = sum(d.values())\n for k in d:\n d[k] = d[k] / total\n return d\n\n\ndef get_repeated_letter_words(filename, num_repeats=1):\n \"\"\"Return list of words with repeated letters from supplied list file.\"\"\"\n word_list = []\n with open(filename) as file:\n for word in file:\n counts = dict.fromkeys(string.ascii_lowercase, 0)\n word = word.rstrip()\n for char in word:\n counts[char] += 1\n\n for v in counts.values():\n if v > num_repeats:\n word_list.append(word)\n break\n return word_list\n\n\ndef report_words_with_repeat_letters(filenames):\n \"\"\"Return some statistics on how often words have repeated letters\"\"\"\n n = 50\n print(\"-\" * n)\n print(\"Repeat statistics\")\n print(\"-\" * n)\n for f in filenames:\n wordlist_size = get_size_of_wordlist(f)\n print(f\"{f} has {wordlist_size} entries\")\n for i in range(0, 4):\n wordlist = get_repeated_letter_words(f, i)\n p = round(len(wordlist) / wordlist_size * 100, 2)\n print(f\"Words with at least {i} repeated letters:\\t{len(wordlist)}\\t({p}%)\")\n # print(wordlist)\n print(\"-\" * n)\n\n\ndef report_letter_frequency(filenames):\n \"\"\"Generate graphs with letter frequency data.\"\"\"\n for f in filenames:\n counts = get_letter_counts(f)\n sorted_counts = sort_dict(counts, reverse=True)\n generate_bar_graph(sorted_counts, f)\n\n\ndef report_word_difficulty(filename):\n \"\"\"Return a dictionary of all possible words, with a difficulty score.\n\n A lower score means the letters occur less frequently, making the\n word harder to guess.\n \"\"\"\n letter_counts = get_letter_counts(valid_solutions)\n letter_scores = normalize_dict(letter_counts)\n score_dict = {}\n with open(filename) as file:\n for word in file:\n word = word.rstrip()\n score = 0\n for char in word:\n score += letter_scores[char]\n score_dict[word] = score\n return score_dict\n\n\n## Repeat stats\n# report_words_with_repeat_letters(file_list)\n\n## Frequency stats\n# report_letter_frequency(file_list)\n\n\n## Word difficulty rank stats\n# scores = report_word_difficulty(valid_solutions)\n# print(f\"Scores generated for {len(scores)} words\")\n# easiest_word = get_max_key(scores)\n# hardest_word = get_min_key(scores)\n# print(f\"Easiest word (highest score): {easiest_word} ({round(scores[easiest_word],3)})\")\n# print(f\"Hardest word (lowest score): {hardest_word} ({round(scores[hardest_word],3)})\")\n\n# generate_bar_graph_by_position(valid_solutions)\n# generate_bar_graph_by_position(valid_guesses)\n\n\"\"\"\n* number of times letter appears in any word (but only once if it is multiple)\n* lowest frequency score word (hardest to guess)\n* highest frequency word (easiest to guess)\n* score for how hard a given word is to guess\n\n* how does knowing the guess and solution set effect performance?\n\"\"\"\n\n\ndef get_words(filename):\n \"\"\"Return a list of all the words.\"\"\"\n result = []\n with open(filename) as file:\n for line in file:\n result.append(line.rstrip())\n return result\n\n\ndef contains(wordlist, letter):\n \"\"\"Return a list of words that contain the correct letter.\"\"\"\n result = []\n for word in wordlist:\n if letter in word:\n result.append(word)\n return result\n\n\ndef does_not_contain(wordlist, letter):\n \"\"\"Return the words in wordlist that don't contain the specified\n letter. This corresponds to a grey guess in Wordle.\n \"\"\"\n result = []\n for word in wordlist:\n if letter not in word:\n result.append(word)\n return result\n\n\ndef does_not_contain_at_position(wordlist, letter, position):\n \"\"\"Return the words in wordlist that don't contain the specified\n letter at the specified position. This corresponds to a repeated\n letter that was marked grey but does exist elsewhere in the word.\n \"\"\"\n result = []\n for word in wordlist:\n if letter != word[position - 1]:\n result.append(word)\n return result\n\n\ndef contains_at_position(wordlist, letter, position):\n \"\"\"Return the words that have the letter at the specified position.\n This corresponds to a green guess in Wordle.\n \"\"\"\n result = []\n for word in wordlist:\n if word[position - 1] == letter:\n result.append(word)\n return result\n\n\ndef contains_not_at_position(wordlist, letter, position):\n \"\"\"Return the words that have the letter, but not at the specified\n position. These correspond to yellow guesses in wordle.\n \"\"\"\n result = []\n wordlist = contains(wordlist, letter)\n for word in wordlist:\n if word[position - 1] != letter:\n result.append(word)\n return result\n\n\ndef report_occurences_by_word(words):\n \"\"\"Report how many words contain each letter.\"\"\"\n counts = dict.fromkeys(string.ascii_lowercase, 0)\n for w in words:\n for c in counts:\n if c in w:\n counts[c] += 1\n return sort_dict(counts, reverse=True)\n\n\ndef simple_bar_graph(d, num_words):\n \"\"\"A quick and dirty bar chart.\"\"\"\n plt.ylim([0, max(d.values()) * 1.3])\n plt.bar(range(len(d)), list(d.values()), align=\"center\")\n plt.xticks(range(len(d)), list(d.keys()))\n\n for i, v in enumerate(d.values()):\n percent = str(round(v / num_words * 100, 2))\n label = \" \" + percent + \"% (\" + str(v) + \")\"\n plt.text(i + 0.075, v + 1, label, ha=\"center\", size=\"x-small\", rotation=90)\n\n plt.show()\n\n\ndef get_letter_scores(wordlist):\n \"\"\"Return a normalized percent count of each letter. The result is\n what percent of the words in the wordlist contain at least one of\n the letter.\n \"\"\"\n counts = dict.fromkeys(string.ascii_lowercase, 0)\n for w in wordlist:\n for c in counts:\n if c in w:\n counts[c] += 1\n\n for c in counts:\n counts[c] = counts[c] / len(wordlist)\n return counts\n\n\ndef get_letter_scores_by_position(wordlist):\n \"\"\"Return a normalized percent count of each letter. The result is\n what percent of the words in the wordlist contain at least one of\n the letter, separated into positions.\n\n e.g. : a [0.061, 0.131, 0.133, 0.070, 0.028] means the char 'a'\n occurs in the first position 6.1% of the time, in the second\n position 13.1% of the time, etc.\n \"\"\"\n # scores = dict.fromkeys(string.ascii_lowercase, [0, 0, 0, 0, 0])\n scores = dict.fromkeys(string.ascii_lowercase)\n for char in scores:\n scores[char] = [0, 0, 0, 0, 0]\n for word in wordlist:\n for i, char in enumerate(word):\n scores[char][i] += 1\n for char in scores:\n for i, score in enumerate(scores[char]):\n scores[char][i] = score / len(wordlist)\n return scores\n\n\ndef position_level_score(wordlist):\n \"\"\"Calculate a score for each word, using scores that are aware of\n positions.\n \"\"\"\n char_frequency = get_letter_scores_by_position(wordlist)\n result = {}\n for word in wordlist:\n this_score = 0\n for i, c in enumerate(word):\n this_score += char_frequency[c][i]\n result[word] = this_score\n return sort_dict(result, reverse=True)\n\n\ndef word_level_score(wordlist):\n \"\"\"Give a score to each word. Each letter adds the % chance it has\n of occuring in a word to the score for the whole word.\n \"\"\"\n scores = get_letter_scores(wordlist)\n result = {}\n for w in wordlist:\n this_score = 0\n for char in scores:\n if char in w:\n this_score += scores[char]\n result[w] = this_score\n return sort_dict(result, reverse=True)\n\n\ndef count_at_position(wordlist):\n counts = []\n for i in range(0, 5):\n counts.append(dict.fromkeys(string.ascii_lowercase, 0))\n for line in wordlist:\n for i, char in enumerate(line.rstrip()):\n counts[i][char] += 1\n return counts\n\n\ndef print_scores(score_dict, num=15000):\n \"\"\"Print out all the scores with highest score first.\"\"\"\n print(f\"Count: {len(score_dict)}\")\n for i, (k, v) in enumerate(score_dict.items()):\n if i < num:\n print(k, v)\n\n\ndef solve(\n wordlist, word, max_guesses=6, p=True, start_word=None, method=word_level_score\n):\n \"\"\"Simulate a game played\"\"\"\n if p:\n print(f\"-- Trying to guess '{word}' with method '{method.__name__}'\")\n for num in range(1, max_guesses + 1):\n if num == 1 and start_word is not None:\n guess_word = start_word\n else:\n guess_word = next(iter(method(wordlist)))\n result = \"\"\n for i, char in enumerate(guess_word):\n if char == word[i]:\n result += f\"{Colors.fg.GREEN}{char}{Colors.reset}\"\n wordlist = contains_at_position(wordlist, char, i + 1)\n elif char in word:\n result += f\"{Colors.fg.YELLOW}{char}{Colors.reset}\"\n wordlist = contains_not_at_position(wordlist, char, i + 1)\n else:\n result += char\n wordlist = does_not_contain(wordlist, char)\n if p:\n print(f\"Guess {num}: {result}\")\n if word == guess_word:\n if p:\n print(f\"Solved! Took {num} guesses.\")\n return num, result\n if p:\n print(f\"Did not solve. Go to: {result} Correct word: {word}\")\n return None, word\n\n\ndef solve_with_stats(wordlist, method=word_level_score):\n \"\"\"Collect stats on solver.\"\"\"\n\n filename = f\"start_word_stats_{method.__name__}.csv\"\n words = get_words(wordlist)\n\n with open(filename, \"a\") as fileout:\n fileout.write(\"start,average,max,failed\\n\")\n\n for ww in words:\n score_list = []\n all_results = {}\n failed = 0\n failed_list = []\n for w in words:\n sw = ww\n score, result = solve(words, w, max_guesses=26, p=False, start_word=sw)\n all_results[result] = score\n if score is None or score > 6:\n failed += 1\n failed_list.append(result)\n score_list.append(score)\n\n avg = sum(score_list) / len(score_list)\n print(f\"Start word: {sw}\")\n print(f\"Average: {avg}\")\n print(f\"Max: {max(score_list)}\")\n print(f\"Failed: {failed}\")\n\n with open(filename, \"a\") as fileout:\n fileout.write(f\"{sw},{avg},{max(score_list)},{failed}\\n\")\n\n\nif __name__ == \"__main__\":\n words = get_words(valid_solutions)\n # solve(words, \"pause\", method=word_level_score, start_word=\"sulci\")\n # solve(words, \"pause\", method=position_level_score)\n\n words = does_not_contain(words, \"o\")\n words = does_not_contain(words, \"r\")\n words = contains_not_at_position(words, \"a\", 3)\n words = does_not_contain(words, \"t\")\n words = does_not_contain(words, \"e\")\n\n words = does_not_contain(words, \"s\")\n words = contains_not_at_position(words, \"u\", 2)\n words = contains_not_at_position(words, \"l\", 3)\n words = contains_not_at_position(words, \"c\", 4)\n words = does_not_contain(words, \"i\")\n\n print(\"\\nWord level suggestions:\")\n print_scores(word_level_score(words), num=30)\n print(\"\\nLetter level suggestions:\")\n print_scores(position_level_score(words), num=30)\n"
]
| [
[
"matplotlib.pyplot.text",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.show"
]
]
|
skumailraza/FRSNet-GA | [
"a1fdf5c84fe0af16b6ec5867f7b5b20abd522656"
]
| [
"models/GANet_ms.py"
]
| [
"import torch\nimport torch.nn as nn\nimport torch.nn.init as init\nfrom libs.GANet.modules.GANet import DisparityRegression, GetCostVolume\nfrom libs.GANet.modules.GANet import MyNormalize\nfrom libs.GANet.modules.GANet import SGA\nfrom libs.GANet.modules.GANet import LGA, LGA2, LGA3\n# from libs.sync_bn.modules.sync_bn import BatchNorm2d, BatchNorm3d\nfrom nets.feature import BasicBlock, BasicConv, Conv2x\nfrom nets.refinement import StereoDRNetRefinement, HourglassRefinement\nimport apex\nimport torch.nn.functional as F\n# from torch.autograd import Variable\n# import numpy as np\n\n\n# class BasicConv(nn.Module):\n#\n# def __init__(self, in_channels, out_channels, deconv=False, is_3d=False, bn=True, relu=True, **kwargs):\n# super(BasicConv, self).__init__()\n# # print(in_channels, out_channels, deconv, is_3d, bn, relu, kwargs)\n# self.relu = relu\n# self.use_bn = bn\n# if is_3d:\n# if deconv:\n# self.conv = nn.ConvTranspose3d(in_channels, out_channels, bias=False, **kwargs)\n# else:\n# self.conv = nn.Conv3d(in_channels, out_channels, bias=False, **kwargs)\n# self.bn = apex.parallel.SyncBatchNorm(out_channels)\n# else:\n# if deconv:\n# self.conv = nn.ConvTranspose2d(in_channels, out_channels, bias=False, **kwargs)\n# else:\n# self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs)\n# self.bn = apex.parallel.SyncBatchNorm(out_channels)\n#\n# def forward(self, x):\n# x = self.conv(x)\n# if self.use_bn:\n# x = self.bn(x)\n# if self.relu:\n# x = F.relu(x, inplace=True)\n# return x\n\n\n# class Conv2x(nn.Module):\n#\n# def __init__(self, in_channels, out_channels, deconv=False, is_3d=False, concat=True, bn=True, relu=True):\n# super(Conv2x, self).__init__()\n# self.concat = concat\n#\n# if deconv and is_3d:\n# kernel = (3, 4, 4)\n# elif deconv:\n# kernel = 4\n# else:\n# kernel = 3\n# self.conv1 = BasicConv(in_channels, out_channels, deconv, is_3d, bn=True, relu=True, kernel_size=kernel, stride=2, padding=1)\n#\n# if self.concat:\n# self.conv2 = BasicConv(out_channels*2, out_channels, False, is_3d, bn, relu, kernel_size=3, stride=1, padding=1)\n# else:\n# self.conv2 = BasicConv(out_channels, out_channels, False, is_3d, bn, relu, kernel_size=3, stride=1, padding=1)\n#\n# def forward(self, x, rem):\n# # print(\"==> Before x.size() , rem.size() : \", x.shape, rem.shape)\n# x = self.conv1(x)\n# # print(\"==> After x.size() , rem.size() : \", x.shape, rem.shape)\n# assert(x.size() == rem.size())\n# if self.concat:\n# x = torch.cat((x, rem), 1)\n# else:\n# x = x + rem\n# x = self.conv2(x)\n# return x\n\n# class Conv2x(nn.Module):\n#\n# def __init__(self, in_channels, out_channels, deconv=False, is_3d=False, concat=True, bn=True, relu=True,\n# mdconv=False):\n# super(Conv2x, self).__init__()\n# self.concat = concat\n#\n# if deconv and is_3d:\n# kernel = (3, 4, 4)\n# elif deconv:\n# kernel = 4\n# else:\n# kernel = 3\n# self.conv1 = BasicConv(in_channels, out_channels, deconv, is_3d, bn=True, relu=True, kernel_size=kernel,\n# stride=2, padding=1)\n#\n# if self.concat:\n# if mdconv:\n# self.conv2 = DeformConv2d(out_channels * 2, out_channels, kernel_size=3, stride=1)\n# else:\n# self.conv2 = BasicConv(out_channels * 2, out_channels, False, is_3d, bn, relu, kernel_size=3,\n# stride=1, padding=1)\n# else:\n# self.conv2 = BasicConv(out_channels, out_channels, False, is_3d, bn, relu, kernel_size=3, stride=1,\n# padding=1)\n#\n# def forward(self, x, rem):\n# x = self.conv1(x)\n# assert (x.size() == rem.size())\n# if self.concat:\n# x = torch.cat((x, rem), 1)\n# else:\n# x = x + rem\n# x = self.conv2(x)\n# return x\n\n\nclass Feature(nn.Module):\n def __init__(self):\n super(Feature, self).__init__()\n\n self.conv_start = nn.Sequential(\n BasicConv(3, 32, kernel_size=3, padding=1),\n BasicConv(32, 32, kernel_size=5, stride=3, padding=2),\n BasicConv(32, 32, kernel_size=3, padding=1))\n self.conv1a = BasicConv(32, 48, kernel_size=3, stride=2, padding=1)\n self.conv2a = BasicConv(48, 64, kernel_size=3, stride=2, padding=1)\n self.conv3a = BasicConv(64, 96, kernel_size=3, stride=2, padding=1)\n self.conv4a = BasicConv(96, 128, kernel_size=3, stride=2, padding=1)\n\n self.deconv4a = Conv2x(128, 96, deconv=True)\n self.deconv3a = Conv2x(96, 64, deconv=True)\n self.deconv2a = Conv2x(64, 48, deconv=True)\n self.deconv1a = Conv2x(48, 32, deconv=True)\n\n self.conv1b = Conv2x(32, 48)\n self.conv2b = Conv2x(48, 64)\n self.conv3b = Conv2x(64, 96)\n self.conv4b = Conv2x(96, 128)\n\n self.deconv4b = Conv2x(128, 96, deconv=True)\n self.deconv3b = Conv2x(96, 64, deconv=True)\n self.deconv2b = Conv2x(64, 48, deconv=True)\n self.deconv1b = Conv2x(48, 32, deconv=True)\n\n def forward(self, x, p=0):\n # print('++> in feature')\n x = self.conv_start(x)\n rem0 = x\n x = self.conv1a(x)\n rem1 = x\n x = self.conv2a(x)\n rem2 = x\n x = self.conv3a(x)\n rem3 = x\n x = self.conv4a(x)\n rem4 = x\n x = self.deconv4a(x, rem3)\n rem3 = x\n\n x = self.deconv3a(x, rem2)\n rem2 = x\n x = self.deconv2a(x, rem1)\n rem1 = x\n x = self.deconv1a(x, rem0)\n rem0 = x\n\n x = self.conv1b(x, rem1)\n rem1 = x\n x = self.conv2b(x, rem2)\n rem2 = x\n x = self.conv3b(x, rem3)\n rem3 = x\n x_48 = self.conv4b(x, rem4)\n\n x_24 = self.deconv4b(x_48, rem3)\n # if (p == -4):\n # return x\n x_12 = self.deconv3b(x_24, rem2)\n # if (p == -3):\n # return x\n x_6 = self.deconv2b(x_12, rem1)\n # if (p == -2):\n # return x\n x_3 = self.deconv1b(x_6, rem0) \n \n return x_3, x_6, x_12, x_24, x_48\n\nclass Guidance(nn.Module):\n def __init__(self):\n super(Guidance, self).__init__()\n\n self.conv0 = BasicConv(64, 16, kernel_size=3, padding=1)\n self.conv1 = nn.Sequential(\n BasicConv(16, 32, kernel_size=5, stride=3, padding=2),\n BasicConv(32, 32, kernel_size=3, padding=1))\n\n self.conv2 = BasicConv(32, 32, kernel_size=3, padding=1)\n self.conv3 = BasicConv(32, 32, kernel_size=3, padding=1)\n\n# self.conv11 = Conv2x(32, 48)\n self.conv11 = nn.Sequential(BasicConv(32, 48, kernel_size=3, stride=2, padding=1),\n BasicConv(48, 48, kernel_size=3, padding=1))\n self.conv12 = BasicConv(48, 48, kernel_size=3, padding=1)\n self.conv13 = BasicConv(48, 48, kernel_size=3, padding=1)\n self.conv14 = BasicConv(48, 48, kernel_size=3, padding=1)\n\n self.weight_sg1 = nn.Conv2d(32, 640, (3, 3), (1, 1), (1, 1), bias=False)\n self.weight_sg2 = nn.Conv2d(32, 640, (3, 3), (1, 1), (1, 1), bias=False)\n self.weight_sg3 = nn.Conv2d(32, 640, (3, 3), (1, 1), (1, 1), bias=False)\n\n self.weight_sg11 = nn.Conv2d(48, 960, (3, 3), (1, 1), (1, 1), bias=False)\n self.weight_sg12 = nn.Conv2d(48, 960, (3, 3), (1, 1), (1, 1), bias=False)\n self.weight_sg13 = nn.Conv2d(48, 960, (3, 3), (1, 1), (1, 1), bias=False)\n self.weight_sg14 = nn.Conv2d(48, 960, (3, 3), (1, 1), (1, 1), bias=False)\n\n self.weight_lg1 = nn.Sequential(BasicConv(16, 16, kernel_size=3, padding=1),\n nn.Conv2d(16, 75, (3, 3), (1, 1), (1, 1) ,bias=False))\n self.weight_lg2 = nn.Sequential(BasicConv(16, 16, kernel_size=3, padding=1),\n nn.Conv2d(16, 75, (3, 3), (1, 1), (1, 1) ,bias=False))\n\n def forward(self, x):\n x = self.conv0(x)\n rem = x\n x = self.conv1(x)\n sg1 = self.weight_sg1(x)\n x = self.conv2(x)\n sg2 = self.weight_sg2(x)\n x = self.conv3(x)\n sg3 = self.weight_sg3(x)\n\n x = self.conv11(x)\n sg11 = self.weight_sg11(x)\n x = self.conv12(x)\n sg12 = self.weight_sg12(x)\n x = self.conv13(x)\n sg13 = self.weight_sg13(x)\n x = self.conv14(x)\n sg14 = self.weight_sg14(x)\n\n lg1 = self.weight_lg1(rem)\n lg2 = self.weight_lg2(rem)\n \n return dict([\n ('sg1', sg1),\n ('sg2', sg2),\n ('sg3', sg3),\n ('sg11', sg11),\n ('sg12', sg12),\n ('sg13', sg13),\n ('sg14', sg14),\n ('lg1', lg1),\n ('lg2', lg2)])\n\nclass Disp(nn.Module):\n\n def __init__(self, maxdisp=192):\n super(Disp, self).__init__()\n self.maxdisp = maxdisp\n self.softmax = nn.Softmin(dim=1)\n self.disparity = DisparityRegression(maxdisp=self.maxdisp)\n# self.conv32x1 = BasicConv(32, 1, kernel_size=3)\n self.conv32x1 = nn.Conv3d(32, 1, (3, 3, 3), (1, 1, 1), (1, 1, 1), bias=False)\n\n def forward(self, x):\n x = F.interpolate(self.conv32x1(x), [self.maxdisp+1, x.size()[3]*3, x.size()[4]*3], mode='trilinear', align_corners=False)\n x = torch.squeeze(x, 1)\n x = self.softmax(x)\n\n return self.disparity(x)\n\nclass DispAgg(nn.Module):\n\n def __init__(self, maxdisp=192):\n super(DispAgg, self).__init__()\n self.maxdisp = maxdisp\n self.LGA3 = LGA3(radius=2)\n self.LGA2 = LGA2(radius=2)\n self.LGA = LGA(radius=2)\n self.softmax = nn.Softmin(dim=1)\n self.disparity = DisparityRegression(maxdisp=self.maxdisp)\n self.dropout = nn.Dropout(p=0.3)\n# self.conv32x1 = BasicConv(32, 1, kernel_size=3)\n self.conv32x1=nn.Conv3d(32, 1, (3, 3, 3), (1, 1, 1), (1, 1, 1), bias=False)\n\n def lga(self, x, g):\n g = F.normalize(g, p=1, dim=1)\n x = self.LGA2(x, g)\n return x\n\n def forward(self, x, lg1, lg2):\n x = F.interpolate(self.conv32x1(x), [self.maxdisp+1, x.size()[3]*3, x.size()[4]*3], mode='trilinear', align_corners=False)\n x = torch.squeeze(x, 1)\n assert(lg1.size() == lg2.size())\n x = self.lga(x, lg1)\n x = self.softmax(x)\n x = self.lga(x, lg2)\n x = F.normalize(x, p=1, dim=1)\n return self.disparity(x)\n\n\nclass SGABlock(nn.Module):\n def __init__(self, channels=32, refine=False):\n super(SGABlock, self).__init__()\n self.refine = refine\n if self.refine:\n self.bn_relu = nn.Sequential(apex.parallel.SyncBatchNorm(channels),\n nn.ReLU(inplace=True))\n self.conv_refine = BasicConv(channels, channels, is_3d=True, kernel_size=3, padding=1, relu=False)\n# self.conv_refine1 = BasicConv(8, 8, is_3d=True, kernel_size=1, padding=1)\n else:\n self.bn = apex.parallel.SyncBatchNorm(channels)\n self.SGA=SGA()\n self.relu = nn.ReLU(inplace=True)\n def forward(self, x, g):\n rem = x\n k1, k2, k3, k4 = torch.split(g, (x.size()[1]*5, x.size()[1]*5, x.size()[1]*5, x.size()[1]*5), 1)\n # print(\"===> k1.shape: \", k1.shape)\n k1 = F.normalize(k1.view(x.size()[0], x.size()[1], 5, x.size()[3], x.size()[4]), p=1, dim=2)\n k2 = F.normalize(k2.view(x.size()[0], x.size()[1], 5, x.size()[3], x.size()[4]), p=1, dim=2)\n k3 = F.normalize(k3.view(x.size()[0], x.size()[1], 5, x.size()[3], x.size()[4]), p=1, dim=2)\n k4 = F.normalize(k4.view(x.size()[0], x.size()[1], 5, x.size()[3], x.size()[4]), p=1, dim=2)\n x = self.SGA(x, k1, k2, k3, k4)\n if self.refine:\n x = self.bn_relu(x)\n x = self.conv_refine(x)\n else:\n x = self.bn(x)\n assert(x.size() == rem.size())\n x += rem\n return self.relu(x) \n# return self.bn_relu(x)\n\n\nclass CostAggregation(nn.Module):\n def __init__(self, maxdisp=192):\n super(CostAggregation, self).__init__()\n self.maxdisp = maxdisp\n self.conv_start = BasicConv(64, 32, is_3d=True, kernel_size=3, padding=1, relu=False)\n\n self.conv1a = BasicConv(32, 48, is_3d=True, kernel_size=3, stride=2, padding=1)\n self.conv2a = BasicConv(48, 64, is_3d=True, kernel_size=3, stride=2, padding=1)\n# self.conv3a = BasicConv(64, 96, is_3d=True, kernel_size=3, stride=2, padding=1)\n\n self.deconv1a = Conv2x(48, 32, deconv=True, is_3d=True, relu=False)\n self.deconv2a = Conv2x(64, 48, deconv=True, is_3d=True)\n# self.deconv3a = Conv2x(96, 64, deconv=True, is_3d=True)\n\n self.conv1b = Conv2x(32, 48, is_3d=True)\n self.conv2b = Conv2x(48, 64, is_3d=True)\n# self.conv3b = Conv2x(64, 96, is_3d=True)\n\n self.deconv1b = Conv2x(48, 32, deconv=True, is_3d=True, relu=False)\n self.deconv2b = Conv2x(64, 48, deconv=True, is_3d=True)\n# self.deconv3b = Conv2x(96, 64, deconv=True, is_3d=True)\n self.deconv0b = Conv2x(8, 8, deconv=True, is_3d=True)\n \n self.sga1 = SGABlock(refine=True)\n self.sga2 = SGABlock(refine=True)\n self.sga3 = SGABlock(refine=True)\n\n self.sga11 = SGABlock(channels=48, refine=True)\n self.sga12 = SGABlock(channels=48, refine=True)\n self.sga13 = SGABlock(channels=48, refine=True)\n self.sga14 = SGABlock(channels=48, refine=True)\n\n self.disp0 = Disp(self.maxdisp)\n self.disp1 = Disp(self.maxdisp)\n self.disp2 = DispAgg(self.maxdisp)\n\n\n def forward(self, x, g):\n # print(\"==> x_in start: \", x.size())\n x = self.conv_start(x)\n\n x = self.sga1(x, g['sg1'])\n rem0 = x\n \n if self.training:\n disp0 = self.disp0(x)\n\n x = self.conv1a(x)\n\n\n x = self.sga11(x, g['sg11'])\n # print(\"==> x_before conv2a(rem1): \", x.size())\n rem1 = x\n x = self.conv2a(x)\n\n\n rem2 = x\n# x = self.conv3a(x)\n# rem3 = x\n\n# x = self.deconv3a(x, rem2)\n# rem2 = x\n # print('++> Came from CostAGG')\n # print(\"==> Before Deconv x.size() , rem.size() : \", x.shape, rem1.shape)\n \n x = self.deconv2a(x, rem1)\n # print('++> out from deconv2a')\n # print(\"==> After Deconv x.size() , rem.size() : \", x.shape, rem1.shape)\n\n x = self.sga12(x, g['sg12'])\n rem1 = x\n x = self.deconv1a(x, rem0)\n # print(\"==> After Deconv1a x.size() , rem.size() : \", x.shape, rem0.shape)\n\n x = self.sga2(x, g['sg2'])\n rem0 = x\n if self.training:\n disp1 = self.disp1(x)\n\n x = self.conv1b(x, rem1)\n x = self.sga13(x, g['sg13'])\n rem1 = x\n x = self.conv2b(x, rem2)\n# rem2 = x\n# x = self.conv3b(x, rem3)\n\n# x = self.deconv3b(x, rem2)\n x = self.deconv2b(x, rem1)\n x = self.sga14(x, g['sg14'])\n x = self.deconv1b(x, rem0)\n x = self.sga3(x, g['sg3'])\n\n disp2 = self.disp2(x, g['lg1'], g['lg2'])\n if self.training:\n return disp0, disp1, disp2\n else:\n return disp2\n\nclass GANet(nn.Module):\n def __init__(self, maxdisp=192):\n super(GANet, self).__init__()\n self.maxdisp = maxdisp\n self.conv_start = nn.Sequential(BasicConv(3, 16, kernel_size=3, padding=1),\n BasicConv(16, 32, kernel_size=3, padding=1))\n\n self.conv_x = BasicConv(32, 32, kernel_size=3, padding=1)\n self.conv_x_6 = BasicConv(48, 32, kernel_size=3, padding=1)\n self.conv_x_12 = BasicConv(64, 32, kernel_size=3, padding=1)\n self.conv_x_24 = BasicConv(96, 32, kernel_size=3, padding=1)\n self.conv_x_48 = BasicConv(128, 32, kernel_size=3, padding=1)\n self.conv_y = BasicConv(32, 32, kernel_size=3, padding=1)\n self.conv_y_6 = BasicConv(48, 32, kernel_size=3, padding=1)\n self.conv_y_12 = BasicConv(64, 32, kernel_size=3, padding=1)\n self.conv_y_24 = BasicConv(96, 32, kernel_size=3, padding=1)\n self.conv_y_48 = BasicConv(128, 32, kernel_size=3, padding=1)\n\n self.conv_refine = nn.Conv2d(32, 32, (3, 3), (1, 1), (1, 1), bias=False)\n self.conv_refine_6 = nn.Conv2d(48, 32, (3, 3), (1, 1), (1,1), bias=False)\n\n\n self.bn_relu = nn.Sequential(apex.parallel.SyncBatchNorm(32),\n nn.ReLU(inplace=True))\n self.feature = Feature()\n self.guidance = Guidance()\n self.guidance_x6 = Guidance()\n self.guidance_x12 = Guidance()\n self.guidance_x24 = Guidance()\n self.guidance_x48 = Guidance()\n self.cost_agg = CostAggregation(self.maxdisp)\n self.cv = GetCostVolume(int(self.maxdisp / 3))\n self.hourglass_refinement = HourglassRefinement()\n\n for m in self.modules():\n if isinstance(m, (nn.Conv2d, nn.Conv3d)):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n elif isinstance(m, (apex.parallel.SyncBatchNorm, apex.parallel.SyncBatchNorm)):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n def conv_x_multi(self, x):\n rem = x\n if x.shape[1] == 32:\n x = self.conv_x(x)\n\n elif x.shape[1] == 48:\n x = self.conv_x_6(x)\n\n elif x.shape[1] == 64:\n x = self.conv_x_12(x)\n\n elif x.shape[1] == 96:\n x = self.conv_x_24(x)\n\n elif x.shape[1] == 128:\n x = self.conv_x_48(x)\n\n return x\n\n def conv_y_multi(self, x):\n rem = x\n if x.shape[1] == 32:\n x = self.conv_y(x)\n\n elif x.shape[1] == 48:\n x = self.conv_y_6(x)\n\n elif x.shape[1] == 64:\n x = self.conv_y_12(x)\n\n elif x.shape[1] == 96:\n x = self.conv_y_24(x)\n\n elif x.shape[1] == 128:\n x = self.conv_y_48(x)\n\n return x\n\n def conv_refine_multi(self, x, s):\n # if s == 0:\n # x1 = self.conv_refine_48(x)\n # elif s == 1:\n # x1 = self.conv_refine_24(x)\n # elif s == 2:\n # x1 = self.conv_refine_12(x)\n if s == 3:\n x1 = self.conv_refine_6(x)\n else:\n x1 = self.conv_refine(x)\n\n x1 = F.interpolate(x1, [x1.size()[2] * 3, x1.size()[3] * 3], mode='bilinear', align_corners=False)\n return x1\n\n def ga_head(self, g, x, y, s, r):\n rem = r\n\n x = self.cv(x, y)\n # print(\"CV: \",x)\n # exit(0)\n x1 = self.conv_refine_multi(rem, s)\n\n x1 = self.bn_relu(x1)\n\n g = F.interpolate(g, [x1.size()[2], x1.size()[3]], mode='bilinear', align_corners=False)\n\n g = torch.cat((g, x1), 1)\n # print('Guidance subnet size: ', g.size())\n # exit(0)\n if s == 0:\n g = self.guidance_x48(g)\n # g = self.guidance(g)\n # print('s == 0')\n elif s == 1:\n # print('s == 1')\n # g = self.guidance(g)\n g = self.guidance_x24(g)\n elif s == 2:\n # print('s == 2')\n # g = self.guidance(g)\n g = self.guidance_x12(g)\n elif s == 3:\n # print('s == 3')\n # g = self.guidance(g)\n g = self.guidance_x6(g)\n else:\n # print('s == 4')\n g = self.guidance(g)\n\n\n if self.training:\n disp0, disp1, disp2 = self.cost_agg(x, g)\n return disp0, disp1, disp2\n\n else:\n return self.cost_agg(x, g)\n\n def disp_downsample(self, disp, s_fac):\n disp = disp.unsqueeze(1)\n disp = F.interpolate(disp, size=[int((disp.size()[2] / s_fac)), int((disp.size()[3] / s_fac))], mode='bilinear',\n align_corners=False)\n disp = disp.squeeze(1)\n disp = disp / s_fac\n return disp\n\n \n def warp(self, x, disp):\n bs, ch, h, w = x.size()\n bg, hg, wg = torch.meshgrid(torch.arange(0,bs) , torch.arange(0,h), torch.arange(0,w))\n\n grid_b, grid_h, grid_w = bg.cuda(), hg.cuda(), wg.cuda()\n warped_gw = torch.sub(grid_w, disp)\n grid = torch.stack([warped_gw, grid_h.float()], dim=-1)\n grid_normalized = ((grid*2)/torch.Tensor([w,h]).cuda()) - 1\n output = F.grid_sample(x, grid_normalized, mode='bilinear', padding_mode='zeros')\n return output\n \n def forward(self, x, y):\n left_img = x\n right_img = y\n g = self.conv_start(x)\n x3, x6, x12, x24, x48 = self.feature(x)\n rem3 = x3\n rem6 = x6\n\n x3 = self.conv_x_multi(x3)\n x6 = self.conv_x_multi(x6)\n x12 = self.conv_x_multi(x12)\n x24 = self.conv_x_multi(x24)\n x48 = self.conv_x_multi(x48)\n\n rem12 = x12\n rem24 = x24\n rem48 = x48\n\n y3, y6, y12, y24, y48 = self.feature(y)\n y3 = self.conv_y_multi(y3)\n y6 = self.conv_y_multi(y6)\n y12 = self.conv_y_multi(y12)\n y24 = self.conv_y_multi(y24)\n y48 = self.conv_y_multi(y48)\n\n ms_disps = []\n\n ''' Resisizing multiscale disparities to add the residual disparity'''\n for i, (x, y, r) in enumerate(zip([x48, x24, x12, x6, x3], [y48, y24, y12, y6, y3], [rem48, rem24, rem12, rem6, rem3])):\n\n if i == 0:\n if self.training:\n disp0, disp1, disp3 = self.ga_head(g, x, y, i, r)\n\n else:\n disp3 = self.ga_head(g, x, y, i, r)\n\n else:\n if self.training:\n disp_for_warping = self.disp_downsample(disp3, 1.5)\n y_warped = self.warp(y, disp_for_warping)\n disp0_res, disp1_res, disp2_res = self.ga_head(g, x, y_warped, i, r)\n disp0 = self.disp_downsample(disp0, 0.5) + disp0_res\n disp1 = self.disp_downsample(disp1, 0.5) + disp1_res\n disp3 = self.disp_downsample(disp3, 0.5) + disp2_res\n\n if i == 4:\n disp3 = self.hourglass_refinement(disp3, left_img, right_img)\n\n ms_disps.append([disp0, disp1, disp3])\n\n else:\n disp_for_warping = self.disp_downsample(disp3, 1.5)\n y_warped = self.warp(y, disp_for_warping)\n\n disp2_res = self.ga_head(g, x, y_warped, i, r)\n disp3 = self.disp_downsample(disp3, 0.5) + disp2_res\n\n\n if i == 4:\n disp3 = self.hourglass_refinement(disp3, left_img, right_img)\n\n if self.training:\n return ms_disps\n else:\n return disp3"
]
| [
[
"torch.nn.functional.normalize",
"torch.nn.Dropout",
"torch.cat",
"torch.arange",
"torch.nn.init.constant_",
"torch.sub",
"torch.nn.init.kaiming_normal_",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.squeeze",
"torch.nn.functional.grid_sample",
"torch.nn.Conv3d",
"torch.nn.Softmin",
"torch.Tensor"
]
]
|
SjoerdCor/micplot | [
"ff0ec25c8fc8840dfcecef919f7639ef0600d4e3"
]
| [
"visualization.py"
]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nThis modules contains all necessary elements to make an effective plot, primarily\nthrough the `visualize` function, which is a wrapper around the Visualization class\n\nBy using `visualize(data)`, where data is a pandas Series or pandas DataFrame,\nthe user receives a Visualization object, with an Axis object as an attribute\nthat contains a plot of the data\n\"\"\"\n\nfrom itertools import cycle\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom micplot import defaults, utils, plotfunctions\n\nclass Annotator:\n \"\"\"Annotates a plot.\"\"\"\n\n def __init__(self, ax, orient, strfmt='.2f', text_alignment=None, text_color=None):\n \"\"\"\n Initialize Annotator object.\n\n Parameters\n ----------\n ax : matplotlib Axes object\n the Axes that should be annotated\n orient : str\n The orientation of the graphic; determines direction of offset\n strfmt : str, optional\n Format specifier for the labels. The default is '.2f'.\n text_alignment : str, optional\n How to align the annotation. The default is None: determine from plot\n text_color : str, optionnal\n Color in which to annotate values. The default is matplotlib default\n\n\n Returns\n -------\n None.\n\n \"\"\"\n self.ax = ax\n if orient not in ['h', 'v']:\n raise ValueError(f'orient must be \"v\" or \"h\", not {orient}')\n self.orient = orient\n self.strfmt = strfmt\n self.text_alignment = text_alignment\n self.text_color = text_color\n\n\n def _determine_offset(self):\n \"\"\"\n Calculate offset in x or y distance, depending on plot orientation.\n\n By default is 2.5% of the plot width\n\n Returns\n -------\n offset : float\n The offset in plot distance\n\n \"\"\"\n if self.orient == 'h':\n lim_min, lim_max = self.ax.get_xlim()\n else:\n lim_min, lim_max = self.ax.get_ylim()\n plotsize = lim_max - lim_min\n\n offset = defaults.OFFSET_FRACTION * plotsize\n return offset\n\n def _determine_alignments(self, value):\n \"\"\"\n Determine text alignment of the annotation.\n\n Determines it with a minimal chance of overlap with the plot\n\n Parameters\n ----------\n value : float\n The value to annotate\n\n Returns\n -------\n ha : str\n Horizontal alignment\n va : str\n Vertical alignment\n\n \"\"\"\n if value < 0:\n if self.orient == 'h':\n ha = self.text_alignment or 'right'\n va = 'center'\n else:\n va = self.text_alignment or 'top'\n ha = 'center'\n else:\n if self.orient == 'h':\n ha = self.text_alignment or 'left'\n va = 'center'\n else:\n va = self.text_alignment or 'bottom'\n ha = 'center'\n return ha, va\n\n def _determine_xy_from_value(self, value, index):\n \"\"\"\n Transform meaningful plus index to x and y coordinate.\n\n Based on plot orientation\n\n Parameters\n ----------\n value : float\n The meaningful value\n index : float\n The index value\n\n Returns\n -------\n x : float\n x coordinate of the input\n y : float\n y coordinate of the input\n\n \"\"\"\n x = value if self.orient == 'h' else index\n y = index if self.orient == 'h' else value\n return (x, y)\n\n def annotate(self, coordinates: pd.Series, display_values=None, index_offset=0):\n \"\"\"\n Annotate the axis.\n\n Parameters\n ----------\n coordinates : pd.Series\n The location of the values\n display_values : pd.Series, optional\n The label of each coordinate. The default is to plot the coordinate values.\n index_offset : float, optional\n How much to displace bars - useful when annotating multiple bars: they become\n smaller, so we must align the numers\n\n Returns\n -------\n None.\n\n \"\"\"\n if display_values is None:\n display_values = coordinates\n\n offset = self._determine_offset()\n\n for i, (v, dv) in enumerate(zip(coordinates, display_values)):\n ind = i + index_offset\n xy = self._determine_xy_from_value(v, ind)\n\n if v < 0:\n v -= offset\n else:\n v += offset\n xytext = self._determine_xy_from_value(v, ind)\n ha, va = self._determine_alignments(v)\n label = '{:{prec}}'.format(dv, prec=self.strfmt)\n self.ax.annotate(label, xy, xytext, va=va, ha=ha, color=self.text_color)\n\n def annotate_scatter(self, coordinates: pd.DataFrame, display_values):\n \"\"\"\n Annotate scatter plot from its coordinates.\n\n Always places labels above the data points\n\n\n Parameters\n ----------\n coordinates : pd.DataFrame\n First column contains x values, second column contains y values.\n display_values : Iterable\n Labels to plot above points. Must be of equal length of the coordinates\n\n Returns\n -------\n None.\n\n \"\"\"\n offset = self._determine_offset()\n\n for label, x, y in zip(display_values, coordinates.iloc[:, 0], coordinates.iloc[:, 1]):\n y2 = y + offset\n self.ax.annotate(label, (x, y), (x, y2))\n\n def annotate_dataframe(self, df: pd.DataFrame):\n \"\"\"\n Annotate each series of the DataFrame.\n\n Corrects for the fact that with multiple columns, bars become smaller\n\n Parameters\n ----------\n df : pd.DataFrame\n The DataFrame of which each series will be annotated.\n\n Returns\n -------\n None.\n\n \"\"\"\n\n for i, colname in enumerate(df):\n index_offset = -0.5 + (i + 1) / (df.shape[1] + 2)\n self.annotate(df[colname], index_offset=index_offset)\n\nclass Consultant:\n \"\"\"Recommend plotting choices.\"\"\"\n\n def recommend_plottype(self, data):\n \"\"\"\n Determine plottype based on shape and content of data.\n\n Based on MIcompany training\n\n Parameters\n ----------\n data: pandas Series or DataFrame\n\n Returns\n -------\n plottype: string of plottype to be used by micompanyify\n \"\"\"\n if isinstance(data.index, pd.DatetimeIndex):\n if len(data) < defaults.LEN_LINEPLOT:\n plottype = 'vertical_bar'\n else:\n plottype = 'line'\n elif isinstance(data, pd.Series):\n if utils.is_percentage_series(data):\n plottype = 'waterfall'\n else:\n plottype = 'bar'\n elif isinstance(data, pd.DataFrame):\n if data.apply(utils.is_percentage_series).all():\n plottype = 'composition_comparison'\n elif data.shape[1] == 2:\n plottype = 'scatter'\n elif data.shape[1] == 3:\n plottype = 'bubble'\n return plottype\n\n def recommend_annotation(self, data, plottype=None):\n \"\"\"\n Recommends whether to annotate a plot.\n \n Parameters\n ----------\n data : pd.Series or pd.DataFrame\n The data which is plotted\n plottype : str, optional\n The type of plot. If not filled, recommends it based on recommended\n plot type\n\n Returns\n -------\n annotate : bool\n Whether to annotate\n\n \"\"\"\n plottype = plottype or self.recommend_plottype(data)\n\n if (plottype in ['bar', 'waterfall', 'vertical_bar', 'composition_comparison']\n or (plottype in ['scatter', 'bubble'] and len(data) <= defaults.LEN_ANNOTATE_SCATTER)):\n return True\n\n return False\n\n def recommend_highlight(self):\n \"\"\"\n Recommends which value(s) to highlight\n\n By default, recommends the top value\n\n Returns\n -------\n list\n indices of values to highlight\n\n \"\"\"\n return [-1]\n\n def recommend_sorting(self, data):\n \"\"\"\n Recommends whether and how to sort the data\n\n See `utils.sort` for the implementation of the sorting\n\n Parameters\n ----------\n data : pd.Series or pd.DataFrame\n The data\n\n Returns\n -------\n str\n sorting parameter\n\n \"\"\"\n if isinstance(data.index, pd.DatetimeIndex):\n return 'index'\n elif isinstance(data, pd.DataFrame):\n return 'original'\n return 'ascending'\n\n def recommend_stringformat(self, data):\n '''\n Determine label precision from data type\n\n Parameters\n ----------\n data : pandas Dataframe or Series with data to label\n '''\n if (isinstance(data, pd.DataFrame) and data.apply(utils.is_percentage_series).all()) or\\\n (isinstance(data, pd.Series) and utils.is_percentage_series(data)):\n strfmt = '.1%'\n elif ((isinstance(data, pd.DataFrame) and data.apply(pd.api.types.is_integer_dtype).all())\n or (isinstance(data, pd.Series) and pd.api.types.is_integer_dtype(data))):\n strfmt = 'd'\n else:\n strfmt = '.2f'\n return strfmt\n\n def recommend_highlight_type(self, data, plottype):\n row_plottypes= ['scatter', 'bubble', 'composition_comparison']\n if isinstance(data, pd.Series) or plottype in row_plottypes:\n return 'row'\n return 'column'\n\n # def recommend_choices(self, data):\n # choices = {}\n # choices['plottype'] = self.recommend_plottype(data)\n # choices['annotated'] = self.recommend_annotation(choices['plottype'], data)\n # choices['highlight'] = self.recommend_highlight()\n # return choices\n\n\nclass Visualization:\n \"\"\"\n Visualize the data and hold all choices as attributes.\n\n Fully customizable through its iniatilization and its attributes\n \"\"\"\n\n plots = {'bar': {'function': plotfunctions.plot_bar,\n 'axes_with_ticks': ['y'],\n 'orient': 'h',\n },\n 'waterfall': {'function': plotfunctions.plot_waterfall,\n 'axes_with_ticks': ['y'],\n 'orient': 'h',\n },\n 'vertical_bar': {'function': plotfunctions.plot_vertical_bar,\n 'axes_with_ticks': ['x'],\n 'orient': 'v',\n },\n 'line': {'function': plotfunctions.plot_line,\n 'axes_with_ticks': ['x', 'y'],\n 'orient': 'v',\n },\n 'scatter': {'function': plotfunctions.plot_scatter,\n 'axes_with_ticks': ['x', 'y'],\n 'orient': 'v',\n },\n 'bubble': {'function': plotfunctions.plot_bubble,\n 'axes_with_ticks': ['x', 'y'],\n 'orient': 'v',\n },\n 'pie': {'function': plotfunctions.plot_pie},\n 'composition_comparison': {'function': plotfunctions.plot_composition_comparison,\n 'axes_with_ticks': ['y'],\n 'orient': 'h'}\n }\n\n\n def __init__(self, data,\n plottype=None,\n highlight=None,\n highlight_color=defaults.HIGHLIGHT_COLOR,\n highlight_type=None,\n sorting=None,\n annotated=None,\n strfmt=None,\n **kwargs,\n ):\n \"\"\"\n Initialize the visualization.\n\n Parameters\n ----------\n data : pd.Series or pd.DataFrame\n The data that is to be visualized\n plottype : str, optional\n The type of plot to use. By default, this is inferred from the data(type). \n Must be one of:\n - 'bar'\n - 'vertical_bar'\n - 'waterfall'\n - 'line'\n - 'scatter'\n - 'bubble'\n - 'pie'\n - 'composition_comparison'\n highlight : iterable, optional\n Iterable of indices of the values which should be highlighted. By default, is top value\n highlight_color : str, optional\n Color str in which to highlight some values. The default is defaults.HIGHLIGHT_COLOR.\n highlight_type : str, optional\n Whether to highlight \"row\" or \"column\". By default, this is determined from the data\n sorting : str, optional\n Whether and how to sort the data. By default, is determined from the data (type)\n Must be one of:\n - 'original': do not sort the data\n - 'index': sort the index of the data ascending\n - 'ascending': sort data ascending\n - 'descending': sort data descending\n annotated : bool, optional\n Whether values should also be displayed in text. By default, this is\n inferred from the data\n strfmt : str, optional\n The format string, how to annotate the data. By default, this is inferred \n from the data type\n kwargs \n Passed to plt.subplots(), e.g. figsize\n\n Raises\n ------\n TypeError\n If data is not of type pd.Series or pd.DataFrame\n\n \"\"\"\n # TODO: make data property\n self.data = data\n if not isinstance(data, pd.DataFrame) and not isinstance(data, pd.Series):\n raise TypeError(f'Data is not of type Series or DataFrame, but type {type(data)}')\n # TODO: validate data is numeric\n self._data_to_plot = self.data.squeeze()\n\n fig, ax = plt.subplots(**kwargs)\n self.ax = ax\n\n self.consultant = Consultant()\n self._sorting = self.consultant.recommend_sorting(self._data_to_plot)\n self.sorting = sorting\n self._highlight = self.consultant.recommend_highlight()\n self.highlight = highlight\n self.highlight_color = highlight_color\n self.strfmt = strfmt or self.consultant.recommend_stringformat(self._data_to_plot)\n\n self._plottype = self.consultant.recommend_plottype(self._data_to_plot)\n self.plottype = plottype\n self._data_to_plot = self.prepare_data()\n self.sorting = sorting\n\n self.highlight_type = (highlight_type\n or self.consultant.recommend_highlight_type(self._data_to_plot,\n self.plottype)\n )\n self.annotated = (annotated\n or self.consultant.recommend_annotation(self._data_to_plot,\n self.plottype)\n )\n\n @property\n def plottype(self):\n return self._plottype\n\n @plottype.setter\n def plottype(self, new_plottype):\n \"\"\"\n Changes plottype after validation\n\n If new_plottype is None, the recommended plottype is set\n Raises ValueError if not an allowed plottype\n \"\"\"\n if new_plottype is None:\n new_plottype = self.consultant.recommend_plottype(self._data_to_plot)\n new_plottype = new_plottype.lower()\n if new_plottype not in self.plots.keys():\n raise ValueError(f'Plottype must be one of {self.plots.keys()}, not `{new_plottype}`')\n self._plottype = new_plottype\n self._determine_annotation()\n self._plot_properties = self.plots[self.plottype]\n # self.plot()\n\n @property\n def highlight(self):\n return self._highlight\n\n @highlight.setter\n def highlight(self, new_highlight):\n \"\"\"\n Changes which data points to highlight\n\n Parameters\n ----------\n new_highlight : Iterable\n\n \"\"\"\n if new_highlight is None:\n new_highlight = self.consultant.recommend_highlight()\n if isinstance(new_highlight, int):\n new_highlight = [new_highlight]\n # TODO: validate is iterable\n self._highlight = new_highlight\n\n @property\n def sorting(self):\n return self._sorting\n\n @sorting.setter\n def sorting(self, new_sorting):\n \"\"\"\n Changes how to sort the data.\n\n Parameters\n ----------\n new_sorting : str, optional\n Must be in ['original', 'index', 'ascending', 'descending']\n \"\"\"\n if new_sorting is None:\n new_sorting = self.consultant.recommend_sorting(self._data_to_plot)\n self._sorting = new_sorting\n\n def prepare_data(self):\n \"\"\"\n Make data uniform and plotworthy.\n \"\"\"\n new_data = (self.data\n .squeeze() # DataFrame with single column should be treated as Series\n .pipe(utils.sort, self.sorting)\n )\n if self.plottype == 'waterfall':\n # TODO: this is not allowed if the index is Categorical <- make sure it's not or add category?\n new_data.loc['Total'] = new_data.sum()\n return new_data\n\n def _determine_annotation(self):\n # TODO: add user preference as an option\n self.annotated = self.consultant.recommend_annotation(self._data_to_plot, self.plottype)\n\n def _find_len_properties(self):\n axis_highlight_type = {'row': 0,\n 'column': 1}\n len_axis = axis_highlight_type[self.highlight_type]\n len_properties = self._data_to_plot.shape[len_axis]\n return len_properties\n\n def _define_colors(self):\n '''\n Return a list of colors with appropiate highlights.\n\n Returns\n -------\n color: list of len(data) with colors and appropriate highlights\n '''\n len_colors = self._find_len_properties()\n color = [defaults.BACKGROUND_COLOR] * len_colors\n\n # Last bar is total, which should not be highlighted\n if self.plottype == 'waterfall':\n color = color[:-1]\n\n for h in self.highlight:\n color[h] = self.highlight_color\n\n # Add darker shade for full bar\n if self.plottype == 'waterfall':\n color += [defaults.BENCHMARK_COLOR]\n return color\n\n def _define_linestyles(self):\n possible_linestyles = ['-', '--', '-.', ':']\n linecycler_background = cycle(possible_linestyles)\n linecycler_highlight = cycle(possible_linestyles)\n linestyles = []\n\n len_axis = self._find_len_properties()\n for _ in range(len_axis):\n linestyles.append(next(linecycler_background))\n for h in self.highlight:\n linestyles[h] = next(linecycler_highlight)\n return linestyles\n\n def annotate(self):\n \"\"\" Annotates values in self.ax.\"\"\"\n if self.plottype == 'waterfall':\n blank = self._data_to_plot.cumsum().shift(1).fillna(0)\n blank.loc['Total'] = 0\n locations = self._data_to_plot + blank\n display_values = self._data_to_plot\n\n elif self.plottype == 'composition_comparison':\n data_begin = self._data_to_plot.cumsum().shift().fillna(0)\n data_end = self._data_to_plot.cumsum()\n if len(self.highlight) > 1:\n raise TypeError('Can only highlight one line in composition comparison')\n\n locations = data_begin.add(data_end).div(2).iloc[self.highlight[0]]\n display_values = self._data_to_plot.iloc[self.highlight[0]]\n else:\n locations = self._data_to_plot\n display_values = self._data_to_plot\n\n if self.plottype == 'composition_comparison':\n # With a composition comparison, annotating is done _in_ the plot\n # intead of just outside it\n text_color = utils.contrasting_text_color(self.highlight_color)\n text_alignment = 'center'\n else:\n text_color = None\n text_alignment = None\n\n ann = Annotator(self.ax, self._plot_properties['orient'], strfmt=self.strfmt,\n text_color=text_color, text_alignment=text_alignment)\n\n if isinstance(display_values, pd.Series):\n ann.annotate(locations, display_values)\n else:\n if self.plottype in ['scatter', 'bubble']:\n ann.annotate_scatter(self._data_to_plot.iloc[:, :2], self._data_to_plot.index)\n else:\n ann.annotate_dataframe(self._data_to_plot)\n\n\n def plot(self):\n \"\"\" Plot the data and show nicely.\"\"\"\n plotter = self._plot_properties['function']\n color = self._define_colors()\n linestyles = self._define_linestyles()\n self.ax = plotter(self._data_to_plot, color=color, style=linestyles, ax=self.ax)\n\n if self.annotated:\n self.annotate()\n\n self.show_nicely()\n\n def show_nicely(self):\n \"\"\" Make the plot look better, by removing fluff.\"\"\"\n\n self.ax.set_frame_on(False)\n\n # TODO: format ticks better, especially for datetimes\n\n if 'x' not in self._plot_properties['axes_with_ticks']:\n self.ax.set_xticks([])\n if 'y' not in self._plot_properties['axes_with_ticks']:\n self.ax.set_yticks([])\n\n # Plot contains legend\n if (isinstance(self._data_to_plot, pd.DataFrame)\n # Legend is fixed in side plotting function\n and self.plottype not in ['scatter', 'bubble']):\n if self.highlight_type == 'row':\n title = self._data_to_plot.index.name\n else:\n title = self._data_to_plot.columns.name\n utils.move_legend_outside_plot(self.ax, title=title)\n \n if isinstance(self._data_to_plot, pd.Series):\n if self._plot_properties['orient'] == 'v' or self.plottype == 'waterfall':\n self.ax.set_ylabel(self._data_to_plot.name)\n else:\n self.ax.set_xlabel(self._data_to_plot.name) \n\ndef visualize(data, **kwargs):\n \"\"\"\n Visualize data and return the visualization containing all attributes\n\n See Visualization for full information\n\n Parameters\n ----------\n data : pd.Series or pd.DataFrame\n The data to visualize\n **kwargs\n See Visualization documentation\n\n Returns\n -------\n vis : `cls::Visualization`\n The visualiziation with all choices as attribtes that can be modified\n\n \"\"\"\n vis = Visualization(data, **kwargs)\n vis.plot()\n return vis\n\nmicompanyify = visualize\n"
]
| [
[
"matplotlib.pyplot.subplots",
"pandas.api.types.is_integer_dtype"
]
]
|
ddehueck/dynaml-lib | [
"64313349ecad0d93d67968a541cf54541ea1009b"
]
| [
"dynaml_lib/experiment.py"
]
| [
"import networkx as nx\nimport numpy as np\nimport json\n\n\"\"\" \nA class for an experiment within our simulated social network environment.\n\nArguments:\n N (int): the number of nodes in the graph\n agent_probs: list of probabilities for each agent type\n\n\"\"\"\n\n\nclass Experiment:\n def __init__(self, N,\n agent_probs=(.1, .8, .1),\n ):\n \"\"\" Initializes an instance of the experiment class to model dynamic graph systems\n\n Arguments:\n N (int): the number of nodes in the graph\n agent_probs: list of probabilities for each agent type\n\n \"\"\"\n # initialize graph\n er = nx.erdos_renyi_graph(N, 0.25)\n self.N = N\n self.edges = np.array(nx.adjacency_matrix(er).todense())\n self.edges = self.edges + np.identity(N)\n\n # Give each node an agent type - fake, neutral, not fake\n self.agents = np.array([np.random.choice([-1, 0, 1], p=agent_probs) for _ in range(N)])\n\n # Give each node an initial state - what kind of info do they carry\n self.states = self.agents.copy()\n\n # state then agent type\n self.transmission_probs = {\n -1: {-1: 0.9, 0: 0.35, 1: 0.1},\n 0: {-1: 0.0, 0: 0.0, 1: 0.0},\n 1: {-1: 0.1, 0: 0.35, 1: 0.9},\n }\n\n # will store a history\n self.state_history = []\n self.transmission_history = []\n self.edge_weight_history = []\n\n def update(self):\n \"\"\" Returns state at next time step \"\"\"\n N = self.N\n random = np.random.rand(N, N)\n new_states = np.zeros(N)\n transmission_matrix = np.zeros((N,N))\n edge_weight_matrix = np.zeros((N,N))\n\n for i in range(N):\n for j in range(N):\n prob_new_state = self.transmission_probs[self.agents[i]][self.states[j]]\n prob_new_state = prob_new_state * self.edges[i][j]\n j_update = self.states[i]\n\n if random[i][j] < prob_new_state:\n transmission_matrix[i][j] = j_update\n\n edge_weight_matrix[i][j] = prob_new_state\n # print(transmission_matrix)\n for j in range(N):\n # nodes wont send to themselves\n identity = sum(transmission_matrix[:, j])\n # print(j, identity)\n if identity > 0:\n new_states[j] = 1\n elif identity < 0:\n new_states[j] = -1\n\n # print(\"new_states\", new_states)\n return new_states, transmission_matrix, edge_weight_matrix\n\n def run(self, steps):\n \"\"\" Runs a simulation of the interaction of the nodes in the social network we have created. This simulation is\n run 'steps' number of times\n \"\"\"\n for i in range(steps):\n new_states, transmission_matrix, edge_weight_matrix = self.update()\n\n self.state_history.append(self.states.tolist())\n self.transmission_history.append(transmission_matrix)\n self.edge_weight_history.append(edge_weight_matrix)\n self.states = new_states.copy()\n return self.state_history, self.transmission_history, self.edge_weight_history\n\n def get_hist(self, steps):\n \"\"\" Returns the history of the states, edges, and edge weights of our network \"\"\"\n state_hist, trans_hist, edge_weight_hist = self.run(steps)\n return process_list_tick_matrices(trans_hist), state_hist\n\n def get_initial(self):\n \"\"\" Returns the initial states and edges of our network \"\"\"\n nodes, edges = initialize_matrix(self.edges)\n graph_dict = {'nodes': nodes, 'edges': edges}\n file_path = \"../api/data.json\"\n with open(file_path, \"w\") as json_file:\n json.dump(graph_dict, json_file)\n\n print(\"graph dict\")\n print(graph_dict)\n return json.dumps(graph_dict)\n\n # def get_pytorch_data(self, generations, file_name):\n # result = self.run(generations)\n # torch.save({\n # \"state_hist\": result[0],\n # \"trans_hist\": result[1],\n # \"edge_hist\": result[2]\n # }, file_name)\n\n\nif __name__ == '__main__':\n # Sample experiment of 100 nodes\n experiment = Experiment(100)"
]
| [
[
"numpy.identity",
"numpy.random.rand",
"numpy.random.choice",
"numpy.zeros"
]
]
|
JunHyun-DS/pandas_testcode | [
"6db3f538f670862f9d22648eb4956cc6194d9c2f"
]
| [
"pandas_test3.py"
]
| [
"import numpy as np\nimport pandas as pd\n\n## 경로\ndata_path = 'C:\\\\Users\\\\bbjjh\\\\OneDrive\\\\바탕 화면\\\\파이썬 스터디\\\\판다스과제\\\\남북한발전전력량.xlsx'\nnewData_path = 'C:\\\\Users\\\\bbjjh\\\\OneDrive\\\\바탕 화면\\\\파이썬 스터디\\\\판다스과제\\\\남북한발전전력량2.xlsx'\n\n## excel파일 읽어오기\ndf = pd.read_excel(data_path)# XlsxWriter 엔진으로 Pandas writer 객체 만들기\n## 원본 데이터\noriginal_df = df\n\n## 남한 : 인덱싱 -> 연도별 부터 시작 -> 수력 값 + 화력 값 = 합게의 값\ndf.iloc[0, 2:] = df.iloc[1, 2:] + df.iloc[2, 2:]\ndf_south_kr = df.iloc[0:3, :]\n\n## 북한 : 인덱싱 -> 연도별 부터 시작 -> 수력 값 + 화력 값 = 합게의 값\ndf.iloc[5, 2:] = df.iloc[6, 2:] + df.iloc[7, 2:]\ndf_north_kr = df.iloc[5:8, :]\n\n# 분리한거 합치기\ndf_kr = pd.concat([df_south_kr, df_north_kr])\n\nwriter = pd.ExcelWriter(newData_path, engine='xlsxwriter')\n\n# DataFrame을 xlsx에 쓰기\noriginal_df.to_excel(writer, sheet_name = 'Sheet1')\ndf_kr.to_excel(writer, sheet_name = 'Sheet2')\n\n# Pandas writer 객체 닫기\nwriter.close()"
]
| [
[
"pandas.read_excel",
"pandas.ExcelWriter",
"pandas.concat"
]
]
|
LishudaNoBug/learning_PyTorch | [
"1026035a9cb3d70e2fe97363b532e63db3ca136d"
]
| [
"tutorial-contents/301_regression.py"
]
| [
"import torch\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\n\n\"\"\"\n 训练回归模型(初级)\n 回归理解为: 对于任意输入有y对应,且y是连续的,形成一条连续的函数图像??\n\"\"\"\n\nx = torch.unsqueeze(torch.linspace(-1, 1, 100),1) # torch.linspace(-1, 1, 100)是-1~1之间取100个数。 unsqueeze是将一维的数处理成二维。因为torch只能处理二维的数,所以这里就变成了(100,1)的数。\ny = x.pow(2) + 0.2*torch.rand(x.size()) # 制造假的y数据: y=x^2+0.2噪声随机数\n\nclass Net(torch.nn.Module):\n def __init__(self, n_feature, n_hidden, n_output): #n_feature:输入的特征数;n_hidden隐藏层神经元数;n_output输出的个数\n super(Net, self).__init__() # 官网固定写法\n self.hidden = torch.nn.Linear(n_feature, n_hidden) # hidden layer\n self.predict = torch.nn.Linear(n_hidden, n_output) # output layer\n\n def forward(self, x): # 重载torch.nn.Module的forward\n x = self.hidden(x) # 隐藏层y=wx+b函数\n x = F.tanh(x) # 激活函数\n x = self.predict(x) # 调用init的predict函数\n return x\n\n\nnet = Net(n_feature=1, n_hidden=10, n_output=1) # 创建Net对象。即一个输入,隐藏层10个1神经元,1个输出\nprint(net) # 打印net对象的hidden和predict属性\n\noptimizer = torch.optim.SGD(net.parameters(), lr=0.2) # optim是优化器,用来初始所有w权重参数。lr是学习率,一般设置小于1。\nloss_func = torch.nn.MSELoss() # MSELoss损失函数,这里用均方误差,但吴恩达说这找不到全局最优解\n\nplt.ion() # plt ion 开启交互模式,当plt.plot打印图片后程序继续执行。如果不开,则plot打印后程序不会继续执行。\n\nfor t in range(1000): #梯度下降200次,\n prediction = net(x) # net(x)会调用Net的forward方法\n\n loss = loss_func(prediction, y) # 损失函数,must be (1. nn output, 2. target)\n\n optimizer.zero_grad() # 清空缓存的梯度\n loss.backward() # 反向传播,先计算各个节点的梯度\n optimizer.step() # 然后应用梯度(这里学习率设置的是0.2)\n\n # plot and show learning process\n if t % 20 == 0: #每训练5次打印一下\n plt.cla() # matplotlib 维护的 figure 有数量上限,在某些情况下,不清理 figure 将有可能造成在第一幅中 plot 的线再次出现在第二幅图中\n plt.scatter(x.data.numpy(), y.data.numpy(),alpha=0.2) # scatter散点图\n plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=1) # plot线;'r-'指red(r)色直线;lw lineWidth;\n plt.text(0.5, 0, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'}) # 前两位0.5,0表示输出信息的坐标(坐标原点0.0);Loss=%.4f 保留小数点后四位;字体尺寸20,颜色红色\n plt.pause(0.1)\n\nplt.ioff()\nplt.show()\n\n"
]
| [
[
"torch.nn.Linear",
"matplotlib.pyplot.ion",
"torch.nn.MSELoss",
"torch.linspace",
"matplotlib.pyplot.cla",
"matplotlib.pyplot.show",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.ioff",
"torch.nn.functional.tanh"
]
]
|
tynguyen/frankmocap | [
"c09e560aa7315e4f94b725cc41417e7de5f6ed4f"
]
| [
"mocap_utils/demo_utils.py"
]
| [
"# Copyright (c) Facebook, Inc. and its affiliates.\n\nimport os, sys, shutil\nimport os.path as osp\nimport cv2\nfrom collections import OrderedDict\nimport mocap_utils.general_utils as gnu\nimport numpy as np\nimport json\nimport subprocess as sp\n\n\ndef setup_render_out(out_dir):\n if out_dir is not None:\n gnu.build_dir(out_dir)\n outputFileName = \"scene_%08d.jpg\" # Hardcoded in glViewer.py\n\n overlaidImageFolder = osp.join(out_dir, \"overlaid\")\n gnu.build_dir(overlaidImageFolder)\n\n sideImageFolder = osp.join(out_dir, \"side\")\n gnu.build_dir(sideImageFolder)\n\n mergedImageFolder = osp.join(out_dir, \"merged\")\n gnu.build_dir(mergedImageFolder)\n\n res_subdirs = [\n outputFileName,\n overlaidImageFolder,\n sideImageFolder,\n mergedImageFolder,\n ]\n return res_subdirs\n\n else:\n return None\n\n\ndef __get_input_type(args):\n input_type = None\n image_exts = (\"jpg\", \"png\", \"jpeg\", \"bmp\")\n video_exts = (\"mp4\", \"avi\", \"mov\")\n extension = osp.splitext(args.input_path)[1][1:]\n\n if extension.lower() in video_exts:\n input_type = \"video\"\n elif osp.isdir(args.input_path):\n file_list = os.listdir(args.input_path)\n assert len(file_list) > 0, f\"{args.input_path} is a blank folder\"\n extension = osp.splitext(file_list[0])[1][1:]\n if extension == \"json\":\n input_type = \"bbox_dir\"\n else:\n assert extension.lower() in image_exts\n input_type = \"image_dir\"\n elif args.input_path == \"webcam\":\n input_type = \"webcam\"\n else:\n assert False, (\n \"Unknown input path. It should be an image,\"\n + \"or an image folder, or a video file, or 'webcam' \"\n )\n return input_type\n\n\ndef __video_setup(args):\n video_path = args.input_path\n video_dir, video_name, video_basename, ext = gnu.analyze_path(video_path)\n args.seq_name = video_basename\n\n if args.save_frame:\n frame_dir = osp.join(args.out_dir, \"frames\")\n gnu.build_dir(frame_dir)\n\n render_out_dir = osp.join(args.out_dir, \"rendered\")\n gnu.build_dir(render_out_dir)\n\n mocap_out_dir = osp.join(args.out_dir, \"mocap\")\n gnu.build_dir(mocap_out_dir)\n\n\ndef __img_seq_setup(args):\n seq_dir_path = args.input_path\n args.seq_name = os.path.basename(args.input_path)\n\n render_out_dir = osp.join(args.out_dir, \"rendered\")\n gnu.build_dir(render_out_dir)\n\n mocap_out_dir = osp.join(args.out_dir, \"mocap\")\n gnu.build_dir(mocap_out_dir)\n\n\ndef setup_input(args):\n \"\"\"\n Input type can be\n an image file\n a video file\n a folder with image files\n a folder with bbox (json) files\n \"webcam\"\n\n \"\"\"\n image_exts = (\"jpg\", \"png\", \"jpeg\", \"bmp\")\n video_exts = (\"mp4\", \"avi\", \"mov\")\n\n # get type of input\n input_type = __get_input_type(args)\n\n if input_type == \"video\":\n cap = cv2.VideoCapture(args.input_path)\n assert cap.isOpened(), f\"Failed in opening video: {args.input_path}\"\n __video_setup(args)\n return input_type, cap\n\n elif input_type == \"webcam\":\n cap = cv2.VideoCapture(0) # webcam input\n return input_type, cap\n\n elif input_type == \"image_dir\":\n image_list = gnu.get_all_files(args.input_path, image_exts, \"relative\")\n image_list = [\n osp.join(args.input_path, image_name) for image_name in image_list\n ]\n if args.dmap_path is not None:\n dmap_list = gnu.get_all_files(args.dmap_path, image_exts, \"relative\")\n dmap_list = [\n osp.join(args.dmap_path, image_name) for image_name in dmap_list\n ]\n\n __img_seq_setup(args)\n if args.dmap_path is not None:\n return input_type, image_list, dmap_list\n return input_type, image_list\n\n elif input_type == \"bbox_dir\":\n __img_seq_setup(args)\n json_files = gnu.get_all_files(args.input_path, \".json\", \"relative\")\n input_data = list()\n for json_file in json_files:\n json_path = osp.join(args.input_path, json_file)\n image_path, body_bbox_list, hand_bbox_list = load_info_from_json(json_path)\n input_data.append(\n dict(\n image_path=image_path,\n hand_bbox_list=hand_bbox_list,\n body_bbox_list=body_bbox_list,\n )\n )\n return input_type, input_data\n\n else:\n assert False, \"Unknown input type\"\n\n\ndef extract_mesh_from_output(pred_output_list):\n pred_mesh_list = list()\n for pred_output in pred_output_list:\n if pred_output is not None:\n if \"left_hand\" in pred_output: # hand mocap\n for hand_type in pred_output:\n if pred_output[hand_type] is not None:\n vertices = pred_output[hand_type][\"pred_vertices_img\"]\n faces = pred_output[hand_type][\"faces\"].astype(np.int32)\n pred_mesh_list.append(dict(vertices=vertices, faces=faces))\n else: # body mocap (includes frank/whole/total mocap)\n vertices = pred_output[\"pred_vertices_img\"]\n faces = pred_output[\"faces\"].astype(np.int32)\n pred_mesh_list.append(dict(vertices=vertices, faces=faces))\n return pred_mesh_list\n\n\ndef load_info_from_json(json_path):\n data = gnu.load_json(json_path)\n # image path\n assert \"image_path\" in data, \"Path of input image should be specified\"\n image_path = data[\"image_path\"]\n assert osp.exists(image_path), f\"{image_path} does not exists\"\n # body bboxes\n body_bbox_list = list()\n if \"body_bbox_list\" in data:\n body_bbox_list = data[\"body_bbox_list\"]\n assert isinstance(body_bbox_list, list)\n for b_id, body_bbox in enumerate(body_bbox_list):\n if isinstance(body_bbox, list) and len(body_bbox) == 4:\n body_bbox_list[b_id] = np.array(body_bbox)\n # hand bboxes\n hand_bbox_list = list()\n if \"hand_bbox_list\" in data:\n hand_bbox_list = data[\"hand_bbox_list\"]\n assert isinstance(hand_bbox_list, list)\n for hand_bbox in hand_bbox_list:\n for hand_type in [\"left_hand\", \"right_hand\"]:\n if hand_type in hand_bbox:\n bbox = hand_bbox[hand_type]\n if isinstance(bbox, list) and len(bbox) == 4:\n hand_bbox[hand_type] = np.array(bbox)\n else:\n hand_bbox[hand_type] = None\n return image_path, body_bbox_list, hand_bbox_list\n\n\ndef save_info_to_json(args, image_path, body_bbox_list, hand_bbox_list):\n saved_data = dict()\n\n # image_path\n saved_data[\"image_path\"] = image_path\n\n # body_bbox_list\n saved_body_bbox_list = list()\n for body_bbox in body_bbox_list:\n if body_bbox is not None:\n saved_body_bbox_list.append(body_bbox.tolist())\n saved_data[\"body_bbox_list\"] = saved_body_bbox_list\n\n # hand_bbox_list\n saved_hand_bbox_list = list()\n for hand_bbox in hand_bbox_list:\n if hand_bbox is not None:\n saved_hand_bbox = dict(left_hand=None, right_hand=None)\n for hand_type in saved_hand_bbox:\n bbox = hand_bbox[hand_type]\n if bbox is not None:\n saved_hand_bbox[hand_type] = bbox.tolist()\n saved_hand_bbox_list.append(saved_hand_bbox)\n saved_data[\"hand_bbox_list\"] = saved_hand_bbox_list\n\n # write data to json\n img_name = osp.basename(image_path)\n record = img_name.split(\".\")\n json_name = f\"{'.'.join(record[:-1])}_bbox.json\"\n json_path = osp.join(args.out_dir, \"bbox\", json_name)\n gnu.make_subdir(json_path)\n gnu.save_json(json_path, saved_data)\n print(f\"Bbox saved: {json_path}\")\n\n\ndef save_pred_to_pkl(\n args, demo_type, image_path, body_bbox_list, hand_bbox_list, pred_output_list\n):\n\n smpl_type = \"smplx\" if args.use_smplx else \"smpl\"\n assert demo_type in [\"hand\", \"body\", \"frank\"]\n if demo_type in [\"hand\", \"frank\"]:\n assert smpl_type == \"smplx\"\n\n assert len(hand_bbox_list) == len(body_bbox_list)\n assert len(body_bbox_list) == len(pred_output_list)\n\n saved_data = dict()\n # demo type / smpl type / image / bbox\n saved_data = OrderedDict()\n saved_data[\"demo_type\"] = demo_type\n saved_data[\"smpl_type\"] = smpl_type\n saved_data[\"image_path\"] = osp.abspath(image_path)\n saved_data[\"body_bbox_list\"] = body_bbox_list\n saved_data[\"hand_bbox_list\"] = hand_bbox_list\n saved_data[\"save_mesh\"] = args.save_mesh\n\n saved_data[\"pred_output_list\"] = list()\n num_subject = len(hand_bbox_list)\n for s_id in range(num_subject):\n # predict params\n pred_output = pred_output_list[s_id]\n if pred_output is None:\n saved_pred_output = None\n else:\n saved_pred_output = dict()\n if demo_type == \"hand\":\n for hand_type in [\"left_hand\", \"right_hand\"]:\n pred_hand = pred_output[hand_type]\n saved_pred_output[hand_type] = dict()\n saved_data_hand = saved_pred_output[hand_type]\n if pred_hand is None:\n saved_data_hand = None\n else:\n for pred_key in pred_hand:\n if pred_key.find(\"vertices\") < 0 or pred_key == \"faces\":\n saved_data_hand[pred_key] = pred_hand[pred_key]\n else:\n if args.save_mesh:\n if pred_key != \"faces\":\n saved_data_hand[pred_key] = pred_hand[\n pred_key\n ].astype(np.float16)\n else:\n saved_data_hand[pred_key] = pred_hand[pred_key]\n else:\n for pred_key in pred_output:\n if pred_key.find(\"vertices\") < 0 or pred_key == \"faces\":\n saved_pred_output[pred_key] = pred_output[pred_key]\n else:\n if args.save_mesh:\n if pred_key != \"faces\":\n saved_pred_output[pred_key] = pred_output[\n pred_key\n ].astype(np.float16)\n else:\n saved_pred_output[pred_key] = pred_output[pred_key]\n\n saved_data[\"pred_output_list\"].append(saved_pred_output)\n\n # write data to pkl\n img_name = osp.basename(image_path)\n record = img_name.split(\".\")\n pkl_name = f\"{'.'.join(record[:-1])}_prediction_result.pkl\"\n pkl_path = osp.join(args.out_dir, \"mocap\", pkl_name)\n gnu.make_subdir(pkl_path)\n gnu.save_pkl(pkl_path, saved_data)\n print(f\"Prediction saved: {pkl_path}\")\n\n\ndef save_res_img(out_dir, image_path, res_img):\n out_dir = osp.join(out_dir, \"rendered\")\n img_name = osp.basename(image_path)\n img_name = img_name[:-4] + \".jpg\" # Always save as jpg\n res_img_path = osp.join(out_dir, img_name)\n gnu.make_subdir(res_img_path)\n cv2.imwrite(res_img_path, res_img)\n print(f\"Visualization saved: {res_img_path}\")\n\n\ndef gen_video_out(out_dir, seq_name):\n outVideo_fileName = osp.join(out_dir, seq_name + \".mp4\")\n print(f\">> Generating video in {outVideo_fileName}\")\n\n in_dir = osp.abspath(osp.join(out_dir, \"rendered\"))\n out_path = osp.abspath(osp.join(out_dir, seq_name + \".mp4\"))\n ffmpeg_cmd = f'ffmpeg -y -f image2 -framerate 25 -pattern_type glob -i \"{in_dir}/*.jpg\" -pix_fmt yuv420p -c:v libx264 -x264opts keyint=25:min-keyint=25:scenecut=-1 -vf \"scale=trunc(iw/2)*2:trunc(ih/2)*2\" {out_path}'\n os.system(ffmpeg_cmd)\n # print(ffmpeg_cmd.split())\n # sp.run(ffmpeg_cmd.split())\n # sp.Popen(ffmpeg_cmd.split(), stdout=sp.PIPE, stderr=sp.PIPE)\n"
]
| [
[
"numpy.array"
]
]
|
AlbertoRoper/GW_turbulence | [
"758be3b86f21c37ceb6f8405c98890069264da24"
]
| [
"JCAP_2107_05356/generate_plots_interferometry.py"
]
| [
"\"\"\"\ngenerate_plots_interferometry.py is a Python routine\nto generate the plots of Appendix B (LISA and Taiji interferometry)\nof A. Roper Pol, S. Mandal, A. Brandenburg, and T. Kahniashvili,\n\"Polarization of gravitational waves from helical MHD turbulent sources\",\nhttps://arxiv.org/abs/2107.05356.\n\"\"\"\n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport astropy.units as u\n\nplt.rcParams.update({'xtick.labelsize': 'x-large',\n 'ytick.labelsize': 'x-large',\n 'axes.labelsize': 'x-large'})\n\n# get working directory, where the runs and routines should be stored\ndir0 = os.getcwd() + '/'\nHOME = dir0 + '/..'\nos.chdir(HOME)\n\nimport plot_sets\nimport interferometry as inte\n\n# response functions of LISA and Taiji\nfs, MAs, MAEs, MTs, DAEs, MAs_Tai, MAEs_Tai, MTs_Tai, DAEs_Tai = \\\n inte.read_response_LISA_Taiji()\n\n# Noise power spectral density of LISA channel A and Taiji channel C\nPnA, PnT = inte.Pn_TDI(fs)\nPnX, PnXY = inte.Pn_f(fs)\nL = 3e6*u.km\nPnC, PnS = inte.Pn_TDI(fs, P=8, A=3, L=L)\nPnX_Tai, PnXY_Tai = inte.Pn_f(fs, P=8, A=3, L=L)\n# strain sensitivities\nSnA = PnA/MAs\nSnT = PnT/MTs\nSnX = PnX/MAs\nSnC = PnC/MAs_Tai\nSnX_Tai = PnX_Tai/MAs_Tai\nSnS = PnS/MTs_Tai\n\n# Dipole response sensitivities\nv = 1.23e-3\nSnAE_Xi = PnA/v/abs(DAEs)\nSnCD_Xi = PnC/v/abs(DAEs_Tai)\n\nf_AC, M_AC = inte.read_MAC()\nf_AD, M_AD = inte.read_MAC(M='MAD')\nf_EC, M_EC = inte.read_MAC(M='MEC')\nf_ED, M_ED = inte.read_MAC(M='MED')\nf_ED_I, M_ED_I = inte.read_MAC(M='MED', V='I')\n\n# refine and interpolate in fs\nf_ED_I, M_ED_I = inte.refine_M(f_ED_I, M_ED_I, A=0.028277196782809974)\nM_ED_I = np.interp(fs, f_ED_I, M_ED_I)\nM_ED_I[np.where(fs > f_ED_I[-1])] = 1e-50\nf_AC, M_AC = inte.refine_M(f_AC, M_AC, A=15, exp=1)\nM_AC = np.interp(fs, f_AC, M_AC)\nM_AC[np.where(fs > f_AC[-1])] = 1e-50\nf_AD, M_AD = inte.refine_M(f_AD, M_AD, A=10, exp=1)\nM_AD = np.interp(fs, f_AD, M_AD)\nM_AD[np.where(fs > f_AD[-1])] = 1e-50\nf_EC, M_EC = inte.refine_M(f_EC[2:], M_EC[2:], A=-9, exp=1)\nM_EC = np.interp(fs, f_EC, M_EC)\nM_EC[np.where(fs > f_EC[-1])] = 1e-50\nf_ED, M_ED = inte.refine_M(f_ED[2:], M_ED[2:], A=-13, exp=1)\nM_ED = np.interp(fs, f_ED, M_ED)\nM_ED[np.where(fs > f_ED[-1])] = 1e-50\n\n# multiply R functions by 2 to get monopole response function\nM_AC*=2.\nM_AD*=2.\nM_EC*=2.\nM_ED*=2.\nM_ED_I*=2.\n\n# Sensitivity of the cross-correlated channels of the LISA-Taiji network\n# Stokes parameter I\nSn_ED_I = np.sqrt(PnA*PnC)/abs(M_ED_I)\nSn_AC_V = np.sqrt(PnA*PnC)/abs(M_AC)\nSn_AD_V = np.sqrt(PnA*PnC)/abs(M_AD)\nSn_EC_V = np.sqrt(PnA*PnC)/abs(M_EC)\nSn_ED_V = np.sqrt(PnA*PnC)/abs(M_ED)\n\n# noise functions\nPacc = inte.Pacc_f(fs)\nPacc_Tai = inte.Pacc_f(fs, A=3, L=L)\nPoms = inte.Poms_f(fs)\nPoms_Tai = inte.Poms_f(fs, P=8, L=L)\n\n# GW energy density sensitivity\nOmSA = inte.Oms(fs, SnA)\nOmST = inte.Oms(fs, SnT)\nOmSC = inte.Oms(fs, SnC)\nOmSS = inte.Oms(fs, SnS)\nOmS_ED_I = .5*inte.Oms(fs, Sn_ED_I)\nOmS_comb = 1/np.sqrt(1/OmSA**2 + 1/OmSC**2)\n\n###### GW polarization sensitivity\n# From LISA and Taiji dipole response functions\nXiSAE = .5*inte.Oms(fs, SnAE_Xi)\nXiSCD = .5*inte.Oms(fs, SnCD_Xi)\n# From monopole response functions of cross-correlated channels of the\n# LISA-Taiji network\nXiSAC = inte.Oms(fs, Sn_AC_V)\nXiSAD = inte.Oms(fs, Sn_AD_V)\nXiSEC = inte.Oms(fs, Sn_EC_V)\nXiSED = inte.Oms(fs, Sn_ED_V)\nXiS_comb = 1/np.sqrt(1/XiSAD**2 + 1/XiSAC**2 + \\\n 1/XiSEC**2 + 1/XiSED**2)\nT = 1*u.yr\nT = T.to(u.s)\nXiflat = .5/np.sqrt(np.trapz(1/XiSAE**2, fs.value)*T.value)\nXiflat_Tai = .5/np.sqrt(np.trapz(1/XiSCD**2, fs.value)*T.value)\nXiflat_comb = .5/np.sqrt(np.trapz(1/XiS_comb**2, fs.value)*T.value)\n\nos.chdir(dir0)\n\ndef get_response():\n return fs, MAs, MAEs, MTs, DAEs, MAs_Tai, MAEs_Tai, MTs_Tai, DAEs_Tai\ndef get_response_LT():\n return fs, M_AC, M_AD, M_EC, M_ED\ndef get_sensitivity():\n return fs, SnX, SnA, SnT, SnX_Tai, SnC, SnS\ndef get_ED_I():\n return fs, M_ED_I, Sn_ED_I, OmS_ED_I\ndef get_sensitivity_V():\n return fs, Sn_AC_V, Sn_AD_V, Sn_EC_V, Sn_ED_V\ndef get_noise():\n return fs, Pacc, Poms, PnX, PnA, PnT, Pacc_Tai, Poms_Tai, PnX_Tai, PnC, PnS\ndef get_Omega_sensitivity():\n return fs, OmSA, OmST, OmSC, OmSS, OmS_comb\ndef get_Xi_sensitivity():\n return fs, XiSAE, XiSCD, XiSAD, XiSAC, XiSEC, XiSED, XiS_comb\ndef get_Xiflat():\n return Xiflat, Xiflat_Tai, Xiflat_comb\n\ndef get_Omega_PLS(beta):\n\n \"\"\"\n Function that returns the PLS of the GW energy density\n for SNR = 1 and 1 year.\n\n Arguments:\n beta -- array of values of beta to compute the PLS\n \"\"\"\n\n OmPLS = inte.OmPLS(fs, OmSA, beta)\n OmPLS_Tai = inte.OmPLS(fs, OmSC, beta)\n OmPLS_comb = inte.OmPLS(fs, OmS_comb, beta)\n return fs, OmPLS, OmPLS_Tai, OmPLS_comb\n\ndef get_Xi_PLS_dip(beta, Xi=.25):\n\n \"\"\"\n Function that returns the PLS helical GW energy density using the dipole\n response function for SNR = 1 and 1 year.\n\n Arguments:\n beta -- array of values of beta to compute the PLS\n Xi -- factor to be included in the computation of the PLS\n (default is 0.25, which corresponds to the dipole response,\n Xi=0 can be used for PLS obtained using monopole response)\n Returns:\n fs -- frequency array\n XiPLS -- helical PLS from LISA dipole response function\n XiPLS_Tai -- helical PLS from Taiji dipole response function\n \"\"\"\n\n XiPLS = inte.OmPLS(fs, XiSAE, beta, Xi=Xi)\n XiPLS_Tai = inte.OmPLS(fs, XiSCD, beta, Xi=Xi)\n return fs, XiPLS, XiPLS_Tai\n\ndef get_Xi_PLS(beta):\n\n \"\"\"\n Function that returns the PLS helical GW energy density using the monopole\n response function of cross-correlated channels of the LISA-Taiji network\n for SNR = 1 and 1 year.\n\n Arguments:\n beta -- array of values of beta to compute the PLS\n Returns:\n fs -- frequency array\n XiPLS_comb -- helical PLS from the combination of the cross-correlated\n channels of the LISA-Taiji network\n \"\"\"\n\n XiPLS_comb = inte.OmPLS(fs, XiS_comb, beta)\n return fs, XiPLS_comb\n\ndef plot_Mf(save=True, ED_I=False):\n\n \"\"\"\n Function that generates the plot of the LISA and Taiji monopole\n response functions.\n\n It corresponds to left panel of figure 15 of A. Roper Pol, S. Mandal,\n A. Brandenburg, and T. Kahniashvili, \"Polarization of gravitational waves\n from helical MHD turbulent sources,\" submitted to JCAP,\n https://arxiv.org/abs/2107.05356.\n\n Arguments:\n save -- option to save the figure in \"plots/LISA_Taiji_response.pdf\"\n (default True)\n ED_I -- option to plot the response function of cross-correlating\n channels E and D of the LISA-Taiji network (default False)\n \"\"\"\n\n plt.figure(figsize=(12,10))\n plt.rc('font', size=30)\n plt.plot(fs, MAs, color='black', label=r'${\\cal M}_{\\rm AA} (f)$')\n plt.plot(fs, MAs_Tai, color='black', ls='-.',\n label=r'${\\cal M}_{\\rm CC} (f)$')\n plt.plot(fs, MTs, color='blue', label=r'${\\cal M}_{\\rm TT} (f)$')\n plt.plot(fs, MTs_Tai, color='blue', ls='-.',\n label=r'${\\cal M}_{\\rm SS} (f)$')\n aaux = ''\n if ED_I == True:\n gg = np.where(abs(M_ED_I) > 1e-48)\n plt.plot(fs[gg], abs(M_ED_I[gg]), color='purple', alpha=.5)\n plt.text(3e-3, 6e-3, r'$|{\\cal M}^I_{\\rm ED}|$', color='purple')\n aaux = 'ED'\n Rf = inte.R_f(fs)\n L = 3e6*u.km\n Rf_Tai = inte.R_f(fs, L=L)\n plt.plot(fs, Rf, color='black', ls='dashed', lw=.7)\n plt.plot(fs, Rf_Tai, color='black', ls='dashed', lw=.7)\n plt.text(5e-2, 7e-2, r'$\\tilde {\\cal R}^{\\rm A, C}(f)$', fontsize=34)\n plt.xscale('log')\n plt.yscale('log')\n plt.xlim(1e-3, 1)\n plt.ylim(1e-7, 1e0)\n plt.legend(fontsize=28, frameon=False, loc='center left')\n plt.xlabel(r'$f$ [Hz]')\n plt.ylabel(r'${\\cal M} (f)$')\n plot_sets.axes_lines()\n plt.yticks(np.logspace(-7, 0, 8))\n\n ax = plt.gca()\n ax.tick_params(axis='x', pad=20)\n ax.tick_params(axis='y', pad=10)\n\n if save: plt.savefig('plots/LISA_Taiji_response' + aaux + '.pdf',\n bbox_inches='tight')\n\ndef DAE_posneg(f, D, lw=1, ls='solid'):\n\n \"\"\"\n Function to plot negative values in red and positive values in blue\n of a function D.\n\n Arguments:\n f -- frequency array\n D -- dipole response function\n lw -- line width of lines (default 1)\n ls -- line style of lines (default 'solid')\n \"\"\"\n\n sgn = np.sign(D)\n converge = False\n sgn0 = sgn[0]\n i = 0\n while not converge:\n sign = False\n i0 = i\n while not sign and not converge:\n if sgn0 == 1: col='blue'\n else: col='red'\n if i==len(sgn) - 2: converge=True\n if sgn[i] != sgn0:\n sign = True\n sgn0 = sgn[i]\n i += 1\n else: i += 1\n plt.plot(f[i0:i + 1], abs(D[i0:i + 1]),\n color=col, ls=ls, lw=lw)\n if i == len(sgn) - 2: converge=True\n\ndef plot_Df(save=True):\n\n \"\"\"\n Function that generates the plot of the LISA and Taiji dipole\n response functions.\n\n It corresponds to right panel of figure 15 of A. Roper Pol, S. Mandal,\n A. Brandenburg, and T. Kahniashvili, \"Polarization of gravitational waves\n from helical MHD turbulent sources,\" submitted to JCAP,\n https://arxiv.org/abs/2107.05356.\n\n Arguments:\n save -- option to save the figure in \"plots/DEA_LISA_Taiji.pdf\"\n (default True)\n \"\"\"\n\n fig, ax0 = plt.subplots(figsize=(12,10))\n # plt.rc('font', size=30)\n DAE_posneg(fs, DAEs)\n DAE_posneg(fs, DAEs_Tai, ls='-.')\n plt.xlim(1e-3, 1)\n plt.ylim(1e-7, 1)\n plt.xlabel(r'$f$ [Hz]')\n plt.ylabel(r'${\\cal D}(f)$')\n plt.xscale('log')\n plt.yscale('log')\n plot_sets.axes_lines()\n plt.text(4.7e-2, 2e-2, r'${\\cal D}_{AE}(f)$', fontsize=30)\n plt.text(1.3e-2, 7e-3, r'${\\cal D}_{CD}(f)$', fontsize=30)\n #plt.text(2.1e-2, 3e-3, r'${\\cal D}_{CD}(f)$', fontsize=20)\n\n line_pos, = ax0.plot([], [], color='blue', lw=.7,\n label=r'positive values')\n line_neg, = ax0.plot([], [], color='red', lw=.7,\n label=r'negative values')\n handles = [line_pos, line_neg]\n lgd = ax0.legend(handles=handles, loc='lower left',\n fontsize=34, frameon=False)\n\n ax = plt.gca()\n ax.tick_params(axis='x', pad=20)\n ax.tick_params(axis='y', pad=10)\n\n plt.yticks(np.logspace(-7, 0, 8))\n\n if save: plt.savefig('plots/DEA_LISA_Taiji.pdf', bbox_inches='tight')\n\ndef plot_sensitivity(save=True):\n\n \"\"\"\n Function that generates the plot of LISA and Taiji strain sensitivities.\n\n Arguments:\n save -- option to save the figure in \"plots/sensitivity_LISA_Taiji.pdf\"\n (default True)\n \"\"\"\n\n plt.figure(figsize=(12,8))\n plt.rc('font', size=20)\n plt.plot(fs, np.sqrt(SnX), color='red', label='channel X')\n plt.plot(fs, np.sqrt(SnA), color='blue', label='TDI channel A')\n plt.plot(fs, np.sqrt(SnT), color='orange', label='TDI channel T',\n alpha=.6)\n\n plt.plot(fs, np.sqrt(SnX_Tai), color='red', ls='-.')\n plt.plot(fs, np.sqrt(SnC), color='blue', ls='-.')\n plt.plot(fs, np.sqrt(SnS), color='orange', ls='-.', alpha=.6)\n gg = np.where(abs(M_ED_I) > 1e-48)\n plt.plot(fs[gg], np.sqrt(Sn_ED_I[gg]), color='purple', alpha=.5,\n label='TDI channels ED')\n\n plt.legend(fontsize=20)\n plt.xlabel('$f$ [Hz]')\n plt.ylabel(r'Strain sensitivity $\\left[{\\rm Hz}^{-1/2}\\right]$')\n plt.xscale('log')\n plt.yscale('log')\n plt.text(1e-1, 3e-19, 'LISA', fontsize=20)\n plt.text(1e-1, 8e-21, 'Taiji', fontsize=20)\n plt.ylim(1e-21, 1e-12)\n plt.xlim(1e-5, 1e0)\n plot_sets.axes_lines()\n ax = plt.gca()\n ytics = 10**np.array(np.linspace(-21, -12, 10))\n ax.set_yticks(ytics)\n\n if save: plt.savefig('plots/sensitivity_LISA_Taiji.pdf',\n bbox_inches='tight')\n\ndef plot_Omega_sensitivity(OmPLS, OmPLS_Tai, OmPLS_comb,\n SNR=10, T=4, save=True):\n\n \"\"\"\n Function that generates the plot of LISA and Taiji GW energy density\n sensitivities and PLS.\n\n It corresponds to left panel of figure 16 of A. Roper Pol, S. Mandal,\n A. Brandenburg, and T. Kahniashvili, \"Polarization of gravitational waves\n from helical MHD turbulent sources,\" submitted to JCAP,\n https://arxiv.org/abs/2107.05356.\n\n Arguments:\n OmPLS -- power law sensitivity (PLS) of LISA for T = 1yr and SNR = 1\n OmPLS_Tai -- power law sensitivity (PLS) of Taiji for T = 1yr\n and SNR = 1\n OmPLS_comb -- power law sensitivity (PLS) of the LISA-Taiji network\n for T = 1yr and SNR = 1\n SNR -- signal-to-noise ratio (SNR) for the plotted PLS (default 10)\n T -- duration of the observations for the plotted PLS in\n years (default 4)\n save -- option to save the figure in \"plots/Omega_LISA_Taiji.pdf\"\n (default True)\n \"\"\"\n\n import pandas as pd\n\n fact = SNR/np.sqrt(T)\n fig, ax0 = plt.subplots(figsize=(12,10))\n line_OmPLS, = ax0.plot([], [], color='green',\n label=r'$\\Omega_{\\rm PLS}^{\\rm A}$')\n line_OmPLS_Tai, = ax0.plot([], [], color='green', ls='-.',\n label=r'$\\Omega_{\\rm PLS}^{\\rm C}$')\n line_OmPLS_comb, = ax0.plot([], [], color='green', lw=.8,\n label=r'$\\Omega_{\\rm PLS}^{\\rm comb}$')\n\n line_OmSA, = ax0.plot([], [], color='blue',\n label=r'$\\Omega_{\\rm s}^{\\rm A}$')\n line_OmSC, = ax0.plot([], [], color='blue', ls='-.',\n label=r'$\\Omega_{\\rm s}^{\\rm C}$')\n line_OmS_comb, = ax0.plot([], [], color='blue', lw=.8,\n label=r'$\\Omega_{\\rm s}^{\\rm comb}$')\n\n line_OmST, = ax0.plot([], [], color='orange', alpha=.5,\n label=r'$\\Omega_{\\rm s}^{\\rm T}$')\n line_OmSS, = ax0.plot([], [], color='orange', ls='-.', alpha=.5,\n label=r'$\\Omega_{\\rm s}^{\\rm S}$')\n line_OmS_ED_I, = ax0.plot([], [], color='purple', alpha=.5,\n label=r'$\\Omega_{\\rm s}^{\\rm ED}$')\n\n handles = [line_OmSA, line_OmSC, line_OmS_comb]\n lgd1 = ax0.legend(handles=handles, loc='lower right',\n fontsize=28, frameon=False)\n handles2 = [line_OmST, line_OmSS, line_OmS_ED_I]\n lgd2 = ax0.legend(handles=handles2, loc='upper left',\n fontsize=28, frameon=False)\n handles3 = [line_OmPLS, line_OmPLS_Tai, line_OmPLS_comb]\n lgd3 = ax0.legend(handles=handles3, loc='lower left',\n fontsize=28, frameon=False)\n ax0.add_artist(lgd1)\n ax0.add_artist(lgd2)\n\n # plt.rc('font', size=30)\n plt.plot(fs, OmSA, color='blue')\n plt.plot(fs, OmST, color='orange', alpha=.5)\n plt.plot(fs, OmPLS*fact, color='green')\n plt.plot(fs, OmSC, '-.', color='blue')\n plt.plot(fs, OmSS, '-.', color='orange', alpha=.5)\n plt.plot(fs, OmPLS_Tai*fact, '-.', color='green')\n gg = np.where(abs(M_ED_I) > 1e-48)\n plt.plot(fs[gg], OmS_ED_I[gg], color='purple', alpha=.5)\n plt.plot(fs, OmS_comb, color='blue', lw=.8)\n plt.plot(fs, OmPLS_comb*fact, color='green', lw=.8)\n\n # Add reference PLS from Caprini et al 2019\n dir = '../detector_sensitivity/'\n df = pd.read_csv(dir + 'OmegaPLS_Caprinietal19.csv')\n f = np.array(df['f'])\n ff = np.logspace(np.log10(f[0]), np.log10(f[-1]), 70)\n OmGW_PLS_LISA = np.array(df['Omega'])\n OmGW_PLS_LISA = np.interp(ff, f, OmGW_PLS_LISA)\n plt.plot(ff, OmGW_PLS_LISA, '.', color='green', alpha=.4)\n\n plot_sets.axes_lines()\n plt.ylim(1e-14, 1e-2)\n plt.yticks(np.logspace(-14, -2, 8))\n plt.xlim(1e-5, 1e0)\n plt.xlabel('$f$ [Hz]')\n plt.ylabel(r'$h_0^2\\,\\Omega_{\\rm s} (f)$')\n plt.xscale('log')\n plt.yscale('log')\n ax = plt.gca()\n ax.tick_params(axis='x', pad=20)\n ax.tick_params(axis='y', pad=10)\n plt.yticks(np.logspace(-14, -2, 7))\n plt.xticks(np.logspace(-5, 0, 6))\n\n if save: plt.savefig('plots/Omega_LISA_Taiji.pdf',\n bbox_inches='tight')\n\ndef plot_Xi_sensitivity(XiPLSa, XiPLSb, XiPLSa_Tai, XiPLSb_Tai, XiPLS_comb,\n SNR=10, T=4, save=True):\n\n \"\"\"\n Function that generates the plot of LISA and Taiji GW energy density\n polarization sensitivities and PLS.\n\n It corresponds to right panel of figure 16 of A. Roper Pol, S. Mandal,\n A. Brandenburg, and T. Kahniashvili, \"Polarization of gravitational waves\n from helical MHD turbulent sources,\" submitted to JCAP,\n https://arxiv.org/abs/2107.05356.\n\n Arguments:\n XiPLSa -- polarization PLS of the dipole response function of LISA\n with beta_max = 2 for T = 1yr and SNR = 1\n XiPLSb -- polarization PLS of the dipole response function of LISA\n with beta_max = 3 for T = 1yr and SNR = 1\n XiPLSa_Tai -- polarization PLS of the dipole response function of Taiji\n with beta_max = 2 for T = 1yr and SNR = 1\n XiPLSb_Tai -- polarization PLS of the dipole response function of Taiji\n with beta_max = 3 for T = 1yr and SNR = 1\n XiPLS_comb -- polarization PLS of the LISA-Taiji network\n for T = 1yr and SNR = 1\n SNR -- signal-to-noise ratio (SNR) for the plotted PLS (default 10)\n T -- duration of the observations for the plotted PLS in\n years (default 4)\n save -- option to save the figure in \"plots/Xi_LISA_Taiji.pdf\"\n (default True)\n \"\"\"\n\n fact = SNR/np.sqrt(T)\n fig, ax0 = plt.subplots(figsize=(12,10))\n #plt.rc('font', size=18)\n plt.plot(fs, XiSAE, color='blue')\n plt.plot(fs, XiSCD, color='blue', ls='-.')\n\n gg = np.where(XiS_comb < 1e5)\n plt.plot(fs[gg], XiS_comb[gg], color='blue', lw=.6)\n\n plt.plot(fs, XiPLSa*fact, color='green')\n plt.plot(fs, XiPLSb*fact, color='green')\n plt.plot(fs, XiPLSa_Tai*fact, color='green', ls='-.')\n plt.plot(fs, XiPLSb_Tai*fact, color='green', ls='-.')\n\n plt.plot(fs, XiPLS_comb*fact, color='green', lw=.6)\n\n line_XiPLS, = ax0.plot([], [], color='green',\n label=r'$\\Xi_{\\rm PLS}^{\\rm AE}$')\n line_XiPLS_Tai, = ax0.plot([], [], color='green', ls='-.',\n label=r'$\\Xi_{\\rm PLS}^{\\rm CD}$')\n line_XiPLS_comb, = ax0.plot([], [], color='green', lw=.8,\n label=r'$\\Xi_{\\rm PLS}^{\\rm comb}$')\n\n line_XiSA, = ax0.plot([], [], color='blue',\n label=r'$\\Xi_{\\rm s}^{\\rm AE}$')\n line_XiSC, = ax0.plot([], [], color='blue', ls='-.',\n label=r'$\\Omega_{\\rm s}^{\\rm CD}$')\n line_XiS_comb, = ax0.plot([], [], color='blue', lw=.8,\n label=r'$\\Xi_{\\rm s}^{\\rm comb}$')\n\n handles = [line_XiSA, line_XiSC, line_XiS_comb]\n lgd1 = ax0.legend(handles=handles, loc='lower right',\n fontsize=28, frameon=False)\n handles2 = [line_XiPLS, line_XiPLS_Tai, line_XiPLS_comb]\n lgd2 = ax0.legend(handles=handles2, loc='lower left',\n fontsize=28, frameon=False)\n ax0.add_artist(lgd1)\n\n #plt.legend(fontsize=30, loc='lower right', frameon=False)\n plt.xlabel(r'$f$ [Hz]')\n plt.ylabel(r'$h_0^2\\, \\Xi_{\\rm s} (f)$')\n plt.xscale('log')\n plt.yscale('log')\n plt.ylim(1e-14, 1e-2)\n plt.xlim(1e-5, 1e0)\n plot_sets.axes_lines()\n\n plt.text(1e-1, 8e-9, r'$\\beta_{\\rm max}=2$', color='green', fontsize=30)\n plt.text(9e-2, 6e-4, r'$\\beta_{\\rm max}=3$', color='green', fontsize=30)\n\n ax = plt.gca()\n ax.tick_params(axis='x', pad=20)\n ax.tick_params(axis='y', pad=10)\n plt.yticks(np.logspace(-14, -2, 7))\n plt.xticks(np.logspace(-5, 0, 6))\n\n if save: plt.savefig('plots/Xi_LISA_Taiji.pdf',\n bbox_inches='tight')\n\ndef plot_Xi_sensitivity_dipole(XiPLSa, XiPLSb, XiPLSc, XiPLSd,\n XiPLSe, XiPLSf, XiPLSg, XiPLS0, XiPLS_comb,\n interf='LISA', SNR=10, T=4, save=True):\n\n \"\"\"\n Function that generates the plot of the GW energy density\n polarization PLS for different values of beta_max.\n\n It corresponds to figure 17 of A. Roper Pol, S. Mandal,\n A. Brandenburg, and T. Kahniashvili, \"Polarization of gravitational waves\n from helical MHD turbulent sources,\" submitted to JCAP,\n https://arxiv.org/abs/2107.05356.\n\n Arguments:\n XiPLSa -- polarization PLS of the dipole response function of LISA\n with beta_max = 2 for T = 1yr and SNR = 1\n XiPLSb -- polarization PLS of the dipole response function of LISA\n with beta_max = 3 for T = 1yr and SNR = 1\n XiPLSc -- polarization PLS of the dipole response function of LISA\n with beta_max = 3.7 for T = 1yr and SNR = 1\n XiPLSd -- polarization PLS of the dipole response function of LISA\n with beta_max = 3.95 for T = 1yr and SNR = 1\n XiPLSe -- polarization PLS of the dipole response function of LISA\n with beta_max = 3.999 for T = 1yr and SNR = 1\n XiPLSf -- polarization PLS of the dipole response function of LISA\n with beta_max = 3.999999 for T = 1yr and SNR = 1\n XiPLSg -- polarization PLS of the dipole response function of LISA\n with beta values in (-20, 0)U(5, 20) for T = 1yr and SNR = 1\n XiPLS0 -- polarization PLS of the dipole response function of LISA\n omitting 1/(1 - beta/4) term for T = 1yr and SNR = 1\n XiPLS_comb -- polarization PLS of the LISA-Taiji network\n for T = 1yr and SNR = 1\n interf -- selects interferometer (default 'LISA',\n also available 'Taiji')\n SNR -- signal-to-noise ratio (SNR) for the plotted PLS (default 10)\n T -- duration of the observations for the plotted PLS in\n years (default 4)\n save -- option to save the figure in \"plots/Xi_PLS_interf.pdf\"\n (default True)\n \"\"\"\n\n import pandas as pd\n fact = SNR/np.sqrt(T)\n plt.figure(figsize=(12,10))\n if interf=='LISA':\n AE = 'AE'\n ybeta_a = 1.3e-8\n ybeta_b = 1.5e-7\n ybeta_c = 3e-8\n ybeta_d = 1e-7\n ybeta_e = 1e-8\n ybeta_f = 3e-8\n if interf=='Taiji':\n AE = 'CD'\n ybeta_a = 3e-9\n ybeta_b = 3.5e-8\n ybeta_c = 8e-9\n ybeta_d = 3e-8\n ybeta_e = 2.5e-9\n ybeta_f = 6e-9\n # plot PLS using dipole for different beta_max\n plt.plot(fs, XiPLSa*fact, color='blue', lw=1,\n label=r'$\\Xi_{\\rm PLS}^{\\rm %s}$'%AE)\n plt.plot(fs, XiPLSb*fact, color='blue', lw=.8, ls='-.')\n plt.plot(fs, XiPLSc*fact, color='blue', lw=.8, ls='-.')\n plt.plot(fs, XiPLSd*fact, color='blue', lw=.8, ls='-.')\n plt.plot(fs, XiPLSe*fact, color='blue', lw=.8, ls='-.')\n plt.plot(fs, XiPLSf*fact, color='blue', lw=.8, ls='-.')\n # plot PLS using dipole ignoring 1/abs(1 - beta/4) term\n plt.plot(fs, XiPLS0*fact, color='red', lw=.8,\n label=r'$\\Xi_{\\rm PLS}^{0, {\\rm %s}}$'%AE)\n # plot PLS using LISA-Taiji combined network\n plt.plot(fs, XiPLS_comb*fact, color='green', lw=.8,\n label=r'$\\Xi_{\\rm PLS}^{\\rm comb}$')\n\n # text with values of beta_max\n plt.text(2.5e-2, ybeta_a/4, r'$\\beta_{\\rm max}=2$', color='blue',\n fontsize=22,\n bbox=dict(facecolor='white', edgecolor='none',\n boxstyle='round,pad=.2'))\n plt.text(3.2e-2, ybeta_b/4, r'$\\beta_{\\rm max}=3$', color='blue',\n fontsize=22,\n bbox=dict(facecolor='white', edgecolor='none',\n boxstyle='round,pad=.2'))\n plt.text(5.3e-3, ybeta_c, r'$\\beta_{\\rm max}=3.7$', color='blue',\n fontsize=22,\n bbox=dict(facecolor='white', edgecolor='none',\n boxstyle='round,pad=.2'))\n plt.text(5.5e-3, ybeta_d*3, r'$\\beta_{\\rm max}=3.95$', color='blue',\n fontsize=22,\n bbox=dict(facecolor='white', edgecolor='none',\n boxstyle='round,pad=.2'))\n plt.text(8e-4, ybeta_e, r'$\\beta_{\\rm max}=3.999$', color='blue',\n fontsize=22)\n plt.text(2e-4, ybeta_f*5, r'$\\beta_{\\rm max}=3.999999$',\n fontsize=22, color='blue')\n\n plt.hlines(Xiflat*fact, 1e-3, 7e-2, color='blue', lw=.7)\n plt.hlines(Xiflat_Tai*fact, 1e-3, 7e-2, color='blue',\n ls='-.', lw=.7)\n plt.hlines(Xiflat_comb*fact, 1.e-3, 7e-2, color='green', lw=.8)\n plt.text(3e-2, 1.5e-10, r'$\\Xi_{\\rm flat}^{\\rm AE}$',\n fontsize=28, color='blue')\n plt.text(3e-2, 1.7e-11, r'$\\Xi_{\\rm flat}^{\\rm CD}$',\n fontsize=28, color='blue')\n plt.text(3e-2, 8e-13, r'$\\Xi_{\\rm flat}^{\\rm comb}$',\n fontsize=28, color='green')\n\n # read reference Xi PLS from Ellis et al 2019\n if interf=='Taiji':\n dir = '../detector_sensitivity/'\n df = pd.read_csv(dir + 'XiPLS_Ellisetal19.csv')\n f = np.array(df['f'])\n ff = np.logspace(np.log10(f[0]), np.log10(f[-1]), 50)\n XiGW_PLS_LISA = np.array(df['Xi'])\n XiGW_PLS_LISA = np.interp(ff, f, XiGW_PLS_LISA)\n plt.plot(ff, XiGW_PLS_LISA, '.', color='blue', alpha=.4)\n plt.text(1.15e-2, 1.5e-10, r'$\\sim\\!f^5$',\n fontsize=22, color='blue')\n gg = np.where(XiPLSg > Xiflat_Tai*1.01)\n hh = np.where(fs.value[gg] > 4e-3)\n plt.plot(fs[gg][hh], XiPLSg[gg][hh]*fact, color='blue', lw=.5)\n\n plt.legend(fontsize=28, loc='lower left', frameon=False)\n plt.xlabel(r'$f$ [Hz]')\n plt.ylabel(r'$h_0^2\\, \\Xi_{\\rm PLS} (f)$')\n plt.xscale('log')\n plt.yscale('log')\n plt.ylim(1e-13, 1e-6)\n plt.xlim(1e-4, 1e-1)\n plot_sets.axes_lines()\n\n ax = plt.gca()\n ax.tick_params(axis='x', pad=20)\n ax.tick_params(axis='y', pad=10)\n plt.yticks(np.logspace(-13, -6, 8))\n\n if save: plt.savefig('plots/Xi_PLS_' + interf + '.pdf',\n bbox_inches='tight')\n\ndef plot_MAC(save=True, log=False):\n\n \"\"\"\n Function that generates the plot of the helical (V Stokes parameter)\n monopole responses of the cross-correlated channels of the LISA-Taiji\n network.\n\n It corresponds to figure 18 of A. Roper Pol, S. Mandal,\n A. Brandenburg, and T. Kahniashvili, \"Polarization of gravitational waves\n from helical MHD turbulent sources,\" submitted to JCAP,\n https://arxiv.org/abs/2107.05356.\n\n Arguments:\n save -- option to save the figure in\n \"plots/Mcross_LISA_Taiji.pdf\" (default True)\n log -- option to plot loglog with absolute values of the response\n functions (default False)\n \"\"\"\n\n plt.figure(figsize=(12,8))\n #plt.rc('font', size=20)\n lg = ''\n if log:\n MAC = abs(M_AC)\n MAD = abs(M_AD)\n MEC = abs(M_ED)\n MED = abs(M_ED)\n MED_I = abs(M_ED_I)\n plt.xscale('log')\n plt.yscale('log')\n lg = '_log'\n else:\n MAC = M_AC\n MAD = M_AD\n MEC = M_EC\n MED = M_ED\n MED_I = M_ED_I\n plt.plot(fs, MAC, color='black',\n label=r'${\\cal M}^V_{\\rm AC}$')\n plt.plot(fs, MAD, color='blue', ls='dotted',\n label=r'${\\cal M}^V_{\\rm AD}$')\n plt.plot(fs, MEC, color='red', ls='-.',\n label=r'${\\cal M}^V_{\\rm EC}$')\n plt.plot(fs, MED, color='green', ls='--',\n label=r'${\\cal M}^V_{\\rm ED}$')\n gg = np.where(abs(MED_I) > 1e-48)\n plt.plot(fs[gg], MED_I[gg], color='purple', alpha=.8,\n label=r'${\\cal M}^I_{\\rm ED}$')\n plt.legend(fontsize=18, frameon=False)\n plt.xlabel('$f$ [Hz]')\n plt.ylabel(r'${\\cal M} (f)$')\n plt.xscale('log')\n if log:\n plt.xlim(1e-4, 4e-2)\n plt.ylim(1e-4, 2e-1)\n else:\n plt.xlim(3e-5, 4e-2)\n plt.ylim(-0.08, 0.08)\n plt.yticks(np.linspace(-.075, .075, 7))\n plot_sets.axes_lines()\n\n if save: plt.savefig('plots/Mcross_LISA_Taiji' + lg + '.pdf',\n bbox_inches='tight')\n\ndef plot_Xi_sensitivity_comb(save=True):\n\n \"\"\"\n Function that generates the plot of the GW energy density\n polarization sensitivity obtained by combining the cross-correlated\n channels of the LISA-Taiji network.\n\n Arguments:\n save -- option to save the figure in \"plots/Xi_LISA_Taiji_comb.pdf\"\n (default True)\n \"\"\"\n\n plt.figure(figsize=(12,8))\n #plt.rc('font', size=18)\n plt.plot(fs, XiSAC, color='black', lw=.8,\n label = r'$h_0^2\\, \\Xi_{\\rm s}^{AC} (f)$')\n plt.plot(fs, XiSAD, color='blue', ls='dotted',\n label = r'$h_0^2\\, \\Xi_{\\rm s}^{AD} (f)$')\n plt.plot(fs, XiSEC, color='red', ls='-.',\n label = r'$h_0^2\\, \\Xi_{\\rm s}^{EC} (f)$')\n plt.plot(fs, XiSED, color='green', ls='--', lw=.6,\n label = r'$h_0^2\\, \\Xi_{\\rm s}^{ED} (f)$')\n plt.plot(fs, XiS_comb, color='blue',\n label = r'$h_0^2\\, \\Xi_{\\rm s}^{\\rm comb} (f)$')\n\n plt.legend(fontsize=20, loc='lower right', frameon=False)\n plt.xlabel(r'$f$ [Hz]')\n plt.ylabel(r'$h_0^2\\, \\Xi_{\\rm s} (f)$')\n plt.xscale('log')\n plt.yscale('log')\n plt.ylim(1e-12, 1e-4)\n plt.xlim(1e-4, 1e-1)\n plot_sets.axes_lines()\n\n if save: plt.savefig('plots/Xi_LISA_Taiji_comb.pdf',\n bbox_inches='tight')\n\ndef plot_noise_PSD(interf='LISA', save=True):\n\n \"\"\"\n Function that generates the plot of LISA (Taiji) noise PSD of the channel\n A (C) and compares with the optical metrology system P_oms and\n mass acceleration P_acc PSD noises.\n\n Arguments:\n interf -- selects interferometer (default 'LISA',\n also available 'Taiji')\n save -- option to save the figure in \"plots/noise_PSD_interf.pdf\"\n (default True)\n \"\"\"\n\n plt.figure(figsize=(12,8))\n if interf=='LISA':\n #plt.plot(fs, PnX, color='blue')\n plt.plot(fs, PnA, color='red')\n plt.plot(fs, Pacc, color='blue', ls='-.', lw=.8)\n plt.plot(fs, Poms, color='blue', ls='-.', lw=.8)\n yPn = 1e-40\n yPoms = 1e-40\n yPacc = 6e-43\n A = 'A'\n\n if interf=='Taiji':\n #plt.plot(fs, PnX_Tai, color='blue')\n plt.plot(fs, PnC, color='red')\n plt.plot(fs, Pacc_Tai, color='blue', ls='-.', lw=.8)\n plt.plot(fs, Poms_Tai, color='blue', ls='-.', lw=.8)\n yPn = 2e-41\n yPoms = 2e-41\n yPacc = 4e-43\n A = 'C'\n\n plt.xlabel('$f$ [Hz]')\n plt.ylabel('noise PSD $(f)$')\n plt.xscale('log')\n plt.yscale('log')\n plt.ylim(1e-43, 1e-30)\n plt.xlim(1e-5, 1e0)\n plt.text(1e-1, yPoms, r'$P_{\\rm oms} (f)$', color='blue')\n plt.text(1e-1, yPacc, r'$P_{\\rm acc} (f)$', color='blue')\n plt.text(1e-2, yPn, r'$P_n^{\\rm %s} (f)$'%A, color='red')\n plt.text(1e-1, 1e-32, interf, fontsize=24,\n bbox=dict(facecolor='none', edgecolor='black',\n boxstyle='round,pad=.5'))\n plot_sets.axes_lines()\n\n if save: plt.savefig('plots/noise_PSD_' + interf + '.pdf',\n bbox_inches='tight')\n"
]
| [
[
"matplotlib.pyplot.text",
"matplotlib.pyplot.xlim",
"numpy.sign",
"numpy.where",
"pandas.read_csv",
"numpy.logspace",
"matplotlib.pyplot.savefig",
"numpy.interp",
"matplotlib.pyplot.subplots",
"numpy.trapz",
"numpy.sqrt",
"matplotlib.pyplot.gca",
"numpy.log10",
"matplotlib.pyplot.yscale",
"matplotlib.pyplot.hlines",
"matplotlib.pyplot.rcParams.update",
"numpy.array",
"matplotlib.pyplot.xscale",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.ylabel",
"numpy.linspace"
]
]
|
valeoai/QuEST | [
"02a23d2d8e0d059b4a30433f92eec5db146467f4"
]
| [
"distillation/architectures/feature_extractors/wide_resnet.py"
]
| [
"import math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport distillation.architectures.tools as tools\n\n\"\"\"\nOriginal Author: Wei Yang\n\"\"\"\n\n__all__ = ['wrn']\n\n\nclass BasicBlock(nn.Module):\n def __init__(self, in_planes, out_planes, stride, dropRate=0.0):\n super(BasicBlock, self).__init__()\n self.bn1 = nn.BatchNorm2d(in_planes)\n self.relu1 = nn.ReLU(inplace=True)\n self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(out_planes)\n self.relu2 = nn.ReLU(inplace=True)\n self.conv2 = nn.Conv2d(out_planes, out_planes, kernel_size=3, stride=1,\n padding=1, bias=False)\n self.droprate = dropRate\n self.equalInOut = (in_planes == out_planes)\n self.convShortcut = (not self.equalInOut) and nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride,\n padding=0, bias=False) or None\n\n def forward(self, x):\n if not self.equalInOut:\n x = self.relu1(self.bn1(x))\n else:\n out = self.relu1(self.bn1(x))\n out = self.relu2(self.bn2(self.conv1(out if self.equalInOut else x)))\n if self.droprate > 0:\n out = F.dropout(out, p=self.droprate, training=self.training)\n out = self.conv2(out)\n return torch.add(x if self.equalInOut else self.convShortcut(x), out)\n\n\nclass NetworkBlock(nn.Module):\n def __init__(self, nb_layers, in_planes, out_planes, block, stride, dropRate=0.0):\n super(NetworkBlock, self).__init__()\n self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, dropRate)\n\n def _make_layer(self, block, in_planes, out_planes, nb_layers, stride, dropRate):\n layers = []\n for i in range(nb_layers):\n layers.append(block(i == 0 and in_planes or out_planes, out_planes, i == 0 and stride or 1, dropRate))\n return nn.Sequential(*layers)\n\n def forward(self, x):\n return self.layer(x)\n\n\nclass WideResnet(nn.Module):\n def __init__(self, depth, num_classes, widen_factor=1, dropRate=0.0, pool='avg', downscale=False):\n super(WideResnet, self).__init__()\n self.downscale = downscale\n self.pool = pool\n nChannels = [16, 16*widen_factor, 32*widen_factor, 64*widen_factor]\n assert (depth - 4) % 6 == 0, 'depth should be 6n+4'\n n = (depth - 4) // 6\n block = BasicBlock\n # 1st conv before any network block\n self.conv1 = nn.Conv2d(3, nChannels[0], kernel_size=3, stride=1,\n padding=1, bias=False)\n # 1st block\n self.block1 = NetworkBlock(n, nChannels[0], nChannels[1], block, 1, dropRate)\n # 2nd block\n self.block2 = NetworkBlock(n, nChannels[1], nChannels[2], block, 2, dropRate)\n # 3rd block\n self.block3 = NetworkBlock(n, nChannels[2], nChannels[3], block, 2, dropRate)\n # global average pooling and classifier\n self.bn1 = nn.BatchNorm2d(nChannels[3])\n self.relu = nn.ReLU(inplace=True)\n if self.downscale:\n self.avgpool_2x2 = nn.AvgPool2d((2,2), stride=(2,2))\n if self.pool == 'max' or self.pool == 'avg':\n self.gpool = tools.GlobalPooling(pool_type=pool)\n self.reshape = tools.Reshape(-1, nChannels[3])\n self.fc = nn.Linear(nChannels[3], num_classes)\n self.nChannels = nChannels[3]\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.bias.data.zero_()\n\n def get_feat_modules(self):\n feat_m = nn.ModuleList([])\n feat_m.append(self.conv1)\n feat_m.append(self.block1)\n feat_m.append(self.block2)\n feat_m.append(self.block3)\n return feat_m\n\n def get_bn_before_relu(self):\n bn1 = self.block2.layer[0].bn1\n bn2 = self.block3.layer[0].bn1\n bn3 = self.bn1\n\n return [bn1, bn2, bn3]\n\n def forward(self, x, is_feat=False, preact=False):\n out = self.conv1(x)\n f0 = out\n out = self.block1(out)\n f1 = out\n out = self.block2(out)\n f2 = out\n out = self.block3(out)\n f3 = out\n out = self.relu(self.bn1(out))\n if self.downscale:\n out = self.avgpool_2x2(out)\n if self.pool == 'max' or self.pool == 'avg':\n out = self.gpool(out)\n out = self.reshape(out)\n f4 = out\n out = self.fc(out)\n if is_feat:\n if preact:\n f1 = self.block2.layer[0].bn1(f1)\n f2 = self.block3.layer[0].bn1(f2)\n f3 = self.bn1(f3)\n return [f0, f1, f2, f3, f4], out\n else:\n return out\n\ndef create_model(opt):\n depth = opt['depth']\n num_classes = opt['num_classes']\n widen_factor = opt['widen_Factor']\n dropRate = opt.get('dropRate', 0.0)\n pool = opt.get('pool', 'avg')\n downscale = False\n if 'downscale' in list(opt.keys()):\n downscale = opt['downscale']\n return WideResnet(\n depth=depth,\n num_classes = num_classes,\n widen_factor=widen_factor,\n dropRate=dropRate, pool=pool, downscale=downscale)\n\n\n\ndef wrn(**kwargs):\n \"\"\"\n Constructs a Wide Residual Networks.\n \"\"\"\n model = WideResnet(**kwargs)\n return model\n\n\ndef wrn_40_2(**kwargs):\n model = WideResnet(depth=40, widen_factor=2, **kwargs)\n return model\n\n\ndef wrn_40_1(**kwargs):\n model = WideResnet(depth=40, widen_factor=1, **kwargs)\n return model\n\n\ndef wrn_16_2(**kwargs):\n model = WideResnet(depth=16, widen_factor=2, **kwargs)\n return model\n\n\ndef wrn_16_1(**kwargs):\n model = WideResnet(depth=16, widen_factor=1, **kwargs)\n return model\n\nif __name__ == '__main__':\n import torch\n\n x = torch.randn(2, 3, 32, 32)\n net = wrn_40_2(num_classes=100)\n feats, logit = net(x, is_feat=True, preact=True)\n\n for f in feats:\n print(f.shape, f.min().item())\n print(logit.shape)\n\n for m in net.get_bn_before_relu():\n if isinstance(m, nn.BatchNorm2d):\n print('pass')\n else:\n print('warning')\n"
]
| [
[
"torch.nn.Linear",
"torch.nn.ModuleList",
"torch.nn.Sequential",
"torch.nn.AvgPool2d",
"torch.nn.BatchNorm2d",
"torch.nn.functional.dropout",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.randn"
]
]
|
danicaxiao/LSTMVis | [
"80c8271fe2a6ac898dcf9a75f0d52a31fef47568"
]
| [
"tools/txt_to_hdf5_dict.py"
]
| [
"#!/usr/bin/env python\n\n\"\"\"\nTakes a .txt file with the source data for the trained model and\ncreates the sparse word indices as well as a dictionary that maps\nthe word indices to the actual words. \nTo transform into validation and test with the same dictionary, \nuse model/preprocess.py\n\nUsage: python txt_to_hdf5_dict.py INPUT.txt OUTPUTNAME\n\n\"\"\"\n\nimport os\nimport sys\nimport argparse\nimport numpy\nimport h5py\nimport itertools\n\n__author__ = 'Sebastian Gehrmann'\n\n\nclass Indexer:\n def __init__(self):\n self.counter = 1\n self.d = {}\n self.rev = {}\n self._lock = False\n \n def convert(self, w):\n if w not in self.d:\n if self._lock:\n return self.d[\"<unk>\"]\n self.d[w] = self.counter\n self.rev[self.counter] = w\n self.counter += 1\n return self.d[w]\n\n def write(self, outfile):\n out = open(outfile, \"w\")\n items = [(v, k) for k, v in self.d.iteritems()]\n items.sort()\n for v, k in items:\n print >>out, k, v\n out.close()\n \ndef get_data(args):\n target_indexer = Indexer()\n #add special words to indices in the target_indexer\n target_indexer.convert(\"<s>\")\n target_indexer.convert(\"<unk>\")\n target_indexer.convert(\"</s>\")\n \n words = []\n wordschar = []\n targets = []\n for i, targ_orig in enumerate(args.targetfile):\n targ_orig = targ_orig.replace(\"<eos>\", \"\")\n targ = targ_orig.strip().split() + [\"</s>\"]\n #here put something for shifting window\n target_sent = [target_indexer.convert(w) for w in targ]\n words += target_sent\n \n words = numpy.array(words, dtype=int)\n\n # plus 1 for the next word\n targ_output = numpy.array(words[1:] + [target_indexer.convert(\"</s>\")])\n original_index = numpy.array([i+1 for i, v in enumerate(words)], dtype=int)\n\n print (words.shape, \"shape of the word array before preprocessing\")\n \n # Write output.\n f = h5py.File(args.outputfile + \".hdf5\", \"w\")\n f[\"target\"] = words\n f[\"indices\"] = original_index\n f[\"target_output\"] = targ_output\n f[\"target_size\"] = numpy.array([target_indexer.counter])\n f[\"set_size\"] = words.shape[0]\n\n target_indexer.write(args.outputfile + \".targ.dict\")\n \ndef main(arguments):\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('targetfile', help=\"Target Input file\", \n type=argparse.FileType('r'))\n parser.add_argument('outputfile', help=\"Output file name\", \n type=str)\n args = parser.parse_args(arguments)\n get_data(args)\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv[1:]))\n"
]
| [
[
"numpy.array"
]
]
|
peter0749/PointNetGPD | [
"5e2be543057657f1faaef87e80074d392823e5df"
]
| [
"meshpy/tools/convert_image_to_obj.py"
]
| [
"\"\"\"\nScript to convert a directory of 3D models to .OBJ wavefront format for use in meshpy using meshlabserver.\nAuthor: Jeff Mahler\n\"\"\"\nimport argparse\nimport logging\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport sys\n\nimport autolab_core.utils as utils\nfrom perception import BinaryImage\nfrom meshpy import ImageToMeshConverter, ObjFile\nfrom visualization import Visualizer2D as vis2d\nfrom visualization import Visualizer3D as vis\n\nif __name__ == '__main__':\n # set up logger\n logging.getLogger().setLevel(logging.INFO)\n\n # parse args\n parser = argparse.ArgumentParser(description='Convert an image into an extruded 3D mesh model')\n parser.add_argument('input_image', type=str, help='path to image to convert')\n parser.add_argument('--extrusion', type=float, default=1000, help='amount to extrude')\n parser.add_argument('--scale_factor', type=float, default=1.0, help='scale factor to apply to the mesh')\n parser.add_argument('--output_filename', type=str, default=None, help='output obj filename')\n\n args = parser.parse_args()\n image_filename = args.input_image\n extrusion = args.extrusion\n scale_factor = args.scale_factor\n output_filename = args.output_filename\n\n # read the image\n binary_im = BinaryImage.open(image_filename)\n sdf = binary_im.to_sdf()\n #plt.figure()\n #plt.imshow(sdf)\n #plt.show()\n\n # convert to a mesh\n mesh = ImageToMeshConverter.binary_image_to_mesh(binary_im, extrusion=extrusion, scale_factor=scale_factor)\n vis.figure()\n vis.mesh(mesh)\n vis.show()\n\n # optionally save\n if output_filename is not None:\n file_root, file_ext = os.path.splitext(output_filename)\n binary_im.save(file_root+'.jpg')\n ObjFile(file_root+'.obj').write(mesh)\n np.savetxt(file_root+'.csv', sdf, delimiter=',',\n header='%d %d'%(sdf.shape[0], sdf.shape[1]))\n"
]
| [
[
"numpy.savetxt"
]
]
|
zl3311/COVID_prediction_US | [
"c41a40a259383305a5a04f019769252163fc09cf"
]
| [
"covid_api/web/app.py"
]
| [
"from flask import Flask, jsonify, request\nfrom flask_restful import Api, Resource\nimport pandas as pd\nimport numpy as np\nimport pickle\nimport datetime\nfrom statsmodels.tsa.api import STLForecast\nfrom statsmodels.tsa.ar_model import AutoReg\nimport tensorflow.compat.v1 as tf\ngraph = tf.get_default_graph()\nfrom keras.models import load_model\n\napp = Flask(__name__)\napi = Api(app)\n\n# Load preprocessed objects\nscaler = pickle.load(open(\"data/scaler.pkl\",\"rb\")) # the scaler to transform the original X variables before feeding to model\ndata_pred = pickle.load(open(\"data/data_pred.pkl\",\"rb\")) # the dataframe of variables of all states and time\ndict_state_params = pickle.load(open(\"data/dict_state_params.pkl\",\"rb\")) # the dictionary of quadratic coefficients of the test case time series\nmodel = load_model(\"data/model_new.h5\") # neural network model of confirmed probability\n\ndef predict(state, duration):\n \"\"\"Predicting future COVID confirmed numbers of a state\n Args:\n state(str): state full name to be predicted.\n duration(str): prediction duration as a string of an integer.\n Returns:\n result(List(float)): predicted future time series of the given state.\n Status Code: returned API status indicator (success or not).\n \"\"\"\n\n df_temp = data_pred.loc[data_pred[\"Province_State\"]==state, :].reset_index(drop=True) # Filter the data for the specific state\n total_pop = df_temp.loc[0, \"Total_pop\"] # Access state total population\n df_future = {\n \"Date\": pd.date_range(df_temp[\"Date\"].tail(1).values[0], periods=duration+1, freq=\"D\")[1:],\n } # Create a dictionary of the predicted features which is further transformed into a dataframe\n cols = df_temp.columns[4:29] # Filter the feature columns\n \n for col in cols: \n # For each column:\n # Predict the future time series of each feature independently.\n # 1. First, decompose the entire series into seasonal and trend patterns using seasonal trend decomposition\n # 2. Then, fit and forecast the overall trend time series using auto-regression model\n # 3. Lastly, add back the seasonal pattern to the forecasted trend time series\n s = df_temp.loc[:, col]\n s.index = df_temp[\"Date\"]\n df_future[col] = STLForecast(s, AutoReg, model_kwargs={\"lags\": 30}).fit().forecast(duration).values \n\n df_future = pd.DataFrame.from_dict(df_future) # transform dictionary into dataframe\n df_future[\"Tested_Daily_pred\"] = df_future.apply(lambda row: int(dict_state_params[state][\"People_Tested_PolyCoef\"]*(1+2*(row[\"Date\"]-datetime.datetime(2020, 4, 12)).days)), axis=1) # predict the number of tested cases using the quadratic function\n confirmed = df_temp[\"Active_pred\"][-7:].values.tolist() # compute the 7-day rolling average of confirmed cases\n\n for i, row in df_future.iterrows():\n # For each future day:\n # 1. construct the average confirmed rate\n # 2. rescale the original features using the imported scalers\n # 3. predict the confirmed probability using the imported neural network model\n # 4. compute the death and recover cases of the state and minus them from the confirmed numbers\n It_r7 = np.mean(confirmed[-7:]) / total_pop\n x_ = scaler.transform(np.array([[It_r7] + row[cols].values.tolist()]))\n with graph.as_default():\n dI = int(row[\"Tested_Daily_pred\"] * model.predict(x_)[0])\n dD = int(dI * dict_state_params[state][\"death_rate\"])\n dR = int(dI * dict_state_params[state][\"recover_rate\"])\n dI_ = dI - dD - dR\n confirmed.append(dI_ + confirmed[-1])\n\n\n return confirmed[7:]\n\n\nclass Pred(Resource):\n \"\"\"Add prediction functionality\n \"\"\"\n def post(self):\n info = request.get_json()\n state = info[\"state\"] # extract state information from the request JSON\n duration = int(info[\"duration\"]) # extract duration information from the request JSON\n\n pred = predict(state, duration) # call the prediction function and save prediction result\n result = {\n \"result\": pred,\n \"Status Code\": 202,\n } # prepare the API return result\n\n return jsonify(result) # jsonify the API result\n\napi.add_resource(Pred, '/pred')\[email protected](\"/\")\ndef hello():\n return \"Hi\"\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\")\n"
]
| [
[
"pandas.DataFrame.from_dict",
"tensorflow.compat.v1.get_default_graph",
"numpy.mean"
]
]
|
jvrana/pyro-graphnets | [
"a346324e77f20739e00a82f97530dda4906f59dd"
]
| [
"caldera/blocks/select.py"
]
| [
"import torch\n\n\nclass Select(torch.nn.Module):\n \"\"\"Differentiable select block.\"\"\"\n\n def __init__(self, input_size: int, output_size: int):\n super().__init__()\n self.blocks = torch.nn.Sequential(\n torch.nn.Linear(input_size, output_size), torch.nn.Sigmoid()\n )\n\n def forward(self, data: torch.Tensor, latent: torch.Tensor) -> torch.Tensor:\n out = self.blocks(latent)\n i = torch.where(torch.round(out) == 1)[0]\n return data[i]\n"
]
| [
[
"torch.nn.Linear",
"torch.round",
"torch.nn.Sigmoid"
]
]
|
text-machine-lab/dark-secrets-of-BERT | [
"c413ebea2f2f79d9cb8f0dd5f380c9993e4fae81"
]
| [
"examples/run_classifier.py"
]
| [
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.\n# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"BERT finetuning runner.\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport sys\nsys.path.insert(0, \"/home/okovaleva/projects/bert_attention/pretrained_bert/pytorch-pretrained-BERT\")\nprint(sys.path)\n\n\nimport argparse\nimport csv\nimport logging\nimport os\nimport random\nimport sys\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,\n TensorDataset)\nfrom torch.utils.data.distributed import DistributedSampler\nfrom tqdm import tqdm, trange\n\nfrom torch.nn import CrossEntropyLoss, MSELoss\nfrom scipy.stats import pearsonr, spearmanr\nfrom sklearn.metrics import matthews_corrcoef, f1_score\n\nfrom pytorch_pretrained_bert.file_utils import PYTORCH_PRETRAINED_BERT_CACHE, WEIGHTS_NAME, CONFIG_NAME\nfrom pytorch_pretrained_bert.modeling import BertForSequenceClassification, BertConfig\nfrom pytorch_pretrained_bert.tokenization import BertTokenizer\nfrom pytorch_pretrained_bert.optimization import BertAdam, warmup_linear\n\nlogger = logging.getLogger(__name__)\n\n\nclass InputExample(object):\n \"\"\"A single training/test example for simple sequence classification.\"\"\"\n\n def __init__(self, guid, text_a, text_b=None, label=None):\n \"\"\"Constructs a InputExample.\n\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\n text_b: (Optional) string. The untokenized text of the second sequence.\n Only must be specified for sequence pair tasks.\n label: (Optional) string. The label of the example. This should be\n specified for train and dev examples, but not for test examples.\n \"\"\"\n self.guid = guid\n self.text_a = text_a\n self.text_b = text_b\n self.label = label\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self, input_ids, input_mask, segment_ids, label_id):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.label_id = label_id\n\n\nclass DataProcessor(object):\n \"\"\"Base class for data converters for sequence classification data sets.\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the train set.\"\"\"\n raise NotImplementedError()\n\n def get_dev_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the dev set.\"\"\"\n raise NotImplementedError()\n\n def get_labels(self):\n \"\"\"Gets the list of labels for this data set.\"\"\"\n raise NotImplementedError()\n\n @classmethod\n def _read_tsv(cls, input_file, quotechar=None):\n \"\"\"Reads a tab separated value file.\"\"\"\n with open(input_file, \"r\", encoding=\"utf-8\") as f:\n reader = csv.reader(f, delimiter=\"\\t\", quotechar=quotechar)\n lines = []\n for line in reader:\n if sys.version_info[0] == 2:\n line = list(unicode(cell, 'utf-8') for cell in line)\n lines.append(line)\n return lines\n\n\nclass MrpcProcessor(DataProcessor):\n \"\"\"Processor for the MRPC data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n logger.info(\"LOOKING AT {}\".format(os.path.join(data_dir, \"train.tsv\")))\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = line[3]\n text_b = line[4]\n label = line[0]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass MnliProcessor(DataProcessor):\n \"\"\"Processor for the MultiNLI data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev_matched.tsv\")),\n \"dev_matched\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"contradiction\", \"entailment\", \"neutral\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[8]\n text_b = line[9]\n label = line[-1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass MnliMismatchedProcessor(MnliProcessor):\n \"\"\"Processor for the MultiNLI Mismatched data set (GLUE version).\"\"\"\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev_mismatched.tsv\")),\n \"dev_matched\")\n\n\nclass ColaProcessor(DataProcessor):\n \"\"\"Processor for the CoLA data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n guid = \"%s-%s\" % (set_type, i)\n text_a = line[3]\n label = line[1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=None, label=label))\n return examples\n\n\nclass Sst2Processor(DataProcessor):\n \"\"\"Processor for the SST-2 data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = line[0]\n label = line[1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=None, label=label))\n return examples\n\n\nclass StsbProcessor(DataProcessor):\n \"\"\"Processor for the STS-B data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [None]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[7]\n text_b = line[8]\n label = line[-1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass QqpProcessor(DataProcessor):\n \"\"\"Processor for the STS-B data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n try:\n text_a = line[3]\n text_b = line[4]\n label = line[5]\n except IndexError:\n continue\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass QnliProcessor(DataProcessor):\n \"\"\"Processor for the STS-B data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \n \"dev_matched\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"entailment\", \"not_entailment\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[1]\n text_b = line[2]\n label = line[-1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass RteProcessor(DataProcessor):\n \"\"\"Processor for the RTE data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"entailment\", \"not_entailment\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[1]\n text_b = line[2]\n label = line[-1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass WnliProcessor(DataProcessor):\n \"\"\"Processor for the WNLI data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[1]\n text_b = line[2]\n label = line[-1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\ndef convert_examples_to_features(examples, label_list, max_seq_length,\n tokenizer, output_mode):\n \"\"\"Loads a data file into a list of `InputBatch`s.\"\"\"\n\n label_map = {label : i for i, label in enumerate(label_list)}\n\n features = []\n for (ex_index, example) in enumerate(examples):\n if ex_index % 10000 == 0:\n logger.info(\"Writing example %d of %d\" % (ex_index, len(examples)))\n\n tokens_a = tokenizer.tokenize(example.text_a)\n\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\"\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n # Account for [CLS] and [SEP] with \"- 2\"\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[:(max_seq_length - 2)]\n\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambiguously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = [\"[CLS]\"] + tokens_a + [\"[SEP]\"]\n segment_ids = [0] * len(tokens)\n\n if tokens_b:\n tokens += tokens_b + [\"[SEP]\"]\n segment_ids += [1] * (len(tokens_b) + 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 padding = [0] * (max_seq_length - len(input_ids))\n input_ids += padding\n input_mask += padding\n segment_ids += padding\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 if output_mode == \"classification\":\n label_id = label_map[example.label]\n elif output_mode == \"regression\":\n label_id = float(example.label)\n else:\n raise KeyError(output_mode)\n\n if ex_index < 5:\n logger.info(\"*** Example ***\")\n logger.info(\"guid: %s\" % (example.guid))\n logger.info(\"tokens: %s\" % \" \".join(\n [str(x) for x in tokens]))\n logger.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n logger.info(\"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n logger.info(\n \"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\n logger.info(\"label: %s (id = %d)\" % (example.label, label_id))\n\n features.append(\n InputFeatures(input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id))\n return features\n\n\ndef _truncate_seq_pair(tokens_a, tokens_b, max_length):\n \"\"\"Truncates a sequence pair in place to the maximum length.\"\"\"\n\n # This is a simple heuristic which will always truncate the longer sequence\n # one token at a time. This makes more sense than truncating an equal percent\n # of tokens from each, since if one sequence is very short then each token\n # that's truncated likely contains more information than a longer sequence.\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n\n\ndef simple_accuracy(preds, labels):\n return (preds == labels).mean()\n\n\ndef acc_and_f1(preds, labels):\n acc = simple_accuracy(preds, labels)\n f1 = f1_score(y_true=labels, y_pred=preds)\n return {\n \"acc\": acc,\n \"f1\": f1,\n \"acc_and_f1\": (acc + f1) / 2,\n }\n\n\ndef pearson_and_spearman(preds, labels):\n pearson_corr = pearsonr(preds, labels)[0]\n spearman_corr = spearmanr(preds, labels)[0]\n return {\n \"pearson\": pearson_corr,\n \"spearmanr\": spearman_corr,\n \"corr\": (pearson_corr + spearman_corr) / 2,\n }\n\n\ndef compute_metrics(task_name, preds, labels):\n assert len(preds) == len(labels)\n if task_name == \"cola\":\n return {\"mcc\": matthews_corrcoef(labels, preds)}\n elif task_name == \"sst-2\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"mrpc\":\n return acc_and_f1(preds, labels)\n elif task_name == \"sts-b\":\n return pearson_and_spearman(preds, labels)\n elif task_name == \"qqp\":\n return acc_and_f1(preds, labels)\n elif task_name == \"mnli\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"mnli-mm\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"qnli\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"rte\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"wnli\":\n return {\"acc\": simple_accuracy(preds, labels)}\n else:\n raise KeyError(task_name)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n ## Required parameters\n parser.add_argument(\"--data_dir\",\n default=None,\n type=str,\n required=True,\n help=\"The input data dir. Should contain the .tsv files (or other data files) for the task.\")\n parser.add_argument(\"--bert_model\", default=None, type=str, required=True,\n help=\"Bert pre-trained model selected in the list: bert-base-uncased, \"\n \"bert-large-uncased, bert-base-cased, bert-large-cased, bert-base-multilingual-uncased, \"\n \"bert-base-multilingual-cased, bert-base-chinese.\")\n parser.add_argument(\"--task_name\",\n default=None,\n type=str,\n required=True,\n help=\"The name of the task to train.\")\n parser.add_argument(\"--output_dir\",\n default=None,\n type=str,\n required=True,\n help=\"The output directory where the model predictions and checkpoints will be written.\")\n\n ## Other parameters\n parser.add_argument(\"--cache_dir\",\n default=\"\",\n type=str,\n help=\"Where do you want to store the pre-trained models downloaded from s3\")\n parser.add_argument(\"--max_seq_length\",\n default=128,\n type=int,\n help=\"The maximum total input sequence length after WordPiece tokenization. \\n\"\n \"Sequences longer than this will be truncated, and sequences shorter \\n\"\n \"than this will be padded.\")\n parser.add_argument(\"--do_train\",\n action='store_true',\n help=\"Whether to run training.\")\n parser.add_argument(\"--do_eval\",\n action='store_true',\n help=\"Whether to run eval on the dev set.\")\n parser.add_argument(\"--do_lower_case\",\n action='store_true',\n help=\"Set this flag if you are using an uncased model.\")\n parser.add_argument(\"--train_batch_size\",\n default=32,\n type=int,\n help=\"Total batch size for training.\")\n parser.add_argument(\"--eval_batch_size\",\n default=8,\n type=int,\n help=\"Total batch size for eval.\")\n parser.add_argument(\"--learning_rate\",\n default=5e-5,\n type=float,\n help=\"The initial learning rate for Adam.\")\n parser.add_argument(\"--num_train_epochs\",\n default=3.0,\n type=float,\n help=\"Total number of training epochs to perform.\")\n parser.add_argument(\"--warmup_proportion\",\n default=0.1,\n type=float,\n help=\"Proportion of training to perform linear learning rate warmup for. \"\n \"E.g., 0.1 = 10%% of training.\")\n parser.add_argument(\"--no_cuda\",\n action='store_true',\n help=\"Whether not to use CUDA when available\")\n parser.add_argument(\"--local_rank\",\n type=int,\n default=-1,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument('--seed',\n type=int,\n default=42,\n help=\"random seed for initialization\")\n parser.add_argument('--gradient_accumulation_steps',\n type=int,\n default=1,\n help=\"Number of updates steps to accumulate before performing a backward/update pass.\")\n parser.add_argument('--fp16',\n action='store_true',\n help=\"Whether to use 16-bit float precision instead of 32-bit\")\n parser.add_argument('--loss_scale',\n type=float, default=0,\n help=\"Loss scaling to improve fp16 numeric stability. Only used when fp16 set to True.\\n\"\n \"0 (default value): dynamic loss scaling.\\n\"\n \"Positive power of 2: static loss scaling value.\\n\")\n parser.add_argument('--server_ip', type=str, default='', help=\"Can be used for distant debugging.\")\n parser.add_argument('--server_port', type=str, default='', help=\"Can be used for distant debugging.\")\n args = parser.parse_args()\n\n if args.server_ip and args.server_port:\n # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script\n import ptvsd\n print(\"Waiting for debugger attach\")\n ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)\n ptvsd.wait_for_attach()\n\n processors = {\n \"cola\": ColaProcessor,\n \"mnli\": MnliProcessor,\n \"mnli-mm\": MnliMismatchedProcessor,\n \"mrpc\": MrpcProcessor,\n \"sst-2\": Sst2Processor,\n \"sts-b\": StsbProcessor,\n \"qqp\": QqpProcessor,\n \"qnli\": QnliProcessor,\n \"rte\": RteProcessor,\n \"wnli\": WnliProcessor,\n }\n\n output_modes = {\n \"cola\": \"classification\",\n \"mnli\": \"classification\",\n \"mrpc\": \"classification\",\n \"sst-2\": \"classification\",\n \"sts-b\": \"regression\",\n \"qqp\": \"classification\",\n \"qnli\": \"classification\",\n \"rte\": \"classification\",\n \"wnli\": \"classification\",\n }\n\n if args.local_rank == -1 or args.no_cuda:\n device = torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\")\n n_gpu = torch.cuda.device_count()\n else:\n torch.cuda.set_device(args.local_rank)\n device = torch.device(\"cuda\", args.local_rank)\n n_gpu = 1\n # Initializes the distributed backend which will take care of sychronizing nodes/GPUs\n torch.distributed.init_process_group(backend='nccl')\n\n logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt = '%m/%d/%Y %H:%M:%S',\n level = logging.INFO if args.local_rank in [-1, 0] else logging.WARN)\n\n logger.info(\"device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}\".format(\n device, n_gpu, bool(args.local_rank != -1), args.fp16))\n\n if args.gradient_accumulation_steps < 1:\n raise ValueError(\"Invalid gradient_accumulation_steps parameter: {}, should be >= 1\".format(\n args.gradient_accumulation_steps))\n\n args.train_batch_size = args.train_batch_size // args.gradient_accumulation_steps\n\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n\n if not args.do_train and not args.do_eval:\n raise ValueError(\"At least one of `do_train` or `do_eval` must be True.\")\n\n if os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train:\n raise ValueError(\"Output directory ({}) already exists and is not empty.\".format(args.output_dir))\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n\n task_name = args.task_name.lower()\n\n if task_name not in processors:\n raise ValueError(\"Task not found: %s\" % (task_name))\n\n processor = processors[task_name]()\n output_mode = output_modes[task_name]\n\n label_list = processor.get_labels()\n num_labels = len(label_list)\n\n tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case)\n\n train_examples = None\n num_train_optimization_steps = None\n if args.do_train:\n train_examples = processor.get_train_examples(args.data_dir)\n num_train_optimization_steps = int(\n len(train_examples) / args.train_batch_size / args.gradient_accumulation_steps) * args.num_train_epochs\n if args.local_rank != -1:\n num_train_optimization_steps = num_train_optimization_steps // torch.distributed.get_world_size()\n\n # Prepare model\n cache_dir = args.cache_dir if args.cache_dir else os.path.join(str(PYTORCH_PRETRAINED_BERT_CACHE), 'distributed_{}'.format(args.local_rank))\n model = BertForSequenceClassification.from_pretrained(args.bert_model,\n cache_dir=cache_dir,\n num_labels=num_labels)\n\n ### RANDOM INITIALIZATION ####\n # config = BertConfig.from_dict({\n # \"attention_probs_dropout_prob\": 0.1,\n # \"hidden_act\": \"gelu\",\n # \"hidden_dropout_prob\": 0.1,\n # \"hidden_size\": 768,\n # \"initializer_range\": 0.02,\n # \"intermediate_size\": 3072,\n # \"max_position_embeddings\": 512,\n # \"num_attention_heads\": 12,\n # \"num_hidden_layers\": 12,\n # \"type_vocab_size\": 2,\n # \"vocab_size\": 30522\n # })\n # model = BertForSequenceClassification(config=config, num_labels=num_labels)\n\n\n ###############################\n\n if args.fp16:\n model.half()\n model.to(device)\n if args.local_rank != -1:\n try:\n from apex.parallel import DistributedDataParallel as DDP\n except ImportError:\n raise ImportError(\"Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.\")\n\n model = DDP(model)\n elif n_gpu > 1:\n model = torch.nn.DataParallel(model)\n\n # Prepare optimizer\n param_optimizer = list(model.named_parameters())\n no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\n optimizer_grouped_parameters = [\n {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},\n {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\n ]\n if args.fp16:\n try:\n from apex.optimizers import FP16_Optimizer\n from apex.optimizers import FusedAdam\n except ImportError:\n raise ImportError(\"Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.\")\n\n optimizer = FusedAdam(optimizer_grouped_parameters,\n lr=args.learning_rate,\n bias_correction=False,\n max_grad_norm=1.0)\n if args.loss_scale == 0:\n optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)\n else:\n optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)\n\n else:\n optimizer = BertAdam(optimizer_grouped_parameters,\n lr=args.learning_rate,\n warmup=args.warmup_proportion,\n t_total=num_train_optimization_steps)\n\n global_step = 0\n nb_tr_steps = 0\n tr_loss = 0\n if args.do_train:\n train_features = convert_examples_to_features(\n train_examples, label_list, args.max_seq_length, tokenizer, output_mode)\n logger.info(\"***** Running training *****\")\n logger.info(\" Num examples = %d\", len(train_examples))\n logger.info(\" Batch size = %d\", args.train_batch_size)\n logger.info(\" Num steps = %d\", num_train_optimization_steps)\n all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long)\n all_input_mask = torch.tensor([f.input_mask for f in train_features], dtype=torch.long)\n all_segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long)\n\n if output_mode == \"classification\":\n all_label_ids = torch.tensor([f.label_id for f in train_features], dtype=torch.long)\n elif output_mode == \"regression\":\n all_label_ids = torch.tensor([f.label_id for f in train_features], dtype=torch.float)\n\n train_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)\n if args.local_rank == -1:\n train_sampler = RandomSampler(train_data)\n else:\n train_sampler = DistributedSampler(train_data)\n train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size)\n\n model.train()\n for _ in trange(int(args.num_train_epochs), desc=\"Epoch\"):\n tr_loss = 0\n nb_tr_examples, nb_tr_steps = 0, 0\n for step, batch in enumerate(tqdm(train_dataloader, desc=\"Iteration\")):\n batch = tuple(t.to(device) for t in batch)\n input_ids, input_mask, segment_ids, label_ids = batch\n\n # define a new function to compute loss values for both output_modes\n logits, _ = model(input_ids, segment_ids, input_mask, labels=None)\n\n if output_mode == \"classification\":\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, num_labels), label_ids.view(-1))\n elif output_mode == \"regression\":\n loss_fct = MSELoss()\n loss = loss_fct(logits.view(-1), label_ids.view(-1))\n\n if n_gpu > 1:\n loss = loss.mean() # mean() to average on multi-gpu.\n if args.gradient_accumulation_steps > 1:\n loss = loss / args.gradient_accumulation_steps\n\n if args.fp16:\n optimizer.backward(loss)\n else:\n loss.backward()\n\n tr_loss += loss.item()\n print(loss.item())\n nb_tr_examples += input_ids.size(0)\n nb_tr_steps += 1\n if (step + 1) % args.gradient_accumulation_steps == 0:\n if args.fp16:\n # modify learning rate with special warm up BERT uses\n # if args.fp16 is False, BertAdam is used that handles this automatically\n lr_this_step = args.learning_rate * warmup_linear(global_step/num_train_optimization_steps, args.warmup_proportion)\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr_this_step\n optimizer.step()\n optimizer.zero_grad()\n global_step += 1\n\n if args.do_train and (args.local_rank == -1 or torch.distributed.get_rank() == 0):\n # Save a trained model, configuration and tokenizer\n model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self\n\n # If we save using the predefined names, we can load using `from_pretrained`\n output_model_file = os.path.join(args.output_dir, WEIGHTS_NAME)\n output_config_file = os.path.join(args.output_dir, CONFIG_NAME)\n\n torch.save(model_to_save.state_dict(), output_model_file)\n model_to_save.config.to_json_file(output_config_file)\n tokenizer.save_vocabulary(args.output_dir)\n\n # Load a trained model and vocabulary that you have fine-tuned\n model = BertForSequenceClassification.from_pretrained(args.output_dir, num_labels=num_labels)\n tokenizer = BertTokenizer.from_pretrained(args.output_dir, do_lower_case=args.do_lower_case)\n else:\n model = BertForSequenceClassification.from_pretrained(args.bert_model, num_labels=num_labels)\n model.to(device)\n\n if args.do_eval and (args.local_rank == -1 or torch.distributed.get_rank() == 0):\n eval_examples = processor.get_dev_examples(args.data_dir)\n eval_features = convert_examples_to_features(\n eval_examples, label_list, args.max_seq_length, tokenizer, output_mode)\n logger.info(\"***** Running evaluation *****\")\n logger.info(\" Num examples = %d\", len(eval_examples))\n logger.info(\" Batch size = %d\", args.eval_batch_size)\n all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)\n all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)\n all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)\n\n if output_mode == \"classification\":\n all_label_ids = torch.tensor([f.label_id for f in eval_features], dtype=torch.long)\n elif output_mode == \"regression\":\n all_label_ids = torch.tensor([f.label_id for f in eval_features], dtype=torch.float)\n\n eval_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)\n # Run prediction for full data\n eval_sampler = SequentialSampler(eval_data)\n eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size)\n\n model.eval()\n eval_loss = 0\n nb_eval_steps = 0\n preds = []\n\n for input_ids, input_mask, segment_ids, label_ids in tqdm(eval_dataloader, desc=\"Evaluating\"):\n input_ids = input_ids.to(device)\n input_mask = input_mask.to(device)\n segment_ids = segment_ids.to(device)\n label_ids = label_ids.to(device)\n\n with torch.no_grad():\n logits, attns = model(input_ids, segment_ids, input_mask, labels=None)\n\n # create eval loss and other metric required by the task\n if output_mode == \"classification\":\n loss_fct = CrossEntropyLoss()\n tmp_eval_loss = loss_fct(logits.view(-1, num_labels), label_ids.view(-1))\n elif output_mode == \"regression\":\n loss_fct = MSELoss()\n tmp_eval_loss = loss_fct(logits.view(-1), label_ids.view(-1))\n\n eval_loss += tmp_eval_loss.mean().item()\n nb_eval_steps += 1\n if len(preds) == 0:\n preds.append(logits.detach().cpu().numpy())\n else:\n preds[0] = np.append(preds[0], logits.detach().cpu().numpy(), axis=0)\n\n eval_loss = eval_loss / nb_eval_steps\n preds = preds[0]\n if output_mode == \"classification\":\n preds = np.argmax(preds, axis=1)\n elif output_mode == \"regression\":\n preds = np.squeeze(preds)\n result = compute_metrics(task_name, preds, all_label_ids.numpy())\n loss = tr_loss/nb_tr_steps if args.do_train else None\n\n result['eval_loss'] = eval_loss\n result['global_step'] = global_step\n result['loss'] = loss\n\n output_eval_file = os.path.join(args.output_dir, \"eval_results.txt\")\n with open(output_eval_file, \"w\") as writer:\n logger.info(\"***** Eval results *****\")\n for key in sorted(result.keys()):\n logger.info(\" %s = %s\", key, str(result[key]))\n writer.write(\"%s = %s\\n\" % (key, str(result[key])))\n\n # hack for MNLI-MM\n if task_name == \"mnli\":\n task_name = \"mnli-mm\"\n processor = processors[task_name]()\n\n if os.path.exists(args.output_dir + '-MM') and os.listdir(args.output_dir + '-MM') and args.do_train:\n raise ValueError(\"Output directory ({}) already exists and is not empty.\".format(args.output_dir))\n if not os.path.exists(args.output_dir + '-MM'):\n os.makedirs(args.output_dir + '-MM')\n\n eval_examples = processor.get_dev_examples(args.data_dir)\n eval_features = convert_examples_to_features(\n eval_examples, label_list, args.max_seq_length, tokenizer, output_mode)\n logger.info(\"***** Running evaluation *****\")\n logger.info(\" Num examples = %d\", len(eval_examples))\n logger.info(\" Batch size = %d\", args.eval_batch_size)\n all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)\n all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)\n all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)\n all_label_ids = torch.tensor([f.label_id for f in eval_features], dtype=torch.long)\n\n eval_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)\n # Run prediction for full data\n eval_sampler = SequentialSampler(eval_data)\n eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size)\n\n model.eval()\n eval_loss = 0\n nb_eval_steps = 0\n preds = []\n\n for input_ids, input_mask, segment_ids, label_ids in tqdm(eval_dataloader, desc=\"Evaluating\"):\n input_ids = input_ids.to(device)\n input_mask = input_mask.to(device)\n segment_ids = segment_ids.to(device)\n label_ids = label_ids.to(device)\n\n with torch.no_grad():\n logits = model(input_ids, segment_ids, input_mask, labels=None)\n \n loss_fct = CrossEntropyLoss()\n tmp_eval_loss = loss_fct(logits.view(-1, num_labels), label_ids.view(-1))\n \n eval_loss += tmp_eval_loss.mean().item()\n nb_eval_steps += 1\n if len(preds) == 0:\n preds.append(logits.detach().cpu().numpy())\n else:\n preds[0] = np.append(\n preds[0], logits.detach().cpu().numpy(), axis=0)\n\n eval_loss = eval_loss / nb_eval_steps\n preds = preds[0]\n preds = np.argmax(preds, axis=1)\n result = compute_metrics(task_name, preds, all_label_ids.numpy())\n loss = tr_loss/nb_tr_steps if args.do_train else None\n\n result['eval_loss'] = eval_loss\n result['global_step'] = global_step\n result['loss'] = loss\n\n output_eval_file = os.path.join(args.output_dir + '-MM', \"eval_results.txt\")\n with open(output_eval_file, \"w\") as writer:\n logger.info(\"***** Eval results *****\")\n for key in sorted(result.keys()):\n logger.info(\" %s = %s\", key, str(result[key]))\n writer.write(\"%s = %s\\n\" % (key, str(result[key])))\n\n\nif __name__ == \"__main__\":\n main()\n"
]
| [
[
"torch.distributed.get_world_size",
"torch.utils.data.RandomSampler",
"scipy.stats.pearsonr",
"torch.cuda.is_available",
"sklearn.metrics.f1_score",
"torch.nn.CrossEntropyLoss",
"torch.nn.DataParallel",
"torch.distributed.init_process_group",
"torch.manual_seed",
"torch.tensor",
"torch.utils.data.DataLoader",
"numpy.argmax",
"torch.distributed.get_rank",
"torch.device",
"torch.cuda.manual_seed_all",
"sklearn.metrics.matthews_corrcoef",
"torch.utils.data.SequentialSampler",
"torch.cuda.device_count",
"torch.cuda.set_device",
"numpy.squeeze",
"torch.utils.data.TensorDataset",
"torch.nn.MSELoss",
"numpy.random.seed",
"torch.no_grad",
"scipy.stats.spearmanr",
"torch.utils.data.distributed.DistributedSampler"
]
]
|
ratnadeepb/LinearAlgebra | [
"0f4399c15ba12a3e7c0e2a796c77efa66520e462"
]
| [
"InnerProductSpaces/Examples/matspace.py"
]
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 25 16:13:40 2017\n\n@author: ratnadeepb\n@License: MIT\n\"\"\"\n\n'''\nSquare matrices (n x n) are also vector space where an inner product can \nbe defined.\n\nIn M2,2 space let:\n A = [[a11, a21], [a12, a22]]\n B = [[b11, b21], [b12, b22]]\n \nInner Product in M2,2:\n <A, B> = a11*b11 + a21*b21 + a12*b12 + a22*b22\n'''\n\nimport numpy as np\nimport sys\n\n# Dot product of A and B\ndef mat_dot(A, B):\n try:\n A = np.array(A)\n B = np.array(B)\n except:\n sys.exit(\"Not compatible\")\n \n bl = A.ndim == B.ndim\n if not bl:\n sys.exit(\"Not compatible\")\n s = 0\n for i in range(A.ndim):\n for a, b in zip(A[i], B[i]):\n s += a * b\n return s\n\n# Norm of a Matrix\ndef mat_norm(A):\n return np.sqrt(mat_dot(A, A))\n\n# Angle between two matrices\ndef mat_angle(A, B, op=\"radians\"):\n if op not in [\"radians\", \"degrees\"]:\n sys.exit(\"At this time we only handle radians and degrees\")\n if op == \"degrees\":\n return (mat_dot(A, B) / (mat_norm(A) * mat_norm(B))) * (180 / np.pi)\n else:\n return (mat_dot(A, B) / (mat_norm(A) * mat_norm(B)))\n\nif __name__ == \"__main__\":\n A = [[11, -10], [4, 3]]\n B = [[8, 7], [9, 16]]\n\n print(\"Dot product of these matrices is:\", mat_dot(A, B))\n print(\"Angle betwee the matrices is:\", mat_angle(A, B, \"degrees\"))"
]
| [
[
"numpy.array"
]
]
|
dailysergey/dlcourse_ai | [
"ee6a5cd19de4e02420573a959b7b8ade2672f3a5"
]
| [
"assignments/assignment1/metrics.py"
]
| [
"import numpy as np\n\ndef binary_classification_metrics(prediction, ground_truth):\n '''\n Computes metrics for binary classification\n\n Arguments:\n prediction, np array of bool (num_samples) - model predictions\n ground_truth, np array of bool (num_samples) - true labels\n\n Returns:\n precision, recall, f1, accuracy - classification metrics\n '''\n true_positives = np.sum(prediction[prediction == True] == ground_truth[prediction == True])\n all_positives = np.sum(ground_truth == True)\n all_positives_pred = np.sum(prediction == True)\n\n precision = true_positives / all_positives_pred\n recall = true_positives / all_positives\n \n accuracy = np.sum(prediction == ground_truth)/len(prediction)\n \n f1 = 2*(precision*recall)/(precision+recall)\n # TODO: implement metrics!\n # Some helpful links:\n # https://en.wikipedia.org/wiki/Precision_and_recall\n # https://en.wikipedia.org/wiki/F1_score\n \n return precision, recall, f1, accuracy\n\n\ndef multiclass_accuracy(prediction, ground_truth):\n '''\n Computes metrics for multiclass classification\n\n Arguments:\n prediction, np array of int (num_samples) - model predictions\n ground_truth, np array of int (num_samples) - true labels\n\n Returns:\n accuracy - ratio of accurate predictions to total samples\n '''\n # TODO: Implement computing accuracy\n return 0\n"
]
| [
[
"numpy.sum"
]
]
|
davisan/PRNUPythonColab | [
"0cd2ff9ffa894034557d893e8f8a1617d4c2f566"
]
| [
"src/Filter.py"
]
| [
"\"\"\"\nPlease read the copyright notice located on the readme file (README.md). \n\"\"\"\nimport cv2 as cv\nimport numpy as np\nfrom scipy import signal\nimport PRNUPythonColab.src.Functions as Fu\n\n\ndef Threshold(y, t):\n \"\"\"\n Applies max(0,y-t).\n\n Parameters\n ----------\n y : numpy.ndarray('float32')\n Array of Wavelet coefficients \n t : float32\n Variance of PRNU\n\n Returns\n -------\n numpy.ndarray('float32')\n The thresholded Wavelet coefficients for a later filtering\n\n \"\"\"\n res = y - t\n x = np.maximum(res, 0.)\n return x\n\n\ndef WaveNoise(coef, NoiseVar):\n \"\"\"\n Applies Wiener-like filter in Wavelet Domain (residual filtering).\n \n Models each detail wavelet coefficient as conditional Gaussian random \n variable and use four square NxN moving windows, N in [3,5,7,9], to \n estimate the variance of noise-free image for each wavelet coefficient. \n Then it applies a Wiener-type denoising filter to the coefficients.\n\n Parameters\n ----------\n coef : numpy.ndarray('float32')\n Wavelet detailed coefficient at certain level \n NoiseVar : float32\n Variance of the additive noise (PRNU)\n\n Returns\n -------\n numpy.ndarray('float32')\n Attenuated (filtered) Wavelet coefficient\n numpy.ndarray('float32')\n Finall estimated variances for each Wavelet coefficient\n \"\"\"\n\n tc = np.power(coef, 2)\n coefVar = Threshold(\n signal.fftconvolve(tc, np.ones([3, 3], dtype=np.float32) / (3 * 3), mode='same'),\n NoiseVar)\n\n for w in range(5, 9 + 1, 2):\n EstVar = Threshold(\n signal.fftconvolve(tc, np.ones([w, w], dtype=np.float32) / (w * w), mode='same'),\n NoiseVar)\n coefVar = np.minimum(coefVar, EstVar)\n\n # Wiener filter like attenuation\n tc = np.multiply(coef, np.divide(NoiseVar, coefVar + NoiseVar))\n\n return tc, coefVar\n\n'''\ndef WaveFilter(coef, NoiseVar):\n \"\"\"\n Applies Wiener-like filter in Wavelet Domain (image filtering).\n \n Models each detail wavelet coefficient as conditional Gaussian random \n variable and use four square NxN moving windows, N in [3,5,7,9], to \n estimate the variance of noise-free image for each wavelet coefficient. \n Then it applies a Wiener-type denoising filter to the coefficients.\n\n Parameters\n ----------\n coef : numpy.ndarray('float32')\n Wavelet detailed coefficient at certain level \n NoiseVar : float32\n Variance of the additive noise\n\n Returns\n -------\n numpy.ndarray('float32')\n Attenuated (filtered) Wavelet coefficient\n numpy.ndarray('float32')\n Finall estimated variances for each Wavelet coefficient\n \"\"\"\n\n tc = np.power(coef, 2)\n coefVar = Threshold(\n signal.fftconvolve(np.ones([3, 3]) / (3. * 3.), tc, mode='valid'),\n NoiseVar);\n\n for w in range(5, 9 + 1, 2):\n EstVar = Threshold(\n signal.fftconvolve(np.ones([w, w]) / (w * w), tc, mode='valid'),\n NoiseVar)\n coefVar = min(coefVar, EstVar)\n\n # Wiener filter like attenuation\n tc = np.multiply(coef, np.divide(coefVar, coefVar + NoiseVar))\n\n return tc, coefVar\n'''\n\ndef NoiseExtractFromImage(image, sigma=3.0, color=False, noZM=False):\n \"\"\"\n Estimates PRNU from one image\n\n Parameters\n ----------\n image : str or numpy.ndarray('uint8')\n either test image filename or numpy matrix of image\n sigma : float32\n std of noise to be used for identicication\n (recomended value between 2 and 3)\n color : bool\n for an RGB image, whether to extract noise for the three channels \n separately (default: False)\n noZM\n whether to apply zero-mean to the extracted (filtered) noise\n\n Returns\n -------\n numpy.ndarray('float32')\n extracted noise from the input image, a rough estimate of PRNU fingerprint\n \n Example\n -------\n noise = NoiseExtractFromImage('DSC00123.JPG',2);\n \n Reference\n ---------\n [1] M. Goljan, T. Filler, and J. Fridrich. Large Scale Test of Sensor\n Fingerprint Camera Identification. In N.D. Memon and E.J. Delp and P.W. Wong and\n J. Dittmann, editors, Proc. of SPIE, Electronic Imaging, Media Forensics and\n Security XI, volume 7254, pages # 0I010I12, January 2009.\n\n \"\"\"\n \n # ----- Parameters ----- #\n L = 4 # number of wavelet decomposition levels (between 2-5 as well)\n if isinstance(image, str):\n X = cv.imread(image)\n if np.ndim(X)==3: X = X[:,:,::-1] # BGR2RGB\n else:\n X = image\n del image\n\n M0, N0, three = X.shape\n if X.dtype == 'uint8':\n # convert to [0,255]\n X = X.astype(np.float)\n elif X.dtype == 'uint16':\n X = X.astype(np.float) / 65535 * 255\n\n qmf = [ \t.230377813309,\t.714846570553, .630880767930, -.027983769417,\n -.187034811719,\t.030841381836, .032883011667, -.010597401785]\n qmf /= np.linalg.norm(qmf)\n \n if three != 3:\n Noise = Fu.NoiseExtract(X, qmf, sigma, L)\n else:\n Noise = np.zeros(X.shape)\n for j in range(3):\n Noise[:, :, j] = Fu.NoiseExtract(X[:, :, j], qmf, sigma, L)\n if not color:\n Noise = Fu.rgb2gray1(Noise)\n if noZM:\n print('not removing the linear pattern')\n else:\n Noise, _ = Fu.ZeroMeanTotal(Noise)\n\n #Noise = Noise.astype(np.float)\n\n return Noise\n\n#%% ----- 'mdwt' mex code ported to python -----#\ndef mdwt(x, h, L):\n \"\"\"\n multi-level Discrete Wavelet Transform, implemented similar to \n Rice Wavelet Toolbox (https://www.ece.rice.edu/dsp/software/rwt.shtml)\n \n Parameters\n ----------\n X : numpy.ndarray('float32')\n 2D input image\n h : list\n db4 (D8) decomposition lowpass filter\n L : Int\n Number of levels for DWT decomposition\n \n Returns\n -------\n numpy.ndarray('float32')\n input image in DWT domain \n \n \"\"\"\n \n isint = lambda x: x % 1 == 0\n\n m, n = x.shape[0], x.shape[1] \n if m > 1:\n mtest = m / (2.**L)\n if not isint(mtest):\n raise(ValueError(\"Number of rows in input image must be of size m*2^(L)\"))\n if n > 1:\n ntest = n / (2.**L)\n if not isint(ntest):\n raise(ValueError(\"Number of columns in input image must be of size n*2^(L)\"))\n \n \n # -- internal --\n \n def _fpsconv(x_in, lx, h0, h1, lhm1, x_outl, x_outh):\n # circular-like padding\n x_in[lx:lx+lhm1] = x_in[:lhm1]\n #\n tmp = np.convolve(x_in[:lx+lhm1],h0)\n x_outl[:lx//2]= tmp[lhm1:-lhm1-1:2]\n tmp = np.convolve(x_in[:lx+lhm1],h1)\n x_outh[:lx//2]= tmp[lhm1:-lhm1-1:2]\n '''\n # or (as in the C++ implementation):\n ind = 0\n for i in range(0,lx,2):\n x_outl[ind] = np.dot( x_in[i:i+lhm1+1], np.flip(h0) )\n x_outh[ind] = np.dot( x_in[i:i+lhm1+1], np.flip(h1) )\n ind += 1\n '''\n return x_in, x_outl, x_outh\n \n def _MDWT(x, h, L):\n lh = len(h)\n _m, _n = x.shape[0], x.shape[1] \n y = np.zeros([_m,_n], dtype=np.float32)\n \n xdummy = np.zeros([max(_m,_n) + lh-1], dtype=np.float32)\n ydummyl = np.zeros([max(_m,_n)], dtype=np.float32)\n ydummyh = np.zeros([max(_m,_n)], dtype=np.float32)\n \n # analysis lowpass and highpass\n if _n == 1:\n _n = _m\n _m = 1\n \n h0 = np.flip(h)\n h1 = [h[i]*(-1)**(i+1) for i in range(lh)] \n lhm1 = lh - 1\n actual_m = 2 * _m\n actual_n = 2 * _n\n \n # main loop\n for actual_L in range(1, L+1):\n if _m == 1:\n actual_m = 1\n else:\n actual_m = actual_m // 2\n r_o_a = actual_m // 2\n actual_n = actual_n // 2\n c_o_a = actual_n // 2\n \n # go by rows\n for ir in range(actual_m):# loop over rows\n # store in dummy variable\n if actual_L == 1:\n xdummy[:actual_n] = x[ir, :actual_n]# from input\n else:\n xdummy[:actual_n] = y[ir, :actual_n]# from LL of previous level\n # perform filtering lowpass and highpass\n xdummy, ydummyl, ydummyh = _fpsconv(xdummy, actual_n, h0, h1, lhm1, ydummyl, ydummyh)\n # restore dummy variables in matrices\n y[ir, :c_o_a ] = ydummyl[:c_o_a]\n y[ir, c_o_a:2*c_o_a] = ydummyh[:c_o_a]\n \n \n if _m > 1: # in case of a 2D signal\n # go by columns\n for ic in range(actual_n):# loop over column\n # store in dummy variables \n xdummy[:actual_m] = y[:actual_m, ic]\n # perform filtering lowpass and highpass\n xdummy, ydummyl, ydummyh = _fpsconv(xdummy, actual_m, h0, h1, lhm1, ydummyl, ydummyh)\n # restore dummy variables in matrix\n y[:r_o_a, ic] = ydummyl[:r_o_a]\n y[r_o_a:2*r_o_a, ic] = ydummyh[:r_o_a]\n \n return y\n\n # --------------\n \n y = _MDWT(x, h, L)\n \n return y\n\n#%% ----- 'midwt' mex code ported to python -----#\ndef midwt(y, h, L):\n \"\"\"\n multi-level inverse Discrete Wavelet Transform, implemented similar to \n Rice Wavelet Toolbox (https://www.ece.rice.edu/dsp/software/rwt.shtml)\n \n Parameters\n ----------\n y : numpy.ndarray('float32')\n 2D matrix of image in multi-level DWT domain\n h : list\n db4 (D8) decomposition lowpass filter\n L : Int\n Number of levels for DWT decomposition\n \n Returns\n -------\n numpy.ndarray('float32')\n input image in DWT domain \n \n \"\"\"\n \n isint = lambda x: x % 1 == 0\n \n m, n = y.shape[0], y.shape[1] \n if m > 1:\n mtest = m / (2.**L)\n if not isint(mtest):\n raise(ValueError(\"Number of rows in input image must be of size m*2^(L)\"))\n if n > 1:\n ntest = n / (2.**L)\n if not isint(ntest):\n raise(ValueError(\"Number of columns in input image must be of size n*2^(L)\"))\n \n # -- internal --\n def _bpsconv(x_out, lx, g0, g1, lhhm1, x_inl, x_inh):\n x_inl[:lhhm1] = x_inl[lx:lx+lhhm1]\n x_inh[:lhhm1] = x_inh[lx:lx+lhhm1]\n \n tmp = np.convolve(x_inl[:lx+lhhm1+1], g0[::2]) + \\\n np.convolve(x_inh[:lx+lhhm1+1], g1[::2]);\n x_out[:2*lx:2] = tmp[lhhm1:-lhhm1-1]\n \n tmp = np.convolve(x_inl[:lx+lhhm1+1], g0[1::2]) + \\\n np.convolve(x_inh[:lx+lhhm1+1], g1[1::2])\n x_out[1:2*lx:2] = tmp[lhhm1:-lhhm1-1]\n '''\n # or (as in the C++ implementation):\n ind = 0\n for i in range(lx):\n x_out[ind] = np.dot(x_inl[i:i+lhhm1+1], np.flip(g0[::2])) + \\\n np.dot(x_inh[i:i+lhhm1+1], np.flip(g1[::2]))\n x_out[ind+1] = np.dot(x_inl[i:i+lhhm1+1], np.flip(g0[1::2])) + \\\n np.dot(x_inh[i:i+lhhm1+1], np.flip(g1[1::2]))\n ind += 2\n '''\n return x_out\n \n def _MIDWT(y, h, L):\n lh = len(h)\n _m, _n = y.shape[0], y.shape[1]\n xdummy = np.zeros([max(_m, _n)], dtype=np.float32)\n ydummyl = np.zeros([max(_m, _n)+lh//2-1], dtype=np.float32)\n ydummyh = np.zeros([max(_m, _n)+lh//2-1], dtype=np.float32)\n \n # synthesis lowpass and highpass\n if _n == 1:\n _n = _m\n _m = 1\n \n g0 = h\n g1 = [h[lh-i-1]*((-1)**i) for i in range(lh)] \n #lhm1 = lh - 1\n lhhm1 = lh // 2 - 1\n \n # 2^L\n sample_f = 2**(L-1)\n \n actual_m = _m // sample_f if _m > 1 else 1\n actual_n = _n // sample_f\n \n x = y\n \n # main loop\n for actual_L in range(L,0,-1):\n r_o_a = actual_m // 2\n c_o_a = actual_n // 2\n \n # in case of a 2D signal\n if _m > 1:\n # go by columns\n for ic in range(actual_n):# loop over column\n # store in dummy variables\n ydummyl[lhhm1:lhhm1+r_o_a] = x[:r_o_a, ic]\n ydummyh[lhhm1:lhhm1+r_o_a] = x[r_o_a:2*r_o_a, ic]\n # perform filtering lowpass and highpass \n xdummy = _bpsconv(xdummy, r_o_a, g0, g1, lhhm1, ydummyl, ydummyh)\n # restore dummy variables in matrix\n x[:actual_m, ic] = xdummy[:actual_m]\n # go by rows\n for ir in range(actual_m):# loop over rows\n # store in dummy variable\n ydummyl[lhhm1:lhhm1+c_o_a] = x[ir, :c_o_a]\n ydummyh[lhhm1:lhhm1+c_o_a] = x[ir, c_o_a:2*c_o_a]\n # perform filtering lowpass and highpass\n xdummy = _bpsconv(xdummy, c_o_a, g0, g1, lhhm1, ydummyl, ydummyh);\n # restore dummy variables in matrices\n x[ir, :actual_n] = xdummy[:actual_n]\n \n actual_m = 1 if _m == 1 else actual_m * 2\n actual_n = actual_n * 2\n \n return x\n # --------------\n \n x = _MIDWT(y, h, L)\n \n return x\n\n"
]
| [
[
"numpy.divide",
"numpy.linalg.norm",
"numpy.zeros",
"numpy.minimum",
"numpy.ones",
"numpy.convolve",
"numpy.power",
"numpy.ndim",
"numpy.flip",
"numpy.maximum"
]
]
|
pdhung3012/Text-Classification-Pytorch | [
"e2f4e0de9469d9966305ab2ecf9ce1b4db3660f2"
]
| [
"LSTM_3.py"
]
| [
"\"\"\"\nText classification with the torchtext library\n==================================\nIn this tutorial, we will show how to use the torchtext library to build the dataset for the text classification analysis. Users will have the flexibility to\n - Access to the raw data as an iterator\n - Build data processing pipeline to convert the raw text strings into ``torch.Tensor`` that can be used to train the model\n - Shuffle and iterate the data with `torch.utils.data.DataLoader <https://pytorch.org/docs/stable/data.html?highlight=dataloader#torch.utils.data.DataLoader>`__\n\"\"\"\n\n######################################################################\n# Access to the raw dataset iterators\n# -----------------------------------\n#\n# The torchtext library provides a few raw dataset iterators, which yield the raw text strings. For example, the ``AG_NEWS`` dataset iterators yield the raw data as a tuple of label and text.\n\nimport torch\nfrom torchtext.datasets import AG_NEWS\n\ntrain_iter = AG_NEWS(split='train')\nprint('type of {}'.format(type(train_iter)))\n\n######################################################################\n# ::\n#\n# next(train_iter)\n# >>> (3, \"Wall St. Bears Claw Back Into the Black (Reuters) Reuters -\n# Short-sellers, Wall Street's dwindling\\\\band of ultra-cynics, are seeing green\n# again.\")\n#\n# next(train_iter)\n# >>> (3, 'Carlyle Looks Toward Commercial Aerospace (Reuters) Reuters - Private\n# investment firm Carlyle Group,\\\\which has a reputation for making well-timed\n# and occasionally\\\\controversial plays in the defense industry, has quietly\n# placed\\\\its bets on another part of the market.')\n#\n# next(train_iter)\n# >>> (3, \"Oil and Economy Cloud Stocks' Outlook (Reuters) Reuters - Soaring\n# crude prices plus worries\\\\about the economy and the outlook for earnings are\n# expected to\\\\hang over the stock market next week during the depth of\n# the\\\\summer doldrums.\")\n#\n\n\n######################################################################\n# Prepare data processing pipelines\n# ---------------------------------\n#\n# We have revisited the very basic components of the torchtext library, including vocab, word vectors, tokenizer. Those are the basic data processing building blocks for raw text string.\n#\n# Here is an example for typical NLP data processing with tokenizer and vocabulary. The first step is to build a vocabulary with the raw training dataset. Here we use built in\n# factory function `build_vocab_from_iterator` which accepts iterator that yield list or iterator of tokens. Users can also pass any special symbols to be added to the\n# vocabulary.\n\n\nfrom torchtext.data.utils import get_tokenizer\nfrom torchtext.vocab import build_vocab_from_iterator\n\ntokenizer = get_tokenizer('basic_english')\ntrain_iter = AG_NEWS(split='train')\n\n\ndef yield_tokens(data_iter):\n for _, text in data_iter:\n print('{} aaa {}'.format(_,text))\n yield tokenizer(text)\n\n\nvocab = build_vocab_from_iterator(yield_tokens(train_iter), specials=[\"<unk>\"])\nvocab.set_default_index(vocab[\"<unk>\"])\n\n######################################################################\n# The vocabulary block converts a list of tokens into integers.\n#\n# ::\n#\n# vocab(['here', 'is', 'an', 'example'])\n# >>> [475, 21, 30, 5286]\n#\n# Prepare the text processing pipeline with the tokenizer and vocabulary. The text and label pipelines will be used to process the raw data strings from the dataset iterators.\n\ntext_pipeline = lambda x: vocab(tokenizer(x))\nlabel_pipeline = lambda x: int(x) - 1\n\n######################################################################\n# The text pipeline converts a text string into a list of integers based on the lookup table defined in the vocabulary. The label pipeline converts the label into integers. For example,\n#\n# ::\n#\n# text_pipeline('here is the an example')\n# >>> [475, 21, 2, 30, 5286]\n# label_pipeline('10')\n# >>> 9\n#\n\n\n######################################################################\n# Generate data batch and iterator\n# --------------------------------\n#\n# `torch.utils.data.DataLoader <https://pytorch.org/docs/stable/data.html?highlight=dataloader#torch.utils.data.DataLoader>`__\n# is recommended for PyTorch users (a tutorial is `here <https://pytorch.org/tutorials/beginner/data_loading_tutorial.html>`__).\n# It works with a map-style dataset that implements the ``getitem()`` and ``len()`` protocols, and represents a map from indices/keys to data samples. It also works with an iterable dataset with the shuffle argument of ``False``.\n#\n# Before sending to the model, ``collate_fn`` function works on a batch of samples generated from ``DataLoader``. The input to ``collate_fn`` is a batch of data with the batch size in ``DataLoader``, and ``collate_fn`` processes them according to the data processing pipelines declared previously. Pay attention here and make sure that ``collate_fn`` is declared as a top level def. This ensures that the function is available in each worker.\n#\n# In this example, the text entries in the original data batch input are packed into a list and concatenated as a single tensor for the input of ``nn.EmbeddingBag``. The offset is a tensor of delimiters to represent the beginning index of the individual sequence in the text tensor. Label is a tensor saving the labels of individual text entries.\n\n\nfrom torch.utils.data import DataLoader\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef collate_batch(batch):\n label_list, text_list, offsets = [], [], [0]\n for (_label, _text) in batch:\n label_list.append(label_pipeline(_label))\n processed_text = torch.tensor(text_pipeline(_text), dtype=torch.int64)\n text_list.append(processed_text)\n offsets.append(processed_text.size(0))\n label_list = torch.tensor(label_list, dtype=torch.int64)\n offsets = torch.tensor(offsets[:-1]).cumsum(dim=0)\n text_list = torch.cat(text_list)\n return label_list.to(device), text_list.to(device), offsets.to(device)\n\n\ntrain_iter = AG_NEWS(split='train')\ndataloader = DataLoader(train_iter, batch_size=8, shuffle=False, collate_fn=collate_batch)\n\n######################################################################\n# Define the model\n# ----------------\n#\n# The model is composed of the `nn.EmbeddingBag <https://pytorch.org/docs/stable/nn.html?highlight=embeddingbag#torch.nn.EmbeddingBag>`__ layer plus a linear layer for the classification purpose. ``nn.EmbeddingBag`` with the default mode of \"mean\" computes the mean value of a “bag” of embeddings. Although the text entries here have different lengths, nn.EmbeddingBag module requires no padding here since the text lengths are saved in offsets.\n#\n# Additionally, since ``nn.EmbeddingBag`` accumulates the average across\n# the embeddings on the fly, ``nn.EmbeddingBag`` can enhance the\n# performance and memory efficiency to process a sequence of tensors.\n#\n# .. image:: ../_static/img/text_sentiment_ngrams_model.png\n#\n\nfrom torch import nn\n\n\nclass TextClassificationModel(nn.Module):\n\n def __init__(self, vocab_size, embed_dim, num_class):\n super(TextClassificationModel, self).__init__()\n self.embedding = nn.EmbeddingBag(vocab_size, embed_dim, sparse=True)\n self.fc = nn.Linear(embed_dim, num_class)\n self.init_weights()\n\n def init_weights(self):\n initrange = 0.5\n self.embedding.weight.data.uniform_(-initrange, initrange)\n self.fc.weight.data.uniform_(-initrange, initrange)\n self.fc.bias.data.zero_()\n\n def forward(self, text, offsets):\n embedded = self.embedding(text, offsets)\n return self.fc(embedded)\n\n\n######################################################################\n# Initiate an instance\n# --------------------\n#\n# The ``AG_NEWS`` dataset has four labels and therefore the number of classes is four.\n#\n# ::\n#\n# 1 : World\n# 2 : Sports\n# 3 : Business\n# 4 : Sci/Tec\n#\n# We build a model with the embedding dimension of 64. The vocab size is equal to the length of the vocabulary instance. The number of classes is equal to the number of labels,\n#\n\ntrain_iter = AG_NEWS(split='train')\nnum_class = len(set([label for (label, text) in train_iter]))\nvocab_size = len(vocab)\nemsize = 64\nmodel = TextClassificationModel(vocab_size, emsize, num_class).to(device)\n\n######################################################################\n# Define functions to train the model and evaluate results.\n# ---------------------------------------------------------\n#\n\n\nimport time\n\n\ndef train(dataloader):\n model.train()\n total_acc, total_count = 0, 0\n log_interval = 500\n start_time = time.time()\n\n for idx, (label, text, offsets) in enumerate(dataloader):\n optimizer.zero_grad()\n predicted_label = model(text, offsets)\n loss = criterion(predicted_label, label)\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), 0.1)\n optimizer.step()\n total_acc += (predicted_label.argmax(1) == label).sum().item()\n total_count += label.size(0)\n if idx % log_interval == 0 and idx > 0:\n elapsed = time.time() - start_time\n print('| epoch {:3d} | {:5d}/{:5d} batches '\n '| accuracy {:8.3f}'.format(epoch, idx, len(dataloader),\n total_acc / total_count))\n total_acc, total_count = 0, 0\n start_time = time.time()\n\n\ndef evaluate(dataloader):\n model.eval()\n total_acc, total_count = 0, 0\n\n with torch.no_grad():\n for idx, (label, text, offsets) in enumerate(dataloader):\n predicted_label = model(text, offsets)\n loss = criterion(predicted_label, label)\n total_acc += (predicted_label.argmax(1) == label).sum().item()\n total_count += label.size(0)\n return total_acc / total_count\n\n\n######################################################################\n# Split the dataset and run the model\n# -----------------------------------\n#\n# Since the original ``AG_NEWS`` has no valid dataset, we split the training\n# dataset into train/valid sets with a split ratio of 0.95 (train) and\n# 0.05 (valid). Here we use\n# `torch.utils.data.dataset.random_split <https://pytorch.org/docs/stable/data.html?highlight=random_split#torch.utils.data.random_split>`__\n# function in PyTorch core library.\n#\n# `CrossEntropyLoss <https://pytorch.org/docs/stable/nn.html?highlight=crossentropyloss#torch.nn.CrossEntropyLoss>`__\n# criterion combines ``nn.LogSoftmax()`` and ``nn.NLLLoss()`` in a single class.\n# It is useful when training a classification problem with C classes.\n# `SGD <https://pytorch.org/docs/stable/_modules/torch/optim/sgd.html>`__\n# implements stochastic gradient descent method as the optimizer. The initial\n# learning rate is set to 5.0.\n# `StepLR <https://pytorch.org/docs/master/_modules/torch/optim/lr_scheduler.html#StepLR>`__\n# is used here to adjust the learning rate through epochs.\n#\n\n\nfrom torch.utils.data.dataset import random_split\nfrom torchtext.data.functional import to_map_style_dataset\n\n# Hyperparameters\nEPOCHS = 10 # epoch\nLR = 5 # learning rate\nBATCH_SIZE = 64 # batch size for training\n\ncriterion = torch.nn.CrossEntropyLoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=LR)\nscheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.1)\ntotal_accu = None\ntrain_iter, test_iter = AG_NEWS()\ntrain_dataset = to_map_style_dataset(train_iter)\ntest_dataset = to_map_style_dataset(test_iter)\nnum_train = int(len(train_dataset) * 0.95)\n# torchtext.data.functional.to_map_style_dataset.<locals>._MapStyleDataset\nsplit_train_, split_valid_ = \\\n random_split(train_dataset, [num_train, len(train_dataset) - num_train])\nprint('type {}\\n{}'.format(type(test_dataset),test_dataset))\ninput('aaaa ')\ntrain_dataloader = DataLoader(split_train_, batch_size=BATCH_SIZE,\n shuffle=True, collate_fn=collate_batch)\nvalid_dataloader = DataLoader(split_valid_, batch_size=BATCH_SIZE,\n shuffle=True, collate_fn=collate_batch)\ntest_dataloader = DataLoader(test_dataset, batch_size=BATCH_SIZE,\n shuffle=True, collate_fn=collate_batch)\n\nfor epoch in range(1, EPOCHS + 1):\n epoch_start_time = time.time()\n train(train_dataloader)\n accu_val = evaluate(valid_dataloader)\n if total_accu is not None and total_accu > accu_val:\n scheduler.step()\n else:\n total_accu = accu_val\n print('-' * 59)\n print('| end of epoch {:3d} | time: {:5.2f}s | '\n 'valid accuracy {:8.3f} '.format(epoch,\n time.time() - epoch_start_time,\n accu_val))\n print('-' * 59)\n\n######################################################################\n# Evaluate the model with test dataset\n# ------------------------------------\n#\n\n\n######################################################################\n# Checking the results of the test dataset…\n\nprint('Checking the results of test dataset.')\naccu_test = evaluate(test_dataloader)\nprint('test accuracy {:8.3f}'.format(accu_test))\n\n######################################################################\n# Test on a random news\n# ---------------------\n#\n# Use the best model so far and test a golf news.\n#\n\n\nag_news_label = {1: \"World\",\n 2: \"Sports\",\n 3: \"Business\",\n 4: \"Sci/Tec\"}\n\n\ndef predict(text, text_pipeline):\n with torch.no_grad():\n text = torch.tensor(text_pipeline(text))\n output = model(text, torch.tensor([0]))\n return output.argmax(1).item() + 1\n\n\nex_text_str = \"MEMPHIS, Tenn. – Four days ago, Jon Rahm was \\\n enduring the season’s worst weather conditions on Sunday at The \\\n Open on his way to a closing 75 at Royal Portrush, which \\\n considering the wind and the rain was a respectable showing. \\\n Thursday’s first round at the WGC-FedEx St. Jude Invitational \\\n was another story. With temperatures in the mid-80s and hardly any \\\n wind, the Spaniard was 13 strokes better in a flawless round. \\\n Thanks to his best putting performance on the PGA Tour, Rahm \\\n finished with an 8-under 62 for a three-stroke lead, which \\\n was even more impressive considering he’d never played the \\\n front nine at TPC Southwind.\"\n\nmodel = model.to(\"cpu\")\n\nprint(\"This is a %s news\" % ag_news_label[predict(ex_text_str, text_pipeline)])"
]
| [
[
"torch.nn.Linear",
"torch.cat",
"torch.nn.EmbeddingBag",
"torch.optim.lr_scheduler.StepLR",
"torch.no_grad",
"torch.cuda.is_available",
"torch.tensor",
"torch.utils.data.DataLoader",
"torch.nn.CrossEntropyLoss"
]
]
|
Mojusko/sensepy | [
"550a15859791799db5aba93580913317c1905b2e"
]
| [
"sensepy/capture_ids.py"
]
| [
"import torch\nimport matplotlib.pyplot as plt\nfrom stpy.borel_set import BorelSet,HierarchicalBorelSets\nfrom stpy.kernels import KernelFunction\nfrom typing import Callable, Type, Union, Tuple, List\nfrom stpy.point_processes.poisson_rate_estimator import PoissonRateEstimator\nfrom stpy.point_processes.poisson.poisson import PoissonPointProcess\nfrom sensepy.capture_ucb import CaptureUCB\nimport numpy as np\nfrom scipy import optimize\n\nclass CaptureIDS(CaptureUCB):\n\n\tdef __init__(self,\n\t\t\t\t *args,\n\t\t\t\t actions = None,\n\t\t\t\t original_ids = True, # original or using experimental precomputaiton\n\t\t\t\t **kwargs)->None:\n\t\t\"\"\"\n\t\tCreate IDS algorithm for poisson sesning of Mutny & Krause (2021)\n\t\t:param args: see parent class\n\t\t:param actions: set of actions to work with\n\t\t:param original_ids:\n\t\t:param kwargs:\n\t\t\"\"\"\n\t\tsuper().__init__(*args,**kwargs)\n\t\tself.precomputed = None\n\t\tself.original = original_ids\n\t\tif actions is not None:\n\t\t\tself.precomputed = {}\n\t\t\tfor S in actions:\n\t\t\t\tind = []\n\t\t\t\tfor index, set in enumerate(self.estimator.basic_sets):\n\t\t\t\t\tif S.inside(set):\n\t\t\t\t\t\tind.append(index)\n\t\t\t\tUpsilon = self.estimator.varphis[ind, :]\n\t\t\t\tself.precomputed[S] = Upsilon\n\n\tdef acquisition_function(self, actions: List)->torch.Tensor:\n\t\t\"\"\"\n\t\tCalculate the acqusition function for Capture IDS without optimization\n\t\t:param actions:\n\t\t:return:\n\t\t\"\"\"\n\t\tif self.original == True:\n\t\t\treturn self.acquisition_function_original(actions)\n\t\telse:\n\t\t\tself.estimator.ucb_identified = False\n\t\t\tgaps = [self.estimator.gap(action, actions, self.w, dt=self.dt) for action in actions]\n\t\t\tinf = [self.estimator.information(action, self.dt, precomputed=self.precomputed) for action in actions]\n\t\t\tgaps = np.array(gaps)\n\t\t\tinf = np.array(inf)\n\t\t\tindex = np.argmin((gaps**2)/inf)\n\t\t\treturn index\n\n\tdef acquisition_function_original(self, actions):\n\t\t\"\"\"\n\t\tCalculate the acqusition function for Capture IDS with optimized distribution\n\t\t:param actions:\n\t\t:return:\n\t\t\"\"\"\n\t\tgaps = []\n\t\tinf = []\n\t\tself.estimator.ucb_identified = False\n\n\t\tfor action in actions:\n\t\t\tgaps.append(self.estimator.gap(action,actions,self.w, dt = self.dt))\n\t\t\tinf.append(self.estimator.information(action,self.dt,precomputed=self.precomputed))\n\n\t\tgaps = np.array(gaps)\n\t\tinf = np.array(inf)\n\n\t\tindex1 = np.argmin(gaps)\n\t\tindex2 = np.argmin(gaps/inf)\n\n\t\tgaps_squared = gaps**2\n\n\t\tratio = lambda p: (gaps_squared[index1]*p + gaps_squared[index2]*(1-p))/(inf[index1]*p + inf[index2]*(1-p))\n\t\tres = optimize.minimize_scalar(ratio, bounds = (0,1), method = \"bounded\")\n\t\tp = res.x\n\n\t\tif np.random.uniform() < p:\n\t\t\tprint (\"greedy.\")\n\t\t\treturn index1\n\t\telse:\n\t\t\tprint (\"informative.\")\n\t\t\treturn index2\n\n\n\n\n\tdef step(self, actions,\n\t\t\t verbose: bool = False,\n\t\t\t points: bool = False):\n\t\t\"\"\"\n\n\t\t:param actions: set of actions\n\t\t:param verbose: verobiste level (T/F)\n\t\t:param points: returns also location of the points (T/F)\n\t\t:return: see parent class\n\t\t\"\"\"\n\t\tself.fit_estimator()\n\n\t\t# acquisiton function\n\t\tbest_region = self.acquisition_function(actions)\n\t\tbest_indices = [best_region]\n\t\tif verbose == True:\n\t\t\tprint (\"Sensing:\", actions[best_region].bounds)\n\n\t\tsensed_actions = [actions[best_region]]\n\t\t# sense\n\t\tdata_point = []\n\t\tcost = 0\n\t\tpoints_loc = None\n\t\tfor action in sensed_actions:\n\t\t\tdata_point = self.sense(action)\n\t\t\tself.add_data(data_point)\n\t\t\tcost += self.w(data_point[0])\n\n\t\t\tif points_loc is None and data_point[1] is not None:\n\t\t\t\tpoints_loc = data_point[1]\n\t\t\telif points_loc is not None and data_point[1] is not None:\n\t\t\t\tpoints_loc = torch.cat((points_loc, data_point[1]), dim=0)\n\n\t\tif points == False:\n\t\t\tif points_loc is not None:\n\t\t\t\treturn (cost, points_loc.size()[0], sensed_actions, best_indices)\n\t\t\telse:\n\t\t\t\treturn (cost, 0, sensed_actions, best_indices)\n\t\telse:\n\t\t\tif points_loc is not None:\n\t\t\t\treturn (cost, points_loc, sensed_actions, best_indices)\n\t\t\telse:\n\t\t\t\treturn (cost, None, sensed_actions, best_indices)\n\n"
]
| [
[
"torch.cat",
"numpy.array",
"numpy.argmin",
"scipy.optimize.minimize_scalar",
"numpy.random.uniform"
]
]
|
Tajnymag/vsb-pai-game-of-life | [
"f0e19d96bd948a0507d5bf5cd0fd42bb1f22ea71"
]
| [
"gol-py/src/gol.py"
]
| [
"from numpy.typing import NDArray\n\nimport numpy as np\nfrom scipy.ndimage import convolve\n\n\ndef evolve_cells(board: NDArray[bool]) -> NDArray[bool]:\n kernel = [\n [1, 1, 1],\n [1, 0, 1],\n [1, 1, 1]\n ]\n\n neighbors = convolve(input=np.array(board).astype(int), weights=kernel, mode=\"constant\", cval=0)\n\n where_alive = board\n where_neighbors_two_or_three = (neighbors == 2) | (neighbors == 3)\n where_dead = np.logical_not(board)\n where_neighbors_three = neighbors == 3\n survived = where_alive & where_neighbors_two_or_three\n resurrected = where_dead & where_neighbors_three\n evolved = survived | resurrected\n\n return evolved\n\n\n"
]
| [
[
"numpy.logical_not",
"numpy.array"
]
]
|
sjfleming/pyro | [
"c8dc40a75cc4ff1f43c6ff9178d91c08155d7973",
"c8dc40a75cc4ff1f43c6ff9178d91c08155d7973",
"eadca9c9ed9654573037acdf4f48b34ea40037fe"
]
| [
"pyro/infer/autoguide/guides.py",
"pyro/optim/optim.py",
"examples/contrib/epidemiology/regional.py"
]
| [
"# Copyright (c) 2017-2019 Uber Technologies, Inc.\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"\nThe :mod:`pyro.infer.autoguide` module provides algorithms to automatically\ngenerate guides from simple models, for use in :class:`~pyro.infer.svi.SVI`.\nFor example to generate a mean field Gaussian guide::\n\n def model():\n ...\n\n guide = AutoNormal(model) # a mean field guide\n svi = SVI(model, guide, Adam({'lr': 1e-3}), Trace_ELBO())\n\nAutomatic guides can also be combined using :func:`pyro.poutine.block` and\n:class:`AutoGuideList`.\n\"\"\"\nimport functools\nimport operator\nimport warnings\nimport weakref\nfrom collections import OrderedDict, defaultdict\nfrom contextlib import ExitStack\nfrom types import SimpleNamespace\nfrom typing import Callable, Dict, Optional, Union\n\nimport torch\nfrom torch import nn\nfrom torch.distributions import biject_to\n\nimport pyro\nimport pyro.distributions as dist\nimport pyro.poutine as poutine\nfrom pyro.distributions import constraints\nfrom pyro.distributions.transforms import affine_autoregressive, iterated\nfrom pyro.distributions.util import eye_like, is_identically_zero, sum_rightmost\nfrom pyro.infer.autoguide.initialization import (\n InitMessenger,\n init_to_feasible,\n init_to_median,\n)\nfrom pyro.infer.enum import config_enumerate\nfrom pyro.infer.inspect import get_dependencies\nfrom pyro.nn import PyroModule, PyroParam\nfrom pyro.ops.hessian import hessian\nfrom pyro.ops.tensor_utils import periodic_repeat\nfrom pyro.poutine.util import site_is_subsample\n\nfrom .utils import _product, helpful_support_errors\n\n\ndef _deep_setattr(obj, key, val):\n \"\"\"\n Set an attribute `key` on the object. If any of the prefix attributes do\n not exist, they are set to :class:`~pyro.nn.PyroModule`.\n \"\"\"\n\n def _getattr(obj, attr):\n obj_next = getattr(obj, attr, None)\n if obj_next is not None:\n return obj_next\n setattr(obj, attr, PyroModule())\n return getattr(obj, attr)\n\n lpart, _, rpart = key.rpartition(\".\")\n # Recursive getattr while setting any prefix attributes to PyroModule\n if lpart:\n obj = functools.reduce(_getattr, [obj] + lpart.split(\".\"))\n setattr(obj, rpart, val)\n\n\ndef _deep_getattr(obj, key):\n for part in key.split(\".\"):\n obj = getattr(obj, part)\n return obj\n\n\ndef prototype_hide_fn(msg):\n # Record only stochastic sites in the prototype_trace.\n return msg[\"type\"] != \"sample\" or msg[\"is_observed\"] or site_is_subsample(msg)\n\n\nclass AutoGuide(PyroModule):\n \"\"\"\n Base class for automatic guides.\n\n Derived classes must implement the :meth:`forward` method, with the\n same ``*args, **kwargs`` as the base ``model``.\n\n Auto guides can be used individually or combined in an\n :class:`AutoGuideList` object.\n\n :param callable model: A pyro model.\n :param callable create_plates: An optional function inputing the same\n ``*args,**kwargs`` as ``model()`` and returning a :class:`pyro.plate`\n or iterable of plates. Plates not returned will be created\n automatically as usual. This is useful for data subsampling.\n \"\"\"\n\n def __init__(self, model, *, create_plates=None):\n super().__init__(name=type(self).__name__)\n self.master = None\n # Do not register model as submodule\n self._model = (model,)\n self.create_plates = create_plates\n self.prototype_trace = None\n self._prototype_frames = {}\n\n @property\n def model(self):\n return self._model[0]\n\n def _update_master(self, master_ref):\n self.master = master_ref\n\n def call(self, *args, **kwargs):\n \"\"\"\n Method that calls :meth:`forward` and returns parameter values of the\n guide as a `tuple` instead of a `dict`, which is a requirement for\n JIT tracing. Unlike :meth:`forward`, this method can be traced by\n :func:`torch.jit.trace_module`.\n\n .. warning::\n This method may be removed once PyTorch JIT tracer starts accepting\n `dict` as valid return types. See\n `issue <https://github.com/pytorch/pytorch/issues/27743>_`.\n \"\"\"\n result = self(*args, **kwargs)\n return tuple(v for _, v in sorted(result.items()))\n\n def sample_latent(*args, **kwargs):\n \"\"\"\n Samples an encoded latent given the same ``*args, **kwargs`` as the\n base ``model``.\n \"\"\"\n pass\n\n def __setattr__(self, name, value):\n if isinstance(value, AutoGuide):\n master_ref = self if self.master is None else self.master\n value._update_master(weakref.ref(master_ref))\n super().__setattr__(name, value)\n\n def _create_plates(self, *args, **kwargs):\n if self.master is None:\n if self.create_plates is None:\n self.plates = {}\n else:\n plates = self.create_plates(*args, **kwargs)\n if isinstance(plates, pyro.plate):\n plates = [plates]\n assert all(\n isinstance(p, pyro.plate) for p in plates\n ), \"create_plates() returned a non-plate\"\n self.plates = {p.name: p for p in plates}\n for name, frame in sorted(self._prototype_frames.items()):\n if name not in self.plates:\n full_size = getattr(frame, \"full_size\", frame.size)\n self.plates[name] = pyro.plate(\n name, full_size, dim=frame.dim, subsample_size=frame.size\n )\n else:\n assert (\n self.create_plates is None\n ), \"Cannot pass create_plates() to non-master guide\"\n self.plates = self.master().plates\n return self.plates\n\n def _setup_prototype(self, *args, **kwargs):\n # run the model so we can inspect its structure\n model = poutine.block(self.model, prototype_hide_fn)\n self.prototype_trace = poutine.block(poutine.trace(model).get_trace)(\n *args, **kwargs\n )\n if self.master is not None:\n self.master()._check_prototype(self.prototype_trace)\n\n self._prototype_frames = {}\n for name, site in self.prototype_trace.iter_stochastic_nodes():\n for frame in site[\"cond_indep_stack\"]:\n if frame.vectorized:\n self._prototype_frames[frame.name] = frame\n else:\n raise NotImplementedError(\n \"AutoGuide does not support sequential pyro.plate\"\n )\n\n def median(self, *args, **kwargs):\n \"\"\"\n Returns the posterior median value of each latent variable.\n\n :return: A dict mapping sample site name to median tensor.\n :rtype: dict\n \"\"\"\n raise NotImplementedError\n\n\nclass AutoGuideList(AutoGuide, nn.ModuleList):\n \"\"\"\n Container class to combine multiple automatic guides.\n\n Example usage::\n\n guide = AutoGuideList(my_model)\n guide.append(AutoDiagonalNormal(poutine.block(model, hide=[\"assignment\"])))\n guide.append(AutoDiscreteParallel(poutine.block(model, expose=[\"assignment\"])))\n svi = SVI(model, guide, optim, Trace_ELBO())\n\n :param callable model: a Pyro model\n \"\"\"\n\n def _check_prototype(self, part_trace):\n for name, part_site in part_trace.nodes.items():\n if part_site[\"type\"] != \"sample\":\n continue\n self_site = self.prototype_trace.nodes[name]\n assert part_site[\"fn\"].batch_shape == self_site[\"fn\"].batch_shape\n assert part_site[\"fn\"].event_shape == self_site[\"fn\"].event_shape\n assert part_site[\"value\"].shape == self_site[\"value\"].shape\n\n def _update_master(self, master_ref):\n self.master = master_ref\n for submodule in self:\n submodule._update_master(master_ref)\n\n def append(self, part):\n \"\"\"\n Add an automatic guide for part of the model. The guide should\n have been created by blocking the model to restrict to a subset of\n sample sites. No two parts should operate on any one sample site.\n\n :param part: a partial guide to add\n :type part: AutoGuide or callable\n \"\"\"\n if not isinstance(part, AutoGuide):\n part = AutoCallable(self.model, part)\n if part.master is not None:\n raise RuntimeError(\n \"The module `{}` is already added.\".format(self._pyro_name)\n )\n setattr(self, str(len(self)), part)\n\n def add(self, part):\n \"\"\"Deprecated alias for :meth:`append`.\"\"\"\n warnings.warn(\n \"The method `.add` has been deprecated in favor of `.append`.\",\n DeprecationWarning,\n )\n self.append(part)\n\n def forward(self, *args, **kwargs):\n \"\"\"\n A composite guide with the same ``*args, **kwargs`` as the base ``model``.\n\n .. note:: This method is used internally by :class:`~torch.nn.Module`.\n Users should instead use :meth:`~torch.nn.Module.__call__`.\n\n :return: A dict mapping sample site name to sampled value.\n :rtype: dict\n \"\"\"\n # if we've never run the model before, do so now so we can inspect the model structure\n if self.prototype_trace is None:\n self._setup_prototype(*args, **kwargs)\n\n # create all plates\n self._create_plates(*args, **kwargs)\n\n # run slave guides\n result = {}\n for part in self:\n result.update(part(*args, **kwargs))\n return result\n\n def median(self, *args, **kwargs):\n \"\"\"\n Returns the posterior median value of each latent variable.\n\n :return: A dict mapping sample site name to median tensor.\n :rtype: dict\n \"\"\"\n result = {}\n for part in self:\n result.update(part.median(*args, **kwargs))\n return result\n\n def quantiles(self, quantiles, *args, **kwargs):\n \"\"\"\n Returns the posterior quantile values of each latent variable.\n\n :param list quantiles: A list of requested quantiles between 0 and 1.\n :returns: A dict mapping sample site name to quantiles tensor.\n :rtype: dict\n \"\"\"\n result = {}\n for part in self:\n result.update(part.quantiles(quantiles, *args, **kwargs))\n return result\n\n\nclass AutoCallable(AutoGuide):\n \"\"\"\n :class:`AutoGuide` wrapper for simple callable guides.\n\n This is used internally for composing autoguides with custom user-defined\n guides that are simple callables, e.g.::\n\n def my_local_guide(*args, **kwargs):\n ...\n\n guide = AutoGuideList(model)\n guide.add(AutoDelta(poutine.block(model, expose=['my_global_param']))\n guide.add(my_local_guide) # automatically wrapped in an AutoCallable\n\n To specify a median callable, you can instead::\n\n def my_local_median(*args, **kwargs)\n ...\n\n guide.add(AutoCallable(model, my_local_guide, my_local_median))\n\n For more complex guides that need e.g. access to plates, users should\n instead subclass ``AutoGuide``.\n\n :param callable model: a Pyro model\n :param callable guide: a Pyro guide (typically over only part of the model)\n :param callable median: an optional callable returning a dict mapping\n sample site name to computed median tensor.\n \"\"\"\n\n def __init__(self, model, guide, median=lambda *args, **kwargs: {}):\n super().__init__(model)\n self._guide = guide\n self.median = median\n\n def forward(self, *args, **kwargs):\n result = self._guide(*args, **kwargs)\n return {} if result is None else result\n\n\nclass AutoDelta(AutoGuide):\n \"\"\"\n This implementation of :class:`AutoGuide` uses Delta distributions to\n construct a MAP guide over the entire latent space. The guide does not\n depend on the model's ``*args, **kwargs``.\n\n .. note:: This class does MAP inference in constrained space.\n\n Usage::\n\n guide = AutoDelta(model)\n svi = SVI(model, guide, ...)\n\n Latent variables are initialized using ``init_loc_fn()``. To change the\n default behavior, create a custom ``init_loc_fn()`` as described in\n :ref:`autoguide-initialization` , for example::\n\n def my_init_fn(site):\n if site[\"name\"] == \"level\":\n return torch.tensor([-1., 0., 1.])\n if site[\"name\"] == \"concentration\":\n return torch.ones(k)\n return init_to_sample(site)\n\n :param callable model: A Pyro model.\n :param callable init_loc_fn: A per-site initialization function.\n See :ref:`autoguide-initialization` section for available functions.\n :param callable create_plates: An optional function inputing the same\n ``*args,**kwargs`` as ``model()`` and returning a :class:`pyro.plate`\n or iterable of plates. Plates not returned will be created\n automatically as usual. This is useful for data subsampling.\n \"\"\"\n\n def __init__(self, model, init_loc_fn=init_to_median, *, create_plates=None):\n self.init_loc_fn = init_loc_fn\n model = InitMessenger(self.init_loc_fn)(model)\n super().__init__(model, create_plates=create_plates)\n\n def _setup_prototype(self, *args, **kwargs):\n super()._setup_prototype(*args, **kwargs)\n\n # Initialize guide params\n for name, site in self.prototype_trace.iter_stochastic_nodes():\n value = site[\"value\"].detach()\n event_dim = site[\"fn\"].event_dim\n\n # If subsampling, repeat init_value to full size.\n for frame in site[\"cond_indep_stack\"]:\n full_size = getattr(frame, \"full_size\", frame.size)\n if full_size != frame.size:\n dim = frame.dim - event_dim\n value = periodic_repeat(value, full_size, dim).contiguous()\n\n value = PyroParam(value, site[\"fn\"].support, event_dim)\n with helpful_support_errors(site):\n _deep_setattr(self, name, value)\n\n def forward(self, *args, **kwargs):\n \"\"\"\n An automatic guide with the same ``*args, **kwargs`` as the base ``model``.\n\n .. note:: This method is used internally by :class:`~torch.nn.Module`.\n Users should instead use :meth:`~torch.nn.Module.__call__`.\n\n :return: A dict mapping sample site name to sampled value.\n :rtype: dict\n \"\"\"\n # if we've never run the model before, do so now so we can inspect the model structure\n if self.prototype_trace is None:\n self._setup_prototype(*args, **kwargs)\n\n plates = self._create_plates(*args, **kwargs)\n result = {}\n for name, site in self.prototype_trace.iter_stochastic_nodes():\n with ExitStack() as stack:\n for frame in site[\"cond_indep_stack\"]:\n if frame.vectorized:\n stack.enter_context(plates[frame.name])\n attr_get = operator.attrgetter(name)\n result[name] = pyro.sample(\n name, dist.Delta(attr_get(self), event_dim=site[\"fn\"].event_dim)\n )\n return result\n\n @torch.no_grad()\n def median(self, *args, **kwargs):\n \"\"\"\n Returns the posterior median value of each latent variable.\n\n :return: A dict mapping sample site name to median tensor.\n :rtype: dict\n \"\"\"\n result = self(*args, **kwargs)\n return {k: v.detach() for k, v in result.items()}\n\n\nclass AutoNormal(AutoGuide):\n \"\"\"This implementation of :class:`AutoGuide` uses a Normal distribution\n with a diagonal covariance matrix to construct a guide over the entire\n latent space. The guide does not depend on the model's ``*args, **kwargs``.\n\n It should be equivalent to :class: `AutoDiagonalNormal` , but with\n more convenient site names and with better support for\n :class:`~pyro.infer.trace_mean_field_elbo.TraceMeanField_ELBO` .\n\n In :class:`AutoDiagonalNormal` , if your model has N named\n parameters with dimensions k_i and sum k_i = D, you get a single\n vector of length D for your mean, and a single vector of length D\n for sigmas. This guide gives you N distinct normals that you can\n call by name.\n\n Usage::\n\n guide = AutoNormal(model)\n svi = SVI(model, guide, ...)\n\n :param callable model: A Pyro model.\n :param callable init_loc_fn: A per-site initialization function.\n See :ref:`autoguide-initialization` section for available functions.\n :param float init_scale: Initial scale for the standard deviation of each\n (unconstrained transformed) latent variable.\n :param callable create_plates: An optional function inputing the same\n ``*args,**kwargs`` as ``model()`` and returning a :class:`pyro.plate`\n or iterable of plates. Plates not returned will be created\n automatically as usual. This is useful for data subsampling.\n \"\"\"\n\n scale_constraint = constraints.softplus_positive\n\n def __init__(\n self, model, *, init_loc_fn=init_to_feasible, init_scale=0.1, create_plates=None\n ):\n self.init_loc_fn = init_loc_fn\n\n if not isinstance(init_scale, float) or not (init_scale > 0):\n raise ValueError(\"Expected init_scale > 0. but got {}\".format(init_scale))\n self._init_scale = init_scale\n\n model = InitMessenger(self.init_loc_fn)(model)\n super().__init__(model, create_plates=create_plates)\n\n def _setup_prototype(self, *args, **kwargs):\n super()._setup_prototype(*args, **kwargs)\n\n self._event_dims = {}\n self.locs = PyroModule()\n self.scales = PyroModule()\n\n # Initialize guide params\n for name, site in self.prototype_trace.iter_stochastic_nodes():\n # Collect unconstrained event_dims, which may differ from constrained event_dims.\n with helpful_support_errors(site):\n init_loc = (\n biject_to(site[\"fn\"].support).inv(site[\"value\"].detach()).detach()\n )\n event_dim = site[\"fn\"].event_dim + init_loc.dim() - site[\"value\"].dim()\n self._event_dims[name] = event_dim\n\n # If subsampling, repeat init_value to full size.\n for frame in site[\"cond_indep_stack\"]:\n full_size = getattr(frame, \"full_size\", frame.size)\n if full_size != frame.size:\n dim = frame.dim - event_dim\n init_loc = periodic_repeat(init_loc, full_size, dim).contiguous()\n init_scale = torch.full_like(init_loc, self._init_scale)\n\n _deep_setattr(\n self.locs, name, PyroParam(init_loc, constraints.real, event_dim)\n )\n _deep_setattr(\n self.scales,\n name,\n PyroParam(init_scale, self.scale_constraint, event_dim),\n )\n\n def _get_loc_and_scale(self, name):\n site_loc = _deep_getattr(self.locs, name)\n site_scale = _deep_getattr(self.scales, name)\n return site_loc, site_scale\n\n def forward(self, *args, **kwargs):\n \"\"\"\n An automatic guide with the same ``*args, **kwargs`` as the base ``model``.\n\n .. note:: This method is used internally by :class:`~torch.nn.Module`.\n Users should instead use :meth:`~torch.nn.Module.__call__`.\n\n :return: A dict mapping sample site name to sampled value.\n :rtype: dict\n \"\"\"\n # if we've never run the model before, do so now so we can inspect the model structure\n if self.prototype_trace is None:\n self._setup_prototype(*args, **kwargs)\n\n plates = self._create_plates(*args, **kwargs)\n result = {}\n for name, site in self.prototype_trace.iter_stochastic_nodes():\n transform = biject_to(site[\"fn\"].support)\n\n with ExitStack() as stack:\n for frame in site[\"cond_indep_stack\"]:\n if frame.vectorized:\n stack.enter_context(plates[frame.name])\n\n site_loc, site_scale = self._get_loc_and_scale(name)\n unconstrained_latent = pyro.sample(\n name + \"_unconstrained\",\n dist.Normal(\n site_loc,\n site_scale,\n ).to_event(self._event_dims[name]),\n infer={\"is_auxiliary\": True},\n )\n\n value = transform(unconstrained_latent)\n if poutine.get_mask() is False:\n log_density = 0.0\n else:\n log_density = transform.inv.log_abs_det_jacobian(\n value,\n unconstrained_latent,\n )\n log_density = sum_rightmost(\n log_density,\n log_density.dim() - value.dim() + site[\"fn\"].event_dim,\n )\n delta_dist = dist.Delta(\n value,\n log_density=log_density,\n event_dim=site[\"fn\"].event_dim,\n )\n\n result[name] = pyro.sample(name, delta_dist)\n\n return result\n\n @torch.no_grad()\n def median(self, *args, **kwargs):\n \"\"\"\n Returns the posterior median value of each latent variable.\n\n :return: A dict mapping sample site name to median tensor.\n :rtype: dict\n \"\"\"\n medians = {}\n for name, site in self.prototype_trace.iter_stochastic_nodes():\n site_loc, _ = self._get_loc_and_scale(name)\n median = biject_to(site[\"fn\"].support)(site_loc)\n if median is site_loc:\n median = median.clone()\n medians[name] = median\n\n return medians\n\n @torch.no_grad()\n def quantiles(self, quantiles, *args, **kwargs):\n \"\"\"\n Returns posterior quantiles each latent variable. Example::\n\n print(guide.quantiles([0.05, 0.5, 0.95]))\n\n :param quantiles: A list of requested quantiles between 0 and 1.\n :type quantiles: torch.Tensor or list\n :return: A dict mapping sample site name to a tensor of quantile values.\n :rtype: dict\n \"\"\"\n results = {}\n\n for name, site in self.prototype_trace.iter_stochastic_nodes():\n site_loc, site_scale = self._get_loc_and_scale(name)\n\n site_quantiles = torch.tensor(\n quantiles, dtype=site_loc.dtype, device=site_loc.device\n )\n site_quantiles = site_quantiles.reshape((-1,) + (1,) * site_loc.dim())\n site_quantiles_values = dist.Normal(site_loc, site_scale).icdf(\n site_quantiles\n )\n constrained_site_quantiles = biject_to(site[\"fn\"].support)(\n site_quantiles_values\n )\n results[name] = constrained_site_quantiles\n\n return results\n\n\nclass AutoContinuous(AutoGuide):\n \"\"\"\n Base class for implementations of continuous-valued Automatic\n Differentiation Variational Inference [1].\n\n This uses :mod:`torch.distributions.transforms` to transform each\n constrained latent variable to an unconstrained space, then concatenate all\n variables into a single unconstrained latent variable. Each derived class\n implements a :meth:`get_posterior` method returning a distribution over\n this single unconstrained latent variable.\n\n Assumes model structure and latent dimension are fixed, and all latent\n variables are continuous.\n\n :param callable model: a Pyro model\n\n Reference:\n\n [1] `Automatic Differentiation Variational Inference`,\n Alp Kucukelbir, Dustin Tran, Rajesh Ranganath, Andrew Gelman, David M.\n Blei\n\n :param callable model: A Pyro model.\n :param callable init_loc_fn: A per-site initialization function.\n See :ref:`autoguide-initialization` section for available functions.\n \"\"\"\n\n def __init__(self, model, init_loc_fn=init_to_median):\n model = InitMessenger(init_loc_fn)(model)\n super().__init__(model)\n\n def _setup_prototype(self, *args, **kwargs):\n super()._setup_prototype(*args, **kwargs)\n self._unconstrained_shapes = {}\n self._cond_indep_stacks = {}\n for name, site in self.prototype_trace.iter_stochastic_nodes():\n # Collect the shapes of unconstrained values.\n # These may differ from the shapes of constrained values.\n with helpful_support_errors(site):\n self._unconstrained_shapes[name] = (\n biject_to(site[\"fn\"].support).inv(site[\"value\"]).shape\n )\n\n # Collect independence contexts.\n self._cond_indep_stacks[name] = site[\"cond_indep_stack\"]\n\n self.latent_dim = sum(\n _product(shape) for shape in self._unconstrained_shapes.values()\n )\n if self.latent_dim == 0:\n raise RuntimeError(\n \"{} found no latent variables; Use an empty guide instead\".format(\n type(self).__name__\n )\n )\n\n def _init_loc(self):\n \"\"\"\n Creates an initial latent vector using a per-site init function.\n \"\"\"\n parts = []\n for name, site in self.prototype_trace.iter_stochastic_nodes():\n constrained_value = site[\"value\"].detach()\n unconstrained_value = biject_to(site[\"fn\"].support).inv(constrained_value)\n parts.append(unconstrained_value.reshape(-1))\n latent = torch.cat(parts)\n assert latent.size() == (self.latent_dim,)\n return latent\n\n def get_base_dist(self):\n \"\"\"\n Returns the base distribution of the posterior when reparameterized\n as a :class:`~pyro.distributions.TransformedDistribution`. This\n should not depend on the model's `*args, **kwargs`.\n\n .. code-block:: python\n\n posterior = TransformedDistribution(self.get_base_dist(), self.get_transform(*args, **kwargs))\n\n :return: :class:`~pyro.distributions.TorchDistribution` instance representing the base distribution.\n \"\"\"\n raise NotImplementedError\n\n def get_transform(self, *args, **kwargs):\n \"\"\"\n Returns the transform applied to the base distribution when the posterior\n is reparameterized as a :class:`~pyro.distributions.TransformedDistribution`.\n This may depend on the model's `*args, **kwargs`.\n\n .. code-block:: python\n\n posterior = TransformedDistribution(self.get_base_dist(), self.get_transform(*args, **kwargs))\n\n :return: a :class:`~torch.distributions.Transform` instance.\n \"\"\"\n raise NotImplementedError\n\n def get_posterior(self, *args, **kwargs):\n \"\"\"\n Returns the posterior distribution.\n \"\"\"\n base_dist = self.get_base_dist()\n transform = self.get_transform(*args, **kwargs)\n return dist.TransformedDistribution(base_dist, transform)\n\n def sample_latent(self, *args, **kwargs):\n \"\"\"\n Samples an encoded latent given the same ``*args, **kwargs`` as the\n base ``model``.\n \"\"\"\n pos_dist = self.get_posterior(*args, **kwargs)\n return pyro.sample(\n \"_{}_latent\".format(self._pyro_name), pos_dist, infer={\"is_auxiliary\": True}\n )\n\n def _unpack_latent(self, latent):\n \"\"\"\n Unpacks a packed latent tensor, iterating over tuples of the form::\n\n (site, unconstrained_value)\n \"\"\"\n batch_shape = latent.shape[\n :-1\n ] # for plates outside of _setup_prototype, e.g. parallel particles\n pos = 0\n for name, site in self.prototype_trace.iter_stochastic_nodes():\n constrained_shape = site[\"value\"].shape\n unconstrained_shape = self._unconstrained_shapes[name]\n size = _product(unconstrained_shape)\n event_dim = (\n site[\"fn\"].event_dim + len(unconstrained_shape) - len(constrained_shape)\n )\n unconstrained_shape = torch.broadcast_shapes(\n unconstrained_shape, batch_shape + (1,) * event_dim\n )\n unconstrained_value = latent[..., pos : pos + size].view(\n unconstrained_shape\n )\n yield site, unconstrained_value\n pos += size\n if not torch._C._get_tracing_state():\n assert pos == latent.size(-1)\n\n def forward(self, *args, **kwargs):\n \"\"\"\n An automatic guide with the same ``*args, **kwargs`` as the base ``model``.\n\n .. note:: This method is used internally by :class:`~torch.nn.Module`.\n Users should instead use :meth:`~torch.nn.Module.__call__`.\n\n :return: A dict mapping sample site name to sampled value.\n :rtype: dict\n \"\"\"\n # if we've never run the model before, do so now so we can inspect the model structure\n if self.prototype_trace is None:\n self._setup_prototype(*args, **kwargs)\n\n latent = self.sample_latent(*args, **kwargs)\n plates = self._create_plates(*args, **kwargs)\n\n # unpack continuous latent samples\n result = {}\n for site, unconstrained_value in self._unpack_latent(latent):\n name = site[\"name\"]\n transform = biject_to(site[\"fn\"].support)\n value = transform(unconstrained_value)\n if poutine.get_mask() is False:\n log_density = 0.0\n else:\n log_density = transform.inv.log_abs_det_jacobian(\n value,\n unconstrained_value,\n )\n log_density = sum_rightmost(\n log_density,\n log_density.dim() - value.dim() + site[\"fn\"].event_dim,\n )\n delta_dist = dist.Delta(\n value,\n log_density=log_density,\n event_dim=site[\"fn\"].event_dim,\n )\n\n with ExitStack() as stack:\n for frame in self._cond_indep_stacks[name]:\n stack.enter_context(plates[frame.name])\n result[name] = pyro.sample(name, delta_dist)\n\n return result\n\n def _loc_scale(self, *args, **kwargs):\n \"\"\"\n :returns: a tuple ``(loc, scale)`` used by :meth:`median` and\n :meth:`quantiles`\n \"\"\"\n raise NotImplementedError\n\n @torch.no_grad()\n def median(self, *args, **kwargs):\n \"\"\"\n Returns the posterior median value of each latent variable.\n\n :return: A dict mapping sample site name to median tensor.\n :rtype: dict\n \"\"\"\n loc, _ = self._loc_scale(*args, **kwargs)\n loc = loc.detach()\n return {\n site[\"name\"]: biject_to(site[\"fn\"].support)(unconstrained_value)\n for site, unconstrained_value in self._unpack_latent(loc)\n }\n\n @torch.no_grad()\n def quantiles(self, quantiles, *args, **kwargs):\n \"\"\"\n Returns posterior quantiles each latent variable. Example::\n\n print(guide.quantiles([0.05, 0.5, 0.95]))\n\n :param quantiles: A list of requested quantiles between 0 and 1.\n :type quantiles: torch.Tensor or list\n :return: A dict mapping sample site name to a tensor of quantile values.\n :rtype: dict\n \"\"\"\n loc, scale = self._loc_scale(*args, **kwargs)\n quantiles = torch.tensor(\n quantiles, dtype=loc.dtype, device=loc.device\n ).unsqueeze(-1)\n latents = dist.Normal(loc, scale).icdf(quantiles)\n result = {}\n for latent in latents:\n for site, unconstrained_value in self._unpack_latent(latent):\n result.setdefault(site[\"name\"], []).append(\n biject_to(site[\"fn\"].support)(unconstrained_value)\n )\n result = {k: torch.stack(v) for k, v in result.items()}\n return result\n\n\nclass AutoMultivariateNormal(AutoContinuous):\n \"\"\"\n This implementation of :class:`AutoContinuous` uses a Cholesky\n factorization of a Multivariate Normal distribution to construct a guide\n over the entire latent space. The guide does not depend on the model's\n ``*args, **kwargs``.\n\n Usage::\n\n guide = AutoMultivariateNormal(model)\n svi = SVI(model, guide, ...)\n\n By default the mean vector is initialized by ``init_loc_fn()`` and the\n Cholesky factor is initialized to the identity times a small factor.\n\n :param callable model: A generative model.\n :param callable init_loc_fn: A per-site initialization function.\n See :ref:`autoguide-initialization` section for available functions.\n :param float init_scale: Initial scale for the standard deviation of each\n (unconstrained transformed) latent variable.\n \"\"\"\n\n scale_tril_constraint = constraints.softplus_lower_cholesky\n\n def __init__(self, model, init_loc_fn=init_to_median, init_scale=0.1):\n if not isinstance(init_scale, float) or not (init_scale > 0):\n raise ValueError(\"Expected init_scale > 0. but got {}\".format(init_scale))\n self._init_scale = init_scale\n super().__init__(model, init_loc_fn=init_loc_fn)\n\n def _setup_prototype(self, *args, **kwargs):\n super()._setup_prototype(*args, **kwargs)\n # Initialize guide params\n self.loc = nn.Parameter(self._init_loc())\n self.scale_tril = PyroParam(\n eye_like(self.loc, self.latent_dim) * self._init_scale,\n self.scale_tril_constraint,\n )\n\n def get_base_dist(self):\n return dist.Normal(\n torch.zeros_like(self.loc), torch.zeros_like(self.loc)\n ).to_event(1)\n\n def get_transform(self, *args, **kwargs):\n return dist.transforms.LowerCholeskyAffine(self.loc, scale_tril=self.scale_tril)\n\n def get_posterior(self, *args, **kwargs):\n \"\"\"\n Returns a MultivariateNormal posterior distribution.\n \"\"\"\n return dist.MultivariateNormal(self.loc, scale_tril=self.scale_tril)\n\n def _loc_scale(self, *args, **kwargs):\n return self.loc, self.scale_tril.diag()\n\n\nclass AutoDiagonalNormal(AutoContinuous):\n \"\"\"\n This implementation of :class:`AutoContinuous` uses a Normal distribution\n with a diagonal covariance matrix to construct a guide over the entire\n latent space. The guide does not depend on the model's ``*args, **kwargs``.\n\n Usage::\n\n guide = AutoDiagonalNormal(model)\n svi = SVI(model, guide, ...)\n\n By default the mean vector is initialized to zero and the scale is\n initialized to the identity times a small factor.\n\n :param callable model: A generative model.\n :param callable init_loc_fn: A per-site initialization function.\n See :ref:`autoguide-initialization` section for available functions.\n :param float init_scale: Initial scale for the standard deviation of each\n (unconstrained transformed) latent variable.\n \"\"\"\n\n scale_constraint = constraints.softplus_positive\n\n def __init__(self, model, init_loc_fn=init_to_median, init_scale=0.1):\n if not isinstance(init_scale, float) or not (init_scale > 0):\n raise ValueError(\"Expected init_scale > 0. but got {}\".format(init_scale))\n self._init_scale = init_scale\n super().__init__(model, init_loc_fn=init_loc_fn)\n\n def _setup_prototype(self, *args, **kwargs):\n super()._setup_prototype(*args, **kwargs)\n # Initialize guide params\n self.loc = nn.Parameter(self._init_loc())\n self.scale = PyroParam(\n self.loc.new_full((self.latent_dim,), self._init_scale),\n self.scale_constraint,\n )\n\n def get_base_dist(self):\n return dist.Normal(\n torch.zeros_like(self.loc), torch.zeros_like(self.loc)\n ).to_event(1)\n\n def get_transform(self, *args, **kwargs):\n return dist.transforms.AffineTransform(self.loc, self.scale)\n\n def get_posterior(self, *args, **kwargs):\n \"\"\"\n Returns a diagonal Normal posterior distribution.\n \"\"\"\n return dist.Normal(self.loc, self.scale).to_event(1)\n\n def _loc_scale(self, *args, **kwargs):\n return self.loc, self.scale\n\n\nclass AutoLowRankMultivariateNormal(AutoContinuous):\n \"\"\"\n This implementation of :class:`AutoContinuous` uses a low rank plus\n diagonal Multivariate Normal distribution to construct a guide\n over the entire latent space. The guide does not depend on the model's\n ``*args, **kwargs``.\n\n Usage::\n\n guide = AutoLowRankMultivariateNormal(model, rank=10)\n svi = SVI(model, guide, ...)\n\n By default the ``cov_diag`` is initialized to a small constant and the\n ``cov_factor`` is initialized randomly such that on average\n ``cov_factor.matmul(cov_factor.t())`` has the same scale as ``cov_diag``.\n\n :param callable model: A generative model.\n :param rank: The rank of the low-rank part of the covariance matrix.\n Defaults to approximately ``sqrt(latent dim)``.\n :type rank: int or None\n :param callable init_loc_fn: A per-site initialization function.\n See :ref:`autoguide-initialization` section for available functions.\n :param float init_scale: Approximate initial scale for the standard\n deviation of each (unconstrained transformed) latent variable.\n \"\"\"\n\n scale_constraint = constraints.softplus_positive\n\n def __init__(self, model, init_loc_fn=init_to_median, init_scale=0.1, rank=None):\n if not isinstance(init_scale, float) or not (init_scale > 0):\n raise ValueError(\"Expected init_scale > 0. but got {}\".format(init_scale))\n if not (rank is None or isinstance(rank, int) and rank > 0):\n raise ValueError(\"Expected rank > 0 but got {}\".format(rank))\n self._init_scale = init_scale\n self.rank = rank\n super().__init__(model, init_loc_fn=init_loc_fn)\n\n def _setup_prototype(self, *args, **kwargs):\n super()._setup_prototype(*args, **kwargs)\n # Initialize guide params\n self.loc = nn.Parameter(self._init_loc())\n if self.rank is None:\n self.rank = int(round(self.latent_dim ** 0.5))\n self.scale = PyroParam(\n self.loc.new_full((self.latent_dim,), 0.5 ** 0.5 * self._init_scale),\n constraint=self.scale_constraint,\n )\n self.cov_factor = nn.Parameter(\n self.loc.new_empty(self.latent_dim, self.rank).normal_(\n 0, 1 / self.rank ** 0.5\n )\n )\n\n def get_posterior(self, *args, **kwargs):\n \"\"\"\n Returns a LowRankMultivariateNormal posterior distribution.\n \"\"\"\n scale = self.scale\n cov_factor = self.cov_factor * scale.unsqueeze(-1)\n cov_diag = scale * scale\n return dist.LowRankMultivariateNormal(self.loc, cov_factor, cov_diag)\n\n def _loc_scale(self, *args, **kwargs):\n scale = self.scale * (self.cov_factor.pow(2).sum(-1) + 1).sqrt()\n return self.loc, scale\n\n\nclass AutoNormalizingFlow(AutoContinuous):\n \"\"\"\n This implementation of :class:`AutoContinuous` uses a Diagonal Normal\n distribution transformed via a sequence of bijective transforms\n (e.g. various :mod:`~pyro.distributions.TransformModule` subclasses)\n to construct a guide over the entire latent space. The guide does not\n depend on the model's ``*args, **kwargs``.\n\n Usage::\n\n transform_init = partial(iterated, block_autoregressive,\n repeats=2)\n guide = AutoNormalizingFlow(model, transform_init)\n svi = SVI(model, guide, ...)\n\n :param callable model: a generative model\n :param init_transform_fn: a callable which when provided with the latent\n dimension returns an instance of :class:`~torch.distributions.Transform`\n , or :class:`~pyro.distributions.TransformModule` if the transform has\n trainable params.\n \"\"\"\n\n def __init__(self, model, init_transform_fn):\n super().__init__(model, init_loc_fn=init_to_feasible)\n self._init_transform_fn = init_transform_fn\n self.transform = None\n self._prototype_tensor = torch.tensor(0.0)\n\n def get_base_dist(self):\n loc = self._prototype_tensor.new_zeros(1)\n scale = self._prototype_tensor.new_ones(1)\n return dist.Normal(loc, scale).expand([self.latent_dim]).to_event(1)\n\n def get_transform(self, *args, **kwargs):\n return self.transform\n\n def get_posterior(self, *args, **kwargs):\n if self.transform is None:\n self.transform = self._init_transform_fn(self.latent_dim)\n # Update prototype tensor in case transform parameters\n # device/dtype is not the same as default tensor type.\n for _, p in self.named_pyro_params():\n self._prototype_tensor = p\n break\n return super().get_posterior(*args, **kwargs)\n\n\nclass AutoIAFNormal(AutoNormalizingFlow):\n \"\"\"\n This implementation of :class:`AutoContinuous` uses a Diagonal Normal\n distribution transformed via a :class:`~pyro.distributions.transforms.AffineAutoregressive`\n to construct a guide over the entire latent space. The guide does not depend on the model's\n ``*args, **kwargs``.\n\n Usage::\n\n guide = AutoIAFNormal(model, hidden_dim=latent_dim)\n svi = SVI(model, guide, ...)\n\n :param callable model: a generative model\n :param list[int] hidden_dim: number of hidden dimensions in the IAF\n :param callable init_loc_fn: A per-site initialization function.\n See :ref:`autoguide-initialization` section for available functions.\n\n .. warning::\n\n This argument is only to preserve backwards compatibility\n and has no effect in practice.\n\n :param int num_transforms: number of :class:`~pyro.distributions.transforms.AffineAutoregressive`\n transforms to use in sequence.\n :param init_transform_kwargs: other keyword arguments taken by\n :func:`~pyro.distributions.transforms.affine_autoregressive`.\n \"\"\"\n\n def __init__(\n self,\n model,\n hidden_dim=None,\n init_loc_fn=None,\n num_transforms=1,\n **init_transform_kwargs,\n ):\n if init_loc_fn:\n warnings.warn(\n \"The `init_loc_fn` argument to AutoIAFNormal is not used in practice. \"\n \"Please consider removing, as this may be removed in a future release.\",\n category=FutureWarning,\n )\n super().__init__(\n model,\n init_transform_fn=functools.partial(\n iterated,\n num_transforms,\n affine_autoregressive,\n hidden_dims=hidden_dim,\n **init_transform_kwargs,\n ),\n )\n\n\nclass AutoLaplaceApproximation(AutoContinuous):\n r\"\"\"\n Laplace approximation (quadratic approximation) approximates the posterior\n :math:`\\log p(z | x)` by a multivariate normal distribution in the\n unconstrained space. Under the hood, it uses Delta distributions to\n construct a MAP guide over the entire (unconstrained) latent space. Its\n covariance is given by the inverse of the hessian of :math:`-\\log p(x, z)`\n at the MAP point of `z`.\n\n Usage::\n\n delta_guide = AutoLaplaceApproximation(model)\n svi = SVI(model, delta_guide, ...)\n # ...then train the delta_guide...\n guide = delta_guide.laplace_approximation()\n\n By default the mean vector is initialized to an empirical prior median.\n\n :param callable model: a generative model\n :param callable init_loc_fn: A per-site initialization function.\n See :ref:`autoguide-initialization` section for available functions.\n \"\"\"\n\n def _setup_prototype(self, *args, **kwargs):\n super()._setup_prototype(*args, **kwargs)\n # Initialize guide params\n self.loc = nn.Parameter(self._init_loc())\n\n def get_posterior(self, *args, **kwargs):\n \"\"\"\n Returns a Delta posterior distribution for MAP inference.\n \"\"\"\n return dist.Delta(self.loc).to_event(1)\n\n def laplace_approximation(self, *args, **kwargs):\n \"\"\"\n Returns a :class:`AutoMultivariateNormal` instance whose posterior's `loc` and\n `scale_tril` are given by Laplace approximation.\n \"\"\"\n guide_trace = poutine.trace(self).get_trace(*args, **kwargs)\n model_trace = poutine.trace(\n poutine.replay(self.model, trace=guide_trace)\n ).get_trace(*args, **kwargs)\n loss = guide_trace.log_prob_sum() - model_trace.log_prob_sum()\n\n H = hessian(loss, self.loc)\n cov = H.inverse()\n loc = self.loc\n scale_tril = torch.linalg.cholesky(cov)\n\n gaussian_guide = AutoMultivariateNormal(self.model)\n gaussian_guide._setup_prototype(*args, **kwargs)\n # Set loc, scale_tril parameters as computed above.\n gaussian_guide.loc = loc\n gaussian_guide.scale_tril = scale_tril\n return gaussian_guide\n\n\nclass AutoDiscreteParallel(AutoGuide):\n \"\"\"\n A discrete mean-field guide that learns a latent discrete distribution for\n each discrete site in the model.\n \"\"\"\n\n def _setup_prototype(self, *args, **kwargs):\n # run the model so we can inspect its structure\n model = poutine.block(config_enumerate(self.model), prototype_hide_fn)\n self.prototype_trace = poutine.block(poutine.trace(model).get_trace)(\n *args, **kwargs\n )\n if self.master is not None:\n self.master()._check_prototype(self.prototype_trace)\n\n self._discrete_sites = []\n self._cond_indep_stacks = {}\n self._prototype_frames = {}\n for name, site in self.prototype_trace.iter_stochastic_nodes():\n if site[\"infer\"].get(\"enumerate\") != \"parallel\":\n raise NotImplementedError(\n 'Expected sample site \"{}\" to be discrete and '\n \"configured for parallel enumeration\".format(name)\n )\n\n # collect discrete sample sites\n fn = site[\"fn\"]\n Dist = type(fn)\n if Dist in (dist.Bernoulli, dist.Categorical, dist.OneHotCategorical):\n params = [\n (\"probs\", fn.probs.detach().clone(), fn.arg_constraints[\"probs\"])\n ]\n else:\n raise NotImplementedError(\"{} is not supported\".format(Dist.__name__))\n self._discrete_sites.append((site, Dist, params))\n\n # collect independence contexts\n self._cond_indep_stacks[name] = site[\"cond_indep_stack\"]\n for frame in site[\"cond_indep_stack\"]:\n if frame.vectorized:\n self._prototype_frames[frame.name] = frame\n else:\n raise NotImplementedError(\n \"AutoDiscreteParallel does not support sequential pyro.plate\"\n )\n # Initialize guide params\n for site, Dist, param_spec in self._discrete_sites:\n name = site[\"name\"]\n for param_name, param_init, param_constraint in param_spec:\n _deep_setattr(\n self,\n \"{}_{}\".format(name, param_name),\n PyroParam(param_init, constraint=param_constraint),\n )\n\n def forward(self, *args, **kwargs):\n \"\"\"\n An automatic guide with the same ``*args, **kwargs`` as the base ``model``.\n\n .. note:: This method is used internally by :class:`~torch.nn.Module`.\n Users should instead use :meth:`~torch.nn.Module.__call__`.\n\n :return: A dict mapping sample site name to sampled value.\n :rtype: dict\n \"\"\"\n # if we've never run the model before, do so now so we can inspect the model structure\n if self.prototype_trace is None:\n self._setup_prototype(*args, **kwargs)\n\n plates = self._create_plates(*args, **kwargs)\n\n # enumerate discrete latent samples\n result = {}\n for site, Dist, param_spec in self._discrete_sites:\n name = site[\"name\"]\n dist_params = {\n param_name: operator.attrgetter(\"{}_{}\".format(name, param_name))(self)\n for param_name, param_init, param_constraint in param_spec\n }\n discrete_dist = Dist(**dist_params)\n\n with ExitStack() as stack:\n for frame in self._cond_indep_stacks[name]:\n stack.enter_context(plates[frame.name])\n result[name] = pyro.sample(\n name, discrete_dist, infer={\"enumerate\": \"parallel\"}\n )\n\n return result\n\n\ndef _config_auxiliary(msg):\n return {\"is_auxiliary\": True}\n\n\nclass AutoStructured(AutoGuide):\n \"\"\"\n Structured guide whose conditional distributions are Delta, Normal,\n MultivariateNormal, or by a callable, and whose latent variables can depend\n on each other either linearly (in unconstrained space) or via shearing by a\n callable.\n\n Usage::\n\n def model(data):\n x = pyro.sample(\"x\", dist.LogNormal(0, 1))\n with pyro.plate(\"plate\", len(data)):\n y = pyro.sample(\"y\", dist.Normal(0, 1))\n pyro.sample(\"z\", dist.Normal(y, x), obs=data)\n\n # Either fully automatic...\n guide = AutoStructured(model)\n\n # ...or with specified conditional and dependency types...\n guide = AutoStructured(\n model, conditionals=\"normal\", dependencies=\"linear\"\n )\n\n # ...or with custom dependency structure and distribution types.\n guide = AutoStructured(\n model=model,\n conditionals={\"x\": \"normal\", \"y\": \"delta\"},\n dependencies={\"x\": {\"y\": \"linear\"}},\n )\n\n Once trained, this guide can be used with\n :class:`~pyro.infer.reparam.structured.StructuredReparam` to precondition a\n model for use in HMC and NUTS inference.\n\n .. note:: If you declare a dependency of a high-dimensional downstream\n variable on a low-dimensional upstream variable, you may want to use\n a lower learning rate for that weight, e.g.::\n\n def optim_config(param_name):\n config = {\"lr\": 0.01}\n if \"deps.my_downstream.my_upstream\" in param_name:\n config[\"lr\"] *= 0.1\n return config\n\n adam = pyro.optim.Adam(optim_config)\n\n :param callable model: A Pyro model.\n :param conditionals: Either a single distribution type or a dict mapping\n each latent variable name to a distribution type. A distribution type\n is either a string in {\"delta\", \"normal\", \"mvn\"} or a callable that\n returns a sample from a zero mean (or approximately centered) noise\n distribution (such callables typically call ``pyro.param()`` and\n ``pyro.sample()`` internally).\n :param dependencies: Dependency type, or a dict mapping each site name to a\n dict mapping its upstream dependencies to dependency types. If only a\n dependecy type is provided, dependency structure will be inferred. A\n dependency type is either the string \"linear\" or a callable that maps a\n *flattened* upstream perturbation to *flattened* downstream\n perturbation. The string \"linear\" is equivalent to\n ``nn.Linear(upstream.numel(), downstream.numel(), bias=False)``.\n Dependencies must not contain cycles or self-loops.\n :param callable init_loc_fn: A per-site initialization function.\n See :ref:`autoguide-initialization` section for available functions.\n :param float init_scale: Initial scale for the standard deviation of each\n (unconstrained transformed) latent variable.\n :param callable create_plates: An optional function inputing the same\n ``*args,**kwargs`` as ``model()`` and returning a :class:`pyro.plate`\n or iterable of plates. Plates not returned will be created\n automatically as usual. This is useful for data subsampling.\n \"\"\"\n\n scale_constraint = constraints.softplus_positive\n scale_tril_constraint = constraints.softplus_lower_cholesky\n\n def __init__(\n self,\n model,\n *,\n conditionals: Union[str, Dict[str, Union[str, Callable]]] = \"mvn\",\n dependencies: Union[str, Dict[str, Dict[str, Union[str, Callable]]]] = \"linear\",\n init_loc_fn: Callable = init_to_feasible,\n init_scale: float = 0.1,\n create_plates: Optional[Callable] = None,\n ):\n assert isinstance(conditionals, (dict, str))\n if isinstance(conditionals, dict):\n for name, fn in conditionals.items():\n assert isinstance(name, str)\n assert isinstance(fn, str) or callable(fn)\n assert isinstance(dependencies, (dict, str))\n if isinstance(dependencies, dict):\n for downstream, deps in dependencies.items():\n assert downstream in conditionals\n assert isinstance(deps, dict)\n for upstream, dep in deps.items():\n assert upstream in conditionals\n assert upstream != downstream\n assert isinstance(dep, str) or callable(dep)\n self.conditionals = conditionals\n self.dependencies = dependencies\n\n if not isinstance(init_scale, float) or not (init_scale > 0):\n raise ValueError(f\"Expected init_scale > 0. but got {init_scale}\")\n self._init_scale = init_scale\n self._original_model = (model,)\n model = InitMessenger(init_loc_fn)(model)\n super().__init__(model, create_plates=create_plates)\n\n def _auto_config(self, sample_sites, args, kwargs):\n # Instantiate conditionals as dictionaries.\n if not isinstance(self.conditionals, dict):\n self.conditionals = {\n name: self.conditionals for name, site in sample_sites.items()\n }\n\n # Instantiate dependencies as dictionaries.\n if not isinstance(self.dependencies, dict):\n model = self._original_model[0]\n meta = poutine.block(get_dependencies)(model, args, kwargs)\n # Use posterior dependency edges but with prior ordering. This\n # allows sampling of globals before locals on which they depend.\n prior_order = {name: i for i, name in enumerate(sample_sites)}\n dependencies = defaultdict(dict)\n for d, upstreams in meta[\"posterior_dependencies\"].items():\n assert d in sample_sites\n for u, plates in upstreams.items():\n # TODO use plates to reduce dimension of dependency.\n if u in sample_sites:\n if prior_order[u] > prior_order[d]:\n dependencies[u][d] = self.dependencies\n elif prior_order[d] > prior_order[u]:\n dependencies[d][u] = self.dependencies\n self.dependencies = dict(dependencies)\n\n def _setup_prototype(self, *args, **kwargs):\n super()._setup_prototype(*args, **kwargs)\n\n self.locs = PyroModule()\n self.scales = PyroModule()\n self.scale_trils = PyroModule()\n self.conds = PyroModule()\n self.deps = PyroModule()\n self._batch_shapes = {}\n self._unconstrained_event_shapes = {}\n sample_sites = OrderedDict(self.prototype_trace.iter_stochastic_nodes())\n self._auto_config(sample_sites, args, kwargs)\n\n # Collect unconstrained shapes.\n init_locs = {}\n numel = {}\n for name, site in sample_sites.items():\n with helpful_support_errors(site):\n init_loc = (\n biject_to(site[\"fn\"].support).inv(site[\"value\"].detach()).detach()\n )\n self._batch_shapes[name] = site[\"fn\"].batch_shape\n self._unconstrained_event_shapes[name] = init_loc.shape[\n len(site[\"fn\"].batch_shape) :\n ]\n numel[name] = init_loc.numel()\n init_locs[name] = init_loc.reshape(-1)\n\n # Initialize guide params.\n children = defaultdict(list)\n num_pending = {}\n for name, site in sample_sites.items():\n # Initialize location parameters.\n init_loc = init_locs[name]\n _deep_setattr(self.locs, name, PyroParam(init_loc))\n\n # Initialize parameters of conditional distributions.\n conditional = self.conditionals[name]\n if callable(conditional):\n _deep_setattr(self.conds, name, conditional)\n else:\n if conditional not in (\"delta\", \"normal\", \"mvn\"):\n raise ValueError(f\"Unsupported conditional type: {conditional}\")\n if conditional in (\"normal\", \"mvn\"):\n init_scale = torch.full_like(init_loc, self._init_scale)\n _deep_setattr(\n self.scales, name, PyroParam(init_scale, self.scale_constraint)\n )\n if conditional == \"mvn\":\n init_scale_tril = eye_like(init_loc, init_loc.numel())\n _deep_setattr(\n self.scale_trils,\n name,\n PyroParam(init_scale_tril, self.scale_tril_constraint),\n )\n\n # Initialize dependencies on upstream variables.\n num_pending[name] = 0\n deps = PyroModule()\n _deep_setattr(self.deps, name, deps)\n for upstream, dep in self.dependencies.get(name, {}).items():\n assert upstream in sample_sites\n children[upstream].append(name)\n num_pending[name] += 1\n if isinstance(dep, str) and dep == \"linear\":\n dep = torch.nn.Linear(numel[upstream], numel[name], bias=False)\n dep.weight.data.zero_()\n elif not callable(dep):\n raise ValueError(\n f\"Expected either the string 'linear' or a callable, but got {dep}\"\n )\n _deep_setattr(deps, upstream, dep)\n\n # Topologically sort sites.\n # TODO should we choose a more optimal structure?\n self._sorted_sites = []\n while num_pending:\n name, count = min(num_pending.items(), key=lambda kv: (kv[1], kv[0]))\n assert count == 0, f\"cyclic dependency: {name}\"\n del num_pending[name]\n for child in children[name]:\n num_pending[child] -= 1\n site = self._compress_site(sample_sites[name])\n self._sorted_sites.append((name, site))\n\n # Prune non-essential parts of the trace to save memory.\n for name, site in self.prototype_trace.nodes.items():\n site.clear()\n\n @staticmethod\n def _compress_site(site):\n # Save memory by retaining only necessary parts of the site.\n return {\n \"name\": site[\"name\"],\n \"type\": site[\"type\"],\n \"cond_indep_stack\": site[\"cond_indep_stack\"],\n \"fn\": SimpleNamespace(\n support=site[\"fn\"].support,\n event_dim=site[\"fn\"].event_dim,\n ),\n }\n\n @poutine.infer_config(config_fn=_config_auxiliary)\n def get_deltas(self, save_params=None):\n deltas = {}\n aux_values = {}\n compute_density = poutine.get_mask() is not False\n for name, site in self._sorted_sites:\n if save_params is not None and name not in save_params:\n continue\n\n # Sample zero-mean blockwise independent Delta/Normal/MVN.\n log_density = 0.0\n loc = _deep_getattr(self.locs, name)\n zero = torch.zeros_like(loc)\n conditional = self.conditionals[name]\n if callable(conditional):\n aux_value = _deep_getattr(self.conds, name)()\n elif conditional == \"delta\":\n aux_value = zero\n elif conditional == \"normal\":\n aux_value = pyro.sample(\n name + \"_aux\",\n dist.Normal(zero, 1).to_event(1),\n infer={\"is_auxiliary\": True},\n )\n scale = _deep_getattr(self.scales, name)\n aux_value = aux_value * scale\n if compute_density:\n log_density = (-scale.log()).expand_as(aux_value)\n elif conditional == \"mvn\":\n # This overparametrizes by learning (scale,scale_tril),\n # enabling faster learning of the more-global scale parameter.\n aux_value = pyro.sample(\n name + \"_aux\",\n dist.Normal(zero, 1).to_event(1),\n infer={\"is_auxiliary\": True},\n )\n scale = _deep_getattr(self.scales, name)\n scale_tril = _deep_getattr(self.scale_trils, name)\n aux_value = aux_value @ scale_tril.T * scale\n if compute_density:\n log_density = (\n -scale_tril.diagonal(dim1=-2, dim2=-1).log() - scale.log()\n ).expand_as(aux_value)\n else:\n raise ValueError(f\"Unsupported conditional type: {conditional}\")\n\n # Accumulate upstream dependencies.\n # Note: by accumulating upstream dependencies before updating the\n # aux_values dict, we encode a block-sparse structure of the\n # precision matrix; if we had instead accumulated after updating\n # aux_values, we would encode a block-sparse structure of the\n # covariance matrix.\n # Note: these shear transforms have no effect on the Jacobian\n # determinant, and can therefore be excluded from the log_density\n # computation below, even for nonlinear dep().\n deps = _deep_getattr(self.deps, name)\n for upstream in self.dependencies.get(name, {}):\n dep = _deep_getattr(deps, upstream)\n aux_value = aux_value + dep(aux_values[upstream])\n aux_values[name] = aux_value\n\n # Shift by loc and reshape.\n batch_shape = torch.broadcast_shapes(\n aux_value.shape[:-1], self._batch_shapes[name]\n )\n unconstrained = (aux_value + loc).reshape(\n batch_shape + self._unconstrained_event_shapes[name]\n )\n if not is_identically_zero(log_density):\n log_density = log_density.reshape(batch_shape + (-1,)).sum(-1)\n\n # Transform to constrained space.\n transform = biject_to(site[\"fn\"].support)\n value = transform(unconstrained)\n if compute_density and conditional != \"delta\":\n assert transform.codomain.event_dim == site[\"fn\"].event_dim\n log_density = log_density + transform.inv.log_abs_det_jacobian(\n value, unconstrained\n )\n\n # Create a reparametrized Delta distribution.\n deltas[name] = dist.Delta(value, log_density, site[\"fn\"].event_dim)\n\n return deltas\n\n def forward(self, *args, **kwargs):\n if self.prototype_trace is None:\n self._setup_prototype(*args, **kwargs)\n\n deltas = self.get_deltas()\n plates = self._create_plates(*args, **kwargs)\n result = {}\n for name, site in self._sorted_sites:\n with ExitStack() as stack:\n for frame in site[\"cond_indep_stack\"]:\n if frame.vectorized:\n stack.enter_context(plates[frame.name])\n result[name] = pyro.sample(name, deltas[name])\n\n return result\n\n @torch.no_grad()\n def median(self, *args, **kwargs):\n result = {}\n for name, site in self._sorted_sites:\n loc = _deep_getattr(self.locs, name).detach()\n shape = self._batch_shapes[name] + self._unconstrained_event_shapes[name]\n loc = loc.reshape(shape)\n result[name] = biject_to(site[\"fn\"].support)(loc)\n return result\n",
"# Copyright (c) 2017-2019 Uber Technologies, Inc.\n# SPDX-License-Identifier: Apache-2.0\n\nimport inspect\nfrom typing import (\n Any,\n Callable,\n Dict,\n Iterable,\n List,\n Optional,\n Type,\n Union,\n ValuesView,\n)\n\nimport torch\nfrom torch import Tensor\nfrom torch.nn.utils import clip_grad_norm_, clip_grad_value_\nfrom torch.optim import Optimizer\n\nimport pyro\nfrom pyro.optim.adagrad_rmsprop import AdagradRMSProp as pt_AdagradRMSProp\nfrom pyro.optim.clipped_adam import ClippedAdam as pt_ClippedAdam\nfrom pyro.optim.dct_adam import DCTAdam as pt_DCTAdam\nfrom pyro.params.param_store import (\n module_from_param_with_module_name,\n normalize_param_name,\n user_param_name,\n)\n\n\ndef is_scheduler(optimizer) -> bool:\n \"\"\"\n Helper method to determine whether a PyTorch object is either a PyTorch\n optimizer (return false) or a optimizer wrapped in an LRScheduler e.g. a\n ``ReduceLROnPlateau`` or subclasses of ``_LRScheduler`` (return true).\n \"\"\"\n # This uses duck typing rather than isinstance() because (1) PyTorch\n # provides no comprehensive class hierarchy, and (2) the base class\n # _LRScheduler of the majority of schedulers is private.\n return hasattr(optimizer, \"optimizer\")\n\n\ndef _get_state_dict(optimizer) -> dict:\n \"\"\"\n Helper to get the state dict for either a raw optimizer or an optimizer\n wrapped in an LRScheduler.\n \"\"\"\n if is_scheduler(optimizer):\n state = {\n \"scheduler\": optimizer.state_dict(),\n \"optimizer\": optimizer.optimizer.state_dict(),\n }\n else:\n state = optimizer.state_dict()\n return state\n\n\ndef _load_state_dict(optimizer, state: dict) -> None:\n \"\"\"\n Helper to load the state dict into either a raw optimizer or an optimizer\n wrapped in an LRScheduler.\n \"\"\"\n if is_scheduler(optimizer):\n optimizer.load_state_dict(state[\"scheduler\"])\n optimizer.optimizer.load_state_dict(state[\"optimizer\"])\n else:\n optimizer.load_state_dict(state)\n\n\nclass PyroOptim:\n \"\"\"\n A wrapper for torch.optim.Optimizer objects that helps with managing dynamically generated parameters.\n\n :param optim_constructor: a torch.optim.Optimizer\n :param optim_args: a dictionary of learning arguments for the optimizer or a callable that returns\n such dictionaries\n :param clip_args: a dictionary of clip_norm and/or clip_value args or a callable that returns\n such dictionaries\n \"\"\"\n\n def __init__(\n self,\n optim_constructor: Union[Callable, Optimizer, Type[Optimizer]],\n optim_args: Union[Dict, Callable[..., Dict]],\n clip_args: Optional[Union[Dict, Callable[..., Dict]]] = None,\n ):\n self.pt_optim_constructor = optim_constructor\n\n # must be callable or dict\n assert callable(optim_args) or isinstance(\n optim_args, dict\n ), \"optim_args must be function that returns defaults or a defaults dictionary\"\n\n if clip_args is None:\n clip_args = {}\n\n # must be callable or dict\n assert callable(clip_args) or isinstance(\n clip_args, dict\n ), \"clip_args must be function that returns defaults or a defaults dictionary\"\n\n # hold our args to be called/used\n self.pt_optim_args = optim_args\n if callable(optim_args):\n self.pt_optim_args_argc = len(inspect.signature(optim_args).parameters)\n self.pt_clip_args = clip_args\n\n # holds the torch optimizer objects\n self.optim_objs: Dict = {}\n self.grad_clip: Dict = {}\n\n # any optimizer state that's waiting to be consumed (because that parameter hasn't been seen before)\n self._state_waiting_to_be_consumed: Dict = {}\n\n def __call__(self, params: Union[List, ValuesView], *args, **kwargs) -> None:\n \"\"\"\n :param params: a list of parameters\n :type params: an iterable of strings\n\n Do an optimization step for each param in params. If a given param has never been seen before,\n initialize an optimizer for it.\n \"\"\"\n for p in params:\n # if we have not seen this param before, we instantiate an optim object to deal with it\n if p not in self.optim_objs:\n # create a single optim object for that param\n optimizer = self.optim_objs[p] = self._get_optim(p)\n # create a gradient clipping function if specified\n self.grad_clip[p] = self._get_grad_clip(p)\n # set state from _state_waiting_to_be_consumed if present\n param_name = pyro.get_param_store().param_name(p)\n state = self._state_waiting_to_be_consumed.pop(param_name, None)\n if state is not None:\n _load_state_dict(optimizer, state)\n\n if self.grad_clip[p] is not None:\n self.grad_clip[p](p)\n\n if isinstance(\n self.optim_objs[p], torch.optim.lr_scheduler._LRScheduler\n ) or isinstance(\n self.optim_objs[p], torch.optim.lr_scheduler.ReduceLROnPlateau\n ):\n # if optim object was a scheduler, perform an optimizer step\n self.optim_objs[p].optimizer.step(*args, **kwargs)\n else:\n self.optim_objs[p].step(*args, **kwargs)\n\n def get_state(self) -> Dict:\n \"\"\"\n Get state associated with all the optimizers in the form of a dictionary with\n key-value pairs (parameter name, optim state dicts)\n \"\"\"\n state_dict = {}\n for param in self.optim_objs:\n param_name = pyro.get_param_store().param_name(param)\n state_dict[param_name] = _get_state_dict(self.optim_objs[param])\n return state_dict\n\n def set_state(self, state_dict: Dict) -> None:\n \"\"\"\n Set the state associated with all the optimizers using the state obtained\n from a previous call to get_state()\n \"\"\"\n self._state_waiting_to_be_consumed.update(state_dict)\n\n def save(self, filename: str) -> None:\n \"\"\"\n :param filename: file name to save to\n :type filename: str\n\n Save optimizer state to disk\n \"\"\"\n with open(filename, \"wb\") as output_file:\n torch.save(self.get_state(), output_file)\n\n def load(self, filename: str) -> None:\n \"\"\"\n :param filename: file name to load from\n :type filename: str\n\n Load optimizer state from disk\n \"\"\"\n with open(filename, \"rb\") as input_file:\n state = torch.load(input_file)\n self.set_state(state)\n\n def _get_optim(self, param: Union[Iterable[Tensor], Iterable[Dict[Any, Any]]]):\n return self.pt_optim_constructor([param], **self._get_optim_args(param)) # type: ignore\n\n # helper to fetch the optim args if callable (only used internally)\n def _get_optim_args(self, param: Union[Iterable[Tensor], Iterable[Dict]]):\n # If we were passed a function, we call function with a\n # fully qualified name e.g. 'mymodule.mysubmodule.bias'.\n if callable(self.pt_optim_args):\n param_name = pyro.get_param_store().param_name(param)\n if self.pt_optim_args_argc == 1:\n # Normalize to the format of nn.Module.named_parameters().\n normal_name = normalize_param_name(param_name)\n opt_dict = self.pt_optim_args(normal_name)\n else:\n # DEPRECATED Split param name in to pieces.\n module_name = module_from_param_with_module_name(param_name)\n stripped_param_name = user_param_name(param_name)\n opt_dict = self.pt_optim_args(module_name, stripped_param_name)\n\n # must be dictionary\n assert isinstance(\n opt_dict, dict\n ), \"per-param optim arg must return defaults dictionary\"\n return opt_dict\n else:\n return self.pt_optim_args\n\n def _get_grad_clip(self, param: str):\n grad_clip_args = self._get_grad_clip_args(param)\n\n if not grad_clip_args:\n return None\n\n def _clip_grad(params: Union[Tensor, Iterable[Tensor]]):\n self._clip_grad(params, **grad_clip_args)\n\n return _clip_grad\n\n def _get_grad_clip_args(self, param: str) -> Dict:\n # if we were passed a fct, we call fct with param info\n # arguments are (module name, param name) e.g. ('mymodule', 'bias')\n if callable(self.pt_clip_args):\n\n # get param name\n param_name = pyro.get_param_store().param_name(param)\n module_name = module_from_param_with_module_name(param_name)\n stripped_param_name = user_param_name(param_name)\n\n # invoke the user-provided callable\n clip_dict = self.pt_clip_args(module_name, stripped_param_name)\n\n # must be dictionary\n assert isinstance(\n clip_dict, dict\n ), \"per-param clip arg must return defaults dictionary\"\n return clip_dict\n else:\n return self.pt_clip_args\n\n @staticmethod\n def _clip_grad(\n params: Union[Tensor, Iterable[Tensor]],\n clip_norm: Optional[Union[int, float]] = None,\n clip_value: Optional[Union[int, float]] = None,\n ) -> None:\n if clip_norm is not None:\n clip_grad_norm_(params, clip_norm)\n if clip_value is not None:\n clip_grad_value_(params, clip_value)\n\n\ndef AdagradRMSProp(optim_args: Dict) -> PyroOptim:\n \"\"\"\n Wraps :class:`pyro.optim.adagrad_rmsprop.AdagradRMSProp` with :class:`~pyro.optim.optim.PyroOptim`.\n \"\"\"\n return PyroOptim(pt_AdagradRMSProp, optim_args)\n\n\ndef ClippedAdam(optim_args: Dict) -> PyroOptim:\n \"\"\"\n Wraps :class:`pyro.optim.clipped_adam.ClippedAdam` with :class:`~pyro.optim.optim.PyroOptim`.\n \"\"\"\n return PyroOptim(pt_ClippedAdam, optim_args)\n\n\ndef DCTAdam(optim_args: Dict) -> PyroOptim:\n \"\"\"\n Wraps :class:`pyro.optim.dct_adam.DCTAdam` with :class:`~pyro.optim.optim.PyroOptim`.\n \"\"\"\n return PyroOptim(pt_DCTAdam, optim_args)\n",
"# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nimport argparse\nimport logging\n\nimport torch\n\nimport pyro\nfrom pyro.contrib.epidemiology.models import RegionalSIRModel\n\nlogging.basicConfig(format=\"%(message)s\", level=logging.INFO)\n\n\ndef Model(args, data):\n assert 0 <= args.coupling <= 1, args.coupling\n population = torch.full((args.num_regions,), float(args.population))\n coupling = torch.eye(args.num_regions).clamp(min=args.coupling)\n return RegionalSIRModel(population, coupling, args.recovery_time, data)\n\n\ndef generate_data(args):\n extended_data = [None] * (args.duration + args.forecast)\n model = Model(args, extended_data)\n logging.info(\"Simulating from a {}\".format(type(model).__name__))\n for attempt in range(100):\n samples = model.generate(\n {\n \"R0\": args.basic_reproduction_number,\n \"rho_c1\": 10 * args.response_rate,\n \"rho_c0\": 10 * (1 - args.response_rate),\n }\n )\n obs = samples[\"obs\"][: args.duration]\n S2I = samples[\"S2I\"]\n\n obs_sum = int(obs.sum())\n S2I_sum = int(S2I[: args.duration].sum())\n if obs_sum >= args.min_observations:\n logging.info(\n \"Observed {:d}/{:d} infections:\\n{}\".format(\n obs_sum, S2I_sum, \" \".join(str(int(x)) for x in obs[:, 0])\n )\n )\n return {\"S2I\": S2I, \"obs\": obs}\n\n raise ValueError(\n \"Failed to generate {} observations. Try increasing \"\n \"--population or decreasing --min-observations\".format(args.min_observations)\n )\n\n\ndef infer_mcmc(args, model):\n energies = []\n\n def hook_fn(kernel, *unused):\n e = float(kernel._potential_energy_last)\n energies.append(e)\n if args.verbose:\n logging.info(\"potential = {:0.6g}\".format(e))\n\n mcmc = model.fit_mcmc(\n heuristic_num_particles=args.smc_particles,\n heuristic_ess_threshold=args.ess_threshold,\n warmup_steps=args.warmup_steps,\n num_samples=args.num_samples,\n max_tree_depth=args.max_tree_depth,\n num_quant_bins=args.num_bins,\n haar=args.haar,\n haar_full_mass=args.haar_full_mass,\n jit_compile=args.jit,\n hook_fn=hook_fn,\n )\n\n mcmc.summary()\n if args.plot:\n import matplotlib.pyplot as plt\n\n plt.figure(figsize=(6, 3))\n plt.plot(energies)\n plt.xlabel(\"MCMC step\")\n plt.ylabel(\"potential energy\")\n plt.title(\"MCMC energy trace\")\n plt.tight_layout()\n\n\ndef infer_svi(args, model):\n losses = model.fit_svi(\n heuristic_num_particles=args.smc_particles,\n heuristic_ess_threshold=args.ess_threshold,\n num_samples=args.num_samples,\n num_steps=args.svi_steps,\n num_particles=args.svi_particles,\n haar=args.haar,\n jit=args.jit,\n )\n\n if args.plot:\n import matplotlib.pyplot as plt\n\n plt.figure(figsize=(6, 3))\n plt.plot(losses)\n plt.xlabel(\"SVI step\")\n plt.ylabel(\"loss\")\n plt.title(\"SVI Convergence\")\n plt.tight_layout()\n\n\ndef predict(args, model, truth):\n samples = model.predict(forecast=args.forecast)\n S2I = samples[\"S2I\"]\n median = S2I.median(dim=0).values\n lines = [\"Median prediction of new infections (starting on day 0):\"]\n for r in range(args.num_regions):\n lines.append(\n \"Region {}: {}\".format(r, \" \".join(map(str, map(int, median[:, r]))))\n )\n logging.info(\"\\n\".join(lines))\n\n # Optionally plot the latent and forecasted series of new infections.\n if args.plot:\n import matplotlib.pyplot as plt\n\n fig, axes = plt.subplots(\n args.num_regions, sharex=True, figsize=(6, 1 + args.num_regions)\n )\n time = torch.arange(args.duration + args.forecast)\n p05 = S2I.kthvalue(int(round(0.5 + 0.05 * args.num_samples)), dim=0).values\n p95 = S2I.kthvalue(int(round(0.5 + 0.95 * args.num_samples)), dim=0).values\n for r, ax in enumerate(axes):\n ax.fill_between(\n time, p05[:, r], p95[:, r], color=\"red\", alpha=0.3, label=\"90% CI\"\n )\n ax.plot(time, median[:, r], \"r-\", label=\"median\")\n ax.plot(time[: args.duration], model.data[:, r], \"k.\", label=\"observed\")\n ax.plot(time, truth[:, r], \"k--\", label=\"truth\")\n ax.axvline(args.duration - 0.5, color=\"gray\", lw=1)\n ax.set_xlim(0, len(time) - 1)\n ax.set_ylim(0, None)\n axes[0].set_title(\n \"New infections among {} regions each of size {}\".format(\n args.num_regions, args.population\n )\n )\n axes[args.num_regions // 2].set_ylabel(\"inf./day\")\n axes[-1].set_xlabel(\"day after first infection\")\n axes[-1].legend(loc=\"upper left\")\n plt.tight_layout()\n plt.subplots_adjust(hspace=0)\n\n\ndef main(args):\n pyro.set_rng_seed(args.rng_seed)\n\n # Generate data.\n dataset = generate_data(args)\n obs = dataset[\"obs\"]\n\n # Run inference.\n model = Model(args, obs)\n infer = {\"mcmc\": infer_mcmc, \"svi\": infer_svi}[args.infer]\n infer(args, model)\n\n # Predict latent time series.\n predict(args, model, truth=dataset[\"S2I\"])\n\n\nif __name__ == \"__main__\":\n assert pyro.__version__.startswith(\"1.7.0\")\n parser = argparse.ArgumentParser(\n description=\"Regional compartmental epidemiology modeling using HMC\"\n )\n parser.add_argument(\"-p\", \"--population\", default=1000, type=int)\n parser.add_argument(\"-r\", \"--num-regions\", default=2, type=int)\n parser.add_argument(\"-c\", \"--coupling\", default=0.1, type=float)\n parser.add_argument(\"-m\", \"--min-observations\", default=3, type=int)\n parser.add_argument(\"-d\", \"--duration\", default=20, type=int)\n parser.add_argument(\"-f\", \"--forecast\", default=10, type=int)\n parser.add_argument(\"-R0\", \"--basic-reproduction-number\", default=1.5, type=float)\n parser.add_argument(\"-tau\", \"--recovery-time\", default=7.0, type=float)\n parser.add_argument(\"-rho\", \"--response-rate\", default=0.5, type=float)\n parser.add_argument(\"--infer\", default=\"mcmc\")\n parser.add_argument(\"--mcmc\", action=\"store_const\", const=\"mcmc\", dest=\"infer\")\n parser.add_argument(\"--svi\", action=\"store_const\", const=\"svi\", dest=\"infer\")\n parser.add_argument(\"--haar\", action=\"store_true\")\n parser.add_argument(\"-hfm\", \"--haar-full-mass\", default=0, type=int)\n parser.add_argument(\"-n\", \"--num-samples\", default=200, type=int)\n parser.add_argument(\"-np\", \"--smc-particles\", default=1024, type=int)\n parser.add_argument(\"-ss\", \"--svi-steps\", default=5000, type=int)\n parser.add_argument(\"-sp\", \"--svi-particles\", default=32, type=int)\n parser.add_argument(\"-ess\", \"--ess-threshold\", default=0.5, type=float)\n parser.add_argument(\"-w\", \"--warmup-steps\", type=int)\n parser.add_argument(\"-t\", \"--max-tree-depth\", default=5, type=int)\n parser.add_argument(\"-nb\", \"--num-bins\", default=1, type=int)\n parser.add_argument(\"--double\", action=\"store_true\", default=True)\n parser.add_argument(\"--single\", action=\"store_false\", dest=\"double\")\n parser.add_argument(\"--rng-seed\", default=0, type=int)\n parser.add_argument(\"--cuda\", action=\"store_true\")\n parser.add_argument(\"--jit\", action=\"store_true\", default=True)\n parser.add_argument(\"--nojit\", action=\"store_false\", dest=\"jit\")\n parser.add_argument(\"--verbose\", action=\"store_true\")\n parser.add_argument(\"--plot\", action=\"store_true\")\n args = parser.parse_args()\n\n if args.warmup_steps is None:\n args.warmup_steps = args.num_samples\n if args.double:\n if args.cuda:\n torch.set_default_tensor_type(torch.cuda.DoubleTensor)\n else:\n torch.set_default_dtype(torch.float64)\n elif args.cuda:\n torch.set_default_tensor_type(torch.cuda.FloatTensor)\n\n main(args)\n\n if args.plot:\n import matplotlib.pyplot as plt\n\n plt.show()\n"
]
| [
[
"torch.nn.Linear",
"torch.cat",
"torch.distributions.biject_to",
"torch.linalg.cholesky",
"torch.stack",
"torch.no_grad",
"torch.full_like",
"torch._C._get_tracing_state",
"torch.tensor",
"torch.broadcast_shapes",
"torch.zeros_like"
],
[
"torch.nn.utils.clip_grad_value_",
"torch.load",
"torch.nn.utils.clip_grad_norm_"
],
[
"torch.arange",
"matplotlib.pyplot.xlabel",
"torch.set_default_tensor_type",
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.figure",
"torch.set_default_dtype",
"torch.eye",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots_adjust"
]
]
|
Royzon/JDE | [
"76258ffbfc51d20ebdd2a1fc152a91fe43a12f1c"
]
| [
"towts.py"
]
| [
"import os\nimport torch\nimport struct\nimport argparse\nimport collections\nimport numpy as np\nimport torch.onnx as onnx\nimport onnxruntime as ort\n\nimport darknet\nimport shufflenetv2\n\nif __name__ == '__main__':\n # parse arguments from command line\n parser = argparse.ArgumentParser(\n description='export PyTorch weidhts to a .wts file')\n parser.add_argument('--pytorch-model', '-pm', type=str,\n help='path to the PyTroch model')\n parser.add_argument('--wts', type=str,\n help='path to the gernerated .wts file')\n parser.add_argument('--backbone', '-bb', type=str, default='shufflenetv2',\n help='backbone architecture, default is shufflenetv2'\n 'other option is darknet')\n parser.add_argument('--thin', type=str, default='0.5x',\n help='shufflenetv2 backbone thin, default is 0.5x, other options'\n 'are 1.0x, 1.5x, and 2.0x')\n args = parser.parse_args()\n \n # construct JDE model\n anchors = np.random.randint(low=0, high=200, size=(12,2))\n if args.backbone == 'shufflenetv2':\n model = shufflenetv2.ShuffleNetV2(anchors, model_size=args.thin)\n elif args.backbone == 'darknet':\n raise NotImplementedError\n else:\n raise NotImplementedError\n \n # load weights if PyTorch model was given\n if args.pytorch_model:\n state_dict = model.state_dict()\n train_state_dict = torch.load(args.pytorch_model)\n # remove identifier classifier from train_state_dict\n train_state_dict = {k:v for k,v in train_state_dict.items() if k in state_dict.keys()}\n train_state_dict = collections.OrderedDict(train_state_dict)\n state_dict.update(train_state_dict)\n model.load_state_dict(state_dict)\n \n model.eval()\n path, filename = os.path.split(args.wts)\n torch.save(model.state_dict(), os.path.join(path, 'model.pth'));\n \n # write layer name and corresponding weidhts to .wts file\n file = open(args.wts, 'w')\n file.write('{}\\n'.format(len(model.state_dict().keys())))\n for k,v in model.state_dict().items():\n print('export {}, size is {}'.format(k, v.shape))\n ws = v.reshape(-1).cpu().numpy()\n file.write('{} {}'.format(k, len(ws)))\n for w in ws:\n file.write(' ')\n file.write(struct.pack('>f', float(w)).hex())\n file.write('\\n')\n \n onnx_model = os.path.join(path, 'model.onnx')\n dummy_input = torch.rand(1, 3, 320, 576)\n onnx.export(model, dummy_input, onnx_model, verbose=True, input_names=['data'],\n output_names=['out1', 'out2', 'out3'], opset_version=11)\n \n session = ort.InferenceSession(onnx_model)\n outputs = session.run(None, {'data':dummy_input.cpu().numpy()})\n for i, output in enumerate(outputs):\n print('branch {} output size is {}'.format(i, output.shape))"
]
| [
[
"torch.rand",
"numpy.random.randint",
"torch.onnx.export",
"torch.load"
]
]
|
bbadass/qmpy | [
"e2fd0015e4f2786e1cca185b616e679c3dcb2114"
]
| [
"qmpy/web/views/data/references.py"
]
| [
"import numpy as np\n\nimport matplotlib\n\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nfrom io import BytesIO\nimport urllib\nimport base64\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\n\nfrom ..tools import get_globals\nfrom qmpy.models import Author, Journal, Reference, Entry\nfrom qmpy.utils import *\n\n\ndef reference_view(request, reference_id):\n ref = Reference.objects.get(id=reference_id)\n data = get_globals()\n data[\"reference\"] = ref\n return render_to_response(\n \"data/reference/paper.html\", data, RequestContext(request)\n )\n\n\ndef journal_view(request, journal_id):\n journal = Journal.objects.get(id=journal_id)\n dates = journal.references.values_list(\"year\", flat=True)\n plt.hist(dates)\n plt.xlabel(\"Year\")\n plt.ylabel(\"# of publications with new materials\")\n img = BytesIO()\n plt.savefig(img, dpi=75, bbox_inches=\"tight\", format='png')\n img.seek(0)\n data_uri = base64.b64encode(img.read())\n data_uri = 'data:image/png;base64,' + urllib.parse.quote(data_uri)\n plt.close()\n\n some_entries = Entry.objects.filter(reference__journal=journal)[:20]\n data = get_globals()\n data.update({\"journal\": journal, \"hist\": data_uri, \"entries\": some_entries})\n return render_to_response(\n \"data/reference/journal.html\", data, RequestContext(request)\n )\n\n\ndef author_view(request, author_id):\n author = Author.objects.get(id=author_id)\n materials = Entry.objects.filter(reference__author_set=author)\n coauths = {}\n for co in Author.objects.filter(references__author_set=author):\n papers = Reference.objects.filter(author_set=author)\n papers = papers.filter(author_set=co)\n mats = Entry.objects.filter(reference__in=papers)\n data = {\n \"papers\": papers.distinct().count(),\n \"materials\": mats.distinct().count(),\n }\n coauths[co] = data\n\n data = get_globals()\n data.update({\"author\": author, \"materials\": materials, \"coauthors\": coauths})\n return render_to_response(\n \"data/reference/author.html\", data, RequestContext(request)\n )\n"
]
| [
[
"matplotlib.use",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.close",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel"
]
]
|
AliMuhammadOfficial/tf-quant-finance | [
"31863c907bf561cb86551b785c1aed947303590d"
]
| [
"tf_quant_finance/experimental/svi/parameterizations.py"
]
| [
"# Lint as: python3\n# Copyright 2021 Google LLC\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Parameterization utilities for the SVI volatility model.\"\"\"\n\nimport tensorflow.compat.v2 as tf\n\n__all__ = ['total_variance_from_raw']\n\n\ndef total_variance_from_raw(svi_parameters,\n log_moneyness,\n dtype=None,\n name=None):\n r\"\"\"Computes modeled total variance from raw SVI parameters.\n\n The SVI volatility model parameterizes an option's total implied variance,\n defined as w(k,t) := sigmaBS(k,t)^2 * t, where k := log(K/F) is the options's\n log-moneyness, t is the time to expiry, and sigmaBS(k,t) is the Black-Scholes\n market implied volatility. For a fixed timeslice (i.e. given expiry t), the\n raw SVI parameterization consists of 5 parameters (a,b,rho,m,sigma), and\n the model approximation formula for w(k,t) as a function of k is (cf.[1]):\n ```None\n w(k) = a + b * (rho * (k - m) + sqrt{(k - m)^2 + sigma^2)}\n ```\n The raw parameters have the following interpretations (cf.[2]):\n a vertically shifts the variance graph\n b controls the angle between the left and right asymptotes\n rho controls the rotation of the variance graph\n m horizontally shifts the variance graph\n sigma controls the graph smoothness at the vertex (ATM)\n\n #### References:\n [1] Gatheral J., Jaquier A., Arbitrage-free SVI volatility surfaces.\n https://arxiv.org/pdf/1204.0646.pdf\n [2] Gatheral J, A parsimonious arbitrage-free implied volatility\n parameterization with application to the valuation of volatility derivatives.\n http://faculty.baruch.cuny.edu/jgatheral/madrid2004.pdf\n\n Args:\n svi_parameters: A rank 2 real `Tensor` of shape [batch_size, 5]. The raw SVI\n parameters for each volatility skew.\n log_moneyness: A rank 2 real `Tensor` of shape [batch_size, num_strikes].\n dtype: Optional `tf.Dtype`. If supplied, the dtype for the input and output\n `Tensor`s will be converted to this.\n Default value: `None` which maps to the dtype inferred from\n `log_moneyness`.\n name: Python str. The name to give to the ops created by this function.\n Default value: `None` which maps to `svi_parameterization`.\n\n Returns:\n A rank 2 real `Tensor` of shape [batch_size, num_strikes].\n \"\"\"\n name = name or 'svi_parameterization'\n with tf.name_scope(name):\n log_moneyness = tf.convert_to_tensor(\n log_moneyness, dtype=dtype, name='log_moneyness')\n dtype = dtype or log_moneyness.dtype\n\n svi_parameters = tf.convert_to_tensor(\n svi_parameters, dtype=dtype, name='svi_parameters')\n # Introduce standard aliases, same as in [1]. Keep the length 1 rightmost\n # dimension of SVI parameters for broadcasting compatibility in the formula.\n a = svi_parameters[..., 0:1]\n b = svi_parameters[..., 1:2]\n rho = svi_parameters[..., 2:3]\n m = svi_parameters[..., 3:4]\n sigma = svi_parameters[..., 4:5]\n k = log_moneyness\n\n return a + b * (rho * (k - m) + tf.sqrt((k - m)**2 + sigma**2))\n"
]
| [
[
"tensorflow.compat.v2.name_scope",
"tensorflow.compat.v2.sqrt",
"tensorflow.compat.v2.convert_to_tensor"
]
]
|
Ahnkyuwon504/Poly_AI | [
"a3e15c93056e3701967bb606b3f48b0fb306d4e2"
]
| [
"testPythonProject1/singleiTest.py"
]
| [
"#####################################\n# 학습 모듈 선언\n#####################################\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#####################################\n# 환경설정\n#####################################\n# 훈련용 데이터 수 선언\ntrainDataNumber = 100\n# 모델 최적화를 위한 학습률 선언\nlearningRate = 0.01\n# 총 학습 횟수 선언\ntotalStep = 1001\n\n#####################################\n# 빌드단계\n# Step 1) 학습 데이터 준비\n#####################################\n# 항상 같은 난수를 생성하기 위하여 시드설정\nnp.random.seed(321)\n\n# 학습 데이터 리스트 선언\nxTrainData = list()\nyTrainData = list()\n\n# 학습 데이터 생성\nxTrainData = np.random.normal(0.0, 1.0, size=trainDataNumber)\n\nfor x in xTrainData:\n # y 데이터 생성\n y = 10 * x + 3 + np.random.normal(0.0, 3)\n yTrainData.append(y)\n\n# 학습 데이터 확인\n\nplt.plot(xTrainData, yTrainData, 'bo')\nplt.title(\"Train data\")\nplt.show()\n\n#####################################\n# 빌드단계\n# Step 2) 모델 생성을 위한 변수 초기화\n#####################################\n# Weight 변수 선언\nW = tf.Variable(tf.random.uniform([1]))\n# Bias 변수 선언\nb = tf.Variable(tf.random.uniform([1]))\n\n# 학습데이터 xTrainData 가 들어갈 플레이스 홀더 선언\nX = tf.compat.v1.placeholder(tf.float32)\n# 학습데이터 yTrainData 가 들어갈 플레이스 홀더 선언\nY = tf.compat.v1.placeholder(tf.float32)\n\n#####################################\n# 빌드단계\n# Step 3) 학습 모델 그래프 구성\n#####################################\n# 3-1) 학습데이터를 대표 하는 가설 그래프 선언\n# 방법 1 : 일반 연산기호를 이용하여 가설 수식 작성\nhypothesis = W * X + b\n# 방법 2 : tensorflow 함수를 이용하여 가설 수식 작성\n# hypothesis = tf.add(tf.multiply(W,X), b)\n\n# 3-2) 비용함수(오차함수, 손실함수) 선언\ncostFunction = tf.reduce_mean(tf.square(hypothesis - Y))\n\n# 3-3) 비용함수의 값이 최소가 되도록 하는 최적화함수 선언\noptimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=learningRate)\ntrain = optimizer.minimize(costFunction)\n\n#####################################\n# 실행단계\n# 학습 모델 그래프를 실행\n#####################################\n# 실행을 위한 세션 선언\nsess = tf.compat.v1.Session()\n# 최적화 과정을 통하여 구해질 변수 W, b 초기화\nsess.run(tf.compat.v1.global_variables_initializer())\n\n# 비용함수 그래프를 그리기 위한 변수 선언\nWeightValueList = list()\ncostFunctionValueList = list()\n\nprint(\"-----------------------------------------\")\nprint(\"Train(Optimization) Start \")\n\n# totalStep 횟수 만큼 학습\nfor step in range(totalStep):\n # X, Y에 학습 데이터 입력하여 비용함수, W, b, train 실행\n cost_val, W_val, b_val, _ = sess.run([costFunction, W, b, train],\n feed_dict={X: xTrainData,\n Y: yTrainData})\n # 학습 결과값 저장\n WeightValueList.append(W_val)\n costFunctionValueList.append(cost_val)\n # 학습 50회 마다 중간 결과 출력\n if step % 50 == 0:\n print(\"Step : {}, cost : {}, W : {}, b : {}\".format(step,\n cost_val,\n W_val,\n b_val))\n # 학습 100회 마다 중간 결과 Fitting Line 추가\n if (step % 100 == 0):\n plt.plot(xTrainData,\n W_val * xTrainData + b_val,\n label='Step : {}'.format(step),\n linewidth=0.5)\n\nprint(\"Train Finished\")\nprint(\"-----------------------------------------------\")\nprint(\"[Train Result]\")\n# 최적화가 끝난 학습 모델의 비용함수 값\ncost_train = sess.run(costFunction, feed_dict={X: xTrainData,\n Y: yTrainData})\n# 최적화가 끝난 W, b 변수의 값\nw_train = sess.run(W)\nb_train = sess.run(b)\nprint(\"Train cost : {}, W : {}, b : {}\".format(cost_train, w_train, b_train))\nprint(\"------------------------------------------------\")\nprint(\"[Test Result]\")\n# 테스트 위하여 x값 선언\ntestXValue = [2.5]\n# 최적화된 모델에 x에 대한 y 값 계산\nresultYValue = sess.run(hypothesis, feed_dict={X: testXValue})\n# 테스트 결과 출력\nprint(\"x value is : {}, y value is : {}\".format(testXValue, resultYValue))\nprint(\"-----------------------------------------------\")\n\n# matplotlib 이용 결과 시각화\n# 결과 확인 그래프\nplt.plot(xTrainData,\n sess.run(W) * xTrainData + sess.run(b),\n 'r',\n label='Fitting Line',\n linewidth=2)\nplt.plot(xTrainData,\n yTrainData,\n 'bo',\n label='Train data')\nplt.legend()\nplt.title(\"Train Result\")\nplt.show()\n\n# 비용함수 최적화 그래프\nplt.plot(WeightValueList, costFunctionValueList)\nplt.title(\"costFunction curve\")\nplt.xlabel(\"Weight\")\nplt.ylabel(\"costFunction value\")\nplt.show()\n\n# 세션 종료\nsess.close()\n\n\n\n\n\n\n\n\n\n\n\n"
]
| [
[
"tensorflow.compat.v1.placeholder",
"numpy.random.normal",
"tensorflow.compat.v1.global_variables_initializer",
"numpy.random.seed",
"tensorflow.compat.v1.train.GradientDescentOptimizer",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend",
"tensorflow.random.uniform",
"tensorflow.compat.v1.Session",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.show",
"tensorflow.square"
]
]
|
dli-invest/fin_news_nlp | [
"a7d18348f6cf6ebde3ff0f964d73d4ce5117ea4a"
]
| [
"scrappers/get_tickers.py"
]
| [
"\"\"\"\n Grab stocks from cad tickers \n\"\"\"\nimport pandas as pd\n\n\nclass TickerControllerV2:\n \"\"\"\n Grabs cad_tickers dataframes and normalized them\n \"\"\"\n\n def __init__(self, cfg: dict):\n \"\"\"\n Extract yahoo finance tickers from website\n Consider using hardcoded csvs sheets for the tickers to\n increase speed, no need to grab all data dynamically.\n \"\"\"\n self.yf_tickers = []\n default_url = cfg.get(\"default_url\", \"https://raw.githubusercontent.com/FriendlyUser/cad_tickers_list/main/static/latest/stocks.csv\")\n # import csv from github\n ticker_df = pd.read_csv(default_url)\n # searchfor = [\".WT\", \".UN\"]\n # ticker_df = ticker_df[~ticker_df.symbol.str.contains('|'.join(searchfor))]\n # purge tickers with .WT\n tickers_config = cfg.get(\"tickers_config\", None)\n us_df = pd.DataFrame()\n if tickers_config != None:\n industries = tickers_config.get(\"industries\")\n if industries != None:\n ticker_df = ticker_df[ticker_df[\"industry\"].isin(industries)]\n price_filter = tickers_config.get(\"price\", 5E5)\n ticker_df = ticker_df[ticker_df[\"price\"] < price_filter]\n market_cap_filter = tickers_config.get(\"market_cap\", 1E15)\n ticker_df = ticker_df[ticker_df[\"MarketCap\"] < market_cap_filter]\n if industries != None:\n ticker_df = ticker_df[ticker_df[\"industry\"].isin(industries)]\n\n # get symbols from tickers\n ytickers_series = ticker_df.apply(self.ex_to_yahoo_ex, axis=1)\n ytickers = ytickers_series.tolist()\n if us_df.empty == False:\n us_ytickers_series = us_df.apply(self.ex_to_yahoo_ex, axis=1)\n us_ytickers = us_ytickers_series.tolist()\n ytickers = [*ytickers, *us_ytickers]\n self.yf_tickers = ytickers\n\n def get_ytickers(self) -> list:\n return self.yf_tickers\n\n @staticmethod\n def ex_to_yahoo_ex(row: pd.Series) -> str:\n \"\"\"\n Parameters:\n ticker: ticker from pandas dataframe from cad_tickers\n exchange: what exchange the ticker is for\n Returns:\n \"\"\"\n ticker = str(row[\"symbol\"])\n exchange = row[\"exShortName\"]\n if exchange == \"CSE\":\n # strip :CNX from symbol\n ticker = ticker.replace(\":CNX\", \"\")\n \n # Missing a exchange code\n if exchange in [\"OTCPK\", \"NYSE\", \"NASDAQ\", \"NYE\", \"NCM\", \"NSM\", \"NGS\"]:\n ticker = ticker.replace(\":US\", \"\")\n ticker = ticker.replace(\":US\", \"\")\n # 1min, 5min, 15min, 30min, 60min, daily, weekly, monthly\n switcher = {\"TSXV\": \"V\", \"TSX\": \"TO\", \"CSE\": \"CN\"}\n yahoo_ex = switcher.get(exchange, None)\n if yahoo_ex != None:\n return f\"{ticker}.{yahoo_ex}\"\n return ticker"
]
| [
[
"pandas.DataFrame",
"pandas.read_csv"
]
]
|
Sharmadisha1608/Machine-Learning | [
"b3d43b417d553c5a7f56b8c88dd5e01aa6fd9a13"
]
| [
"face_answer.py"
]
| [
"import cv2\r\nimport numpy as np\r\nimport os\r\ndef distance(v1,v2):\r\n return np.sqrt(((v1-v2)**2).sum())\r\ndef knn(train,test,k=5):\r\n dist=[]\r\n for i in range(train.shape[0]):\r\n ix=train[i,:-1]\r\n iy=train[i,-1]\r\n d=distance(test,ix)\r\n dist.append([d,iy])\r\n dk=sorted(dist,key=lambda x:x[0])[:k]\r\n labels=np.array(dk)[:,-1]\r\n output=np.unique(labels,return_counts=True)\r\n index=np.argmax(output[1])\r\n return output[0][index]\r\ncap=cv2.VideoCapture(0)\r\nface_cascade = cv2.CascadeClassifier(\"C:\\\\Users\\\\hp\\\\anaconda3\\\\Lib\\\\site-packages\\\\cv2\\\\data\\\\haarcascade_frontalface_alt.xml\")\r\nskip=0\r\ndataset_path=\"C:\\\\Users\\\\hp\\\\Documents\\\\faces\\\\\"\r\nface_data=[]\r\nlabels=[]\r\nclass_id=0\r\nnames={}\r\nfor fx in os.listdir(dataset_path):\r\n if fx.endswith('.npy'):\r\n names[class_id]=fx[:-4]\r\n print(\"Loaded\"+fx)\r\n data_item=np.load(dataset_path+fx)\r\n face_data.append(data_item)\r\n target=class_id *np.ones((data_item.shape[0],))\r\n class_id+=1\r\n labels.append(target)\r\nface_dataset=np.concatenate(face_data,axis=0)\r\nface_labels=np.concatenate(labels,axis=0).reshape((-1,1))\r\nprint(face_dataset.shape)\r\nprint(face_labels.shape)\r\n\r\ntrainset=np.concatenate((face_dataset,face_labels),axis=1)\r\nprint(trainset.shape)\r\nwhile True:\r\n ret,frame=cap.read()\r\n if ret==False:\r\n continue\r\n faces=face_cascade.detectMultiScale(frame,1.3,5)\r\n for face in faces:\r\n x,y,w,h=face\r\n offset=10\r\n face_section=frame[y-offset:y+h+offset,x-offset:x+w+offset]\r\n face_section=cv2.resize(face_section,(100,100))\r\n \r\n out=knn(trainset,face_section.flatten())\r\n pred_name=names[int(out)]\r\n cv2.putText(frame,pred_name,(x,y-10),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0),2,cv2.LINE_AA)\r\n cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)\r\n cv2.imshow(\"Face\",frame) \r\n key_pressed=cv2.waitKey(1) & 0xFF\r\n if key_pressed == ord('q'):\r\n break\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n"
]
| [
[
"numpy.concatenate",
"numpy.array",
"numpy.ones",
"numpy.load",
"numpy.argmax",
"numpy.unique"
]
]
|
ScienceStacks/MicrobEPy | [
"704435e66c58677bab24f27820458870092924e2"
]
| [
"microbepy/tests/model/test_cv_model.py"
]
| [
"from microbepy.common import constants as cn\nfrom microbepy.common import helpers\nfrom microbepy.common import util\nfrom microbepy.data import util_data as ud\nfrom microbepy.model.cv_regression import CVLinearRegression\nfrom microbepy.model.group_splitter import GroupSplitter\n\nimport numpy as np\nimport pandas as pd\nimport random\nimport unittest\n\n\nIGNORE_TEST = False\nCOL_A = 'a'\nCOL_B = 'b'\nCOL_C = 'c'\nCOL_Y = 'y'\nSIZE = 100\nDATA_A = [random.normalvariate(0,1) for _ in range(SIZE)]\nDATA_B = [random.normalvariate(0,1) for _ in range(SIZE)]\nDF_X = pd.DataFrame({\n COL_A: DATA_A,\n COL_B: DATA_B,\n })\nCONST_A = 7\nCONST_B = 5\nDF_Y = pd.DataFrame({\n COL_Y: [CONST_A*x + CONST_B*y for x,y in zip(DATA_A, DATA_B)]\n })\nDF_GROUP = pd.DataFrame({\n COL_A: [\"a\" + str(n) for n,_ in enumerate(DATA_A)],\n COL_B: [\"b\" + str(n) for n,_ in enumerate(DATA_A)],\n })\nNUM_FOLDS = 2\n\n\n################### HELPERS ########################\ndef dotestCVR(cvr):\n \"\"\"\n :param CVRegression cvr:\n :return dict: boolean values\n \"\"\"\n result = {}\n cvr.fit()\n result['test3'] = helpers.isValidDataFrame(\n cvr.df_parameter, [cn.AVG, cn.STD, cn.COUNT])\n # df_parameter\n model = cvr.fitted_models[0]\n params = cvr.df_parameter.index.tolist()\n params.remove(cn.RSQ)\n for param in params:\n std = cvr.df_parameter.loc[param, cn.STD]\n result[param] = std < 0.01\n # df_predict\n result['test2'] = cvr.score > 0.95\n for key in result.keys():\n if not result[key]:\n import pdb; pdb.set_trace()\n pass\n return result\n \n\n\n################### TEST CLASSES ########################\nclass TestCVModel(unittest.TestCase):\n\n def setUp(self):\n self.g_splitter = GroupSplitter(DF_X, DF_Y, DF_GROUP,\n num_folds=NUM_FOLDS)\n\n def testConstructor(self):\n if IGNORE_TEST:\n return\n cvr = CVLinearRegression(self.g_splitter)\n self.assertIsNone(cvr.df_parameter)\n\n def testFit(self):\n if IGNORE_TEST:\n return\n def test(cvr):\n results = dotestCVR(cvr)\n self.assertTrue(all(results.values()))\n #\n g_splitter = GroupSplitter(DF_X, DF_Y, DF_GROUP,\n num_folds=NUM_FOLDS)\n cvr = CVLinearRegression(g_splitter, fit_intercept=False, copy_X=True)\n test(cvr)\n\n def testFindSignificantParameters(self):\n if IGNORE_TEST:\n return\n g_splitter = GroupSplitter(DF_X, DF_Y, DF_GROUP,\n num_folds=NUM_FOLDS)\n cvr = CVLinearRegression(g_splitter, fit_intercept=False, copy_X=True)\n cvr.fit()\n parameters = cvr.findSignificantParameters()\n self.assertEqual(set(parameters), set([COL_A, COL_B]))\n \n\n\nif __name__ == '__main__':\n unittest.main()\n"
]
| [
[
"pandas.DataFrame"
]
]
|
MeriemSebai/MaskMitosis | [
"b61dea7dbadd3e0420464a626b4b55dc2dc83aff"
]
| [
"Mitosis12_segmentation_unsup/labels_generation.py"
]
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 22 20:42:31 2018\n\n@author: meriem\n\"\"\"\nimport os\nimport pickle\nimport numpy as np\nimport math\nfrom PIL import Image\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport matplotlib.cm as cm\nfrom shutil import copyfile\nfrom distutils.dir_util import copy_tree\nfrom scipy.ndimage.measurements import label\n\n\nsrc='./output/masks' # folder that contains all mitosis ground truth masks as np arrays\ndst='gt_train' # create an intermediate folder\nif not os.path.exists(dst):\n os.makedirs(dst)\nobjects = []\nfid=open('segmentation_train.txt','r')\nfor filename in fid: \n filename=filename.strip()\n f = np.loadtxt(os.path.join(src,filename))\n mask=np.zeros([f.shape[0],f.shape[1]])\n labeled_array, num_features = label(f)\n \n if num_features>0:\n indices = [np.nonzero(labeled_array == k) for k in np.unique(labeled_array)[1:]]\n lens=[ind[0].size for ind in indices]\n max_len=np.max(lens)\n max_ind=np.argmax(lens) \n for x,y in zip(indices[max_ind][0],indices[max_ind][1]):\n mask[x,y]=1\n obj_struct = {}\n obj_struct['imagename'] = ['{}_{}'.format(filename.split('_')[0],filename.split('_')[1])] \n obj_struct['det'] = mask\n src_f=filename.split('.')[0]\n obj_struct['coord'] = [int(src_f.split('_')[2]),int(src_f.split('_')[3]),int(src_f.split('_')[4]),int(src_f.split('_')[5])]\n objects.append(obj_struct)\n \nimagesetfile = 'train.txt'\nwith open(imagesetfile, 'r') as f:\n lines = f.readlines()\nimagenames = [x.strip().split('/')[2] for x in lines]\n\n# create the segmented mask of the full image \nfor imagename in imagenames:\n objet = [obj for obj in objects if obj['imagename'][0]==imagename] \n mask=np.zeros([1376,1539]) \n for obj in objet:\n x1=obj['coord'][0]\n y1=obj['coord'][1]\n x2=obj['coord'][2]\n y2=obj['coord'][3] \n m=obj['det'] \n mask[y1:y2,x1:x2]=m \n plt.imsave(os.path.join(dst,'{}.jpg'.format(imagename)), mask, cmap=cm.gray)\n \nsrc='./gt_train' \ndst='./gtImg' \nif not os.path.exists(dst):\n os.makedirs(dst) \nfor f in os.listdir(src): \n src_file=os.path.join(src,f)\n name=f.split('.')[0].split('_')[0]\n directory_name = os.path.join(dst,name)\n if not os.path.exists(directory_name):\n os.makedirs(directory_name)\n dst_file=os.path.join(directory_name,f)\n copyfile(src_file, dst_file)\n\n \n\n \n \n"
]
| [
[
"numpy.max",
"numpy.zeros",
"numpy.nonzero",
"scipy.ndimage.measurements.label",
"numpy.argmax",
"numpy.unique"
]
]
|
jsubercaze/iot-tweet-search-engine | [
"731fe1aed1da40cab7cb183210ff3fe1e6491097"
]
| [
"user.py"
]
| [
"import os\n\nimport networkx as nx\nimport numpy as np\n\nfrom definitions import ROOT_DIR\nfrom parser import Parser\nfrom prediction_profile import PredictionProfile\nfrom topics_classifier import TopicsClassifier\n\n\nclass User:\n\tuser_fname = os.path.join(ROOT_DIR, 'saved_models/users_profile.tsv')\n\tauthor_fname = os.path.join(ROOT_DIR, 'saved_models/authors_profile.tsv')\n\tuser_graph_path = os.path.join(ROOT_DIR, 'corpus/author_graph.net')\n\n\tdef __init__(self, id=None, nb_click=0, vector=np.zeros(300), localisation='', gender='', emotion='',\n\t\t\t\t topic_vector=np.asarray([]), centrality=0., vec_size=300):\n\n\t\tself.id = None\n\n\t\tif id is None:\n\t\t\tself.id = self.next_id()\n\t\t\tself.vec = np.zeros(vec_size)\n\t\t\tself.nb_click = 0\n\t\t\tself.localisation = ''\n\t\t\tself.gender = ''\n\t\t\tself.emotion = ''\n\t\t\tself.topic_vector = np.asarray([])\n\t\t\tself.centrality = 0.\n\t\telse:\n\t\t\tself.id = id\n\t\t\tself.vec = vector\n\t\t\tself.nb_click = nb_click\n\t\t\tself.localisation = localisation\n\t\t\tself.gender = gender\n\t\t\tself.emotion = emotion\n\t\t\tself.topic_vector = topic_vector\n\t\t\tself.centrality = centrality\n\n\t\tself.prediction_profile = None\n\t\tself.topic_classifier = None\n\n\tdef set_prediction_profile(self, pp):\n\t\tself.prediction_profile = pp\n\n\tdef set_topic_classifier(self, tpc):\n\t\tself.topic_classifier = tpc\n\n\tdef get_prediction_profile(self):\n\t\tif self.prediction_profile is None:\n\t\t\tself.prediction_profile = PredictionProfile()\n\n\t\treturn self.prediction_profile\n\n\tdef get_topic_classifier(self):\n\t\tif self.topic_classifier is None:\n\t\t\tself.topic_classifier = TopicsClassifier()\n\n\t\treturn self.topic_classifier\n\n\tdef predict_profile(self):\n\t\t\"\"\"\n\t\tCall all the predictions models to fill the localisation, gender, etc\n\t\t:return:\n\t\t\"\"\"\n\n\t\tself.localisation = self.get_prediction_profile().country_prediction(self.vec)\n\t\tself.gender = self.get_prediction_profile().gender_prediction(self.vec)\n\t\tself.emotion = self.get_prediction_profile().sentiment_prediction(self.vec)\n\t\tself.topic_vector = self.get_topic_classifier().predict(self.vec.reshape(1, -1))[0]\n\n\tdef update_profile(self, vec, predict=True):\n\t\t\"\"\"\n\t\tUpdate the profile of the user with the new vec param\n\t\t:param vec: (np.array) vector of the tweet to add\n\t\t:param predict: (boolean) whether to predict localisation, gender, etc or not\n\t\t:return:\n\t\t\"\"\"\n\t\tself.nb_click += 1\n\t\tfor i in range(len(self.vec)):\n\t\t\tself.vec[i] = (self.vec[i] * (self.nb_click - 1)) / self.nb_click + (vec[i] / self.nb_click)\n\n\t\tif predict:\n\t\t\tself.predict_profile()\n\n\tdef save(self):\n\t\t\"\"\"\n\t\tSave the user in the corresponding file\n\t\t:return:\n\t\t\"\"\"\n\t\tusers_data = {} # user_id => line\n\n\t\tself.create_files()\n\t\tf = open(User.user_fname if type(self.id) is int else User.author_fname, \"r\")\n\t\tcontents = f.readlines()\n\n\t\tfor j in range(1, len(contents)):\n\t\t\titems = contents[j].split('\\t')\n\t\t\tid = int(items[0]) if type(self.id) is int else items[0]\n\t\t\tusers_data[id] = j\n\t\tf.close()\n\n\t\tto_insert = str(self.id) + '\\t' + str(self.nb_click) + '\\t' + str(\n\t\t\tlist(self.vec)) + '\\t' + self.localisation + '\\t' + self.gender + '\\t' + self.emotion + '\\t' + str(\n\t\t\tlist(self.topic_vector)) + (('\\t' + str(self.centrality)) if type(self.id) is str else '') + '\\n'\n\n\t\t# if the id is not in the file\n\t\tif self.id not in users_data:\n\t\t\tcontents.append(to_insert)\n\t\telse:\n\t\t\tcontents[users_data[self.id]] = to_insert\n\n\t\tf = open(User.user_fname if type(self.id) is int else User.author_fname, \"w\")\n\t\tfor l in contents:\n\t\t\tf.write(l)\n\t\tf.close()\n\n\tdef load(self):\n\t\t\"\"\"Load the user from the corresponding file of do nothing\"\"\"\n\t\tassert self.id is not None\n\n\t\tself.create_files()\n\t\tf = open(User.user_fname if type(self.id) is int else User.author_fname, \"r\")\n\t\tlines = f.readlines()\n\t\tfor i in range(1, len(lines)):\n\t\t\tl = lines[i][:-1]\n\t\t\titems = l.split('\\t')\n\t\t\tif items[0] == str(self.id):\n\t\t\t\tself.nb_click = int(items[1])\n\t\t\t\tself.vec = np.asarray([float(x) for x in items[2][1:-1].split(', ')])\n\t\t\t\tself.localisation = items[3]\n\t\t\t\tself.gender = items[4]\n\t\t\t\tself.emotion = items[5]\n\t\t\t\tself.topic_vector = np.asarray([]) if items[6] == '[]' else np.asarray(\n\t\t\t\t\t[float(x) for x in items[6][1:-1].split(', ')])\n\t\t\t\tif type(id) is str:\n\t\t\t\t\tself.centrality = float(items[7])\n\t\t\t\tf.close()\n\t\t\t\treturn\n\n\tdef next_id(self):\n\t\t\"\"\"Get the max +1 id in the file\"\"\"\n\t\tself.create_files()\n\t\tf = open(User.user_fname, \"r\")\n\t\tcontents = f.readlines()\n\t\tif len(contents) == 1:\n\t\t\treturn 1\n\t\treturn int(contents[-1].split('\\t')[0]) + 1\n\n\t@staticmethod\n\tdef get_all_authors():\n\t\t\"\"\"\n\t\tFetch all the authors from the tweets\n\t\t:return:\n\t\t\"\"\"\n\t\tusers = []\n\t\tfile = open(User.author_fname, \"r\")\n\t\tlines = file.readlines()\n\t\tfor i in range(1, len(lines)):\n\t\t\tline = lines[i]\n\t\t\titems = line.split('\\t')\n\t\t\tu = User(\n\t\t\t\tid=items[0],\n\t\t\t\tnb_click=int(items[1]),\n\t\t\t\tvector=np.asarray([float(x) for x in items[2][1:-1].split(', ')]),\n\t\t\t\tlocalisation=items[3],\n\t\t\t\tgender=items[4],\n\t\t\t\temotion=items[5],\n\t\t\t\ttopic_vector=np.asarray([]) if items[6] == '[]' else np.asarray(\n\t\t\t\t\t[float(x) for x in items[6][1:-1].split(', ')]),\n\t\t\t\tcentrality=float(items[7])\n\t\t\t)\n\t\t\tusers.append(u)\n\t\tfile.close()\n\t\treturn users\n\n\tdef create_files(self):\n\t\t\"\"\"\n\t\tCreate the users and authors files if they don't exists\n\t\t:return:\n\t\t\"\"\"\n\t\tif (type(self.id) is int or self.id is None) and not os.path.exists(User.user_fname):\n\t\t\tf = open(User.user_fname, 'w+')\n\t\t\tf.write('User_Name\\tNbClick\\tVector\\tLocalisation\\tGender\\tEmotion\\tTopicVector\\tCentrality\\n')\n\t\t\tf.close()\n\n\t\tif type(self.id) is str and not os.path.exists(User.author_fname):\n\t\t\tf = open(User.author_fname, 'w+')\n\t\t\tf.write('User_Name\\tNbClick\\tVector\\tLocalisation\\tGender\\tEmotion\\tTopicVector\\tCentrality\\n')\n\t\t\tf.close()\n\n\t@staticmethod\n\tdef create_authors(corpus):\n\t\t\"\"\"\n\t\tGenerate the authors_profile.tsv file\n\t\tTo perform just ONE time\n\t\t:type corpus: pandas.DataFrame\n\t\t:return:\n\t\t\"\"\"\n\n\t\ttpc = TopicsClassifier(pd_corpus=corpus)\n\t\tpp = PredictionProfile(pd_corpus=corpus)\n\n\t\tfor index, tweet in corpus.iterrows():\n\t\t\tu = User(tweet.User_Name)\n\t\t\tu.load()\n\t\t\tu.update_profile(tweet.Vector, predict=False)\n\t\t\tu.save()\n\n\t\tgraph = User.load_graph()\n\t\tcentralities = nx.eigenvector_centrality(graph)\n\t\tfor author in User.get_all_authors():\n\t\t\tauthor.centrality = centralities[author.id] if author.id in centralities else 0.\n\t\t\tauthor.set_prediction_profile(pp)\n\t\t\tauthor.set_topic_classifier(tpc)\n\t\t\tauthor.predict_profile()\n\t\t\tauthor.save()\n\t\treturn\n\n\t@staticmethod\n\tdef load_graph(filename=user_graph_path):\n\t\treturn nx.DiGraph(nx.read_adjlist(filename))\n\n\nif __name__ == '__main__':\n\tcorpus = Parser.parsing_iot_corpus_pandas(os.path.join(ROOT_DIR, 'corpus/iot-tweets-vector-v31.tsv'))\n\tprint('Corpus Loaded')\n\tUser.create_authors(corpus)\n"
]
| [
[
"numpy.asarray",
"numpy.zeros"
]
]
|
lukasjarzembowski/Fura2-Calcium-Analysis | [
"f3c58ad0ab5151d5886b23a4a2d57c7f01ef5a3c"
]
| [
"calciumfunctions.py"
]
| [
"import os\nimport pandas as pd\nfrom scipy import stats\nimport dabest\nimport dask.dataframe as dd\n\ndef importrawdata(folderpath, runtime=None, dropcolumns=None, folder=True, name=None):\n #declare an empty dataframe and list for filenames\n targetdf = pd.DataFrame()\n files = []\n\n\n if folder is False:\n if folderpath.endswith(\".xlsx\"):\n files.append(folderpath)\n else:\n print(\"File type is currently not supported (.xlsx only)\")\n\n if folder is True:\n for entry in os.scandir(folderpath):\n if entry.name.endswith(\".xlsx\"):\n files.append(entry)\n else:\n pass\n\n for file in files:\n if folder is False:\n openfile = pd.read_excel(folderpath)\n elif folder is True:\n filepath = folderpath + file.name\n openfile = pd.read_excel(filepath)\n\n if dropcolumns is not None:\n openfile = openfile.drop(columns=[dropcolumns])\n\n if runtime is not None:\n openfile = openfile.truncate(after=runtime, axis=0)\n\n if folder is False:\n openfile.columns = [str(cols) for cols in range(len(openfile.columns))]\n openfile = openfile.add_prefix(file.replace('xlsx',''))\n\n if folder is True:\n openfile.columns = [str(cols) for cols in range(len(openfile.columns))]\n openfile = openfile.add_prefix(file.name.replace('xlsx',''))\n\n targetdf = pd.concat([targetdf, openfile], axis=1)\n\n if name is not None:\n targetdf.name = str(name)\n\n print(len(files), \"files have been successfully imported from\", folderpath, \"into a DataFrame with following shape (rows x columns):\", targetdf.shape)\n return targetdf\n\ndef filterdata(inputdf, threshold=None):\n #based on https://stackoverflow.com/questions/36992046/pandas-dropping-columns-based-on-value-in-last-row\n initialmean = inputdf.iloc[1,:].mean(axis=0)\n initialsd = inputdf.iloc[1,:].std(axis=0)\n if threshold is None:\n threshold = initialmean + initialsd\n mask = inputdf.head(1).squeeze() < threshold\n if threshold is not None:\n mask = inputdf.head(1).squeeze() < threshold\n\n filtered = inputdf.loc[:,mask]\n\n lengthinput = len(inputdf.columns)\n lengthfiltered = len(filtered.columns)\n delta_len = lengthinput - lengthfiltered\n\n try:\n print('Dataframe:', str(inputdf.name))\n except AttributeError:\n print('Dataframe is unnamed')\n print('Initital Mean: ' + str(initialmean) + '. Initial SD: ' + str(initialsd))\n print('Threshold: ' + str(threshold))\n print('Dataframe was filtered')\n print(str(delta_len) + ' cells were removed')\n print('\\n')\n\n return filtered\n\n\ndef measurementavgs(filtered_df, path):\n #get list of all filenames\n files = os.listdir(path)\n #create a new dataframe that stores all averaged data\n avg = pd.DataFrame()\n #for every file in raw folder search for\n #corresponding column in filtered data\n for file in files:\n #remove the .xlsx ending from filename to find the right column\n filename = file.replace('.xlsx','')\n #store mean of rows at each timepoint for all cells the measurement\n mean = filtered_df.filter(regex=filename).mean(axis=1)\n #attached the calculated mean dataframe to the avg dataframe\n avg = pd.concat([avg,mean], axis=1)\n\n\n #make a list of filenames without the .xlsx ending to change column names in avg\n cleanednames = []\n for file in files:\n file = str(file.replace(\".xlsx\", \"\"))\n cleanednames.append(file)\n avg.columns = cleanednames\n\n print('Averages single measurements succesfully calculated!')\n\n return avg\n\ndef calc_totalmean(inputdf, avgs=None):\n totalmeandf=pd.DataFrame()\n totalmeans = inputdf.mean(axis=1)\n totalsd = inputdf.std(axis=1)\n totalSEM = inputdf.sem(axis=1)\n totalnumber = len(inputdf.columns)\n totalmeandf = pd.concat([totalmeans,totalsd,totalSEM], axis=1)\n totalmeandf.columns = ['total_mean','total_sd','total_SEM']\n totalmeandf['number of cells'] = \"\"\n totalmeandf.at[0,'number of cells']= totalnumber\n if avgs is not None:\n avgofavgs = avgs.mean(axis=1)\n sdofavgs = avgs.std(axis=1)\n semofavgs = avgs.sem(axis=1)\n avgofavgs = pd.DataFrame(avgofavgs)\n sdofavgs = pd.DataFrame(sdofavgs)\n semofavgs = pd.DataFrame(semofavgs)\n avgofavgs.columns = ['avgs_mean']\n sdofavgs.columns = ['avgs_sd']\n semofavgs.columns = ['avgs_sem']\n avgstats = pd.concat([avgofavgs,sdofavgs,semofavgs], axis=1)\n\n totalmeandf = pd.concat([totalmeandf,avgstats], axis=1)\n return totalmeandf\n\n else:\n return totalmeandf\n\n print('Means succesfully calculated!')\n\n#change inputdf to a new df that gets returned\ndef calc_mean(inputdf,start,stop):\n inputdf = inputdf.iloc[start:stop,:].mean(axis=0)\n return inputdf\n\ndef calc_max(inputdf,start,stop):\n inputdf = inputdf.iloc[start:stop,:].max(axis=0)\n return inputdf\n\ndef calc_slope(inputdf,start,stop):\n diff = [start, stop] #start and stop of the frames to fit in between\n diff = diff[1] - diff[0] #differences = length of the frames where to fit\n\n x=[] #to do a line fit you need corresponding x values = the number of frames you want to fit your data\n for i in range(diff):\n x.append(i) #creates an array/list that contains as many numbers from 0 till n as needed for the fit as x axis\n slopes = []\n rsqrd = []\n influx = inputdf.iloc[start:stop,:]\n for column in influx.columns:\n slope, intercept, r_value, p_value, std_err = stats.linregress(x, influx[column])\n slopes.append(slope)\n r = r_value ** 2\n rsqrd.append(r)\n return slopes, rsqrd\n\ndef calc_auc(filtereddf, start, stop):\n#calculate the area under the curve using the sklearn metrics.auc function\n#for every column between the specified timepoints = rows\n#added 2020-04-17, also added to ca_analysis function\n column_list = list(filtereddf)\n x = np.arange(0,stop-start)\n auc_list = []\n for i in range(0,len(filtereddf.columns)):\n auc = metrics.auc(x,filtereddf.iloc[start:stop,i])\n auc_list.append(auc)\n return auc_list\n\ndef ca_analysis(filtereddf, parameters_dict, avgs=None):\n results = pd.DataFrame()\n tempdf = pd.DataFrame()\n if avgs is not None:\n for i in avgs:\n filtereddf = filtereddf.drop(columns=[i])\n\n for key in parameters_dict.keys():\n templist = parameters_dict[key]\n\n if len(templist) == 3:\n\n if templist[2] == 'mean':\n tempmeandf = pd.DataFrame()\n tempmeandf[key] = calc_mean(filtereddf,templist[0], templist[1])\n tempdf = pd.concat([tempdf,tempmeandf], axis=1)\n\n elif templist[2] == 'max':\n tempmaxdf = pd.DataFrame()\n tempmaxdf[key] = calc_max(filtereddf,templist[0],templist[1])\n tempdf = pd.concat([tempdf, tempmaxdf], axis=1)\n\n elif templist[2] == 'delta':\n tempdf[key] = tempdf[templist[0]] - tempdf[templist[1]]\n\n elif templist[2] == 'slope':\n slopes, rvalues = calc_slope(filtereddf,templist[0],templist[1])\n tempdf['slope'] = slopes\n tempdf['rsqrd'] = rvalues\n\n elif templist[2] == 'auc':\n tempdf['auc'] = calc_auc(filtereddf, templist[0], templist[1])\n\n else:\n print('Please make sure your parameter ' + str(key) + ' ranges are marked with \"mean\", \"max\", \"slope\", \"auc\" or \"delta\"')\n\n else:\n print('Please make sure your parameter ' + str(key) + ' has following format: \"parameter\": [frame number start, frame number stop, \"operation\"] or: \"parameter\": [parameter b, parameter a, \"delta\"] when calculating deltas = b-a')\n\n print('Kinetics succesfully calculated!')\n\n return tempdf\n\ndef loaddata(data1, data2, parameter, name1, name2, rsmpls=None):\n temp = pd.concat([data1[parameter], data2[parameter]], axis=1, sort=True)\n temp.columns = [name1, name2]\n if rsmpls is not None:\n bootstrap = dabest.load(temp, idx=(name1, name2), resamples=rsmpls)\n else:\n bootstrap = dabest.load(temp, idx=(name1, name2))\n return bootstrap\n\ndef excelexport(datadict):\n outputname = datadict[\"filename\"]\n writer = pd.ExcelWriter(outputname)\n keylist = list(datadict.keys())[1:]\n for key in keylist:\n dftowrite = datadict[key]\n dftowrite.to_excel(writer, sheet_name=key)\n writer.save()\n print(outputname, \"with\", len(datadict)-1, \"sheets has been saved\")\n\ndef normalize_data(inputdf):\n normalizeddf = inputdf.copy()\n column_list = list(normalizeddf)\n for column in column_list:\n first_value = normalizeddf[column].iloc[0]\n normalizeddf[column] = normalizeddf[column].apply(lambda x: x/first_value)\n return normalizeddf\n\n\ndef get_responders(inputdf, column_name, threshold = None):\n# select all rows in a column that are higher than a set threshold as responders\n# and those that are below that threshold as non_responders. If no threshold is passed,\n# the standard deviation of all values will be used as lower threshold\n# added 2020-01-07\n std = inputdf[column_name].std()\n mean = inputdf[column_name].mean()\n\n print(\"Mean:\", str(mean))\n print(\"SD:\", str(std))\n if threshold is None:\n mask = inputdf[column_name].squeeze() > std\n print(\"The threshold used:\", str(std))\n\n if threshold is not None:\n mask = inputdf[column_name].squeeze() > threshold\n print(\"The threshold used:\", str(threshold))\n\n responders = inputdf[column_name].loc[mask]\n non_responders = inputdf[column_name].loc[~mask]\n\n print(\"Total number of cells\", str(len(inputdf.index)))\n print(\"Number of responders:\", str(len(responders.index)))\n print(\"Number of non-responders:\", str(len(non_responders.index)))\n print(\"Percentage of responders:\", str(len(responders.index)/len(inputdf.index)*100))\n print('\\n')\n\n return responders, non_responders\n\ndef intensity_dataframe(timelapse_image,mask,name=None):\n from skimage import measure\n from skimage.measure import regionprops\n import numpy as np\n import pandas as pd\n\n #create empty dataframe\n intensity_df = pd.DataFrame()\n\n #count the number of unique ROIs and remove the background ROI 0\n rois = np.unique(mask).tolist()[1:]\n #create a list with numbered column name and use name argument as prefix if given\n if name is not None:\n col_list = [str(name)+'_roi_%d' % x for x in range(1,len(rois)+1)]\n else:\n col_list = ['roi_%s' % x for x in range(1,len(rois)+1)]\n\n #go through every single frame of the timelapse image\n for i in range(len(timelapse_image)):\n #for each frame clear the list of intensities\n intensity_list = []\n #save all region props in a list for every ROI in this particular frame\n props = regionprops(mask, intensity_image=timelapse_image[i])\n\n #get the mean intensity of every prop and save it to the intensity list\n for j in range(len(props)):\n intensity = props[j].mean_intensity\n intensity_list.append(intensity)\n\n #for each frame save the list of intensities as new row in the dataframe\n intensity_df = intensity_df.append(pd.DataFrame([intensity_list]))\n\n print(\"calculation of intensites for %s frames completed\" % str(len(timelapse_image)))\n\n #add the column names to the dataframe\n intensity_df.columns = col_list\n\n #reset the index and let it start from 1\n intensity_df.index = np.arange(1, len(intensity_df)+1)\n\n return intensity_df\n\ndef intensity_dataframe_long(timelapse_image,mask,measurement,name):\n from skimage import measure\n from skimage.measure import regionprops\n import numpy as np\n import pandas as pd\n\n #create empty dataframe\n intensity_df = pd.DataFrame()\n\n #go through every single frame of the timelapse image\n for i in range(len(timelapse_image)):\n #for each frame clear the list of intensities\n intensity_list = []\n #save all region props in a list for every ROI in this particular frame\n props = regionprops(mask, intensity_image=timelapse_image[i])\n\n #get the mean intensity of every prop and save it to the intensity list\n for j in range(len(props)):\n intensity = props[j].mean_intensity\n intensity_list.append(intensity)\n #\n #for each frame save the list of intensities as new row in the dataframe\n intensity_df = intensity_df.append(pd.DataFrame([intensity_list]))\n\n print(\"calculation of intensites for %s frames completed\" % str(len(timelapse_image)))\n\n #add the column names to the dataframe\n intensity_df[\"timepoint\"] = np.arange(len(timelapse_image))\n intensity_df[\"measurement\"] = measurement\n #reset the index and let it start from 1\n intensity_df.index = np.arange(1, len(intensity_df)+1)\n intensity_df = pd.melt(intensity_df, id_vars=[\"timepoint\", \"measurement\"], value_vars=intensity_df.columns[:-2], var_name=\"roi\")\n intensity_df[\"roi\"] += 1\n\n intensity_df.name = str(name)\n intensity_df[\"group\"]= name\n return intensity_df\n\ndef filterdata_long(inputdf, threshold=None):\n #this function was implemented with help of Jose A. Jimenez\n #https://stackoverflow.com/questions/62957110/pandas-selecting-multiple-rows-based-on-column-pair/\n initialmean = inputdf.loc[inputdf[\"timepoint\"] == 0].mean().array[-1]\n initialsd = inputdf.loc[inputdf[\"timepoint\"] == 0].std().array[-1]\n\n if threshold is None:\n threshold = initialmean + initialsd\n pre_activated_t0 = inputdf[(inputdf['timepoint'] == 0) & (inputdf['value'] > threshold)]\n if threshold is not None:\n pre_activated_t0 = inputdf[(inputdf['timepoint'] == 0) & (inputdf['value'] > threshold)]\n\n pre_activated = inputdf.merge(pre_activated_t0[[\"measurement\", \"roi\"]], how=\"inner\", on=[\"measurement\", \"roi\"])\n filtereddf = inputdf.merge(\n pre_activated,\n how=\"left\",\n on=[\"timepoint\", \"measurement\", \"roi\", \"value\"],\n )\n filtereddf = filtereddf[pd.isna(filtereddf[\"group_y\"])]\n\n filtereddf.drop(\"group_y\", axis=1, inplace=True)\n filtereddf.columns = list(inputdf.columns)\n\n length_input = len(inputdf[inputdf[\"timepoint\"]==0])\n length_filtered = len(filtereddf[filtereddf[\"timepoint\"]==0])\n delta = length_input - length_filtered\n\n try:\n print('Dataframe:', str(inputdf.name))\n except AttributeError:\n print('Dataframe is unnamed')\n print('Initital Mean: ' + str(initialmean) + '. Initial SD: ' + str(initialsd))\n print('Threshold: ' + str(threshold))\n print('Dataframe was filtered')\n print('Total cells: ' + str(length_input))\n print(str(delta) + ' cells were removed')\n print('\\n')\n\n return filtereddf, pre_activated\n\n\n\ndef calc_mean_melted(inputdf,start,stop):\n meandf = inputdf[(inputdf['timepoint'] >= start) & (inputdf['timepoint'] <= stop)].groupby([\"roi\",\"measurement\"]).agg([\"mean\"]).drop([\"timepoint\"],axis = 1)\n meandf.columns = [\"value\"]\n return meandf\n\ndef calc_max_melted(inputdf,start,stop):\n maxdf = inputdf[(inputdf['timepoint'] >= start) & (inputdf['timepoint'] <= stop)].groupby([\"roi\",\"measurement\"]).agg([\"max\"]).drop([\"timepoint\"],axis = 1)\n maxdf.columns = [\"value\",\"group\"]\n return maxdf\n\ndef calc_slope_melted(inputdf,start,stop):\n from scipy.stats import linregress\n subsectiondf = inputdf[(inputdf['timepoint'] >= start) & (inputdf['timepoint'] <= stop)]\n slope = subsectiondf.groupby([\"roi\",\"measurement\"]).apply(lambda v: linregress(v.timepoint, v.value)[0])\n rsqrd = subsectiondf.groupby([\"roi\",\"measurement\"]).apply(lambda v: linregress(v.timepoint, v.value)[2])**2\n slopedf = pd.DataFrame(slope)\n rsqrddf = pd.DataFrame(rsqrd)\n slopedf.columns = [\"value\"]\n rsqrddf.columns = [\"value\"]\n return slopedf, rsqrddf\n\ndef calc_auc_melted(inputdf,start,stop):\n from sklearn import metrics\n subsectiondf = inputdf.loc[(inputdf['timepoint'] >= start) & (inputdf['timepoint'] <= stop)]\n return subsectiondf.groupby([\"roi\",\"measurement\",\"group\"]).apply(lambda v: metrics.auc(v.timepoint, v.value)).drop([\"timepoint\",\"group\"],axis = 1)\n\n\n\ndef ca_analysis_long(filtereddf, parameters_dict,name=None):\n resultsdf = pd.DataFrame()\n result_dict={}\n\n for key in parameters_dict.keys():\n templist = parameters_dict[key]\n\n if len(templist) == 3:\n\n if templist[2] == 'mean':\n tempmeandf = calc_mean_melted(filtereddf,templist[0], templist[1])\n tempmeandf[\"parameter\"]=key\n result_dict[key] = tempmeandf\n\n elif templist[2] == 'max':\n tempmaxdf = calc_max_melted(filtereddf,templist[0],templist[1])\n tempmaxdf[\"parameter\"]=key\n result_dict[key] = tempmaxdf\n\n elif templist[2] == 'delta':\n delta = result_dict[templist[0]][\"value\"] - result_dict[templist[1]][\"value\"]\n delta = pd.DataFrame(delta)\n delta[\"parameter\"] = key\n result_dict[key] = delta\n\n elif templist[2] == 'slope':\n slopes, rsqrd = calc_slope_melted(filtereddf,templist[0],templist[1])\n slopes[\"parameter\"]=key\n rsqrd[\"parameter\"]=\"r_squared\"\n result_dict[key] = slopes\n result_dict[key+\"_rsquared\"] = rsqrd\n\n elif templist[2] == 'auc':\n tempaucdf = calc_auc_melted(filtereddf, templist[0], templist[1])\n tempaucdf[\"parameter\"]=key\n result_dict[key] = tempaucdf\n else:\n print('Please make sure your parameter ' + str(key) + ' ranges are marked with \"mean\", \"max\", \"slope\", \"auc\" or \"delta\"')\n\n else:\n print('Please make sure your parameter ' + str(key) + ' has following format: \"parameter\": [frame number start, frame number stop, \"operation\"] or: \"parameter\": [parameter b, parameter a, \"delta\"] when calculating deltas = b-a')\n\n\n for key in result_dict.keys():\n resultsdf = pd.concat([resultsdf,result_dict[key]])\n\n if name is not None:\n resultsdf[\"group\"]=name\n resultsdf[\"group_parameter\"]=resultsdf.group.str.cat(resultsdf.parameter, sep=\"_\")\n resultsdf.astype(dtype=object)\n\n resultsdf.reset_index(inplace=True)\n print('Kinetics succesfully calculated!')\n return resultsdf\n\ndef get_responders_long(inputdf, parameter, threshold=None, return_trace = False, trace_df = None):\n\n subset = inputdf[inputdf[\"parameter\"]==parameter].copy()\n\n std = subset[\"value\"].std()\n mean = subset[\"value\"].mean()\n\n\n if threshold is None:\n threshold = mean + std\n\n print(\"Mean of parameter %s: %s\" % (parameter, str(mean)))\n print(\"Standard deviation: %s\" % (str(std)))\n print(\"The threshold used:\", str(threshold))\n\n mask = subset[\"value\"] > threshold\n subset[\"response\"] = mask\n\n nr_responders = subset.response.value_counts().to_list()[0]\n nr_nonresponders = subset.response.value_counts().to_list()[1]\n totalcells = len(subset)\n print(\"Total number of cells\", str(totalcells))\n print(\"Number of responders:\", str(nr_responders))\n print(\"Number of non-responders:\", str(nr_nonresponders))\n print(\"Percentage of responders:\", str(nr_responders/totalcells*100))\n\n\n\n\n if return_trace == True and trace_df is not None:\n responder = subset[subset[\"response\"]==True]\n non_responder = subset[subset[\"response\"]==False]\n\n responder_trace = trace_df.merge(responder[[\"measurement\", \"roi\"]], how=\"inner\", on=[\"measurement\", \"roi\"]).sort_values(by=[\"timepoint\",\"roi\"])\n non_responder_trace = trace_df.merge(non_responder[[\"measurement\", \"roi\"]], how=\"inner\", on=[\"measurement\", \"roi\"]).sort_values(by=[\"timepoint\",\"roi\"])\n\n print(\"Responder and non-responder traces returned\")\n print('\\n')\n return subset,responder_trace, non_responder_trace\n\n elif return_trace == True and trace_df is None:\n print(\"Can only get traces if trace df is passed\")\n print('\\n')\n return subset\n\n else:\n print('\\n')\n return subset\n\n\n\ndef filterdata_long_dask(inputdf, threshold=None, nr_of_partitions=None):\n #this function was implemented with help of Jose A. Jimenez\n #https://stackoverflow.com/questions/62957110/pandas-selecting-multiple-rows-based-on-column-pair/\n\n import dask.dataframe as dd\n\n initialmean = inputdf.loc[inputdf[\"timepoint\"] == 0].mean().array[-1]\n initialsd = inputdf.loc[inputdf[\"timepoint\"] == 0].std().array[-1]\n\n if threshold is None:\n threshold = initialmean + initialsd\n pre_activated_t0 = inputdf[(inputdf['timepoint'] == 0) & (inputdf['value'] > threshold)]\n if threshold is not None:\n pre_activated_t0 = inputdf[(inputdf['timepoint'] == 0) & (inputdf['value'] > threshold)]\n\n\n pre_activated = inputdf.merge(pre_activated_t0[[\"measurement\", \"roi\"]], how=\"inner\", on=[\"measurement\", \"roi\"])\n\n if nr_of_partitions is None:\n nr_of_partitions = 30\n\n input_dd = dd.from_pandas(inputdf, npartitions=nr_of_partitions)\n preactivated_dd = dd.from_pandas(pre_activated, npartitions=nr_of_partitions)\n\n merger = dd.merge(input_dd,preactivated_dd, how=\"left\", on=[\"timepoint\", \"measurement\", \"roi\", \"value\"])\n filtereddf = merger.compute()\n\n filtereddf = filtereddf[pd.isna(filtereddf[\"group_y\"])]\n filtereddf.drop(\"group_y\", axis=1, inplace=True)\n filtereddf.columns = list(inputdf.columns)\n\n length_input = len(inputdf[inputdf[\"timepoint\"]==0])\n length_filtered = len(filtereddf[filtereddf[\"timepoint\"]==0])\n delta = length_input - length_filtered\n\n print('Initital Mean: ' + str(initialmean) + '. Initial SD: ' + str(initialsd))\n print('Threshold: ' + str(threshold))\n print('Dataframe was filtered')\n print('Total cells: ' + str(length_input))\n print(str(delta) + ' cells were removed')\n print('\\n')\n\n return filtereddf, pre_activated\n\n\ndef total_means_long(traces_list,kinetics_list,output_total=False):\n\n combined_traces = pd.DataFrame()\n combined_kinetics = pd.DataFrame()\n\n for df in kinetics_list:\n means = df.groupby([\"parameter\",\"measurement\",\"group\",\"group_parameter\"]).mean().drop([\"roi\"],axis=1).reset_index()\n stds = df.groupby([\"parameter\",\"measurement\",\"group\",\"group_parameter\"]).std().drop([\"roi\"],axis=1).reset_index()\n means[\"statistic\"]=\"mean\"\n stds[\"statistic\"] = \"sd\"\n merged_kinetics = pd.merge(means, stds, how=\"outer\")\n combined_kinetics = pd.concat([combined_kinetics,merged_kinetics],axis=0)\n\n for df in traces_list:\n meantrace = df.groupby([\"measurement\",\"group\",\"timepoint\"]).mean().reset_index()\n meantrace[\"statistic\"]=\"mean\"\n sdtrace = df.groupby([\"measurement\",\"group\",\"timepoint\"]).std().reset_index()\n sdtrace[\"statistic\"]=\"sd\"\n merged_traces = pd.merge(meantrace, sdtrace, how=\"outer\")\n combined_traces = pd.concat([combined_traces,merged_traces],axis=0)\n\n combined_traces.reset_index(drop=True)\n combined_kinetics.reset_index(drop=True)\n\n if output_total==False:\n return combined_traces, combined_kinetics\n\n if output_total == True:\n total_traces = pd.concat(traces_list, axis=0).reset_index(drop=True)\n total_kinetics = pd.concat(kinetics_list,axis=0).reset_index(drop=True)\n\n return combined_traces, combined_kinetics,total_traces,total_kinetics\n"
]
| [
[
"pandas.isna",
"pandas.merge",
"pandas.concat",
"pandas.DataFrame",
"pandas.read_excel",
"scipy.stats.linregress",
"numpy.arange",
"pandas.ExcelWriter",
"sklearn.metrics.auc",
"pandas.melt",
"numpy.unique"
]
]
|
riadnassiffe/Simulator | [
"7d9ff09f26367d3714e3d10be3dd4a9817b8ed6b"
]
| [
"src/tools/ecos/cvxpy/cvxpy/atoms/norm1.py"
]
| [
"\"\"\"\nCopyright 2013 Steven Diamond\n\nThis file is part of CVXPY.\n\nCVXPY is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nCVXPY is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with CVXPY. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\n\nfrom cvxpy.atoms.atom import Atom\nimport cvxpy.utilities as u\nimport cvxpy.lin_ops.lin_utils as lu\nfrom cvxpy.atoms.elementwise.abs import abs\nfrom cvxpy.atoms.affine.sum_entries import sum_entries\nfrom numpy import linalg as LA\n\nclass norm1(Atom):\n \"\"\"L1 norm; :math:`\\sum_i|x_i|`.\n\n \"\"\"\n def __init__(self, x):\n super(norm1, self).__init__(x)\n\n @Atom.numpy_numeric\n def numeric(self, values):\n \"\"\"Returns the L1 norm of x.\n \"\"\"\n cols = values[0].shape[1]\n return sum([LA.norm(values[0][:, i], 1) for i in range(cols)])\n\n def shape_from_args(self):\n \"\"\"Resolves to a scalar.\n \"\"\"\n return u.Shape(1, 1)\n\n def sign_from_args(self):\n \"\"\"Always positive.\n \"\"\"\n return u.Sign.POSITIVE\n\n def func_curvature(self):\n \"\"\"Default curvature is convex.\n \"\"\"\n return u.Curvature.CONVEX\n\n def monotonicity(self):\n \"\"\"Increasing for positive arguments and decreasing for negative.\n \"\"\"\n return [u.monotonicity.SIGNED]\n\n @staticmethod\n def graph_implementation(arg_objs, size, data=None):\n \"\"\"Reduces the atom to an affine expression and list of constraints.\n\n Parameters\n ----------\n arg_objs : list\n LinExpr for each argument.\n size : tuple\n The size of the resulting expression.\n data :\n Additional data required by the atom.\n\n Returns\n -------\n tuple\n (LinOp for objective, list of constraints)\n \"\"\"\n x = arg_objs[0]\n obj, abs_constr = abs.graph_implementation([x], x.size)\n obj, sum_constr = sum_entries.graph_implementation([obj], (1, 1))\n return (obj, abs_constr + sum_constr)\n"
]
| [
[
"numpy.linalg.norm"
]
]
|
FlopsKa/StreamDatasets-1 | [
"32a27c079dc70d5cf0009717851ebe207f05524c"
]
| [
"changeds/datastreams.py"
]
| [
"import os\r\n\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom tensorflow import keras\r\nimport numpy as np\r\n\r\nfrom skmultiflow.data import led_generator, random_rbf_generator\r\n\r\nfrom changeds.abstract import ChangeStream, RegionalChangeStream, ClassificationStream, RandomOrderChangeStream\r\nfrom changeds.helper import plot_change_region_2d, preprocess_hipe\r\n\r\n\r\nclass SortedMNIST(ChangeStream, RegionalChangeStream):\r\n def __init__(self, preprocess=None):\r\n (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\r\n x_train = np.reshape(x_train, newshape=(len(x_train), x_train.shape[1] * x_train.shape[2]))\r\n x_test = np.reshape(x_test, newshape=(len(x_test), x_test.shape[1] * x_test.shape[2]))\r\n x = np.vstack([x_train, x_test])\r\n y = np.hstack([y_train, y_test])\r\n sorted_indices = np.argsort(y)\r\n x = x[sorted_indices]\r\n y = y[sorted_indices]\r\n if preprocess:\r\n x = preprocess(x)\r\n self._change_points = np.diff(y, prepend=y[0]).astype(bool)\r\n super(SortedMNIST, self).__init__(data=x, y=y)\r\n\r\n def id(self) -> str:\r\n return \"sMNIST\"\r\n\r\n def change_points(self):\r\n return self._change_points\r\n\r\n def _is_change(self) -> bool:\r\n return self._change_points[self.sample_idx]\r\n\r\n def plot_change_region(self, change_idx: int, binary_thresh: float, save: bool, path=None):\r\n plot_change_region_2d(self, change_idx, binary_thresh, save, path)\r\n\r\n\r\nclass RandomOrderMNIST(RandomOrderChangeStream):\r\n def __init__(self, num_changes: int = 100, preprocess=None):\r\n (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\r\n x_train = np.reshape(x_train, newshape=(len(x_train), x_train.shape[1] * x_train.shape[2]))\r\n x_test = np.reshape(x_test, newshape=(len(x_test), x_test.shape[1] * x_test.shape[2]))\r\n x = np.vstack([x_train, x_test])\r\n y = np.hstack([y_train, y_test])\r\n data, y, change_points = RandomOrderChangeStream.create_changes(x, y, num_changes)\r\n self._change_points = change_points\r\n if preprocess:\r\n data = preprocess(data)\r\n super(RandomOrderMNIST, self).__init__(data=data, y=y)\r\n\r\n def id(self) -> str:\r\n return \"MNIST\"\r\n\r\n def change_points(self):\r\n return self._change_points\r\n\r\n def _is_change(self) -> bool:\r\n return self._change_points[self.sample_idx]\r\n\r\n\r\nclass SortedFashionMNIST(ChangeStream, RegionalChangeStream):\r\n def __init__(self, preprocess=None):\r\n (x_train, y_train), (x_test, y_test) = keras.datasets.fashion_mnist.load_data()\r\n x_train = np.reshape(x_train, newshape=(len(x_train), x_train.shape[1] * x_train.shape[2]))\r\n x_test = np.reshape(x_test, newshape=(len(x_test), x_test.shape[1] * x_test.shape[2]))\r\n x = np.vstack([x_train, x_test])\r\n y = np.hstack([y_train, y_test])\r\n sorted_indices = np.argsort(y)\r\n x = x[sorted_indices]\r\n y = y[sorted_indices]\r\n if preprocess:\r\n x = preprocess(x)\r\n self._change_points = np.diff(y, prepend=y[0]).astype(bool)\r\n super(SortedFashionMNIST, self).__init__(data=x, y=y)\r\n\r\n def id(self) -> str:\r\n return \"sFMNIST\"\r\n\r\n def change_points(self):\r\n return self._change_points\r\n\r\n def _is_change(self) -> bool:\r\n return self._change_points[self.sample_idx]\r\n\r\n def plot_change_region(self, change_idx: int, binary_thresh: float, save: bool, path=None):\r\n plot_change_region_2d(self, change_idx, binary_thresh, save, path)\r\n\r\n\r\nclass RandomOrderFashionMNIST(RandomOrderChangeStream):\r\n def __init__(self, num_changes: int = 100, preprocess=None):\r\n (x_train, y_train), (x_test, y_test) = keras.datasets.fashion_mnist.load_data()\r\n x_train = np.reshape(x_train, newshape=(len(x_train), x_train.shape[1] * x_train.shape[2]))\r\n x_test = np.reshape(x_test, newshape=(len(x_test), x_test.shape[1] * x_test.shape[2]))\r\n x = np.vstack([x_train, x_test])\r\n y = np.hstack([y_train, y_test])\r\n data, y, change_points = RandomOrderChangeStream.create_changes(x, y, num_changes)\r\n self._change_points = change_points\r\n if preprocess:\r\n data = preprocess(data)\r\n super(RandomOrderFashionMNIST, self).__init__(data=data, y=y)\r\n\r\n def id(self) -> str:\r\n return \"FMNIST\"\r\n\r\n def change_points(self):\r\n return self._change_points\r\n\r\n def _is_change(self) -> bool:\r\n return self._change_points[self.sample_idx]\r\n\r\n\r\nclass SortedCIFAR10(ChangeStream, RegionalChangeStream):\r\n def __init__(self, preprocess=None):\r\n (x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()\r\n x_train = x_train.dot([0.299, 0.587, 0.114])\r\n x_test = x_test.dot([0.299, 0.587, 0.114])\r\n x_train = np.reshape(x_train, newshape=(len(x_train), x_train.shape[1] * x_train.shape[2]))\r\n x_test = np.reshape(x_test, newshape=(len(x_test), x_test.shape[1] * x_test.shape[2]))\r\n x = np.vstack([x_train, x_test])\r\n y = np.hstack([y_train.reshape(-1), y_test.reshape(-1)])\r\n sorted_indices = np.argsort(y)\r\n x = x[sorted_indices]\r\n y = y[sorted_indices]\r\n\r\n if preprocess:\r\n x = preprocess(x)\r\n self._change_points = np.diff(y, prepend=y[0]).astype(bool)\r\n super(SortedCIFAR10, self).__init__(data=x, y=y)\r\n\r\n def id(self) -> str:\r\n return \"sCIFAR\"\r\n\r\n def change_points(self):\r\n return self._change_points\r\n\r\n def _is_change(self) -> bool:\r\n return self._change_points[self.sample_idx]\r\n\r\n def plot_change_region(self, change_idx: int, binary_thresh: float, save: bool, path=None):\r\n plot_change_region_2d(self, change_idx, binary_thresh, save, path)\r\n\r\n\r\nclass RandomOrderCIFAR10(RandomOrderChangeStream):\r\n def __init__(self, num_changes: int = 100, preprocess=None):\r\n (x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()\r\n x_train = x_train.dot([0.299, 0.587, 0.114])\r\n x_test = x_test.dot([0.299, 0.587, 0.114])\r\n x_train = np.reshape(x_train, newshape=(len(x_train), x_train.shape[1] * x_train.shape[2]))\r\n x_test = np.reshape(x_test, newshape=(len(x_test), x_test.shape[1] * x_test.shape[2]))\r\n x = np.vstack([x_train, x_test])\r\n y = np.hstack([y_train.reshape(-1), y_test.reshape(-1)])\r\n data, y, change_points = RandomOrderChangeStream.create_changes(x, y, num_changes)\r\n self._change_points = change_points\r\n if preprocess:\r\n data = preprocess(data)\r\n super(RandomOrderCIFAR10, self).__init__(data=data, y=y)\r\n\r\n def id(self) -> str:\r\n return \"CIFAR\"\r\n\r\n def change_points(self):\r\n return self._change_points\r\n\r\n def _is_change(self) -> bool:\r\n return self._change_points[self.sample_idx]\r\n\r\n\r\nclass SortedCIFAR100(ChangeStream, RegionalChangeStream):\r\n def __init__(self, preprocess=None):\r\n (x_train, y_train), (x_test, y_test) = keras.datasets.cifar100.load_data()\r\n x_train = x_train.dot([0.299, 0.587, 0.114])\r\n x_test = x_test.dot([0.299, 0.587, 0.114])\r\n x_train = np.reshape(x_train, newshape=(len(x_train), x_train.shape[1] * x_train.shape[2]))\r\n x_test = np.reshape(x_test, newshape=(len(x_test), x_test.shape[1] * x_test.shape[2]))\r\n x = np.vstack([x_train, x_test])\r\n y = np.hstack([y_train.reshape(-1), y_test.reshape(-1)])\r\n sorted_indices = np.argsort(y)\r\n x = x[sorted_indices]\r\n y = y[sorted_indices]\r\n\r\n if preprocess:\r\n x = preprocess(x)\r\n self._change_points = np.diff(y, prepend=y[0]).astype(bool)\r\n super(SortedCIFAR100, self).__init__(data=x, y=y)\r\n\r\n def id(self) -> str:\r\n return \"sCIFAR100\"\r\n\r\n def change_points(self):\r\n return self._change_points\r\n\r\n def _is_change(self) -> bool:\r\n return self._change_points[self.sample_idx]\r\n\r\n def plot_change_region(self, change_idx: int, binary_thresh: float, save: bool, path=None):\r\n plot_change_region_2d(self, change_idx, binary_thresh, save, path)\r\n\r\n\r\nclass RandomOrderCIFAR100(RandomOrderChangeStream):\r\n def __init__(self, num_changes: int = 100, preprocess=None):\r\n (x_train, y_train), (x_test, y_test) = keras.datasets.cifar100.load_data()\r\n x_train = x_train.dot([0.299, 0.587, 0.114])\r\n x_test = x_test.dot([0.299, 0.587, 0.114])\r\n x_train = np.reshape(x_train, newshape=(len(x_train), x_train.shape[1] * x_train.shape[2]))\r\n x_test = np.reshape(x_test, newshape=(len(x_test), x_test.shape[1] * x_test.shape[2]))\r\n x = np.vstack([x_train, x_test])\r\n y = np.hstack([y_train.reshape(-1), y_test.reshape(-1)])\r\n data, y, change_points = RandomOrderChangeStream.create_changes(x, y, num_changes)\r\n self._change_points = change_points\r\n if preprocess:\r\n data = preprocess(data)\r\n super(RandomOrderCIFAR100, self).__init__(data=data, y=y)\r\n\r\n def id(self) -> str:\r\n return \"CIFAR100\"\r\n\r\n def change_points(self):\r\n return self._change_points\r\n\r\n def _is_change(self) -> bool:\r\n return self._change_points[self.sample_idx]\r\n\r\n\r\nclass HIPE(ChangeStream):\r\n def __init__(self, preprocess=None):\r\n x = preprocess_hipe()\r\n y = np.zeros(shape=len(x))\r\n if preprocess:\r\n x = preprocess(x)\r\n self._change_points = y\r\n super(HIPE, self).__init__(data=x, y=y)\r\n\r\n def id(self) -> str:\r\n return \"HIPE\"\r\n\r\n def change_points(self):\r\n return self._change_points\r\n\r\n def _is_change(self) -> bool:\r\n return self._change_points[self.sample_idx]\r\n\r\n\r\nclass LED(ChangeStream, RegionalChangeStream):\r\n\r\n def __init__(self, n_per_concept: int = 10000, n_drifts: int = 10, has_noise=True, preprocess=None):\r\n \"\"\"\r\n Creates a sudden, but\r\n :param n_per_concept:\r\n :param n_drifts:\r\n :param has_noise:\r\n :param preprocess:\r\n \"\"\"\r\n self.has_noise = has_noise\r\n random_state = 0\r\n x = []\r\n for i in range(n_drifts):\r\n x.append(led_generator.LEDGenerator(random_state=random_state, has_noise=has_noise,\r\n noise_percentage=(i + 1) / n_drifts if i % 2 == 1 else 0\r\n ).next_sample(n_per_concept)[0])\r\n y = [i for i in range(n_drifts) for _ in range(n_per_concept)]\r\n x = np.concatenate(x, axis=0)\r\n if preprocess:\r\n x = preprocess(x)\r\n self._change_points = np.diff(y, prepend=y[0]).astype(bool)\r\n super(LED, self).__init__(data=x, y=np.array(y))\r\n\r\n def id(self) -> str:\r\n return \"LED\"\r\n\r\n def change_points(self):\r\n return self._change_points\r\n\r\n def _is_change(self) -> bool:\r\n return self.change_points()[self.sample_idx]\r\n\r\n def approximate_change_regions(self):\r\n if self.has_noise:\r\n return [1 if i < 7 else 0 for i in range(len(self.y))]\r\n else:\r\n return [1 for _ in range(len(self.y))]\r\n\r\n def plot_change_region(self, change_idx: int, binary_thresh: float, save: bool, path=None):\r\n raise NotImplementedError\r\n\r\n\r\nclass HAR(ChangeStream):\r\n def __init__(self, preprocess=None):\r\n this_dir, _ = os.path.split(__file__)\r\n path_to_data = os.path.join(this_dir, \"..\", \"data\", \"har\")\r\n test = pd.read_csv(os.path.join(path_to_data, \"test.csv\"))\r\n train = pd.read_csv(os.path.join(path_to_data, \"train.csv\"))\r\n x = pd.concat([test, train])\r\n x = x.sort_values(by=\"Activity\")\r\n y = LabelEncoder().fit_transform(x[\"Activity\"])\r\n x = x.drop([\"Activity\", \"subject\"], axis=1)\r\n if preprocess:\r\n x = preprocess(x)\r\n self._change_points = np.diff(y, prepend=y[0]).astype(bool)\r\n super(HAR, self).__init__(data=x, y=y)\r\n\r\n def id(self) -> str:\r\n return \"sHAR\"\r\n\r\n def change_points(self):\r\n return self._change_points\r\n\r\n def _is_change(self) -> bool:\r\n return self._change_points[self.sample_idx]\r\n\r\n\r\nclass RandomOrderHAR(ChangeStream):\r\n def __init__(self, num_changes: int = 100, preprocess=None):\r\n this_dir, _ = os.path.split(__file__)\r\n path_to_data = os.path.join(this_dir, \"..\", \"data\", \"har\")\r\n test = pd.read_csv(os.path.join(path_to_data, \"test.csv\"))\r\n train = pd.read_csv(os.path.join(path_to_data, \"train.csv\"))\r\n x = pd.concat([test, train])\r\n x = x.sort_values(by=\"Activity\")\r\n y = LabelEncoder().fit_transform(x[\"Activity\"])\r\n x = x.drop([\"Activity\", \"subject\"], axis=1).to_numpy()\r\n if preprocess:\r\n x = preprocess(x)\r\n data, y, change_points = RandomOrderChangeStream.create_changes(x, y, num_changes, shuffle_within_concept=True)\r\n self._change_points = change_points\r\n super(RandomOrderHAR, self).__init__(data=data, y=y)\r\n\r\n def id(self) -> str:\r\n return \"HAR\"\r\n\r\n def change_points(self):\r\n return self._change_points\r\n\r\n def _is_change(self) -> bool:\r\n return self._change_points[self.sample_idx]\r\n\r\n\r\nclass RBF(ChangeStream, RegionalChangeStream):\r\n def __init__(self, n_per_concept: int = 10000,\r\n n_drifts: int = 10, dims: int = 100,\r\n n_centroids: int = 10, add_dims_without_drift=True, preprocess=None):\r\n self.add_dims_without_drift = add_dims_without_drift\r\n sample_random_state = 0\r\n x = []\r\n no_drift = []\r\n for i in range(n_drifts):\r\n model_random_state = i\r\n x.append(random_rbf_generator.RandomRBFGenerator(model_random_state=model_random_state,\r\n sample_random_state=sample_random_state, n_features=dims,\r\n n_centroids=n_centroids).next_sample(n_per_concept)[0])\r\n if add_dims_without_drift:\r\n no_drift_model_random_state = n_drifts # a random seed that we will not use to create drifts\r\n no_drift.append(random_rbf_generator.RandomRBFGenerator(model_random_state=no_drift_model_random_state,\r\n sample_random_state=sample_random_state,\r\n n_features=dims, n_centroids=n_centroids\r\n ).next_sample(n_per_concept)[0])\r\n y = [i for i in range(n_drifts) for _ in range(n_per_concept)]\r\n x = np.concatenate(x, axis=0)\r\n if add_dims_without_drift:\r\n noise = np.concatenate(no_drift, axis=0)\r\n x = np.concatenate([x, noise], axis=1)\r\n if preprocess:\r\n x = preprocess(x)\r\n self._change_points = np.diff(y, prepend=y[0]).astype(bool)\r\n super(RBF, self).__init__(data=x, y=np.array(y))\r\n\r\n def id(self) -> str:\r\n return \"RBF\"\r\n\r\n def change_points(self):\r\n return self._change_points\r\n\r\n def _is_change(self) -> bool:\r\n return self.change_points()[self.sample_idx]\r\n\r\n def approximate_change_regions(self):\r\n if self.add_dims_without_drift:\r\n return [1 if i < len(self.y) / 2 else 0 for i in range(len(self.y))]\r\n else:\r\n return [1 for _ in range(len(self.y))]\r\n\r\n def plot_change_region(self, change_idx: int, binary_thresh: float, save: bool, path=None):\r\n raise NotImplementedError\r\n\r\n\r\nclass ArtificialStream(ClassificationStream):\r\n def id(self) -> str:\r\n return self.filename[:-4]\r\n\r\n def __init__(self, filename: str):\r\n self.filename = filename\r\n path, _ = os.path.split(__file__)\r\n path = os.path.join(path, \"..\", \"concept-drift-datasets-scikit-multiflow\", \"artificial\")\r\n file_path = os.path.join(path, filename)\r\n assert os.path.exists(file_path), \"The requested file does not exist in {}\".format(file_path)\r\n super(ArtificialStream, self).__init__(data_path=file_path)\r\n\r\n\r\nclass RealWorldStream(ClassificationStream):\r\n def id(self) -> str:\r\n return self.filename[:-4]\r\n\r\n def __init__(self, filename: str):\r\n self.filename = filename\r\n path, _ = os.path.split(__file__)\r\n path = os.path.join(path, \"..\", \"concept-drift-datasets-scikit-multiflow\", \"real-world\")\r\n file_path = os.path.join(path, filename)\r\n assert os.path.exists(file_path), \"The requested file does not exist in {}\".format(file_path)\r\n super(RealWorldStream, self).__init__(data_path=file_path)\r\n\r\n\r\nif __name__ == '__main__':\r\n stream = RandomOrderHAR()\r\n print(stream.id())\r\n while stream.has_more_samples():\r\n x, y, is_change = stream.next_sample()\r\n if is_change:\r\n print(\"Change at index {}\".format(stream.sample_idx))\r\n\r\n if isinstance(stream, RegionalChangeStream):\r\n change_regions = stream.approximate_change_regions()\r\n stream.plot_change_region(2, binary_thresh=0.5, save=False)\r\n"
]
| [
[
"numpy.concatenate",
"tensorflow.keras.datasets.cifar10.load_data",
"numpy.array",
"tensorflow.keras.datasets.mnist.load_data",
"sklearn.preprocessing.LabelEncoder",
"tensorflow.keras.datasets.fashion_mnist.load_data",
"tensorflow.keras.datasets.cifar100.load_data",
"numpy.diff",
"numpy.argsort",
"pandas.concat",
"numpy.hstack",
"numpy.vstack"
]
]
|
mawanda-jun/numba | [
"3d688932f919dbf5821f0cb8a210ce24abe39e9e",
"8c6658375c1f8fe50e1a5ccd11d4e7bf5a8053de"
]
| [
"numba/tests/test_parfors_caching.py",
"numba/tests/test_dictobject.py"
]
| [
"from __future__ import print_function, absolute_import, division\n\nimport os.path\n\nimport numpy as np\n\nfrom .support import skip_parfors_unsupported\nfrom .test_dispatcher import BaseCacheUsecasesTest\n\n\n@skip_parfors_unsupported\nclass TestParForsCache(BaseCacheUsecasesTest):\n here = os.path.dirname(__file__)\n usecases_file = os.path.join(here, \"parfors_cache_usecases.py\")\n modname = \"parfors_caching_test_fodder\"\n\n def run_test(self, fname, num_funcs=1):\n mod = self.import_module()\n self.check_pycache(0)\n f = getattr(mod, fname)\n ary = np.ones(10)\n self.assertPreciseEqual(f(ary), f.py_func(ary))\n\n dynamic_globals = [cres.library.has_dynamic_globals\n for cres in f.overloads.values()]\n [cres] = f.overloads.values()\n self.assertEqual(dynamic_globals, [False])\n # For each cached func, there're 2 entries (index + data)\n self.check_pycache(num_funcs * 2)\n\n self.run_in_separate_process()\n\n def test_arrayexprs(self):\n f = 'arrayexprs_case'\n self.run_test(f)\n\n def test_prange(self):\n f = 'prange_case'\n self.run_test(f)\n\n def test_caller(self):\n f = 'caller_case'\n # num_funcs=3 because, there's the `caller_case()` which calls\n # the `prange_case()` and `arrayexprs_case()`\n self.run_test(f, num_funcs=3)\n",
"\"\"\"\nTesting numba implementation of the numba dictionary.\n\nThe tests here only check that the numba typing and codegen are working\ncorrectly. Detailed testing of the underlying dictionary operations is done\nin test_dictimpl.py.\n\"\"\"\nfrom __future__ import print_function, absolute_import, division\n\nimport sys\nimport warnings\n\nimport numpy as np\n\nfrom numba import njit, utils, jitclass\nfrom numba import int32, int64, float32, float64, types\nfrom numba import dictobject, typeof\nfrom numba.typed import Dict\nfrom numba.typedobjectutils import _sentry_safe_cast\nfrom numba.utils import IS_PY3\nfrom numba.errors import TypingError\nfrom .support import TestCase, MemoryLeakMixin, unittest\n\nskip_py2 = unittest.skipUnless(IS_PY3, reason='not supported in py2')\n\n\nclass TestDictObject(MemoryLeakMixin, TestCase):\n def test_dict_create(self):\n \"\"\"\n Exercise dictionary creation, insertion and len\n \"\"\"\n @njit\n def foo(n):\n d = dictobject.new_dict(int32, float32)\n for i in range(n):\n d[i] = i + 1\n return len(d)\n\n # Insert nothing\n self.assertEqual(foo(n=0), 0)\n # Insert 1 entry\n self.assertEqual(foo(n=1), 1)\n # Insert 2 entries\n self.assertEqual(foo(n=2), 2)\n # Insert 100 entries\n self.assertEqual(foo(n=100), 100)\n\n def test_dict_get(self):\n \"\"\"\n Exercise dictionary creation, insertion and get\n \"\"\"\n @njit\n def foo(n, targets):\n d = dictobject.new_dict(int32, float64)\n # insertion loop\n for i in range(n):\n d[i] = i\n # retrieval loop\n output = []\n for t in targets:\n output.append(d.get(t))\n return output\n\n self.assertEqual(foo(5, [0, 1, 9]), [0, 1, None])\n self.assertEqual(foo(10, [0, 1, 9]), [0, 1, 9])\n self.assertEqual(foo(10, [-1, 9, 1]), [None, 9, 1])\n\n def test_dict_get_with_default(self):\n \"\"\"\n Exercise dict.get(k, d) where d is set\n \"\"\"\n @njit\n def foo(n, target, default):\n d = dictobject.new_dict(int32, float64)\n # insertion loop\n for i in range(n):\n d[i] = i\n # retrieval loop\n return d.get(target, default)\n\n self.assertEqual(foo(5, 3, -1), 3)\n self.assertEqual(foo(5, 5, -1), -1)\n\n def test_dict_getitem(self):\n \"\"\"\n Exercise dictionary __getitem__\n \"\"\"\n @njit\n def foo(keys, vals, target):\n d = dictobject.new_dict(int32, float64)\n # insertion\n for k, v in zip(keys, vals):\n d[k] = v\n\n # lookup\n return d[target]\n\n keys = [1, 2, 3]\n vals = [0.1, 0.2, 0.3]\n self.assertEqual(foo(keys, vals, 1), 0.1)\n self.assertEqual(foo(keys, vals, 2), 0.2)\n self.assertEqual(foo(keys, vals, 3), 0.3)\n # check no leak so far\n self.assert_no_memory_leak()\n # disable leak check for exception test\n self.disable_leak_check()\n with self.assertRaises(KeyError):\n foo(keys, vals, 0)\n with self.assertRaises(KeyError):\n foo(keys, vals, 4)\n\n def test_dict_popitem(self):\n \"\"\"\n Exercise dictionary .popitem\n \"\"\"\n @njit\n def foo(keys, vals):\n d = dictobject.new_dict(int32, float64)\n # insertion\n for k, v in zip(keys, vals):\n d[k] = v\n\n # popitem\n return d.popitem()\n\n keys = [1, 2, 3]\n vals = [0.1, 0.2, 0.3]\n for i in range(1, len(keys)):\n self.assertEqual(\n foo(keys[:i], vals[:i]),\n (keys[i - 1], vals[i - 1]),\n )\n\n def test_dict_popitem_many(self):\n \"\"\"\n Exercise dictionary .popitem\n \"\"\"\n\n @njit\n def core(d, npop):\n # popitem\n keysum, valsum = 0, 0\n for _ in range(npop):\n k, v = d.popitem()\n keysum += k\n valsum -= v\n return keysum, valsum\n\n @njit\n def foo(keys, vals, npop):\n d = dictobject.new_dict(int32, int32)\n # insertion\n for k, v in zip(keys, vals):\n d[k] = v\n\n return core(d, npop)\n\n keys = [1, 2, 3]\n vals = [10, 20, 30]\n\n for i in range(len(keys)):\n self.assertEqual(\n foo(keys, vals, npop=3),\n core.py_func(dict(zip(keys, vals)), npop=3),\n )\n\n # check no leak so far\n self.assert_no_memory_leak()\n # disable leak check for exception test\n self.disable_leak_check()\n\n with self.assertRaises(KeyError):\n foo(keys, vals, npop=4)\n\n def test_dict_pop(self):\n \"\"\"\n Exercise dictionary .pop\n \"\"\"\n @njit\n def foo(keys, vals, target):\n d = dictobject.new_dict(int32, float64)\n # insertion\n for k, v in zip(keys, vals):\n d[k] = v\n\n # popitem\n return d.pop(target, None), len(d)\n\n keys = [1, 2, 3]\n vals = [0.1, 0.2, 0.3]\n\n self.assertEqual(foo(keys, vals, 1), (0.1, 2))\n self.assertEqual(foo(keys, vals, 2), (0.2, 2))\n self.assertEqual(foo(keys, vals, 3), (0.3, 2))\n self.assertEqual(foo(keys, vals, 0), (None, 3))\n\n # check no leak so far\n self.assert_no_memory_leak()\n # disable leak check for exception test\n self.disable_leak_check()\n\n @njit\n def foo():\n d = dictobject.new_dict(int32, float64)\n # popitem\n return d.pop(0)\n\n with self.assertRaises(KeyError):\n foo()\n\n def test_dict_pop_many(self):\n \"\"\"\n Exercise dictionary .pop\n \"\"\"\n\n @njit\n def core(d, pops):\n total = 0\n for k in pops:\n total += k + d.pop(k, 0.123) + len(d)\n total *= 2\n return total\n\n @njit\n def foo(keys, vals, pops):\n d = dictobject.new_dict(int32, float64)\n # insertion\n for k, v in zip(keys, vals):\n d[k] = v\n # popitem\n return core(d, pops)\n\n keys = [1, 2, 3]\n vals = [0.1, 0.2, 0.3]\n pops = [2, 3, 3, 1, 0, 2, 1, 0, -1]\n\n self.assertEqual(\n foo(keys, vals, pops),\n core.py_func(dict(zip(keys, vals)), pops),\n )\n\n def test_dict_delitem(self):\n @njit\n def foo(keys, vals, target):\n d = dictobject.new_dict(int32, float64)\n # insertion\n for k, v in zip(keys, vals):\n d[k] = v\n del d[target]\n return len(d), d.get(target)\n\n keys = [1, 2, 3]\n vals = [0.1, 0.2, 0.3]\n self.assertEqual(foo(keys, vals, 1), (2, None))\n self.assertEqual(foo(keys, vals, 2), (2, None))\n self.assertEqual(foo(keys, vals, 3), (2, None))\n # check no leak so far\n self.assert_no_memory_leak()\n # disable leak check for exception test\n self.disable_leak_check()\n with self.assertRaises(KeyError):\n foo(keys, vals, 0)\n\n def test_dict_clear(self):\n \"\"\"\n Exercise dict.clear\n \"\"\"\n @njit\n def foo(keys, vals):\n d = dictobject.new_dict(int32, float64)\n # insertion\n for k, v in zip(keys, vals):\n d[k] = v\n b4 = len(d)\n # clear\n d.clear()\n return b4, len(d)\n\n keys = [1, 2, 3]\n vals = [0.1, 0.2, 0.3]\n self.assertEqual(foo(keys, vals), (3, 0))\n\n def test_dict_items(self):\n \"\"\"\n Exercise dict.items\n \"\"\"\n @njit\n def foo(keys, vals):\n d = dictobject.new_dict(int32, float64)\n # insertion\n for k, v in zip(keys, vals):\n d[k] = v\n out = []\n for kv in d.items():\n out.append(kv)\n return out\n\n keys = [1, 2, 3]\n vals = [0.1, 0.2, 0.3]\n\n self.assertEqual(\n foo(keys, vals),\n list(zip(keys, vals)),\n )\n\n # Test .items() on empty dict\n @njit\n def foo():\n d = dictobject.new_dict(int32, float64)\n out = []\n for kv in d.items():\n out.append(kv)\n return out\n\n self.assertEqual(foo(), [])\n\n def test_dict_keys(self):\n \"\"\"\n Exercise dict.keys\n \"\"\"\n @njit\n def foo(keys, vals):\n d = dictobject.new_dict(int32, float64)\n # insertion\n for k, v in zip(keys, vals):\n d[k] = v\n out = []\n for k in d.keys():\n out.append(k)\n return out\n\n keys = [1, 2, 3]\n vals = [0.1, 0.2, 0.3]\n\n self.assertEqual(\n foo(keys, vals),\n keys,\n )\n\n def test_dict_values(self):\n \"\"\"\n Exercise dict.values\n \"\"\"\n @njit\n def foo(keys, vals):\n d = dictobject.new_dict(int32, float64)\n # insertion\n for k, v in zip(keys, vals):\n d[k] = v\n out = []\n for v in d.values():\n out.append(v)\n return out\n\n keys = [1, 2, 3]\n vals = [0.1, 0.2, 0.3]\n\n self.assertEqual(\n foo(keys, vals),\n vals,\n )\n\n def test_dict_iter(self):\n \"\"\"\n Exercise iter(dict)\n \"\"\"\n @njit\n def foo(keys, vals):\n d = dictobject.new_dict(int32, float64)\n # insertion\n for k, v in zip(keys, vals):\n d[k] = v\n out = []\n for k in d:\n out.append(k)\n return out\n\n keys = [1, 2, 3]\n vals = [0.1, 0.2, 0.3]\n\n self.assertEqual(\n foo(keys, vals),\n [1, 2, 3]\n )\n\n def test_dict_contains(self):\n \"\"\"\n Exercise operator.contains\n \"\"\"\n @njit\n def foo(keys, vals, checklist):\n d = dictobject.new_dict(int32, float64)\n # insertion\n for k, v in zip(keys, vals):\n d[k] = v\n out = []\n for k in checklist:\n out.append(k in d)\n return out\n\n keys = [1, 2, 3]\n vals = [0.1, 0.2, 0.3]\n\n self.assertEqual(\n foo(keys, vals, [2, 3, 4, 1, 0]),\n [True, True, False, True, False],\n )\n\n def test_dict_copy(self):\n \"\"\"\n Exercise dict.copy\n \"\"\"\n @njit\n def foo(keys, vals):\n d = dictobject.new_dict(int32, float64)\n # insertion\n for k, v in zip(keys, vals):\n d[k] = v\n return list(d.copy().items())\n\n keys = list(range(20))\n vals = [x + i / 100 for i, x in enumerate(keys)]\n out = foo(keys, vals)\n self.assertEqual(out, list(zip(keys, vals)))\n\n def test_dict_setdefault(self):\n \"\"\"\n Exercise dict.setdefault\n \"\"\"\n @njit\n def foo():\n d = dictobject.new_dict(int32, float64)\n d.setdefault(1, 1.2) # used because key is not in\n a = d.get(1)\n d[1] = 2.3\n b = d.get(1)\n d[2] = 3.4\n d.setdefault(2, 4.5) # not used because key is in\n c = d.get(2)\n return a, b, c\n\n self.assertEqual(foo(), (1.2, 2.3, 3.4))\n\n def test_dict_equality(self):\n \"\"\"\n Exercise dict.__eq__ and .__ne__\n \"\"\"\n @njit\n def foo(na, nb, fa, fb):\n da = dictobject.new_dict(int32, float64)\n db = dictobject.new_dict(int32, float64)\n for i in range(na):\n da[i] = i * fa\n for i in range(nb):\n db[i] = i * fb\n return da == db, da != db\n\n # Same keys and values\n self.assertEqual(foo(10, 10, 3, 3), (True, False))\n # Same keys and diff values\n self.assertEqual(foo(10, 10, 3, 3.1), (False, True))\n # LHS has more keys\n self.assertEqual(foo(11, 10, 3, 3), (False, True))\n # RHS has more keys\n self.assertEqual(foo(10, 11, 3, 3), (False, True))\n\n def test_dict_equality_more(self):\n \"\"\"\n Exercise dict.__eq__\n \"\"\"\n @njit\n def foo(ak, av, bk, bv):\n # The key-value types are different in the two dictionaries\n da = dictobject.new_dict(int32, float64)\n db = dictobject.new_dict(int64, float32)\n for i in range(len(ak)):\n da[ak[i]] = av[i]\n for i in range(len(bk)):\n db[bk[i]] = bv[i]\n return da == db\n\n # Simple equal case\n ak = [1, 2, 3]\n av = [2, 3, 4]\n bk = [1, 2, 3]\n bv = [2, 3, 4]\n self.assertTrue(foo(ak, av, bk, bv))\n\n # Equal with replacement\n ak = [1, 2, 3]\n av = [2, 3, 4]\n bk = [1, 2, 2, 3]\n bv = [2, 1, 3, 4]\n self.assertTrue(foo(ak, av, bk, bv))\n\n # Diff values\n ak = [1, 2, 3]\n av = [2, 3, 4]\n bk = [1, 2, 3]\n bv = [2, 1, 4]\n self.assertFalse(foo(ak, av, bk, bv))\n\n # Diff keys\n ak = [0, 2, 3]\n av = [2, 3, 4]\n bk = [1, 2, 3]\n bv = [2, 3, 4]\n self.assertFalse(foo(ak, av, bk, bv))\n\n def test_dict_equality_diff_type(self):\n \"\"\"\n Exercise dict.__eq__\n \"\"\"\n @njit\n def foo(na, b):\n da = dictobject.new_dict(int32, float64)\n for i in range(na):\n da[i] = i\n return da == b\n\n # dict != int\n self.assertFalse(foo(10, 1))\n # dict != tuple[int]\n self.assertFalse(foo(10, (1,)))\n\n def test_dict_to_from_meminfo(self):\n \"\"\"\n Exercise dictobject.{_as_meminfo, _from_meminfo}\n \"\"\"\n @njit\n def make_content(nelem):\n for i in range(nelem):\n yield i, i + (i + 1) / 100\n\n @njit\n def boxer(nelem):\n d = dictobject.new_dict(int32, float64)\n for k, v in make_content(nelem):\n d[k] = v\n return dictobject._as_meminfo(d)\n\n dcttype = types.DictType(int32, float64)\n\n @njit\n def unboxer(mi):\n d = dictobject._from_meminfo(mi, dcttype)\n return list(d.items())\n\n mi = boxer(10)\n self.assertEqual(mi.refcount, 1)\n\n got = unboxer(mi)\n expected = list(make_content.py_func(10))\n self.assertEqual(got, expected)\n\n def test_001_cannot_downcast_key(self):\n @njit\n def foo(n):\n d = dictobject.new_dict(int32, float64)\n for i in range(n):\n d[i] = i + 1\n # bad key type\n z = d.get(1j)\n return z\n\n with self.assertRaises(TypingError) as raises:\n foo(10)\n self.assertIn(\n 'cannot safely cast complex128 to int32',\n str(raises.exception),\n )\n\n def test_002_cannot_downcast_default(self):\n @njit\n def foo(n):\n d = dictobject.new_dict(int32, float64)\n for i in range(n):\n d[i] = i + 1\n # bad default type\n z = d.get(2 * n, 1j)\n return z\n\n with self.assertRaises(TypingError) as raises:\n foo(10)\n self.assertIn(\n 'cannot safely cast complex128 to float64',\n str(raises.exception),\n )\n\n def test_003_cannot_downcast_key(self):\n @njit\n def foo(n):\n d = dictobject.new_dict(int32, float64)\n for i in range(n):\n d[i] = i + 1\n # bad cast!?\n z = d.get(2.4)\n return z\n\n # should raise\n with self.assertRaises(TypingError) as raises:\n foo(10)\n self.assertIn(\n 'cannot safely cast float64 to int32',\n str(raises.exception),\n )\n\n def test_004_cannot_downcast_key(self):\n @njit\n def foo():\n d = dictobject.new_dict(int32, float64)\n # should raise TypingError\n d[1j] = 7.\n\n with self.assertRaises(TypingError) as raises:\n foo()\n self.assertIn(\n 'cannot safely cast complex128 to int32',\n str(raises.exception),\n )\n\n def test_005_cannot_downcast_value(self):\n @njit\n def foo():\n d = dictobject.new_dict(int32, float64)\n # should raise TypingError\n d[1] = 1j\n\n with self.assertRaises(TypingError) as raises:\n foo()\n self.assertIn(\n 'cannot safely cast complex128 to float64',\n str(raises.exception),\n )\n\n def test_006_cannot_downcast_key(self):\n @njit\n def foo():\n d = dictobject.new_dict(int32, float64)\n # raise TypingError\n d[11.5]\n\n with self.assertRaises(TypingError) as raises:\n foo()\n self.assertIn(\n 'cannot safely cast float64 to int32',\n str(raises.exception),\n )\n\n @unittest.skipUnless(utils.IS_PY3 and sys.maxsize > 2 ** 32,\n \"Python 3, 64 bit test only\")\n def test_007_collision_checks(self):\n # this checks collisions in real life for 64bit systems\n @njit\n def foo(v1, v2):\n d = dictobject.new_dict(int64, float64)\n c1 = np.uint64(2 ** 61 - 1)\n c2 = np.uint64(0)\n assert hash(c1) == hash(c2)\n d[c1] = v1\n d[c2] = v2\n return (d[c1], d[c2])\n\n a, b = 10., 20.\n x, y = foo(a, b)\n self.assertEqual(x, a)\n self.assertEqual(y, b)\n\n def test_008_lifo_popitem(self):\n # check that (keys, vals) are LIFO .popitem()\n @njit\n def foo(n):\n d = dictobject.new_dict(int32, float64)\n for i in range(n):\n d[i] = i + 1\n keys = []\n vals = []\n for i in range(n):\n tmp = d.popitem()\n keys.append(tmp[0])\n vals.append(tmp[1])\n return keys, vals\n\n z = 10\n gk, gv = foo(z)\n\n self.assertEqual(gk, [x for x in reversed(range(z))])\n self.assertEqual(gv, [x + 1 for x in reversed(range(z))])\n\n def test_010_cannot_downcast_default(self):\n @njit\n def foo():\n d = dictobject.new_dict(int32, float64)\n d[0] = 6.\n d[1] = 7.\n # pop'd default must have same type as value\n d.pop(11, 12j)\n\n with self.assertRaises(TypingError) as raises:\n foo()\n self.assertIn(\n \"cannot safely cast complex128 to float64\",\n str(raises.exception),\n )\n\n def test_011_cannot_downcast_key(self):\n @njit\n def foo():\n d = dictobject.new_dict(int32, float64)\n d[0] = 6.\n d[1] = 7.\n # pop'd key must have same type as key\n d.pop(11j)\n\n with self.assertRaises(TypingError) as raises:\n foo()\n self.assertIn(\n \"cannot safely cast complex128 to int32\",\n str(raises.exception),\n )\n\n def test_012_cannot_downcast_key(self):\n @njit\n def foo():\n d = dictobject.new_dict(int32, float64)\n d[0] = 6.\n # invalid key type\n return 1j in d\n\n with self.assertRaises(TypingError) as raises:\n foo()\n self.assertIn(\n \"cannot safely cast complex128 to int32\",\n str(raises.exception),\n )\n\n def test_013_contains_empty_dict(self):\n @njit\n def foo():\n d = dictobject.new_dict(int32, float64)\n # contains on empty dict\n return 1 in d\n\n self.assertFalse(foo())\n\n def test_014_not_contains_empty_dict(self):\n @njit\n def foo():\n d = dictobject.new_dict(int32, float64)\n # not contains empty dict\n return 1 not in d\n\n self.assertTrue(foo())\n\n def test_015_dict_clear(self):\n @njit\n def foo(n):\n d = dictobject.new_dict(int32, float64)\n for i in range(n):\n d[i] = i + 1\n x = len(d)\n d.clear()\n y = len(d)\n return x, y\n\n m = 10\n self.assertEqual(foo(m), (m, 0))\n\n def test_016_cannot_downcast_key(self):\n @njit\n def foo():\n d = dictobject.new_dict(int32, float64)\n # key is wrong type\n d.setdefault(1j, 12.)\n\n with self.assertRaises(TypingError) as raises:\n foo()\n self.assertIn(\n \"cannot safely cast complex128 to int32\",\n str(raises.exception),\n )\n\n def test_017_cannot_downcast_default(self):\n @njit\n def foo():\n d = dictobject.new_dict(int32, float64)\n # default value is wrong type\n d.setdefault(1, 12.j)\n\n with self.assertRaises(TypingError) as raises:\n foo()\n self.assertIn(\n \"cannot safely cast complex128 to float64\",\n str(raises.exception),\n )\n\n def test_018_keys_iter_are_views(self):\n # this is broken somewhere in llvmlite, intent of test is to check if\n # keys behaves like a view or not\n @njit\n def foo():\n d = dictobject.new_dict(int32, float64)\n d[11] = 12.\n k1 = d.keys()\n d[22] = 9.\n k2 = d.keys()\n rk1 = [x for x in k1]\n rk2 = [x for x in k2]\n return rk1, rk2\n\n a, b = foo()\n self.assertEqual(a, b)\n self.assertEqual(a, [11, 22])\n\n # Not implemented yet\n @unittest.expectedFailure\n def test_019(self):\n # should keys/vals be set-like?\n @njit\n def foo():\n d = dictobject.new_dict(int32, float64)\n d[11] = 12.\n d[22] = 9.\n k2 = d.keys() & {12,}\n return k2\n\n print(foo())\n\n @skip_py2\n def test_020_string_key(self):\n @njit\n def foo():\n d = dictobject.new_dict(types.unicode_type, float64)\n d['a'] = 1.\n d['b'] = 2.\n d['c'] = 3.\n d['d'] = 4.\n out = []\n for x in d.items():\n out.append(x)\n return out, d['a']\n\n items, da = foo()\n self.assertEqual(items, [('a', 1.), ('b', 2.), ('c', 3.), ('d', 4)])\n self.assertEqual(da, 1.)\n\n @skip_py2\n def test_021_long_str_key(self):\n @njit\n def foo():\n d = dictobject.new_dict(types.unicode_type, float64)\n tmp = []\n for i in range(10000):\n tmp.append('a')\n s = ''.join(tmp)\n d[s] = 1.\n out = list(d.items())\n return out\n self.assertEqual(foo(), [('a' * 10000, 1)])\n\n def test_022_references_juggle(self):\n @njit\n def foo():\n d = dictobject.new_dict(int32, float64)\n e = d\n d[1] = 12.\n e[2] = 14.\n e = dictobject.new_dict(int32, float64)\n e[1] = 100.\n e[2] = 1000.\n f = d\n d = e\n\n k1 = [x for x in d.items()]\n k2 = [x for x in e.items()]\n k3 = [x for x in f.items()]\n\n return k1, k2, k3\n\n k1, k2, k3 = foo()\n self.assertEqual(k1, [(1, 100.0), (2, 1000.0)])\n self.assertEqual(k2, [(1, 100.0), (2, 1000.0)])\n self.assertEqual(k3, [(1, 12), (2, 14)])\n\n def test_023_closure(self):\n @njit\n def foo():\n d = dictobject.new_dict(int32, float64)\n\n def bar():\n d[1] = 12.\n d[2] = 14.\n bar()\n return [x for x in d.keys()]\n\n self.assertEqual(foo(), [1, 2])\n\n\nclass TestDictTypeCasting(TestCase):\n def check_good(self, fromty, toty):\n _sentry_safe_cast(fromty, toty)\n\n def check_bad(self, fromty, toty):\n with self.assertRaises(TypingError) as raises:\n _sentry_safe_cast(fromty, toty)\n self.assertIn(\n 'cannot safely cast {fromty} to {toty}'.format(**locals()),\n str(raises.exception),\n )\n\n def test_cast_int_to(self):\n self.check_good(types.int32, types.float32)\n self.check_good(types.int32, types.float64)\n self.check_good(types.int32, types.complex128)\n self.check_good(types.int64, types.complex128)\n self.check_bad(types.int32, types.complex64)\n self.check_good(types.int8, types.complex64)\n\n def test_cast_float_to(self):\n self.check_good(types.float32, types.float64)\n self.check_good(types.float32, types.complex64)\n self.check_good(types.float64, types.complex128)\n\n def test_cast_bool_to(self):\n self.check_good(types.boolean, types.int32)\n self.check_good(types.boolean, types.float64)\n self.check_good(types.boolean, types.complex128)\n\n\nclass TestTypedDict(MemoryLeakMixin, TestCase):\n def test_basic(self):\n d = Dict.empty(int32, float32)\n # len\n self.assertEqual(len(d), 0)\n # setitems\n d[1] = 1\n d[2] = 2.3\n d[3] = 3.4\n self.assertEqual(len(d), 3)\n # keys\n self.assertEqual(list(d.keys()), [1, 2, 3])\n # values\n for x, y in zip(list(d.values()), [1, 2.3, 3.4]):\n self.assertAlmostEqual(x, y, places=4)\n # getitem\n self.assertAlmostEqual(d[1], 1)\n self.assertAlmostEqual(d[2], 2.3, places=4)\n self.assertAlmostEqual(d[3], 3.4, places=4)\n # deltiem\n del d[2]\n self.assertEqual(len(d), 2)\n # get\n self.assertIsNone(d.get(2))\n # setdefault\n d.setdefault(2, 100)\n d.setdefault(3, 200)\n self.assertEqual(d[2], 100)\n self.assertAlmostEqual(d[3], 3.4, places=4)\n # update\n d.update({4: 5, 5: 6})\n self.assertAlmostEqual(d[4], 5)\n self.assertAlmostEqual(d[5], 6)\n # contains\n self.assertTrue(4 in d)\n # items\n pyd = dict(d.items())\n self.assertEqual(len(pyd), len(d))\n # pop\n self.assertAlmostEqual(d.pop(4), 5)\n # popitem\n nelem = len(d)\n k, v = d.popitem()\n self.assertEqual(len(d), nelem - 1)\n self.assertTrue(k not in d)\n # __eq__ & copy\n copied = d.copy()\n self.assertEqual(copied, d)\n self.assertEqual(list(copied.items()), list(d.items()))\n\n def test_copy_from_dict(self):\n expect = {k: float(v) for k, v in zip(range(10), range(10, 20))}\n nbd = Dict.empty(int32, float64)\n for k, v in expect.items():\n nbd[k] = v\n got = dict(nbd)\n self.assertEqual(got, expect)\n\n def test_compiled(self):\n @njit\n def producer():\n d = Dict.empty(int32, float64)\n d[1] = 1.23\n return d\n\n @njit\n def consumer(d):\n return d[1]\n\n d = producer()\n val = consumer(d)\n self.assertEqual(val, 1.23)\n\n def check_stringify(self, strfn, prefix=False):\n nbd = Dict.empty(int32, int32)\n d = {}\n nbd[1] = 2\n d[1] = 2\n checker = self.assertIn if prefix else self.assertEqual\n checker(strfn(d), strfn(nbd))\n nbd[2] = 3\n d[2] = 3\n checker(strfn(d), strfn(nbd))\n for i in range(10, 20):\n nbd[i] = i + 1\n d[i] = i + 1\n checker(strfn(d), strfn(nbd))\n if prefix:\n self.assertTrue(strfn(nbd).startswith('DictType'))\n\n def test_repr(self):\n self.check_stringify(repr, prefix=True)\n\n def test_str(self):\n self.check_stringify(str)\n\n\nclass TestDictRefctTypes(MemoryLeakMixin, TestCase):\n @skip_py2\n def test_str_key(self):\n @njit\n def foo():\n d = Dict.empty(\n key_type=types.unicode_type,\n value_type=types.int32,\n )\n d[\"123\"] = 123\n d[\"321\"] = 321\n return d\n\n d = foo()\n self.assertEqual(d['123'], 123)\n self.assertEqual(d['321'], 321)\n expect = {'123': 123, '321': 321}\n self.assertEqual(dict(d), expect)\n # Test insert replacement\n d['123'] = 231\n expect['123'] = 231\n self.assertEqual(d['123'], 231)\n self.assertEqual(dict(d), expect)\n # Test dictionary growth\n nelem = 100\n for i in range(nelem):\n d[str(i)] = i\n expect[str(i)] = i\n for i in range(nelem):\n self.assertEqual(d[str(i)], i)\n self.assertEqual(dict(d), expect)\n\n @skip_py2\n def test_str_val(self):\n @njit\n def foo():\n d = Dict.empty(\n key_type=types.int32,\n value_type=types.unicode_type,\n )\n d[123] = \"123\"\n d[321] = \"321\"\n return d\n\n d = foo()\n self.assertEqual(d[123], '123')\n self.assertEqual(d[321], '321')\n expect = {123: '123', 321: '321'}\n self.assertEqual(dict(d), expect)\n # Test insert replacement\n d[123] = \"231\"\n expect[123] = \"231\"\n self.assertEqual(dict(d), expect)\n # Test dictionary growth\n nelem = 1\n for i in range(nelem):\n d[i] = str(i)\n expect[i] = str(i)\n for i in range(nelem):\n self.assertEqual(d[i], str(i))\n self.assertEqual(dict(d), expect)\n\n @skip_py2\n def test_str_key_array_value(self):\n np.random.seed(123)\n d = Dict.empty(\n key_type=types.unicode_type,\n value_type=types.float64[:],\n )\n expect = []\n expect.append(np.random.random(10))\n d['mass'] = expect[-1]\n expect.append(np.random.random(20))\n d['velocity'] = expect[-1]\n for i in range(100):\n expect.append(np.random.random(i))\n d[str(i)] = expect[-1]\n self.assertEqual(len(d), len(expect))\n self.assertPreciseEqual(d['mass'], expect[0])\n self.assertPreciseEqual(d['velocity'], expect[1])\n # Ordering is kept\n for got, exp in zip(d.values(), expect):\n self.assertPreciseEqual(got, exp)\n\n # Try deleting\n self.assertTrue('mass' in d)\n self.assertTrue('velocity' in d)\n del d['mass']\n self.assertFalse('mass' in d)\n del d['velocity']\n self.assertFalse('velocity' in d)\n del expect[0:2]\n\n for i in range(90):\n k, v = d.popitem()\n w = expect.pop()\n self.assertPreciseEqual(v, w)\n\n # Trigger a resize\n expect.append(np.random.random(10))\n d[\"last\"] = expect[-1]\n\n # Ordering is kept\n for got, exp in zip(d.values(), expect):\n self.assertPreciseEqual(got, exp)\n\n def test_dict_of_dict_int_keyval(self):\n def inner_numba_dict():\n d = Dict.empty(\n key_type=types.intp,\n value_type=types.intp,\n )\n return d\n\n d = Dict.empty(\n key_type=types.intp,\n value_type=types.DictType(types.intp, types.intp),\n )\n\n def usecase(d, make_inner_dict):\n for i in range(100):\n mid = make_inner_dict()\n for j in range(i + 1):\n mid[j] = j * 10000\n d[i] = mid\n return d\n\n got = usecase(d, inner_numba_dict)\n expect = usecase({}, dict)\n\n self.assertIsInstance(expect, dict)\n\n self.assertEqual(dict(got), expect)\n\n # Delete items\n for where in [12, 3, 6, 8, 10]:\n del got[where]\n del expect[where]\n self.assertEqual(dict(got), expect)\n\n def test_dict_of_dict_npm(self):\n inner_dict_ty = types.DictType(types.intp, types.intp)\n\n @njit\n def inner_numba_dict():\n d = Dict.empty(\n key_type=types.intp,\n value_type=types.intp,\n )\n return d\n\n @njit\n def foo(count):\n d = Dict.empty(\n key_type=types.intp,\n value_type=inner_dict_ty,\n )\n for i in range(count):\n d[i] = inner_numba_dict()\n for j in range(i + 1):\n d[i][j] = j\n\n return d\n\n d = foo(100)\n ct = 0\n for k, dd in d.items():\n ct += 1\n self.assertEqual(len(dd), k + 1)\n for kk, vv in dd.items():\n self.assertEqual(kk, vv)\n\n self.assertEqual(ct, 100)\n\n @skip_py2\n def test_delitem(self):\n d = Dict.empty(types.int64, types.unicode_type)\n d[1] = 'apple'\n\n @njit\n def foo(x, k):\n del x[1]\n\n foo(d, 1)\n self.assertEqual(len(d), 0)\n self.assertFalse(d)\n\n def test_getitem_return_type(self):\n # Dict.__getitem__ must return non-optional type.\n d = Dict.empty(types.int64, types.int64[:])\n d[1] = np.arange(10, dtype=np.int64)\n\n @njit\n def foo(d):\n d[1] += 100\n return d[1]\n\n foo(d)\n # Return type is an array, not optional\n retty = foo.nopython_signatures[0].return_type\n self.assertIsInstance(retty, types.Array)\n self.assertNotIsInstance(retty, types.Optional)\n # Value is correctly updated\n self.assertPreciseEqual(d[1], np.arange(10, dtype=np.int64) + 100)\n\n @skip_py2\n def test_storage_model_mismatch(self):\n # https://github.com/numba/numba/issues/4520\n # check for storage model mismatch in refcount ops generation\n dct = Dict()\n ref = [\n (\"a\", True, \"a\"),\n (\"b\", False, \"b\"),\n (\"c\", False, \"c\"),\n ]\n # populate\n for x in ref:\n dct[x] = x\n # test\n for i, x in enumerate(ref):\n self.assertEqual(dct[x], x)\n\n\nclass TestDictForbiddenTypes(TestCase):\n def assert_disallow(self, expect, callable):\n with self.assertRaises(TypingError) as raises:\n callable()\n msg = str(raises.exception)\n self.assertIn(expect, msg)\n\n def assert_disallow_key(self, ty):\n msg = '{} as key is forbidded'.format(ty)\n self.assert_disallow(msg, lambda: Dict.empty(ty, types.intp))\n\n @njit\n def foo():\n Dict.empty(ty, types.intp)\n self.assert_disallow(msg, foo)\n\n def assert_disallow_value(self, ty):\n msg = '{} as value is forbidded'.format(ty)\n self.assert_disallow(msg, lambda: Dict.empty(types.intp, ty))\n\n @njit\n def foo():\n Dict.empty(types.intp, ty)\n self.assert_disallow(msg, foo)\n\n def test_disallow_list(self):\n self.assert_disallow_key(types.List(types.intp))\n self.assert_disallow_value(types.List(types.intp))\n\n def test_disallow_set(self):\n self.assert_disallow_key(types.Set(types.intp))\n self.assert_disallow_value(types.Set(types.intp))\n\n\nclass TestDictInferred(TestCase):\n def test_simple_literal(self):\n @njit\n def foo():\n d = Dict()\n d[123] = 321\n return d\n\n k, v = 123, 321\n d = foo()\n self.assertEqual(dict(d), {k: v})\n self.assertEqual(typeof(d).key_type, typeof(k))\n self.assertEqual(typeof(d).value_type, typeof(v))\n\n def test_simple_args(self):\n @njit\n def foo(k, v):\n d = Dict()\n d[k] = v\n return d\n\n k, v = 123, 321\n d = foo(k, v)\n self.assertEqual(dict(d), {k: v})\n self.assertEqual(typeof(d).key_type, typeof(k))\n self.assertEqual(typeof(d).value_type, typeof(v))\n\n def test_simple_upcast(self):\n @njit\n def foo(k, v, w):\n d = Dict()\n d[k] = v\n d[k] = w\n return d\n\n k, v, w = 123, 32.1, 321\n d = foo(k, v, w)\n self.assertEqual(dict(d), {k: w})\n self.assertEqual(typeof(d).key_type, typeof(k))\n self.assertEqual(typeof(d).value_type, typeof(v))\n\n def test_conflicting_value_type(self):\n @njit\n def foo(k, v, w):\n d = Dict()\n d[k] = v\n d[k] = w\n return d\n\n k, v, w = 123, 321, 32.1\n with self.assertRaises(TypingError) as raises:\n foo(k, v, w)\n self.assertIn(\n 'cannot safely cast float64 to {}'.format(typeof(v)),\n str(raises.exception),\n )\n\n def test_conflicting_key_type(self):\n @njit\n def foo(k, h, v):\n d = Dict()\n d[k] = v\n d[h] = v\n return d\n\n k, h, v = 123, 123.1, 321\n with self.assertRaises(TypingError) as raises:\n foo(k, h, v)\n self.assertIn(\n 'cannot safely cast float64 to {}'.format(typeof(v)),\n str(raises.exception),\n )\n\n def test_conflict_key_type_non_number(self):\n # Allow non-number types to cast unsafely\n @njit\n def foo(k1, v1, k2):\n d = Dict()\n d[k1] = v1\n return d, d[k2]\n\n # k2 will unsafely downcast typeof(k1)\n k1 = (np.int8(1), np.int8(2))\n k2 = (np.int32(1), np.int32(2))\n v1 = np.intp(123)\n\n with warnings.catch_warnings(record=True) as w:\n d, dk2 = foo(k1, v1, k2)\n self.assertEqual(len(w), 1)\n # Make sure the warning is about unsafe cast\n self.assertIn('unsafe cast from tuple(int32 x 2) to tuple(int8 x 2)',\n str(w[0]))\n\n keys = list(d.keys())\n self.assertEqual(keys[0], (1, 2))\n self.assertEqual(dk2, d[(np.int32(1), np.int32(2))])\n\n def test_ifelse_filled_both_branches(self):\n @njit\n def foo(k, v):\n d = Dict()\n if k:\n d[k] = v\n else:\n d[0xdead] = v + 1\n\n return d\n\n k, v = 123, 321\n d = foo(k, v)\n self.assertEqual(dict(d), {k: v})\n k, v = 0, 0\n d = foo(k, v)\n self.assertEqual(dict(d), {0xdead: v + 1})\n\n def test_ifelse_empty_one_branch(self):\n @njit\n def foo(k, v):\n d = Dict()\n if k:\n d[k] = v\n\n return d\n\n k, v = 123, 321\n d = foo(k, v)\n self.assertEqual(dict(d), {k: v})\n k, v = 0, 0\n d = foo(k, v)\n self.assertEqual(dict(d), {})\n self.assertEqual(typeof(d).key_type, typeof(k))\n self.assertEqual(typeof(d).value_type, typeof(v))\n\n def test_loop(self):\n @njit\n def foo(ks, vs):\n d = Dict()\n for k, v in zip(ks, vs):\n d[k] = v\n return d\n\n vs = list(range(4))\n ks = list(map(lambda x : x + 100, vs))\n d = foo(ks, vs)\n self.assertEqual(dict(d), dict(zip(ks, vs)))\n\n def test_unused(self):\n @njit\n def foo():\n d = Dict()\n return d\n\n with self.assertRaises(TypingError) as raises:\n foo()\n self.assertIn(\n \"imprecise type\",\n str(raises.exception)\n )\n\n def test_define_after_use(self):\n @njit\n def foo(define):\n d = Dict()\n ct = len(d)\n for k, v in d.items():\n ct += v\n\n if define:\n # This will set the type\n d[1] = 2\n return ct, d, len(d)\n\n ct, d, n = foo(True)\n self.assertEqual(ct, 0)\n self.assertEqual(n, 1)\n self.assertEqual(dict(d), {1: 2})\n\n ct, d, n = foo(False)\n self.assertEqual(ct, 0)\n self.assertEqual(dict(d), {})\n self.assertEqual(n, 0)\n\n def test_dict_of_dict(self):\n @njit\n def foo(k1, k2, v):\n d = Dict()\n z1 = Dict()\n z1[k1 + 1] = v + k1\n z2 = Dict()\n z2[k2 + 2] = v + k2\n d[k1] = z1\n d[k2] = z2\n return d\n\n k1, k2, v = 100, 200, 321\n d = foo(k1, k2, v)\n self.assertEqual(\n dict(d),\n {\n k1: {k1 + 1: k1 + v},\n k2: {k2 + 2: k2 + v},\n },\n )\n\n\nclass TestNonCompiledInfer(TestCase):\n def test_check_untyped_dict_ops(self):\n # Check operation on untyped dictionary\n d = Dict()\n self.assertFalse(d._typed)\n self.assertEqual(len(d), 0)\n self.assertEqual(str(d), str({}))\n self.assertEqual(list(iter(d)), [])\n # Test __getitem__\n with self.assertRaises(KeyError) as raises:\n d[1]\n self.assertEqual(str(raises.exception), str(KeyError(1)))\n # Test __delitem__\n with self.assertRaises(KeyError) as raises:\n del d[1]\n self.assertEqual(str(raises.exception), str(KeyError(1)))\n # Test .pop\n with self.assertRaises(KeyError):\n d.pop(1)\n self.assertEqual(str(raises.exception), str(KeyError(1)))\n # Test .pop\n self.assertIs(d.pop(1, None), None)\n # Test .get\n self.assertIs(d.get(1), None)\n # Test .popitem\n with self.assertRaises(KeyError) as raises:\n d.popitem()\n self.assertEqual(str(raises.exception),\n str(KeyError('dictionary is empty')))\n # Test setdefault(k)\n with self.assertRaises(TypeError) as raises:\n d.setdefault(1)\n self.assertEqual(\n str(raises.exception),\n str(TypeError('invalid operation on untyped dictionary')),\n )\n # Test __contains__\n self.assertFalse(1 in d)\n # It's untyped\n self.assertFalse(d._typed)\n\n def test_getitem(self):\n # Test __getitem__\n d = Dict()\n d[1] = 2\n # It's typed now\n self.assertTrue(d._typed)\n self.assertEqual(d[1], 2)\n\n def test_setdefault(self):\n # Test setdefault(k, d)\n d = Dict()\n d.setdefault(1, 2)\n # It's typed now\n self.assertTrue(d._typed)\n self.assertEqual(d[1], 2)\n\n\n@jitclass(spec=[('a', types.intp)])\nclass Bag(object):\n def __init__(self, a):\n self.a = a\n\n def __hash__(self):\n return hash(self.a)\n\n\nclass TestDictWithJitclass(TestCase):\n def test_jitclass_as_value(self):\n @njit\n def foo(x):\n d = Dict()\n d[0] = x\n d[1] = Bag(101)\n return d\n\n d = foo(Bag(a=100))\n self.assertEqual(d[0].a, 100)\n self.assertEqual(d[1].a, 101)\n"
]
| [
[
"numpy.ones"
],
[
"numpy.int8",
"numpy.random.seed",
"numpy.arange",
"numpy.intp",
"numpy.uint64",
"numpy.random.random",
"numpy.int32"
]
]
|
jsilter/transformers | [
"d99ed7ad618037ae878f0758157ed0764bd7f935"
]
| [
"src/transformers/file_utils.py"
]
| [
"\"\"\"\nUtilities for working with the local dataset cache.\nThis file is adapted from the AllenNLP library at https://github.com/allenai/allennlp\nCopyright by the AllenNLP authors.\n\"\"\"\n\nimport fnmatch\nimport json\nimport os\nimport re\nimport shutil\nimport sys\nimport tarfile\nimport tempfile\nfrom collections import OrderedDict\nfrom contextlib import contextmanager\nfrom dataclasses import fields\nfrom functools import partial, wraps\nfrom hashlib import sha256\nfrom pathlib import Path\nfrom typing import Any, Dict, Optional, Tuple, Union\nfrom urllib.parse import urlparse\nfrom zipfile import ZipFile, is_zipfile\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nimport requests\nfrom filelock import FileLock\n\nfrom . import __version__\nfrom .utils import logging\n\n\nlogger = logging.get_logger(__name__) # pylint: disable=invalid-name\n\ntry:\n USE_TF = os.environ.get(\"USE_TF\", \"AUTO\").upper()\n USE_TORCH = os.environ.get(\"USE_TORCH\", \"AUTO\").upper()\n if USE_TORCH in (\"1\", \"ON\", \"YES\", \"AUTO\") and USE_TF not in (\"1\", \"ON\", \"YES\"):\n import torch\n\n _torch_available = True # pylint: disable=invalid-name\n logger.info(\"PyTorch version {} available.\".format(torch.__version__))\n else:\n logger.info(\"Disabling PyTorch because USE_TF is set\")\n _torch_available = False\nexcept ImportError:\n _torch_available = False # pylint: disable=invalid-name\n\ntry:\n USE_TF = os.environ.get(\"USE_TF\", \"AUTO\").upper()\n USE_TORCH = os.environ.get(\"USE_TORCH\", \"AUTO\").upper()\n\n if USE_TF in (\"1\", \"ON\", \"YES\", \"AUTO\") and USE_TORCH not in (\"1\", \"ON\", \"YES\"):\n import tensorflow as tf\n\n assert hasattr(tf, \"__version__\") and int(tf.__version__[0]) >= 2\n _tf_available = True # pylint: disable=invalid-name\n logger.info(\"TensorFlow version {} available.\".format(tf.__version__))\n else:\n logger.info(\"Disabling Tensorflow because USE_TORCH is set\")\n _tf_available = False\nexcept (ImportError, AssertionError):\n _tf_available = False # pylint: disable=invalid-name\n\n\ntry:\n import datasets # noqa: F401\n\n # Check we're not importing a \"datasets\" directory somewhere\n _datasets_available = hasattr(datasets, \"__version__\") and hasattr(datasets, \"load_dataset\")\n if _datasets_available:\n logger.debug(f\"Succesfully imported datasets version {datasets.__version__}\")\n else:\n logger.debug(\"Imported a datasets object but this doesn't seem to be the 🤗 datasets library.\")\n\nexcept ImportError:\n _datasets_available = False\n\ntry:\n from torch.hub import _get_torch_home\n\n torch_cache_home = _get_torch_home()\nexcept ImportError:\n torch_cache_home = os.path.expanduser(\n os.getenv(\"TORCH_HOME\", os.path.join(os.getenv(\"XDG_CACHE_HOME\", \"~/.cache\"), \"torch\"))\n )\n\n\ntry:\n import torch_xla.core.xla_model as xm # noqa: F401\n\n if _torch_available:\n _torch_tpu_available = True # pylint: disable=\n else:\n _torch_tpu_available = False\nexcept ImportError:\n _torch_tpu_available = False\n\n\ntry:\n import psutil # noqa: F401\n\n _psutil_available = True\n\nexcept ImportError:\n _psutil_available = False\n\n\ntry:\n import py3nvml # noqa: F401\n\n _py3nvml_available = True\n\nexcept ImportError:\n _py3nvml_available = False\n\n\ntry:\n from apex import amp # noqa: F401\n\n _has_apex = True\nexcept ImportError:\n _has_apex = False\n\n\ntry:\n import faiss # noqa: F401\n\n _faiss_available = True\n logger.debug(f\"Succesfully imported faiss version {faiss.__version__}\")\nexcept ImportError:\n _faiss_available = False\n\ntry:\n import sklearn.metrics # noqa: F401\n\n import scipy.stats # noqa: F401\n\n _has_sklearn = True\nexcept (AttributeError, ImportError):\n _has_sklearn = False\n\ntry:\n # Test copied from tqdm.autonotebook: https://github.com/tqdm/tqdm/blob/master/tqdm/autonotebook.py\n get_ipython = sys.modules[\"IPython\"].get_ipython\n if \"IPKernelApp\" not in get_ipython().config:\n raise ImportError(\"console\")\n if \"VSCODE_PID\" in os.environ:\n raise ImportError(\"vscode\")\n\n import IPython # noqa: F401\n\n _in_notebook = True\nexcept: # noqa: E722\n _in_notebook = False\n\n\ndefault_cache_path = os.path.join(torch_cache_home, \"transformers\")\n\n\nPYTORCH_PRETRAINED_BERT_CACHE = os.getenv(\"PYTORCH_PRETRAINED_BERT_CACHE\", default_cache_path)\nPYTORCH_TRANSFORMERS_CACHE = os.getenv(\"PYTORCH_TRANSFORMERS_CACHE\", PYTORCH_PRETRAINED_BERT_CACHE)\nTRANSFORMERS_CACHE = os.getenv(\"TRANSFORMERS_CACHE\", PYTORCH_TRANSFORMERS_CACHE)\n\nWEIGHTS_NAME = \"pytorch_model.bin\"\nTF2_WEIGHTS_NAME = \"tf_model.h5\"\nTF_WEIGHTS_NAME = \"model.ckpt\"\nCONFIG_NAME = \"config.json\"\nMODEL_CARD_NAME = \"modelcard.json\"\n\n\nMULTIPLE_CHOICE_DUMMY_INPUTS = [\n [[0, 1, 0, 1], [1, 0, 0, 1]]\n] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too.\nDUMMY_INPUTS = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]\nDUMMY_MASK = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]]\n\nS3_BUCKET_PREFIX = \"https://s3.amazonaws.com/models.huggingface.co/bert\"\nCLOUDFRONT_DISTRIB_PREFIX = \"https://cdn.huggingface.co\"\nPRESET_MIRROR_DICT = {\n \"tuna\": \"https://mirrors.tuna.tsinghua.edu.cn/hugging-face-models\",\n \"bfsu\": \"https://mirrors.bfsu.edu.cn/hugging-face-models\",\n}\n\n\ndef is_torch_available():\n return _torch_available\n\n\ndef is_tf_available():\n return _tf_available\n\n\ndef is_torch_tpu_available():\n return _torch_tpu_available\n\n\ndef is_datasets_available():\n return _datasets_available\n\n\ndef is_psutil_available():\n return _psutil_available\n\n\ndef is_py3nvml_available():\n return _py3nvml_available\n\n\ndef is_apex_available():\n return _has_apex\n\n\ndef is_faiss_available():\n return _faiss_available\n\n\ndef is_in_notebook():\n return _in_notebook\n\n\ndef torch_only_method(fn):\n def wrapper(*args, **kwargs):\n if not _torch_available:\n raise ImportError(\n \"You need to install pytorch to use this method or class, \"\n \"or activate it with environment variables USE_TORCH=1 and USE_TF=0.\"\n )\n else:\n return fn(*args, **kwargs)\n\n return wrapper\n\n\ndef is_sklearn_available():\n return _has_sklearn\n\n\nDATASETS_IMPORT_ERROR = \"\"\"\n{0} requires the 🤗 Datasets library but it was not found in your enviromnent. You can install it with:\n```\npip install datasets\n```\nIn a notebook or a colab, you can install it by executing a cell with\n```\n!pip install datasets\n```\nthen restarting your kernel.\n\nNote that if you have a local folder named `datasets` or a local python file named `datasets.py` in your current\nworking directory, python may try to import this instead of the 🤗 Datasets library. You should rename this folder or\nthat python file if that's the case.\n\"\"\"\n\n\nFAISS_IMPORT_ERROR = \"\"\"\n{0} requires the faiss library but it was not found in your enviromnent. Checkout the instructions on the\ninstallation page of its repo: https://github.com/facebookresearch/faiss/blob/master/INSTALL.md and follow the ones\nthat match your enviromnent.\n\"\"\"\n\n\nPYTORCH_IMPORT_ERROR = \"\"\"\n{0} requires the PyTorch library but it was not found in your enviromnent. Checkout the instructions on the\ninstallation page: https://pytorch.org/get-started/locally/ and follow the ones that match your enviromnent.\n\"\"\"\n\n\nSKLEARN_IMPORT_ERROR = \"\"\"\n{0} requires the scikit-learn library but it was not found in your enviromnent. You can install it with:\n```\npip install -U scikit-learn\n```\nIn a notebook or a colab, you can install it by executing a cell with\n```\n!pip install -U scikit-learn\n```\n\"\"\"\n\n\nTENSORFLOW_IMPORT_ERROR = \"\"\"\n{0} requires the TensorFlow library but it was not found in your enviromnent. Checkout the instructions on the\ninstallation page: https://www.tensorflow.org/install and follow the ones that match your enviromnent.\n\"\"\"\n\n\ndef requires_datasets(obj):\n name = obj.__name__ if hasattr(obj, \"__name__\") else obj.__class__.__name__\n if not is_datasets_available():\n raise ImportError(DATASETS_IMPORT_ERROR.format(name))\n\n\ndef requires_faiss(obj):\n name = obj.__name__ if hasattr(obj, \"__name__\") else obj.__class__.__name__\n if not is_faiss_available():\n raise ImportError(FAISS_IMPORT_ERROR.format(name))\n\n\ndef requires_pytorch(obj):\n name = obj.__name__ if hasattr(obj, \"__name__\") else obj.__class__.__name__\n if not is_torch_available():\n raise ImportError(PYTORCH_IMPORT_ERROR.format(name))\n\n\ndef requires_sklearn(obj):\n name = obj.__name__ if hasattr(obj, \"__name__\") else obj.__class__.__name__\n if not is_sklearn_available():\n raise ImportError(SKLEARN_IMPORT_ERROR.format(name))\n\n\ndef requires_tf(obj):\n name = obj.__name__ if hasattr(obj, \"__name__\") else obj.__class__.__name__\n if not is_tf_available():\n raise ImportError(TENSORFLOW_IMPORT_ERROR.format(name))\n\n\ndef add_start_docstrings(*docstr):\n def docstring_decorator(fn):\n fn.__doc__ = \"\".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else \"\")\n return fn\n\n return docstring_decorator\n\n\ndef add_start_docstrings_to_callable(*docstr):\n def docstring_decorator(fn):\n class_name = \":class:`~transformers.{}`\".format(fn.__qualname__.split(\".\")[0])\n intro = \" The {} forward method, overrides the :func:`__call__` special method.\".format(class_name)\n note = r\"\"\"\n\n .. note::\n Although the recipe for forward pass needs to be defined within\n this function, one should call the :class:`Module` instance afterwards\n instead of this since the former takes care of running the\n pre and post processing steps while the latter silently ignores them.\n \"\"\"\n fn.__doc__ = intro + note + \"\".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else \"\")\n return fn\n\n return docstring_decorator\n\n\ndef add_end_docstrings(*docstr):\n def docstring_decorator(fn):\n fn.__doc__ = fn.__doc__ + \"\".join(docstr)\n return fn\n\n return docstring_decorator\n\n\nPT_RETURN_INTRODUCTION = r\"\"\"\n Returns:\n :class:`~{full_output_type}` or :obj:`tuple(torch.FloatTensor)`:\n A :class:`~{full_output_type}` (if ``return_dict=True`` is passed or when ``config.return_dict=True``) or a\n tuple of :obj:`torch.FloatTensor` comprising various elements depending on the configuration\n (:class:`~transformers.{config_class}`) and inputs.\n\n\"\"\"\n\n\nTF_RETURN_INTRODUCTION = r\"\"\"\n Returns:\n :class:`~{full_output_type}` or :obj:`tuple(tf.Tensor)`:\n A :class:`~{full_output_type}` (if ``return_dict=True`` is passed or when ``config.return_dict=True``) or a\n tuple of :obj:`tf.Tensor` comprising various elements depending on the configuration\n (:class:`~transformers.{config_class}`) and inputs.\n\n\"\"\"\n\n\ndef _get_indent(t):\n \"\"\"Returns the indentation in the first line of t\"\"\"\n search = re.search(r\"^(\\s*)\\S\", t)\n return \"\" if search is None else search.groups()[0]\n\n\ndef _convert_output_args_doc(output_args_doc):\n \"\"\"Convert output_args_doc to display properly.\"\"\"\n # Split output_arg_doc in blocks argument/description\n indent = _get_indent(output_args_doc)\n blocks = []\n current_block = \"\"\n for line in output_args_doc.split(\"\\n\"):\n # If the indent is the same as the beginning, the line is the name of new arg.\n if _get_indent(line) == indent:\n if len(current_block) > 0:\n blocks.append(current_block[:-1])\n current_block = f\"{line}\\n\"\n else:\n # Otherwise it's part of the description of the current arg.\n # We need to remove 2 spaces to the indentation.\n current_block += f\"{line[2:]}\\n\"\n blocks.append(current_block[:-1])\n\n # Format each block for proper rendering\n for i in range(len(blocks)):\n blocks[i] = re.sub(r\"^(\\s+)(\\S+)(\\s+)\", r\"\\1- **\\2**\\3\", blocks[i])\n blocks[i] = re.sub(r\":\\s*\\n\\s*(\\S)\", r\" -- \\1\", blocks[i])\n\n return \"\\n\".join(blocks)\n\n\ndef _prepare_output_docstrings(output_type, config_class):\n \"\"\"\n Prepares the return part of the docstring using `output_type`.\n \"\"\"\n docstrings = output_type.__doc__\n\n # Remove the head of the docstring to keep the list of args only\n lines = docstrings.split(\"\\n\")\n i = 0\n while i < len(lines) and re.search(r\"^\\s*(Args|Parameters):\\s*$\", lines[i]) is None:\n i += 1\n if i < len(lines):\n docstrings = \"\\n\".join(lines[(i + 1) :])\n docstrings = _convert_output_args_doc(docstrings)\n\n # Add the return introduction\n full_output_type = f\"{output_type.__module__}.{output_type.__name__}\"\n intro = TF_RETURN_INTRODUCTION if output_type.__name__.startswith(\"TF\") else PT_RETURN_INTRODUCTION\n intro = intro.format(full_output_type=full_output_type, config_class=config_class)\n return intro + docstrings\n\n\nPT_TOKEN_CLASSIFICATION_SAMPLE = r\"\"\"\n Example::\n\n >>> from transformers import {tokenizer_class}, {model_class}\n >>> import torch\n\n >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')\n >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True)\n\n >>> inputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"pt\")\n >>> labels = torch.tensor([1] * inputs[\"input_ids\"].size(1)).unsqueeze(0) # Batch size 1\n\n >>> outputs = model(**inputs, labels=labels)\n >>> loss = outputs.loss\n >>> logits = outputs.logits\n\"\"\"\n\nPT_QUESTION_ANSWERING_SAMPLE = r\"\"\"\n Example::\n\n >>> from transformers import {tokenizer_class}, {model_class}\n >>> import torch\n\n >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')\n >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True)\n\n >>> question, text = \"Who was Jim Henson?\", \"Jim Henson was a nice puppet\"\n >>> inputs = tokenizer(question, text, return_tensors='pt')\n >>> start_positions = torch.tensor([1])\n >>> end_positions = torch.tensor([3])\n\n >>> outputs = model(**inputs, start_positions=start_positions, end_positions=end_positions)\n >>> loss = outputs.loss\n >>> start_scores = outputs.start_logits\n >>> end_scores = outputs.end_logits\n\"\"\"\n\nPT_SEQUENCE_CLASSIFICATION_SAMPLE = r\"\"\"\n Example::\n\n >>> from transformers import {tokenizer_class}, {model_class}\n >>> import torch\n\n >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')\n >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True)\n\n >>> inputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"pt\")\n >>> labels = torch.tensor([1]).unsqueeze(0) # Batch size 1\n >>> outputs = model(**inputs, labels=labels)\n >>> loss = outputs.loss\n >>> logits = outputs.logits\n\"\"\"\n\nPT_MASKED_LM_SAMPLE = r\"\"\"\n Example::\n\n >>> from transformers import {tokenizer_class}, {model_class}\n >>> import torch\n\n >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')\n >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True)\n\n >>> inputs = tokenizer(\"The capital of France is {mask}.\", return_tensors=\"pt\")\n >>> labels = tokenizer(\"The capital of France is Paris.\", return_tensors=\"pt\")[\"input_ids\"]\n\n >>> outputs = model(**inputs, labels=labels)\n >>> loss = outputs.loss\n >>> logits = outputs.logits\n\"\"\"\n\nPT_BASE_MODEL_SAMPLE = r\"\"\"\n Example::\n\n >>> from transformers import {tokenizer_class}, {model_class}\n >>> import torch\n\n >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')\n >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True)\n\n >>> inputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n\n >>> last_hidden_states = outputs.last_hidden_state\n\"\"\"\n\nPT_MULTIPLE_CHOICE_SAMPLE = r\"\"\"\n Example::\n\n >>> from transformers import {tokenizer_class}, {model_class}\n >>> import torch\n\n >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')\n >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True)\n\n >>> prompt = \"In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced.\"\n >>> choice0 = \"It is eaten with a fork and a knife.\"\n >>> choice1 = \"It is eaten while held in the hand.\"\n >>> labels = torch.tensor(0).unsqueeze(0) # choice0 is correct (according to Wikipedia ;)), batch size 1\n\n >>> encoding = tokenizer([[prompt, prompt], [choice0, choice1]], return_tensors='pt', padding=True)\n >>> outputs = model(**{{k: v.unsqueeze(0) for k,v in encoding.items()}}, labels=labels) # batch size is 1\n\n >>> # the linear classifier still needs to be trained\n >>> loss = outputs.loss\n >>> logits = outputs.logits\n\"\"\"\n\nPT_CAUSAL_LM_SAMPLE = r\"\"\"\n Example::\n\n >>> import torch\n >>> from transformers import {tokenizer_class}, {model_class}\n\n >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')\n >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True)\n\n >>> inputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"pt\")\n >>> outputs = model(**inputs, labels=inputs[\"input_ids\"])\n >>> loss = outputs.loss\n >>> logits = outputs.logits\n\"\"\"\n\nTF_TOKEN_CLASSIFICATION_SAMPLE = r\"\"\"\n Example::\n\n >>> from transformers import {tokenizer_class}, {model_class}\n >>> import tensorflow as tf\n\n >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')\n >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True))\n\n >>> inputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"tf\")\n >>> input_ids = inputs[\"input_ids\"]\n >>> inputs[\"labels\"] = tf.reshape(tf.constant([1] * tf.size(input_ids).numpy()), (-1, tf.size(input_ids))) # Batch size 1\n\n >>> outputs = model(inputs)\n >>> loss = outputs.loss\n >>> logits = outputs.logits\n\"\"\"\n\nTF_QUESTION_ANSWERING_SAMPLE = r\"\"\"\n Example::\n\n >>> from transformers import {tokenizer_class}, {model_class}\n >>> import tensorflow as tf\n\n >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')\n >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True))\n\n >>> question, text = \"Who was Jim Henson?\", \"Jim Henson was a nice puppet\"\n >>> input_dict = tokenizer(question, text, return_tensors='tf')\n >>> outputs = model(input_dict)\n >>> start_logits = outputs.start_logits\n >>> end_logits = outputs.end_logits\n\n >>> all_tokens = tokenizer.convert_ids_to_tokens(input_dict[\"input_ids\"].numpy()[0])\n >>> answer = ' '.join(all_tokens[tf.math.argmax(start_logits, 1)[0] : tf.math.argmax(end_logits, 1)[0]+1])\n\"\"\"\n\nTF_SEQUENCE_CLASSIFICATION_SAMPLE = r\"\"\"\n Example::\n\n >>> from transformers import {tokenizer_class}, {model_class}\n >>> import tensorflow as tf\n\n >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')\n >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True))\n\n >>> inputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"tf\")\n >>> inputs[\"labels\"] = tf.reshape(tf.constant(1), (-1, 1)) # Batch size 1\n\n >>> outputs = model(inputs)\n >>> loss = outputs.loss\n >>> logits = outputs.logits\n\"\"\"\n\nTF_MASKED_LM_SAMPLE = r\"\"\"\n Example::\n\n >>> from transformers import {tokenizer_class}, {model_class}\n >>> import tensorflow as tf\n\n >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')\n >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True))\n\n >>> inputs = tokenizer(\"The capital of France is {mask}.\", return_tensors=\"tf\")\n >>> inputs[\"labels\"] = tokenizer(\"The capital of France is Paris.\", return_tensors=\"tf\")[\"input_ids\"]\n\n >>> outputs = model(inputs)\n >>> loss = outputs.loss\n >>> logits = outputs.logits\n\"\"\"\n\nTF_BASE_MODEL_SAMPLE = r\"\"\"\n Example::\n\n >>> from transformers import {tokenizer_class}, {model_class}\n >>> import tensorflow as tf\n\n >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')\n >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True))\n\n >>> inputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"tf\")\n >>> outputs = model(inputs)\n\n >>> last_hidden_states = outputs.last_hidden_states\n\"\"\"\n\nTF_MULTIPLE_CHOICE_SAMPLE = r\"\"\"\n Example::\n\n >>> from transformers import {tokenizer_class}, {model_class}\n >>> import tensorflow as tf\n\n >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')\n >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True))\n\n >>> prompt = \"In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced.\"\n >>> choice0 = \"It is eaten with a fork and a knife.\"\n >>> choice1 = \"It is eaten while held in the hand.\"\n\n >>> encoding = tokenizer([[prompt, prompt], [choice0, choice1]], return_tensors='tf', padding=True)\n >>> inputs = {{k: tf.expand_dims(v, 0) for k, v in encoding.items()}}\n >>> outputs = model(inputs) # batch size is 1\n\n >>> # the linear classifier still needs to be trained\n >>> logits = outputs.logits\n\"\"\"\n\nTF_CAUSAL_LM_SAMPLE = r\"\"\"\n Example::\n\n >>> from transformers import {tokenizer_class}, {model_class}\n >>> import tensorflow as tf\n\n >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')\n >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True))\n\n >>> inputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"tf\")\n >>> outputs = model(inputs)\n >>> logits = outputs.logits\n\"\"\"\n\n\ndef add_code_sample_docstrings(\n *docstr, tokenizer_class=None, checkpoint=None, output_type=None, config_class=None, mask=None\n):\n def docstring_decorator(fn):\n model_class = fn.__qualname__.split(\".\")[0]\n is_tf_class = model_class[:2] == \"TF\"\n doc_kwargs = dict(model_class=model_class, tokenizer_class=tokenizer_class, checkpoint=checkpoint)\n\n if \"SequenceClassification\" in model_class:\n code_sample = TF_SEQUENCE_CLASSIFICATION_SAMPLE if is_tf_class else PT_SEQUENCE_CLASSIFICATION_SAMPLE\n elif \"QuestionAnswering\" in model_class:\n code_sample = TF_QUESTION_ANSWERING_SAMPLE if is_tf_class else PT_QUESTION_ANSWERING_SAMPLE\n elif \"TokenClassification\" in model_class:\n code_sample = TF_TOKEN_CLASSIFICATION_SAMPLE if is_tf_class else PT_TOKEN_CLASSIFICATION_SAMPLE\n elif \"MultipleChoice\" in model_class:\n code_sample = TF_MULTIPLE_CHOICE_SAMPLE if is_tf_class else PT_MULTIPLE_CHOICE_SAMPLE\n elif \"MaskedLM\" in model_class or model_class in [\"FlaubertWithLMHeadModel\", \"XLMWithLMHeadModel\"]:\n doc_kwargs[\"mask\"] = \"[MASK]\" if mask is None else mask\n code_sample = TF_MASKED_LM_SAMPLE if is_tf_class else PT_MASKED_LM_SAMPLE\n elif \"LMHead\" in model_class:\n code_sample = TF_CAUSAL_LM_SAMPLE if is_tf_class else PT_CAUSAL_LM_SAMPLE\n elif \"Model\" in model_class or \"Encoder\" in model_class:\n code_sample = TF_BASE_MODEL_SAMPLE if is_tf_class else PT_BASE_MODEL_SAMPLE\n else:\n raise ValueError(f\"Docstring can't be built for model {model_class}\")\n\n output_doc = _prepare_output_docstrings(output_type, config_class) if output_type is not None else \"\"\n built_doc = code_sample.format(**doc_kwargs)\n fn.__doc__ = (fn.__doc__ or \"\") + \"\".join(docstr) + output_doc + built_doc\n return fn\n\n return docstring_decorator\n\n\ndef replace_return_docstrings(output_type=None, config_class=None):\n def docstring_decorator(fn):\n docstrings = fn.__doc__\n lines = docstrings.split(\"\\n\")\n i = 0\n while i < len(lines) and re.search(r\"^\\s*Returns?:\\s*$\", lines[i]) is None:\n i += 1\n if i < len(lines):\n lines[i] = _prepare_output_docstrings(output_type, config_class)\n docstrings = \"\\n\".join(lines)\n else:\n raise ValueError(\n f\"The function {fn} should have an empty 'Return:' or 'Returns:' in its docstring as placeholder, current docstring is:\\n{docstrings}\"\n )\n fn.__doc__ = docstrings\n return fn\n\n return docstring_decorator\n\n\ndef is_remote_url(url_or_filename):\n parsed = urlparse(url_or_filename)\n return parsed.scheme in (\"http\", \"https\")\n\n\ndef hf_bucket_url(model_id: str, filename: str, use_cdn=True, mirror=None) -> str:\n \"\"\"\n Resolve a model identifier, and a file name, to a HF-hosted url\n on either S3 or Cloudfront (a Content Delivery Network, or CDN).\n\n Cloudfront is replicated over the globe so downloads are way faster\n for the end user (and it also lowers our bandwidth costs). However, it\n is more aggressively cached by default, so may not always reflect the\n latest changes to the underlying file (default TTL is 24 hours).\n\n In terms of client-side caching from this library, even though\n Cloudfront relays the ETags from S3, using one or the other\n (or switching from one to the other) will affect caching: cached files\n are not shared between the two because the cached file's name contains\n a hash of the url.\n \"\"\"\n endpoint = (\n PRESET_MIRROR_DICT.get(mirror, mirror)\n if mirror\n else CLOUDFRONT_DISTRIB_PREFIX\n if use_cdn\n else S3_BUCKET_PREFIX\n )\n legacy_format = \"/\" not in model_id\n if legacy_format:\n return f\"{endpoint}/{model_id}-{filename}\"\n else:\n return f\"{endpoint}/{model_id}/{filename}\"\n\n\ndef url_to_filename(url, etag=None):\n \"\"\"\n Convert `url` into a hashed filename in a repeatable way.\n If `etag` is specified, append its hash to the url's, delimited\n by a period.\n If the url ends with .h5 (Keras HDF5 weights) adds '.h5' to the name\n so that TF 2.0 can identify it as a HDF5 file\n (see https://github.com/tensorflow/tensorflow/blob/00fad90125b18b80fe054de1055770cfb8fe4ba3/tensorflow/python/keras/engine/network.py#L1380)\n \"\"\"\n url_bytes = url.encode(\"utf-8\")\n url_hash = sha256(url_bytes)\n filename = url_hash.hexdigest()\n\n if etag:\n etag_bytes = etag.encode(\"utf-8\")\n etag_hash = sha256(etag_bytes)\n filename += \".\" + etag_hash.hexdigest()\n\n if url.endswith(\".h5\"):\n filename += \".h5\"\n\n return filename\n\n\ndef filename_to_url(filename, cache_dir=None):\n \"\"\"\n Return the url and etag (which may be ``None``) stored for `filename`.\n Raise ``EnvironmentError`` if `filename` or its stored metadata do not exist.\n \"\"\"\n if cache_dir is None:\n cache_dir = TRANSFORMERS_CACHE\n if isinstance(cache_dir, Path):\n cache_dir = str(cache_dir)\n\n cache_path = os.path.join(cache_dir, filename)\n if not os.path.exists(cache_path):\n raise EnvironmentError(\"file {} not found\".format(cache_path))\n\n meta_path = cache_path + \".json\"\n if not os.path.exists(meta_path):\n raise EnvironmentError(\"file {} not found\".format(meta_path))\n\n with open(meta_path, encoding=\"utf-8\") as meta_file:\n metadata = json.load(meta_file)\n url = metadata[\"url\"]\n etag = metadata[\"etag\"]\n\n return url, etag\n\n\ndef cached_path(\n url_or_filename,\n cache_dir=None,\n force_download=False,\n proxies=None,\n resume_download=False,\n user_agent: Union[Dict, str, None] = None,\n extract_compressed_file=False,\n force_extract=False,\n local_files_only=False,\n) -> Optional[str]:\n \"\"\"\n Given something that might be a URL (or might be a local path),\n determine which. If it's a URL, download the file and cache it, and\n return the path to the cached file. If it's already a local path,\n make sure the file exists and then return the path.\n Args:\n cache_dir: specify a cache directory to save the file to (overwrite the default cache dir).\n force_download: if True, re-dowload the file even if it's already cached in the cache dir.\n resume_download: if True, resume the download if incompletly recieved file is found.\n user_agent: Optional string or dict that will be appended to the user-agent on remote requests.\n extract_compressed_file: if True and the path point to a zip or tar file, extract the compressed\n file in a folder along the archive.\n force_extract: if True when extract_compressed_file is True and the archive was already extracted,\n re-extract the archive and overide the folder where it was extracted.\n\n Return:\n None in case of non-recoverable file (non-existent or inaccessible url + no cache on disk).\n Local path (string) otherwise\n \"\"\"\n if cache_dir is None:\n cache_dir = TRANSFORMERS_CACHE\n if isinstance(url_or_filename, Path):\n url_or_filename = str(url_or_filename)\n if isinstance(cache_dir, Path):\n cache_dir = str(cache_dir)\n\n if is_remote_url(url_or_filename):\n # URL, so get it from the cache (downloading if necessary)\n output_path = get_from_cache(\n url_or_filename,\n cache_dir=cache_dir,\n force_download=force_download,\n proxies=proxies,\n resume_download=resume_download,\n user_agent=user_agent,\n local_files_only=local_files_only,\n )\n elif os.path.exists(url_or_filename):\n # File, and it exists.\n output_path = url_or_filename\n elif urlparse(url_or_filename).scheme == \"\":\n # File, but it doesn't exist.\n raise EnvironmentError(\"file {} not found\".format(url_or_filename))\n else:\n # Something unknown\n raise ValueError(\"unable to parse {} as a URL or as a local path\".format(url_or_filename))\n\n if extract_compressed_file:\n if not is_zipfile(output_path) and not tarfile.is_tarfile(output_path):\n return output_path\n\n # Path where we extract compressed archives\n # We avoid '.' in dir name and add \"-extracted\" at the end: \"./model.zip\" => \"./model-zip-extracted/\"\n output_dir, output_file = os.path.split(output_path)\n output_extract_dir_name = output_file.replace(\".\", \"-\") + \"-extracted\"\n output_path_extracted = os.path.join(output_dir, output_extract_dir_name)\n\n if os.path.isdir(output_path_extracted) and os.listdir(output_path_extracted) and not force_extract:\n return output_path_extracted\n\n # Prevent parallel extractions\n lock_path = output_path + \".lock\"\n with FileLock(lock_path):\n shutil.rmtree(output_path_extracted, ignore_errors=True)\n os.makedirs(output_path_extracted)\n if is_zipfile(output_path):\n with ZipFile(output_path, \"r\") as zip_file:\n zip_file.extractall(output_path_extracted)\n zip_file.close()\n elif tarfile.is_tarfile(output_path):\n tar_file = tarfile.open(output_path)\n tar_file.extractall(output_path_extracted)\n tar_file.close()\n else:\n raise EnvironmentError(\"Archive format of {} could not be identified\".format(output_path))\n\n return output_path_extracted\n\n return output_path\n\n\ndef http_get(url, temp_file, proxies=None, resume_size=0, user_agent: Union[Dict, str, None] = None):\n ua = \"transformers/{}; python/{}\".format(__version__, sys.version.split()[0])\n if is_torch_available():\n ua += \"; torch/{}\".format(torch.__version__)\n if is_tf_available():\n ua += \"; tensorflow/{}\".format(tf.__version__)\n if isinstance(user_agent, dict):\n ua += \"; \" + \"; \".join(\"{}/{}\".format(k, v) for k, v in user_agent.items())\n elif isinstance(user_agent, str):\n ua += \"; \" + user_agent\n headers = {\"user-agent\": ua}\n if resume_size > 0:\n headers[\"Range\"] = \"bytes=%d-\" % (resume_size,)\n response = requests.get(url, stream=True, proxies=proxies, headers=headers)\n if response.status_code == 416: # Range not satisfiable\n return\n content_length = response.headers.get(\"Content-Length\")\n total = resume_size + int(content_length) if content_length is not None else None\n progress = tqdm(\n unit=\"B\",\n unit_scale=True,\n total=total,\n initial=resume_size,\n desc=\"Downloading\",\n disable=bool(logging.get_verbosity() == logging.NOTSET),\n )\n for chunk in response.iter_content(chunk_size=1024):\n if chunk: # filter out keep-alive new chunks\n progress.update(len(chunk))\n temp_file.write(chunk)\n progress.close()\n\n\ndef get_from_cache(\n url,\n cache_dir=None,\n force_download=False,\n proxies=None,\n etag_timeout=10,\n resume_download=False,\n user_agent: Union[Dict, str, None] = None,\n local_files_only=False,\n) -> Optional[str]:\n \"\"\"\n Given a URL, look for the corresponding file in the local cache.\n If it's not there, download it. Then return the path to the cached file.\n\n Return:\n None in case of non-recoverable file (non-existent or inaccessible url + no cache on disk).\n Local path (string) otherwise\n \"\"\"\n if cache_dir is None:\n cache_dir = TRANSFORMERS_CACHE\n if isinstance(cache_dir, Path):\n cache_dir = str(cache_dir)\n\n os.makedirs(cache_dir, exist_ok=True)\n\n etag = None\n if not local_files_only:\n try:\n response = requests.head(url, allow_redirects=True, proxies=proxies, timeout=etag_timeout)\n if response.status_code == 200:\n etag = response.headers.get(\"ETag\")\n except (EnvironmentError, requests.exceptions.Timeout):\n # etag is already None\n pass\n\n filename = url_to_filename(url, etag)\n\n # get cache path to put the file\n cache_path = os.path.join(cache_dir, filename)\n\n # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.\n # try to get the last downloaded one\n if etag is None:\n if os.path.exists(cache_path):\n return cache_path\n else:\n matching_files = [\n file\n for file in fnmatch.filter(os.listdir(cache_dir), filename.split(\".\")[0] + \".*\")\n if not file.endswith(\".json\") and not file.endswith(\".lock\")\n ]\n if len(matching_files) > 0:\n return os.path.join(cache_dir, matching_files[-1])\n else:\n # If files cannot be found and local_files_only=True,\n # the models might've been found if local_files_only=False\n # Notify the user about that\n if local_files_only:\n raise ValueError(\n \"Cannot find the requested files in the cached path and outgoing traffic has been\"\n \" disabled. To enable model look-ups and downloads online, set 'local_files_only'\"\n \" to False.\"\n )\n return None\n\n # From now on, etag is not None.\n if os.path.exists(cache_path) and not force_download:\n return cache_path\n\n # Prevent parallel downloads of the same file with a lock.\n lock_path = cache_path + \".lock\"\n with FileLock(lock_path):\n\n # If the download just completed while the lock was activated.\n if os.path.exists(cache_path) and not force_download:\n # Even if returning early like here, the lock will be released.\n return cache_path\n\n if resume_download:\n incomplete_path = cache_path + \".incomplete\"\n\n @contextmanager\n def _resumable_file_manager():\n with open(incomplete_path, \"a+b\") as f:\n yield f\n\n temp_file_manager = _resumable_file_manager\n if os.path.exists(incomplete_path):\n resume_size = os.stat(incomplete_path).st_size\n else:\n resume_size = 0\n else:\n temp_file_manager = partial(tempfile.NamedTemporaryFile, dir=cache_dir, delete=False)\n resume_size = 0\n\n # Download to temporary file, then copy to cache dir once finished.\n # Otherwise you get corrupt cache entries if the download gets interrupted.\n with temp_file_manager() as temp_file:\n logger.info(\"%s not found in cache or force_download set to True, downloading to %s\", url, temp_file.name)\n\n http_get(url, temp_file, proxies=proxies, resume_size=resume_size, user_agent=user_agent)\n\n logger.info(\"storing %s in cache at %s\", url, cache_path)\n os.replace(temp_file.name, cache_path)\n\n logger.info(\"creating metadata file for %s\", cache_path)\n meta = {\"url\": url, \"etag\": etag}\n meta_path = cache_path + \".json\"\n with open(meta_path, \"w\") as meta_file:\n json.dump(meta, meta_file)\n\n return cache_path\n\n\nclass cached_property(property):\n \"\"\"\n Descriptor that mimics @property but caches output in member variable.\n\n From tensorflow_datasets\n\n Built-in in functools from Python 3.8.\n \"\"\"\n\n def __get__(self, obj, objtype=None):\n # See docs.python.org/3/howto/descriptor.html#properties\n if obj is None:\n return self\n if self.fget is None:\n raise AttributeError(\"unreadable attribute\")\n attr = \"__cached_\" + self.fget.__name__\n cached = getattr(obj, attr, None)\n if cached is None:\n cached = self.fget(obj)\n setattr(obj, attr, cached)\n return cached\n\n\ndef torch_required(func):\n # Chose a different decorator name than in tests so it's clear they are not the same.\n @wraps(func)\n def wrapper(*args, **kwargs):\n if is_torch_available():\n return func(*args, **kwargs)\n else:\n raise ImportError(f\"Method `{func.__name__}` requires PyTorch.\")\n\n return wrapper\n\n\ndef tf_required(func):\n # Chose a different decorator name than in tests so it's clear they are not the same.\n @wraps(func)\n def wrapper(*args, **kwargs):\n if is_tf_available():\n return func(*args, **kwargs)\n else:\n raise ImportError(f\"Method `{func.__name__}` requires TF.\")\n\n return wrapper\n\n\ndef is_tensor(x):\n \"\"\" Tests if ``x`` is a :obj:`torch.Tensor`, :obj:`tf.Tensor` or :obj:`np.ndarray`. \"\"\"\n if is_torch_available():\n import torch\n\n if isinstance(x, torch.Tensor):\n return True\n if is_tf_available():\n import tensorflow as tf\n\n if isinstance(x, tf.Tensor):\n return True\n return isinstance(x, np.ndarray)\n\n\nclass ModelOutput(OrderedDict):\n \"\"\"\n Base class for all model outputs as dataclass. Has a ``__getitem__`` that allows indexing by integer or slice (like\n a tuple) or strings (like a dictionary) that will ignore the ``None`` attributes. Otherwise behaves like a\n regular python dictionary.\n\n .. warning::\n You can't unpack a :obj:`ModelOutput` directly. Use the :meth:`~transformers.file_utils.ModelOutput.to_tuple`\n method to convert it to a tuple before.\n \"\"\"\n\n def __post_init__(self):\n class_fields = fields(self)\n\n # Safety and consistency checks\n assert len(class_fields), f\"{self.__class__.__name__} has no fields.\"\n assert all(\n field.default is None for field in class_fields[1:]\n ), f\"{self.__class__.__name__} should not have more than one required field.\"\n\n first_field = getattr(self, class_fields[0].name)\n other_fields_are_none = all(getattr(self, field.name) is None for field in class_fields[1:])\n\n if other_fields_are_none and not is_tensor(first_field):\n try:\n iterator = iter(first_field)\n first_field_iterator = True\n except TypeError:\n first_field_iterator = False\n\n # if we provided an iterator as first field and the iterator is a (key, value) iterator\n # set the associated fields\n if first_field_iterator:\n for element in iterator:\n if (\n not isinstance(element, (list, tuple))\n or not len(element) == 2\n or not isinstance(element[0], str)\n ):\n break\n setattr(self, element[0], element[1])\n if element[1] is not None:\n self[element[0]] = element[1]\n elif first_field is not None:\n self[class_fields[0].name] = first_field\n else:\n for field in class_fields:\n v = getattr(self, field.name)\n if v is not None:\n self[field.name] = v\n\n def __delitem__(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.\")\n\n def setdefault(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.\")\n\n def pop(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``pop`` on a {self.__class__.__name__} instance.\")\n\n def update(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``update`` on a {self.__class__.__name__} instance.\")\n\n def __getitem__(self, k):\n if isinstance(k, str):\n inner_dict = {k: v for (k, v) in self.items()}\n return inner_dict[k]\n else:\n return self.to_tuple()[k]\n\n def __setattr__(self, name, value):\n if name in self.keys() and value is not None:\n # Don't call self.__setitem__ to avoid recursion errors\n super().__setitem__(name, value)\n super().__setattr__(name, value)\n\n def __setitem__(self, key, value):\n # Will raise a KeyException if needed\n super().__setitem__(key, value)\n # Don't call self.__setattr__ to avoid recursion errors\n super().__setattr__(key, value)\n\n def to_tuple(self) -> Tuple[Any]:\n \"\"\"\n Convert self to a tuple containing all the attributes/keys that are not ``None``.\n \"\"\"\n return tuple(self[k] for k in self.keys())\n"
]
| [
[
"torch.hub._get_torch_home"
]
]
|
neurospin/nipy | [
"cc54600a0dca1e003ad393bc05c46f91eef30a68"
]
| [
"nipy/core/reference/spaces.py"
]
| [
"\"\"\" Useful neuroimaging coordinate map makers and utilities \"\"\"\n\nimport numpy as np\n\nfrom .coordinate_system import CoordSysMaker\nfrom .coordinate_map import CoordMapMaker\nfrom ..transforms.affines import from_matrix_vector\n\nscanner_names = ['scanner-' + label for label in 'xyz'] + ['t']\nmni_names = ['mni-' + label for label in 'xyz'] + ['t']\ntalairach_names = ['talairach-' + label for label in 'xyz'] + ['t']\n\n# Some standard coordinate system makers\nvoxel_cs = CoordSysMaker('ijkl', 'array')\nscanner_cs = CoordSysMaker(scanner_names, 'scanner')\nmni_cs = CoordSysMaker(mni_names, 'mni')\ntalairach_cs = CoordSysMaker(talairach_names, 'talairach')\n\n# Standard coordinate map makers\nvox2scanner = CoordMapMaker(voxel_cs, scanner_cs)\nvox2mni = CoordMapMaker(voxel_cs, mni_cs)\nvox2talairach = CoordMapMaker(voxel_cs, talairach_cs)\n\n# Register these xyzs as known\nknown_names = {}\nfor _rcs in (scanner_names, mni_names, talairach_names):\n for _name, _coord in zip(_rcs[:3], 'xyz'):\n known_names[_name] = _coord\n\n\nclass SpaceError(Exception):\n pass\n\nclass SpaceTypeError(SpaceError):\n pass\n\nclass AxesError(SpaceError):\n pass\n\nclass AffineError(SpaceError):\n pass\n\ndef xyz_affine(coordmap, name2xyz=None):\n \"\"\" Return voxel to XYZ affine for `coordmap`\n\n Parameters\n ----------\n coordmap : ``CoordinateMap`` instance\n name2xyz : None or mapping\n Object such that ``name2xyz[ax_name]`` returns 'x', or 'y' or 'z' or\n raises a KeyError for a str ``ax_name``. None means use module default.\n\n Returns\n -------\n xyz_aff : (4,4) array\n voxel to X, Y, Z affine mapping\n\n Raises\n ------\n SpaceTypeError : if this is not an affine coordinate map\n AxesError : if not all of x, y, z recognized in `coordmap` range\n AffineError : if axes dropped from the affine contribute to x, y, z\n coordinates\n\n Examples\n --------\n >>> cmap = vox2mni(np.diag([2,3,4,5,1]))\n >>> cmap\n AffineTransform(\n function_domain=CoordinateSystem(coord_names=('i', 'j', 'k', 'l'), name='array', coord_dtype=float64),\n function_range=CoordinateSystem(coord_names=('mni-x', 'mni-y', 'mni-z', 't'), name='mni', coord_dtype=float64),\n affine=array([[ 2., 0., 0., 0., 0.],\n [ 0., 3., 0., 0., 0.],\n [ 0., 0., 4., 0., 0.],\n [ 0., 0., 0., 5., 0.],\n [ 0., 0., 0., 0., 1.]])\n )\n >>> xyz_affine(cmap)\n array([[ 2., 0., 0., 0.],\n [ 0., 3., 0., 0.],\n [ 0., 0., 4., 0.],\n [ 0., 0., 0., 1.]])\n \"\"\"\n if name2xyz is None:\n name2xyz = known_names\n try:\n affine = coordmap.affine\n except AttributeError:\n raise SpaceTypeError('Need affine coordinate map')\n order = xyz_order(coordmap.function_range, name2xyz)\n affine = affine[order[:3]]\n # Check that dropped dimensions don't provide xyz coordinate info\n extra_cols = affine[:,3:-1]\n if not np.allclose(extra_cols, 0):\n raise AffineError('Dropped dimensions not orthogonal to xyz')\n return from_matrix_vector(affine[:3,:3], affine[:3,-1])\n\n\ndef xyz_order(coordsys, name2xyz=None):\n \"\"\" Vector of orders for sorting coordsys axes in xyz first order\n\n Parameters\n ----------\n coordsys : ``CoordinateSystem`` instance\n name2xyz : None or mapping\n Object such that ``name2xyz[ax_name]`` returns 'x', or 'y' or 'z' or\n raises a KeyError for a str ``ax_name``. None means use module default.\n\n Returns\n -------\n xyz_order : list\n Ordering of axes to get xyz first ordering. See the examples.\n\n Raises\n ------\n AxesError : if there are not all of x, y and z axes\n\n Examples\n --------\n >>> from nipy.core.api import CoordinateSystem\n >>> xyzt_cs = mni_cs(4) # coordsys with t (time) last\n >>> xyzt_cs\n CoordinateSystem(coord_names=('mni-x', 'mni-y', 'mni-z', 't'), name='mni', coord_dtype=float64)\n >>> xyz_order(xyzt_cs)\n [0, 1, 2, 3]\n >>> tzyx_cs = CoordinateSystem(xyzt_cs.coord_names[::-1], 'reversed')\n >>> tzyx_cs\n CoordinateSystem(coord_names=('t', 'mni-z', 'mni-y', 'mni-x'), name='reversed', coord_dtype=float64)\n >>> xyz_order(tzyx_cs)\n [3, 2, 1, 0]\n \"\"\"\n if name2xyz is None:\n name2xyz = known_names\n names = coordsys.coord_names\n N = len(names)\n axvals = np.zeros(N, dtype=int)\n for i, name in enumerate(names):\n try:\n xyz_char = name2xyz[name]\n except KeyError:\n axvals[i] = N+i\n else:\n axvals[i] = 'xyz'.index(xyz_char)\n if not set(axvals).issuperset(range(3)):\n raise AxesError(\"Not all of x, y, z recognized in coordinate map\")\n return list(np.argsort(axvals))\n\n\ndef is_xyz_affable(coordmap, name2xyz=None):\n \"\"\" Return True if the coordap has an xyz affine\n\n Parameters\n ----------\n coordmap : ``CoordinateMap`` instance\n Coordinate map to test\n name2xyz : None or mapping\n Object such that ``name2xyz[ax_name]`` returns 'x', or 'y' or 'z' or\n raises a KeyError for a str ``ax_name``. None means use module default.\n\n Returns\n -------\n tf : bool\n True if `coordmap` has an xyz affine, False otherwise\n\n Examples\n --------\n >>> cmap = vox2mni(np.diag([2,3,4,5,1]))\n >>> cmap\n AffineTransform(\n function_domain=CoordinateSystem(coord_names=('i', 'j', 'k', 'l'), name='array', coord_dtype=float64),\n function_range=CoordinateSystem(coord_names=('mni-x', 'mni-y', 'mni-z', 't'), name='mni', coord_dtype=float64),\n affine=array([[ 2., 0., 0., 0., 0.],\n [ 0., 3., 0., 0., 0.],\n [ 0., 0., 4., 0., 0.],\n [ 0., 0., 0., 5., 0.],\n [ 0., 0., 0., 0., 1.]])\n )\n >>> is_xyz_affable(cmap)\n True\n >>> time0_cmap = cmap.reordered_domain([3,0,1,2])\n >>> time0_cmap\n AffineTransform(\n function_domain=CoordinateSystem(coord_names=('l', 'i', 'j', 'k'), name='array', coord_dtype=float64),\n function_range=CoordinateSystem(coord_names=('mni-x', 'mni-y', 'mni-z', 't'), name='mni', coord_dtype=float64),\n affine=array([[ 0., 2., 0., 0., 0.],\n [ 0., 0., 3., 0., 0.],\n [ 0., 0., 0., 4., 0.],\n [ 5., 0., 0., 0., 0.],\n [ 0., 0., 0., 0., 1.]])\n )\n >>> is_xyz_affable(time0_cmap)\n False\n \"\"\"\n try:\n xyz_affine(coordmap, name2xyz)\n except SpaceError:\n return False\n return True\n"
]
| [
[
"numpy.allclose",
"numpy.argsort",
"numpy.zeros"
]
]
|
nanohop/keras_neural_network | [
"b0eed70c1c8d0f09eb03b72a3ed2acf8ba7465a1"
]
| [
"train_sample_data.py"
]
| [
"from keras.models import Sequential\nfrom keras.layers import Dense\n\nimport numpy as np\n\nmodel = Sequential()\n\n# 10.5, 5, 9.5, 12 => 18.5\n\nmodel.add(Dense(8, activation='relu', input_dim=4))\nmodel.add(Dense(16, activation='relu'))\nmodel.add(Dense(8, activation='relu'))\nmodel.add(Dense(1, activation='linear'))\n\nmodel.compile(\n optimizer='adam', \n loss='mean_squared_error'\n)\n\nx_train = np.array([\n [1, 2, 3, 4],\n [4, 6, 1, 2],\n [10, 9, 10, 11],\n [10, 12, 9, 13],\n [99, 100, 101, 102],\n [105, 111, 109, 102]\n])\n\ny_train = np.array([\n [2.5],\n [3.25],\n [10.0],\n [11.0],\n [100.5],\n [106.75]\n])\n\nmodel.fit(\n x_train,\n y_train,\n batch_size=2,\n epochs=100,\n verbose=1\n)\n"
]
| [
[
"numpy.array"
]
]
|
tusharmishra288/ML-unsupervised-algorithms | [
"9b4a16ab7d84707eabdb95670c88725bec7b4708"
]
| [
"mean shift.py"
]
| [
"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.datasets.samples_generator import make_blobs\r\nfrom sklearn.cluster import MeanShift\r\ncenters=([1,1],[5,7],[10,12])\r\nX,_=make_blobs(n_samples=10000,cluster_std=1,random_state=42,centers=centers) \r\nplt.scatter(X[:,0],X[:,1])\r\nplt.show()\r\nr=MeanShift()\r\nr.fit(X)\r\nlabels=r.predict(X)\r\n#or labels=r.labels_\r\ncluster_centers=r.cluster_centers_\r\nn=len(np.unique(labels))\r\nprint(\"number of clusters:\",n)\r\ncolors=['r.','b.','g.','k.','m.','c.','y.']\r\n#print(colors)\r\n#print(labels)\r\nfor i in range(len(X)):\r\n plt.plot(X[i][0],X[i][1],colors[labels[i]],markersize=10)\r\n \r\nplt.scatter(cluster_centers[:,0],cluster_centers[:,1],marker='o',s=100,zorder=10,c='y'*3)\r\nplt.show() \r\n"
]
| [
[
"sklearn.cluster.MeanShift",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.scatter",
"numpy.unique",
"sklearn.datasets.samples_generator.make_blobs"
]
]
|
Faagerholm/tensorflow | [
"98e30b8748eb018f33836ac9269db67ab60483ab",
"98e30b8748eb018f33836ac9269db67ab60483ab"
]
| [
"tensorflow/python/tpu/tpu_embedding.py",
"tensorflow/python/keras/saving/hdf5_format_test.py"
]
| [
"# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"TPU embedding APIs.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport copy\nimport math\nimport re\nimport six\n\nfrom tensorflow.core.protobuf.tpu import optimization_parameters_pb2\nfrom tensorflow.core.protobuf.tpu import tpu_embedding_configuration_pb2 as elc\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import partitioned_variables\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.tpu import tpu_system_metadata as tpu_system_metadata_lib\nfrom tensorflow.python.tpu.ops import tpu_ops\n\nTRAINING = elc.TPUEmbeddingConfiguration.TRAINING\nINFERENCE = elc.TPUEmbeddingConfiguration.INFERENCE\n\n\nclass TableConfig(\n collections.namedtuple(\n 'TableConfig',\n ['vocabulary_size', 'dimension', 'initializer', 'combiner'])):\n \"\"\"Embedding table configuration.\"\"\"\n\n def __new__(cls,\n vocabulary_size,\n dimension,\n initializer=None,\n combiner='mean'):\n \"\"\"Embedding table configuration.\n\n Args:\n vocabulary_size: Number of vocabulary (/rows) in the table.\n dimension: The embedding dimension.\n initializer: A variable initializer function to be used in embedding\n variable initialization. If not specified, defaults to\n `tf.compat.v1.truncated_normal_initializer` with mean `0.0` and standard\n deviation `1/sqrt(dimension)`.\n combiner: A string specifying how to reduce if there are multiple entries\n in a single row. Currently 'mean', 'sqrtn', 'sum' and None are\n supported, with 'mean' the default. 'sqrtn' often achieves good\n accuracy, in particular with bag-of-words columns. For more information,\n see `tf.nn.embedding_lookup_sparse`. None is only valid for dense rather\n than sparse tensors.\n\n Returns:\n `TableConfig`.\n\n Raises:\n ValueError: if `vocabulary_size` is not positive integer.\n ValueError: if `dimension` is not positive integer.\n ValueError: if `initializer` is specified and is not callable.\n ValueError: if `combiner` is not supported.\n \"\"\"\n if not isinstance(vocabulary_size, int) or vocabulary_size < 1:\n raise ValueError('Invalid vocabulary_size {}.'.format(vocabulary_size))\n\n if not isinstance(dimension, int) or dimension < 1:\n raise ValueError('Invalid dimension {}.'.format(dimension))\n\n if (initializer is not None) and (not callable(initializer)):\n raise ValueError('initializer must be callable if specified.')\n if initializer is None:\n initializer = init_ops.truncated_normal_initializer(\n mean=0.0, stddev=1 / math.sqrt(dimension))\n\n if combiner not in ('mean', 'sum', 'sqrtn', None):\n raise ValueError('Invalid combiner {}'.format(combiner))\n\n return super(TableConfig, cls).__new__(cls, vocabulary_size, dimension,\n initializer, combiner)\n\n\nclass FeatureConfig(\n collections.namedtuple(\n 'FeatureConfig',\n ['table_id', 'max_sequence_length', 'weight_key'])):\n \"\"\"Feature configuration.\"\"\"\n\n def __new__(cls,\n table_id,\n max_sequence_length=0,\n weight_key=None):\n \"\"\"Feature configuration.\n\n Args:\n table_id: Which table the feature is uses for embedding lookups.\n max_sequence_length: If positive, the feature is a sequence feature with\n the corresponding maximum sequence length. If the sequence is longer\n than this, it will be truncated. If 0, the feature is not a sequence\n feature.\n weight_key: If using weights for the combiner, this key specifies which\n input feature contains the weights.\n\n Returns:\n `FeatureConfig`.\n\n Raises:\n ValueError: if `max_sequence_length` non-negative.\n \"\"\"\n if not isinstance(max_sequence_length, int) or max_sequence_length < 0:\n raise ValueError('Invalid max_sequence_length {}.'.format(\n max_sequence_length))\n\n return super(FeatureConfig, cls).__new__(cls, table_id, max_sequence_length,\n weight_key)\n\n\nclass EnqueueData(\n collections.namedtuple(\n 'EnqueueData',\n ['embedding_indices', 'sample_indices', 'aggregation_weights'])):\n \"\"\"Data to be enqueued through generate_enqueue_ops().\"\"\"\n\n def __new__(cls,\n embedding_indices,\n sample_indices=None,\n aggregation_weights=None):\n \"\"\"Data to be enqueued through generate_enqueue_ops().\n\n Args:\n embedding_indices: A rank 1 Tensors, indices into the embedding tables. It\n corresponds to sp_ids.values in embedding_lookup_sparse(). Both int32\n and int64 are allowed and will be converted to int32 internally.\n sample_indices: A rank 2 Tensors specifying the training example to which\n the corresponding embedding_indices and aggregation_weights values\n belong. It corresponds to sp_ids.indices in embedding_lookup_sparse().\n If it is None, we assume each embedding_indices belongs to a different\n sample. Both int32 and int64 are allowed and will be converted to int32\n internally.\n aggregation_weights: A rank 1 Tensors containing per training example\n aggregation weights. It corresponds to sp_weights.values in\n embedding_lookup_sparse(). If it is None, we assume all weights are 1.\n Both float32 and float64 are allowed and will be converted to float32\n internally.\n\n Returns:\n An EnqueueData tuple.\n\n \"\"\"\n return super(EnqueueData, cls).__new__(cls, embedding_indices,\n sample_indices, aggregation_weights)\n\n @staticmethod\n def from_sparse_tensor(sp_tensor, weights=None):\n return EnqueueData(\n sp_tensor.values,\n sp_tensor.indices,\n aggregation_weights=weights.values if weights is not None else None)\n\n\ndef get_enqueue_datas_list_from_sparse_tensors_list(sp_tensors_list):\n \"\"\"Convenient function for generate_enqueue_ops().\n\n Args:\n sp_tensors_list: a list of dictionary mapping from string of feature names\n to SparseTensor. Each dictionary is for one TPU core. Dictionaries for the\n same host should be contiguous on the list.\n\n Returns:\n enqueue_datas_list: a list of dictionary mapping from string\n of feature names to EnqueueData. Each dictionary is for one\n TPU core. Dictionaries for the same host should be contiguous\n on the list.\n\n \"\"\"\n enqueue_datas_list = []\n for sp_tensors in sp_tensors_list:\n enqueue_datas = collections.OrderedDict(\n (k, EnqueueData.from_sparse_tensor(v))\n for k, v in six.iteritems(sp_tensors))\n enqueue_datas_list.append(enqueue_datas)\n return enqueue_datas_list\n\n\nAdamSlotVariableNames = collections.namedtuple(\n 'AdamSlotVariableNames', ['m', 'v'])\n\nAdagradSlotVariableName = collections.namedtuple(\n 'AdagradSlotVariableName', ['accumulator'])\n\nAdamSlotVariables = collections.namedtuple(\n 'AdamSlotVariables', ['m', 'v'])\n\nAdagradSlotVariable = collections.namedtuple(\n 'AdagradSlotVariable', ['accumulator'])\n\nVariablesAndOps = collections.namedtuple(\n 'VariablesAndOps',\n ['embedding_variables_by_table', 'slot_variables_by_table',\n 'load_ops', 'retrieve_ops']\n)\n\n\nclass _OptimizationParameters(object):\n \"\"\"Parameters common to all optimizations.\"\"\"\n\n def __init__(self, learning_rate, use_gradient_accumulation,\n clip_weight_min, clip_weight_max):\n self.learning_rate = learning_rate\n self.use_gradient_accumulation = use_gradient_accumulation\n self.clip_weight_min = clip_weight_min\n self.clip_weight_max = clip_weight_max\n\n\nclass AdagradParameters(_OptimizationParameters):\n \"\"\"Optimization parameters for Adagrad.\"\"\"\n\n def __init__(self,\n learning_rate,\n initial_accumulator=0.1,\n use_gradient_accumulation=True,\n clip_weight_min=None,\n clip_weight_max=None):\n \"\"\"Optimization parameters for Adagrad.\n\n Args:\n learning_rate: used for updating embedding table.\n initial_accumulator: initial accumulator for Adagrad.\n use_gradient_accumulation: setting this to `False` makes embedding\n gradients calculation less accurate but faster. Please see\n `optimization_parameters.proto` for details.\n for details.\n clip_weight_min: the minimum value to clip by; None means -infinity.\n clip_weight_max: the maximum value to clip by; None means +infinity.\n \"\"\"\n super(AdagradParameters,\n self).__init__(learning_rate, use_gradient_accumulation,\n clip_weight_min, clip_weight_max)\n if initial_accumulator <= 0:\n raise ValueError('Adagrad initial_accumulator must be positive')\n self.initial_accumulator = initial_accumulator\n\n\nclass AdamParameters(_OptimizationParameters):\n \"\"\"Optimization parameters for Adam.\"\"\"\n\n def __init__(self,\n learning_rate,\n beta1=0.9,\n beta2=0.999,\n epsilon=1e-08,\n lazy_adam=True,\n sum_inside_sqrt=True,\n use_gradient_accumulation=True,\n clip_weight_min=None,\n clip_weight_max=None):\n \"\"\"Optimization parameters for Adam.\n\n Args:\n learning_rate: a floating point value. The learning rate.\n beta1: A float value.\n The exponential decay rate for the 1st moment estimates.\n beta2: A float value.\n The exponential decay rate for the 2nd moment estimates.\n epsilon: A small constant for numerical stability.\n lazy_adam: Use lazy Adam instead of Adam. Lazy Adam trains faster.\n Please see `optimization_parameters.proto` for details.\n sum_inside_sqrt: This improves training speed. Please see\n `optimization_parameters.proto` for details.\n use_gradient_accumulation: setting this to `False` makes embedding\n gradients calculation less accurate but faster. Please see\n `optimization_parameters.proto` for details.\n for details.\n clip_weight_min: the minimum value to clip by; None means -infinity.\n clip_weight_max: the maximum value to clip by; None means +infinity.\n \"\"\"\n super(AdamParameters,\n self).__init__(learning_rate, use_gradient_accumulation,\n clip_weight_min, clip_weight_max)\n if beta1 < 0. or beta1 >= 1.:\n raise ValueError('beta1 must be between 0. and 1; got {}.'.format(beta1))\n if beta2 < 0. or beta2 >= 1.:\n raise ValueError('beta2 must be between 0. and 1; got {}.'.format(beta2))\n if epsilon <= 0.:\n raise ValueError('epsilon must be positive; got {}.'.format(epsilon))\n if not use_gradient_accumulation and not lazy_adam:\n raise ValueError(\n 'When disabling Lazy Adam, gradient accumulation must be used.')\n\n self.beta1 = beta1\n self.beta2 = beta2\n self.epsilon = epsilon\n self.lazy_adam = lazy_adam\n self.sum_inside_sqrt = sum_inside_sqrt\n\n\nclass StochasticGradientDescentParameters(_OptimizationParameters):\n \"\"\"Optimization parameters for stochastic gradient descent.\"\"\"\n\n def __init__(self, learning_rate, clip_weight_min=None,\n clip_weight_max=None):\n \"\"\"Optimization parameters for stochastic gradient descent.\n\n Args:\n learning_rate: a floating point value. The learning rate.\n clip_weight_min: the minimum value to clip by; None means -infinity.\n clip_weight_max: the maximum value to clip by; None means +infinity.\n \"\"\"\n super(StochasticGradientDescentParameters,\n self).__init__(learning_rate, False, clip_weight_min, clip_weight_max)\n\n\nDeviceConfig = collections.namedtuple('DeviceConfig',\n ['num_hosts', 'num_cores', 'job_name'])\n\n\nclass TPUEmbedding(object):\n \"\"\"API for using TPU for embedding.\n\n Example:\n ```\n table_config_user = tpu_embedding.TableConfig(\n vocabulary_size=4, dimension=2,\n initializer=initializer, combiner='mean')\n table_to_config_dict = {'video': table_config_video,\n 'user': table_config_user}\n feature_to_config_dict = {'watched': tpu_embedding.FeatureConfig('video'),\n 'favorited': tpu_embedding.FeatureConfig('video'),\n 'friends': tpu_embedding.FeatureConfig('user')}\n batch_size = 4\n num_hosts = 1\n optimization_parameters = tpu_embedding.AdagradParameters(1., 1.)\n mode = tpu_embedding.TRAINING\n embedding = tpu_embedding.TPUEmbedding(\n table_to_config_dict, feature_to_config_dict,\n batch_size, num_hosts, mode, optimization_parameters)\n\n batch_size_per_core = embedding.batch_size_per_core\n sparse_features_list = []\n for host in hosts:\n with ops.device(host):\n for _ in range(embedding.num_cores_per_host):\n sparse_features = {}\n sparse_features['watched'] = sparse_tensor.SparseTensor(...)\n sparse_features['favorited'] = sparse_tensor.SparseTensor(...)\n sparse_features['friends'] = sparse_tensor.SparseTensor(...)\n sparse_features_list.append(sparse_features)\n\n enqueue_ops = embedding.generate_enqueue_ops(sparse_features_list)\n embedding_variables_and_ops = embedding.create_variables_and_ops()\n\n def computation():\n activations = embedding.get_activations()\n loss = compute_loss(activations)\n\n base_optimizer = gradient_descent.GradientDescentOptimizer(\n learning_rate=1)\n cross_shard_optimizer = tpu_optimizer.CrossShardOptimizer(\n base_optimizer)\n\n train_op = cross_shard_optimizer.minimize(loss)\n gradients = (\n tpu_embedding_gradient.get_gradients_through_compute_gradients(\n cross_shard_optimizer, loss, activations)\n send_gradients_op = embedding.generate_send_gradients_op(gradients)\n with ops.control_dependencies([train_op, send_gradients_op]):\n loss = array_ops.identity(loss)\n\n loss = tpu.shard(computation,\n num_shards=embedding.num_cores)\n\n with self.test_session() as sess:\n sess.run(tpu.initialize_system(embedding_config=\n embedding.config_proto))\n sess.run(variables.global_variables_initializer())\n sess.run(embedding_variables_and_ops.load_ops())\n sess.run(enqueue_ops)\n loss_val = sess.run(loss)\n ```\n \"\"\"\n\n # TODO(shizhiw): Consider addign a field to FeatureConfig that indicates that\n # the feature should not be used to update embedding table (cr/204852758,\n # cr/204940540). Also, this can support different combiners for different\n # features within the same table.\n # TODO(shizhiw, b/118512626): Remove `batch_size` from `__init__` and move it\n # to `FeatureConfig`?\n\n # TODO(shizhiw): will it be cleaner to make `table_to_config_dict` and\n # `feature_to_config_dict` lists of `TableSpec` and `FeatureSpec`\n # respectively?\n\n # TODO(shizhiw): Consider adding `input_fn` as an option to remove boilerplate\n # for-loops around construction of inputs.\n\n # `optimization_parameter` applies to all tables. If the need arises,\n # we can add `optimization_parameters` to `TableConfig` to override this\n # global setting.\n def __init__(self,\n table_to_config_dict,\n feature_to_config_dict,\n batch_size,\n mode,\n master=None,\n optimization_parameters=None,\n cluster_def=None,\n pipeline_execution_with_tensor_core=False,\n partition_strategy='div',\n device_config=None):\n \"\"\"API for using TPU for embedding lookups.\n\n Args:\n table_to_config_dict: A dictionary mapping from string of table name to\n `TableConfig`. Table refers to an embedding table, e.g. `params`\n argument to `tf.nn.embedding_lookup_sparse()`.\n feature_to_config_dict: A dictionary mapping from string of feature name\n to `FeatureConfig`. Feature refers to ids to lookup in embedding table,\n e.g. `sp_ids` argument to `tf.nn.embedding_lookup_sparse()`.\n batch_size: An `int` representing the global batch size.\n mode: `TRAINING` or `INFERENCE`.\n master: A `string` representing the TensorFlow master to use.\n optimization_parameters: `AdagradParameters`, `AdamParameters`,\n `Stochasticgradientdescentparameters`. Must be set in training and must\n be `None` in inference.\n cluster_def: A ClusterDef object describing the TPU cluster.\n pipeline_execution_with_tensor_core: setting this to `True` makes training\n faster, but trained model will be different if step N and step N+1\n involve the same set of embedding IDs. Please see\n `tpu_embedding_configuration.proto` for details.\n partition_strategy: A string, either 'mod' or 'div', specifying how to map\n the lookup id to the embedding tensor. For more information see\n `tf.nn.embedding_lookup_sparse`.\n device_config: A DeviceConfig instance, used when `master` and\n `cluster_def` are both `None`.\n\n Raises:\n ValueError: if any input is invalid.\n \"\"\"\n if partition_strategy not in ('div', 'mod'):\n raise ValueError(\n 'Invalid partition_strategy {}'.format(partition_strategy))\n self._partition_strategy = partition_strategy\n\n _validate_table_to_config_dict(table_to_config_dict)\n # Avoid nondeterminism from `Dict` iteration order by using `OrderedDict`.\n self._table_to_config_dict = _create_ordered_dict(table_to_config_dict)\n\n _validate_feature_to_config_dict(table_to_config_dict,\n feature_to_config_dict)\n self._feature_to_config_dict = _create_ordered_dict(feature_to_config_dict)\n self._table_to_features_dict, self._table_to_num_features_dict = (\n _create_table_to_features_and_num_features_dicts(\n self._feature_to_config_dict))\n self._combiners = _create_combiners(self._table_to_config_dict,\n self._table_to_features_dict)\n\n self._batch_size = batch_size\n\n if master is None and cluster_def is None:\n if device_config is None:\n raise ValueError('When master and cluster_def are both None,'\n 'device_config must be set but is not.')\n if device_config.num_cores % device_config.num_hosts:\n raise ValueError('num_hosts ({}) should divide num_cores ({}) '\n 'but does not.'.format(device_config.num_cores,\n device_config.num_hosts))\n self._num_hosts = device_config.num_hosts\n self._num_cores = device_config.num_cores\n self._num_cores_per_host = self._num_cores // self._num_hosts\n self._hosts = [\n '{}/replica:0/task:{}/device:CPU:0'.format(device_config.job_name, i)\n for i in range(self._num_hosts)\n ]\n else:\n tpu_system_metadata = (\n tpu_system_metadata_lib._query_tpu_system_metadata( # pylint: disable=protected-access\n master,\n cluster_def=cluster_def))\n if tpu_system_metadata.num_cores == 0:\n raise ValueError('TPUEmbedding needs TPUs, but master {} does not have '\n 'TPUs.'.format(master))\n self._num_hosts = tpu_system_metadata.num_hosts\n master_job_name = tpu_system_metadata_lib.master_job(master, cluster_def)\n self._hosts = []\n for device in tpu_system_metadata.devices:\n if 'device:CPU:' in device.name and (\n master_job_name is None or master_job_name in device.name):\n self._hosts.append(device.name)\n self._num_cores_per_host = tpu_system_metadata.num_of_cores_per_host\n self._num_cores = tpu_system_metadata.num_cores\n\n _validate_batch_size(self._batch_size, self._num_cores)\n self._batch_size_per_core = self._batch_size // self._num_cores\n\n # TODO(shizhiw): remove `mode`?\n if mode == TRAINING:\n _validate_optimization_parameters(optimization_parameters)\n self._optimization_parameters = optimization_parameters\n elif mode == INFERENCE:\n if optimization_parameters is not None:\n raise ValueError('`optimization_parameters` should be `None` '\n 'for inference mode.')\n self._optimization_parameters = (\n StochasticGradientDescentParameters(1.))\n else:\n raise ValueError('`mode` only supports {} and {}; got {}.'\n .format(TRAINING, INFERENCE, mode))\n self._mode = mode\n\n # TODO(shizhiw): move `optimization_parameters` into `_optimizer_handler`\n # and create special handler for inference that inherits from\n # StochasticGradientDescentHandler with more user-friendly error message\n # on get_slot().\n self._optimizer_handler = _get_optimization_handler(\n self._optimization_parameters)\n self._pipeline_execution_with_tensor_core = (\n pipeline_execution_with_tensor_core)\n\n self._config_proto = self._create_config_proto()\n\n @property\n def hosts(self):\n \"\"\"A list of device names for CPU hosts.\n\n Returns:\n A list of device names for CPU hosts.\n \"\"\"\n return copy.copy(self._hosts)\n\n # TODO(shizhiw): change to num_tensor_cores_per_host to be more explicit and\n # to be consistent with `tpu_embedding_configuration.proto`.\n @property\n def num_cores_per_host(self):\n \"\"\"Number of TPU cores on a CPU host.\n\n Returns:\n Number of TPU cores on a CPU host.\n \"\"\"\n return self._num_cores_per_host\n\n @property\n def num_cores(self):\n \"\"\"Total number of TPU cores on all hosts.\n\n Returns:\n Total number of TPU cores on all hosts.\n \"\"\"\n return self._num_cores\n\n @property\n def batch_size_per_core(self):\n \"\"\"Batch size for each TPU core.\n\n The sparse tensors in `sparse_features_list` to `generate_enqueue_ops`\n must have batch dimension equal to this.\n\n Returns:\n Batch size for each TPU core.\n \"\"\"\n return self._batch_size_per_core\n\n @property\n def config_proto(self):\n \"\"\"Create embedding config proto for `tpu.initialize_system()`.\n\n Returns:\n an `TPUEmbeddingConfiguration` proto describing the desired\n configuration of the hardware embedding lookup tables, which\n is passed to `tpu.initialize_system()`.\n \"\"\"\n return self._config_proto\n\n @property\n def table_to_config_dict(self):\n return copy.copy(self._table_to_config_dict)\n\n @property\n def feature_to_config_dict(self):\n return copy.copy(self._feature_to_config_dict)\n\n @property\n def table_to_features_dict(self):\n return copy.copy(self._table_to_features_dict)\n\n @property\n def optimization_parameters(self):\n return self._optimization_parameters\n\n def _create_config_proto(self):\n \"\"\"Create `TPUEmbeddingConfiguration`.\"\"\"\n config_proto = elc.TPUEmbeddingConfiguration()\n for table in self._table_to_config_dict:\n table_descriptor = config_proto.table_descriptor.add()\n table_descriptor.name = table\n\n table_config = self._table_to_config_dict[table]\n # For small tables, we pad to the number of hosts so that at least one\n # id will be assigned to each host.\n table_descriptor.vocabulary_size = max(table_config.vocabulary_size,\n len(self.hosts))\n table_descriptor.dimension = table_config.dimension\n\n table_descriptor.num_features = self._table_to_num_features_dict[table]\n\n table_descriptor.optimization_parameters.learning_rate.constant = (\n self._optimization_parameters.learning_rate)\n table_descriptor.optimization_parameters.gradient_accumulation_status = (\n optimization_parameters_pb2.GradientAccumulationStatus.ENABLED\n if self._optimization_parameters.use_gradient_accumulation else\n optimization_parameters_pb2.GradientAccumulationStatus.DISABLED)\n if self._optimization_parameters.clip_weight_min is not None:\n table_descriptor.optimization_parameters.clipping_limits.lower.value = (\n self._optimization_parameters.clip_weight_min)\n if self._optimization_parameters.clip_weight_max is not None:\n table_descriptor.optimization_parameters.clipping_limits.upper.value = (\n self._optimization_parameters.clip_weight_max)\n self._optimizer_handler.set_optimization_parameters(table_descriptor)\n\n config_proto.mode = self._mode\n config_proto.batch_size_per_tensor_core = self._batch_size_per_core\n config_proto.num_hosts = self._num_hosts\n config_proto.num_tensor_cores = self._num_cores\n config_proto.sharding_strategy = (\n elc.TPUEmbeddingConfiguration.DIV_DEFAULT\n if self._partition_strategy == 'div' else\n elc.TPUEmbeddingConfiguration.MOD)\n config_proto.pipeline_execution_with_tensor_core = (\n self._pipeline_execution_with_tensor_core)\n\n return config_proto\n\n def create_variables_and_ops(self, embedding_variable_name_by_table=None,\n slot_variable_names_by_table=None):\n \"\"\"Create embedding and slot variables, with ops to load and retrieve them.\n\n Args:\n embedding_variable_name_by_table: A dictionary mapping from string of\n table name to string of embedding variable name. If `None`,\n defaults from `get_default_slot_variable_names()` will be used.\n slot_variable_names_by_table: A dictionary mapping from string of table\n name to `AdamSlotVariableNames`, `AdagradSlotVariableNames` etc. If\n `None`, defaults from `get_default_slot_variable_names()` will be used.\n\n Returns:\n `tpu_embedding.VariablesAndOps` with:\n A dictionary mapping from string of table name to embedding variables,\n A dictionary mapping from string of table name to AdagradSlotVariable,\n AdamSlotVariables etc with slot variables,\n A function which returns a list of ops to load embedding and slot\n variables from TPU to CPU.\n A function which returns a list of ops to retrieve embedding and slot\n variables from TPU to CPU.\n \"\"\"\n embedding_variables_by_table = {}\n slot_variables_by_table = {}\n load_op_fns = []\n retrieve_op_fns = []\n for table in self._table_to_config_dict:\n if embedding_variable_name_by_table:\n embedding_variable_name = embedding_variable_name_by_table[table]\n else:\n embedding_variable_name = table\n if slot_variable_names_by_table:\n slot_variable_names = slot_variable_names_by_table[table]\n else:\n slot_variable_names = (\n self._optimizer_handler.get_default_slot_variable_names(table))\n\n device_fn = _create_device_fn(self._hosts)\n with ops.device(device_fn):\n table_variables = _create_partitioned_variables(\n name=embedding_variable_name,\n num_hosts=self._num_hosts,\n vocabulary_size=self._table_to_config_dict[table].vocabulary_size,\n embedding_dimension=self._table_to_config_dict[table].dimension,\n initializer=self._table_to_config_dict[table].initializer,\n collections=[ops.GraphKeys.GLOBAL_VARIABLES])\n embedding_variables_by_table[table] = table_variables\n\n slot_variables_for_table, load_ops_fn, retrieve_ops_fn = (\n self._optimizer_handler.create_variables_and_ops(\n table, slot_variable_names, self._num_hosts,\n self._table_to_config_dict[table], table_variables)\n )\n slot_variables_by_table[table] = slot_variables_for_table\n load_op_fns.append(load_ops_fn)\n retrieve_op_fns.append(retrieve_ops_fn)\n\n def load_ops():\n \"\"\"Calls and returns the load ops for each embedding table.\n\n Returns:\n A list of ops to load embedding and slot variables from CPU to TPU.\n \"\"\"\n load_ops_list = []\n for load_op_fn in load_op_fns:\n load_ops_list.extend(load_op_fn())\n return load_ops_list\n\n def retrieve_ops():\n \"\"\"Calls and returns the retrieve ops for each embedding table.\n\n Returns:\n A list of ops to retrieve embedding and slot variables from TPU to CPU.\n \"\"\"\n retrieve_ops_list = []\n for retrieve_op_fn in retrieve_op_fns:\n retrieve_ops_list.extend(retrieve_op_fn())\n return retrieve_ops_list\n\n return VariablesAndOps(embedding_variables_by_table,\n slot_variables_by_table,\n load_ops, retrieve_ops)\n\n def generate_enqueue_ops(self, enqueue_datas_list):\n \"\"\"Generate enqueue ops.\n\n Args:\n enqueue_datas_list: a list of dictionary mapping from string\n of feature names to EnqueueData. Each dictionary is for one\n TPU core. Dictionaries for the same host should be contiguous\n on the list.\n\n Returns:\n Ops to enqueue to TPU for embedding.\n \"\"\"\n self._validate_generate_enqueue_ops_enqueue_datas_list(enqueue_datas_list)\n return [\n self._generate_enqueue_op(\n enqueue_datas, device_ordinal=i % self._num_cores_per_host)\n for i, enqueue_datas in enumerate(enqueue_datas_list)\n ]\n\n def _validate_generate_enqueue_ops_enqueue_datas_list(self,\n enqueue_datas_list):\n \"\"\"Validate `enqueue_datas_list`.\"\"\"\n feature_set = set(self._feature_to_config_dict.keys())\n contiguous_device = None\n for i, enqueue_datas in enumerate(enqueue_datas_list):\n used_feature_set = set(enqueue_datas.keys())\n\n # Check features are valid.\n missing_feature_set = feature_set - used_feature_set\n if missing_feature_set:\n raise ValueError('`enqueue_datas_list[{}]` misses a feature that is '\n 'in `feature_to_config_dict`: {}.'.format(\n i, missing_feature_set))\n\n extra_feature_set = used_feature_set - feature_set\n if extra_feature_set:\n raise ValueError('`enqueue_datas_list[{}]` has a feature that is not '\n 'in `feature_to_config_dict`: {}.'.format(\n i, extra_feature_set))\n\n device = None\n device_feature = None\n for feature, enqueue_data in six.iteritems(enqueue_datas):\n combiner = self._table_to_config_dict[\n self._feature_to_config_dict[feature].table_id].combiner\n if not isinstance(enqueue_data, EnqueueData):\n raise ValueError('`enqueue_datas_list[{}]` has a feature that is '\n 'not mapped to `EnqueueData`. `feature`: {}'.format(\n i, feature))\n\n if enqueue_data.sample_indices is None and combiner:\n raise ValueError('`enqueue_datas_list[{}]` has a feature that has '\n 'neither `EnqueueData` or `combiner`.'\n '`feature`: {}, combiner: {}.'.format(\n i, feature, combiner))\n\n if (enqueue_data.sample_indices is not None and\n enqueue_data.sample_indices.op.device !=\n enqueue_data.embedding_indices.op.device):\n raise ValueError(\n 'Device of sample_indices does not agree with '\n 'that of emebdding_indices for feature {}.'.format(feature))\n if (enqueue_data.aggregation_weights is not None and\n enqueue_data.aggregation_weights.op.device !=\n enqueue_data.embedding_indices.op.device):\n raise ValueError(\n 'Device of aggregation_weights does not agree with '\n 'that of emebdding_indices for feature {}.'.format(feature))\n # Check all features are on the same device.\n if device is None:\n device = enqueue_data.embedding_indices.op.device\n device_feature = feature\n else:\n if device != enqueue_data.embedding_indices.op.device:\n raise ValueError('Devices are different between features in '\n '`enqueue_datas_list[{}]`; '\n 'devices: {}, {}; features: {}, {}.'.format(\n i, device,\n enqueue_data.embedding_indices.op.device,\n feature, device_feature))\n\n if i % self._num_cores_per_host:\n if device != contiguous_device:\n raise ValueError('We expect the `enqueue_datas` which are on the '\n 'same host to be contiguous in '\n '`enqueue_datas_list`, '\n '`enqueue_datas_list[{}]` is on device {}, '\n 'but is expected to be on device {}.'.format(\n i, device, contiguous_device))\n else:\n contiguous_device = device\n\n def _generate_enqueue_op(self, enqueue_datas, device_ordinal):\n enqueue_data0 = list(enqueue_datas.values())[0]\n with ops.colocate_with(enqueue_data0.embedding_indices):\n (sample_indices_list, embedding_indices_list, aggregation_weights_list,\n table_ids, max_sequence_lengths) = (\n self._format_for_tpu_embedding_sparse_tensor_batch(enqueue_datas))\n return tpu_ops.enqueue_tpu_embedding_sparse_tensor_batch(\n sample_indices_list,\n embedding_indices_list,\n aggregation_weights_list,\n table_ids,\n device_ordinal=device_ordinal,\n combiners=self._combiners,\n max_sequence_lengths=max_sequence_lengths)\n\n def _format_for_tpu_embedding_sparse_tensor_batch(self, enqueue_datas):\n \"\"\"Format sparse features for `enqueue_tpu_embedding_sparse_tensor_batch()`.\n\n Args:\n enqueue_datas: a `Dict` of tensors for embedding. Can be sparse or\n dense.\n\n Returns:\n Arguments for `enqueue_tpu_embedding_sparse_tensor_batch()`.\n \"\"\"\n\n (sample_indices_list, embedding_indices_list, aggregation_weights_list,\n table_ids, max_sequence_lengths) = [], [], [], [], []\n for table_id, table in enumerate(self._table_to_features_dict):\n features = self._table_to_features_dict[table]\n for feature in features:\n enqueue_data = enqueue_datas[feature]\n\n sample_indices = (\n enqueue_data.sample_indices\n if enqueue_data.sample_indices is not None else array_ops.zeros(\n (0,), dtype=dtypes.int32))\n sample_indices_list.append(sample_indices)\n\n aggregation_weights = (\n enqueue_data.aggregation_weights if\n enqueue_data.aggregation_weights is not None else array_ops.zeros(\n (0,), dtype=dtypes.float32))\n aggregation_weights_list.append(aggregation_weights)\n\n embedding_indices_list.append(enqueue_data.embedding_indices)\n\n table_ids.append(table_id)\n max_sequence_lengths.append(\n self._feature_to_config_dict[feature].max_sequence_length)\n\n return (sample_indices_list, embedding_indices_list,\n aggregation_weights_list, table_ids, max_sequence_lengths)\n\n def get_activations(self):\n \"\"\"Get activations for features.\n\n This should be called within `computation` that is passed to\n `tpu.replicate` and friends.\n\n Returns:\n A dictionary mapping from `String` of feature name to `Tensor`\n of activation.\n \"\"\"\n recv_activations = tpu_ops.recv_tpu_embedding_activations(\n num_outputs=len(self._table_to_config_dict),\n config=self._config_proto.SerializeToString())\n\n activations = collections.OrderedDict()\n for table_id, table in enumerate(self._table_to_features_dict):\n features = self._table_to_features_dict[table]\n num_features = self._table_to_num_features_dict[table]\n feature_index = 0\n table_activations = array_ops.reshape(\n recv_activations[table_id],\n [self.batch_size_per_core, num_features, -1])\n for feature in features:\n seq_length = self._feature_to_config_dict[feature].max_sequence_length\n if not seq_length:\n activations[feature] = table_activations[:, feature_index, :]\n feature_index = feature_index + 1\n else:\n activations[feature] = (\n table_activations[:, feature_index:(feature_index+seq_length), :])\n feature_index = feature_index + seq_length\n\n return activations\n\n def generate_send_gradients_op(self, feature_to_gradient_dict):\n \"\"\"Send gradient to TPU embedding.\n\n Args:\n feature_to_gradient_dict: dict mapping feature names to gradient wrt\n activations.\n\n Returns:\n SendTPUEmbeddingGradients Op.\n\n Raises:\n RuntimeError: If `mode` is not `TRAINING`.\n \"\"\"\n if self._mode != TRAINING:\n raise RuntimeError('Only in training mode gradients need to '\n 'be sent to TPU embedding; got mode {}.'\n .format(self._mode))\n gradients = []\n for table in self._table_to_features_dict:\n features = self._table_to_features_dict[table]\n table_gradients = []\n for feature in features:\n gradient = feature_to_gradient_dict[feature]\n # Expand dims for non-sequence feature to match sequence features.\n if gradient.shape.ndims == 2:\n gradient = array_ops.expand_dims(gradient, 1)\n table_gradients.append(gradient)\n interleaved_table_grads = array_ops.reshape(\n array_ops.concat(table_gradients, axis=1),\n [-1, array_ops.shape(table_gradients[0])[-1]])\n gradients.append(interleaved_table_grads)\n return tpu_ops.send_tpu_embedding_gradients(\n inputs=gradients, config=self.config_proto.SerializeToString())\n\n\ndef _validate_table_to_config_dict(table_to_config_dict):\n \"\"\"Validate `table_to_config_dict`.\"\"\"\n for k, v in six.iteritems(table_to_config_dict):\n if not isinstance(v, TableConfig):\n raise ValueError('Value of `table_to_config_dict` must be of type '\n '`TableConfig`, got {} for {}.'.format(type(v), k))\n\n\ndef _validate_feature_to_config_dict(table_to_config_dict,\n feature_to_config_dict):\n \"\"\"Validate `feature_to_config_dict`.\"\"\"\n used_table_set = set([feature.table_id\n for feature in feature_to_config_dict.values()])\n table_set = set(table_to_config_dict.keys())\n\n unused_table_set = table_set - used_table_set\n if unused_table_set:\n raise ValueError('`table_to_config_dict` specifies table that is not '\n 'used in `feature_to_config_dict`: {}.'\n .format(unused_table_set))\n\n extra_table_set = used_table_set - table_set\n if extra_table_set:\n raise ValueError('`feature_to_config_dict` refers to a table that is not '\n 'specified in `table_to_config_dict`: {}.'\n .format(extra_table_set))\n\n\ndef _validate_batch_size(batch_size, num_cores):\n if batch_size % num_cores:\n raise ValueError('`batch_size` is not a multiple of number of '\n 'cores. `batch_size`={}, `_num_cores`={}.'.format(\n batch_size, num_cores))\n\n\ndef _validate_optimization_parameters(optimization_parameters):\n if not isinstance(optimization_parameters, _OptimizationParameters):\n raise ValueError('`optimization_parameters` must inherit from '\n '`_OptimizationPramaters`. '\n '`type(optimization_parameters)`={}'.format(\n type(optimization_parameters)))\n\n\nclass _OptimizerHandler(object):\n \"\"\"Interface class for handling optimizer specific logic.\"\"\"\n\n def __init__(self, optimization_parameters):\n self._optimization_parameters = optimization_parameters\n\n def set_optimization_parameters(self, table_descriptor):\n raise NotImplementedError()\n\n def get_default_slot_variable_names(self, table):\n raise NotImplementedError()\n\n def create_variables_and_ops(self, table, slot_variable_names, num_hosts,\n table_config, table_variables):\n raise NotImplementedError()\n\n\nclass _AdagradHandler(_OptimizerHandler):\n \"\"\"Handles Adagrad specific logic.\"\"\"\n\n def __init__(self, optimization_parameters):\n super(_AdagradHandler, self).__init__(optimization_parameters)\n self._table_to_accumulator_variables_dict = {}\n\n def set_optimization_parameters(self, table_descriptor):\n table_descriptor.optimization_parameters.adagrad.SetInParent()\n\n def get_default_slot_variable_names(self, table):\n return AdagradSlotVariableName('{}/{}'.format(table, 'Adagrad'))\n\n def create_variables_and_ops(self, table, slot_variable_names, num_hosts,\n table_config, table_variables):\n accumulator_initializer = init_ops.constant_initializer(\n self._optimization_parameters.initial_accumulator)\n accumulator_variables = _create_partitioned_variables(\n name=slot_variable_names.accumulator,\n num_hosts=num_hosts,\n vocabulary_size=table_config.vocabulary_size,\n embedding_dimension=table_config.dimension,\n collections=[ops.GraphKeys.GLOBAL_VARIABLES],\n initializer=accumulator_initializer)\n slot_variables = AdagradSlotVariable(accumulator_variables)\n\n def load_ops_fn():\n \"\"\"Returns the retrieve ops for AdaGrad embedding tables.\n\n Returns:\n A list of ops to load embedding and slot variables from CPU to TPU.\n \"\"\"\n load_op_list = []\n for host_id, table_variable, accumulator_variable in (zip(\n range(num_hosts), table_variables, accumulator_variables)):\n with ops.colocate_with(table_variable):\n load_parameters_op = (\n tpu_ops.load_tpu_embedding_adagrad_parameters(\n parameters=table_variable,\n accumulators=accumulator_variable,\n table_name=table,\n num_shards=num_hosts,\n shard_id=host_id))\n load_op_list.append(load_parameters_op)\n return load_op_list\n\n def retrieve_ops_fn():\n \"\"\"Returns the retrieve ops for AdaGrad embedding tables.\n\n Returns:\n A list of ops to retrieve embedding and slot variables from TPU to CPU.\n \"\"\"\n retrieve_op_list = []\n for host_id, table_variable, accumulator_variable in (zip(\n range(num_hosts), table_variables, accumulator_variables)):\n with ops.colocate_with(table_variable):\n retrieved_table, retrieved_accumulator = (\n tpu_ops.retrieve_tpu_embedding_adagrad_parameters(\n table_name=table,\n num_shards=num_hosts,\n shard_id=host_id))\n retrieve_parameters_op = control_flow_ops.group(\n state_ops.assign(table_variable, retrieved_table),\n state_ops.assign(accumulator_variable, retrieved_accumulator))\n retrieve_op_list.append(retrieve_parameters_op)\n return retrieve_op_list\n\n return slot_variables, load_ops_fn, retrieve_ops_fn\n\n\nclass _AdamHandler(_OptimizerHandler):\n \"\"\"Handles Adam specific logic.\"\"\"\n\n def __init__(self, optimization_parameters):\n super(_AdamHandler, self).__init__(optimization_parameters)\n self._table_to_m_variables_dict = {}\n self._table_to_v_variables_dict = {}\n\n def set_optimization_parameters(self, table_descriptor):\n table_descriptor.optimization_parameters.adam.beta1 = (\n self._optimization_parameters.beta1)\n table_descriptor.optimization_parameters.adam.beta2 = (\n self._optimization_parameters.beta2)\n table_descriptor.optimization_parameters.adam.epsilon = (\n self._optimization_parameters.epsilon)\n table_descriptor.optimization_parameters.adam.use_non_lazy_adam = (\n not self._optimization_parameters.lazy_adam)\n table_descriptor.optimization_parameters.adam.use_sum_inside_sqrt = (\n self._optimization_parameters.sum_inside_sqrt)\n\n def get_default_slot_variable_names(self, table):\n return AdamSlotVariableNames('{}/{}/m'.format(table, 'Adam'),\n '{}/{}/v'.format(table, 'Adam'))\n\n def create_variables_and_ops(self, table, slot_variable_names, num_hosts,\n table_config, table_variables):\n m_initializer = init_ops.zeros_initializer()\n m_variables = _create_partitioned_variables(\n name=slot_variable_names.m,\n num_hosts=num_hosts,\n vocabulary_size=table_config.vocabulary_size,\n embedding_dimension=table_config.dimension,\n collections=[ops.GraphKeys.GLOBAL_VARIABLES],\n initializer=m_initializer)\n v_initializer = init_ops.zeros_initializer()\n v_variables = _create_partitioned_variables(\n name=slot_variable_names.v,\n num_hosts=num_hosts,\n vocabulary_size=table_config.vocabulary_size,\n embedding_dimension=table_config.dimension,\n collections=[ops.GraphKeys.GLOBAL_VARIABLES],\n initializer=v_initializer)\n slot_variables = AdamSlotVariables(m_variables, v_variables)\n\n def load_ops_fn():\n \"\"\"Returns the retrieve ops for AdaGrad embedding tables.\n\n Returns:\n A list of ops to load embedding and slot variables from CPU to TPU.\n \"\"\"\n load_op_list = []\n for host_id, table_variable, m_variable, v_variable in (zip(\n range(num_hosts), table_variables,\n m_variables, v_variables)):\n with ops.colocate_with(table_variable):\n load_parameters_op = (\n tpu_ops.load_tpu_embedding_adam_parameters(\n parameters=table_variable,\n momenta=m_variable,\n velocities=v_variable,\n table_name=table,\n num_shards=num_hosts,\n shard_id=host_id))\n load_op_list.append(load_parameters_op)\n return load_op_list\n\n def retrieve_ops_fn():\n \"\"\"Returns the retrieve ops for Adam embedding tables.\n\n Returns:\n A list of ops to retrieve embedding and slot variables from TPU to CPU.\n \"\"\"\n\n retrieve_op_list = []\n for host_id, table_variable, m_variable, v_variable in (zip(\n range(num_hosts), table_variables,\n m_variables, v_variables)):\n with ops.colocate_with(table_variable):\n retrieved_table, retrieved_m, retrieved_v = (\n tpu_ops.retrieve_tpu_embedding_adam_parameters(\n table_name=table,\n num_shards=num_hosts,\n shard_id=host_id))\n retrieve_parameters_op = control_flow_ops.group(\n state_ops.assign(table_variable, retrieved_table),\n state_ops.assign(m_variable, retrieved_m),\n state_ops.assign(v_variable, retrieved_v))\n\n retrieve_op_list.append(retrieve_parameters_op)\n return retrieve_op_list\n\n return slot_variables, load_ops_fn, retrieve_ops_fn\n\n\nclass _StochasticGradientDescentHandler(_OptimizerHandler):\n \"\"\"Handles stochastic gradient descent specific logic.\"\"\"\n\n def set_optimization_parameters(self, table_descriptor):\n (table_descriptor.optimization_parameters.stochastic_gradient_descent\n .SetInParent())\n\n def get_default_slot_variable_names(self, table):\n return None\n\n def create_variables_and_ops(self, table, slot_variable_names, num_hosts,\n table_config, table_variables):\n del table_config\n\n def load_ops_fn():\n \"\"\"Returns the retrieve ops for AdaGrad embedding tables.\n\n Returns:\n A list of ops to load embedding and slot variables from CPU to TPU.\n \"\"\"\n load_op_list = []\n for host_id, table_variable in (zip(\n range(num_hosts), table_variables)):\n with ops.colocate_with(table_variable):\n load_parameters_op = (\n tpu_ops\n .load_tpu_embedding_stochastic_gradient_descent_parameters(\n parameters=table_variable,\n table_name=table,\n num_shards=num_hosts,\n shard_id=host_id))\n\n load_op_list.append(load_parameters_op)\n return load_op_list\n\n def retrieve_ops_fn():\n \"\"\"Returns the retrieve ops for SGD embedding tables.\n\n Returns:\n A list of ops to retrieve embedding and slot variables from TPU to CPU.\n \"\"\"\n\n retrieve_op_list = []\n for host_id, table_variable in (zip(\n range(num_hosts), table_variables)):\n with ops.colocate_with(table_variable):\n retrieved_table = (\n tpu_ops\n .retrieve_tpu_embedding_stochastic_gradient_descent_parameters(\n table_name=table,\n num_shards=num_hosts,\n shard_id=host_id))\n retrieve_parameters_op = control_flow_ops.group(\n state_ops.assign(table_variable, retrieved_table))\n\n retrieve_op_list.append(retrieve_parameters_op)\n return retrieve_op_list\n\n return None, load_ops_fn, retrieve_ops_fn\n\n\ndef _get_optimization_handler(optimization_parameters):\n if isinstance(optimization_parameters, AdagradParameters):\n return _AdagradHandler(optimization_parameters)\n elif isinstance(optimization_parameters, AdamParameters):\n return _AdamHandler(optimization_parameters)\n elif isinstance(optimization_parameters, StochasticGradientDescentParameters):\n return _StochasticGradientDescentHandler(optimization_parameters)\n else:\n return NotImplementedError()\n\n\ndef _create_ordered_dict(d):\n \"\"\"Create an OrderedDict from Dict.\"\"\"\n return collections.OrderedDict((k, d[k]) for k in sorted(d))\n\n\ndef _create_combiners(table_to_config_dict, table_to_features_dict):\n \"\"\"Create a per feature list of combiners, ordered by table.\"\"\"\n combiners = []\n for table in table_to_config_dict:\n combiner = table_to_config_dict[table].combiner or 'sum'\n combiners.extend([combiner] * len(table_to_features_dict[table]))\n return combiners\n\n\ndef _create_table_to_features_and_num_features_dicts(feature_to_config_dict):\n \"\"\"Create mapping from table to a list of its features.\"\"\"\n table_to_features_dict_tmp = {}\n table_to_num_features_dict_tmp = {}\n for feature, feature_config in six.iteritems(feature_to_config_dict):\n if feature_config.table_id in table_to_features_dict_tmp:\n table_to_features_dict_tmp[feature_config.table_id].append(feature)\n else:\n table_to_features_dict_tmp[feature_config.table_id] = [feature]\n table_to_num_features_dict_tmp[feature_config.table_id] = 0\n if feature_config.max_sequence_length == 0:\n table_to_num_features_dict_tmp[feature_config.table_id] = (\n table_to_num_features_dict_tmp[feature_config.table_id] + 1)\n else:\n table_to_num_features_dict_tmp[feature_config.table_id] = (\n table_to_num_features_dict_tmp[feature_config.table_id] +\n feature_config.max_sequence_length)\n\n table_to_features_dict = collections.OrderedDict()\n table_to_num_features_dict = collections.OrderedDict()\n for table in sorted(table_to_features_dict_tmp):\n table_to_features_dict[table] = sorted(table_to_features_dict_tmp[table])\n table_to_num_features_dict[table] = table_to_num_features_dict_tmp[table]\n return table_to_features_dict, table_to_num_features_dict\n\n\ndef _create_device_fn(hosts):\n \"\"\"Create device_fn() to use with _create_partitioned_variables().\"\"\"\n\n def device_fn(op):\n \"\"\"Returns the `device` for `op`.\"\"\"\n part_match = re.match(r'.*/part_(\\d+)(/|$)', op.name)\n dummy_match = re.match(r'.*dummy_(\\d+).*', op.name)\n if not part_match and not dummy_match:\n raise RuntimeError(\n 'Internal Error: Expected {} to contain /part_* or dummy_*'.format(\n op.name))\n\n if part_match:\n idx = int(part_match.group(1))\n else:\n idx = int(dummy_match.group(1))\n\n device = hosts[idx]\n logging.debug('assigning {} to {}.', op, device)\n return device\n\n return device_fn\n\n\ndef _create_partitioned_variables(name,\n num_hosts,\n vocabulary_size,\n embedding_dimension,\n initializer,\n collections=None): # pylint: disable=redefined-outer-name\n \"\"\"Creates ParitionedVariables based on `num_hosts` for `table`.\"\"\"\n\n num_slices = min(vocabulary_size, num_hosts)\n\n var_list = list(\n variable_scope.get_variable(\n name,\n shape=(vocabulary_size, embedding_dimension),\n partitioner=partitioned_variables.fixed_size_partitioner(num_slices),\n dtype=dtypes.float32,\n initializer=initializer,\n collections=collections,\n trainable=False))\n\n if vocabulary_size >= num_hosts:\n return var_list\n\n # For padded part, define the dummy variable to be loaded into TPU system.\n for idx in range(num_hosts - vocabulary_size):\n var_list.append(\n variable_scope.get_variable(\n 'dummy_{}_{}'.format(vocabulary_size + idx, name),\n shape=(1, embedding_dimension),\n dtype=dtypes.float32,\n initializer=initializer,\n collections=[ops.GraphKeys.LOCAL_VARIABLES],\n trainable=False))\n\n return var_list\n",
"# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#,============================================================================\n\"\"\"Tests for model saving in the HDF5 format.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport shutil\nimport tempfile\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python import keras\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.keras import optimizers\nfrom tensorflow.python.keras.engine import training\nfrom tensorflow.python.keras.saving import hdf5_format\nfrom tensorflow.python.lib.io import file_io\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training import checkpoint_management\nfrom tensorflow.python.training import training as training_module\nfrom tensorflow.python.training.tracking import util as trackable\n\ntry:\n import h5py # pylint:disable=g-import-not-at-top\nexcept ImportError:\n h5py = None\n\n\nclass TestWeightSavingAndLoading(test.TestCase, parameterized.TestCase):\n\n @test_util.run_in_graph_and_eager_modes\n def test_weight_loading(self):\n with self.cached_session():\n a = keras.layers.Input(shape=(2,))\n x = keras.layers.Dense(3)(a)\n b = keras.layers.Dense(1)(x)\n model = keras.models.Model(a, b)\n\n x = np.random.random((3, 2))\n ref_y = model.predict(x)\n weights = model.get_weights()\n model.set_weights(weights)\n y = model.predict(x)\n self.assertAllClose(ref_y, y)\n\n with self.assertRaises(ValueError):\n model.set_weights(weights[1:])\n with self.assertRaises(ValueError):\n model.set_weights(weights[::-1])\n\n temp_dir = self.get_temp_dir()\n self.addCleanup(shutil.rmtree, temp_dir)\n\n no_extension_path = os.path.join(temp_dir, 'test')\n model.save_weights(no_extension_path, save_format='tf')\n model.load_weights(no_extension_path)\n y = model.predict(x)\n self.assertAllClose(ref_y, y)\n\n if h5py is None:\n return # Skip rest of test if H5py isn't available.\n\n h5_path = os.path.join(temp_dir, 'test.h5')\n model.save_weights(h5_path)\n model.load_weights(h5_path)\n y = model.predict(x)\n self.assertAllClose(ref_y, y)\n\n model.load_weights(h5_path, by_name=True)\n y = model.predict(x)\n self.assertAllClose(ref_y, y)\n\n model.save_weights(no_extension_path, save_format='hdf5')\n model.load_weights(no_extension_path)\n y = model.predict(x)\n self.assertAllClose(ref_y, y)\n\n @test_util.run_in_graph_and_eager_modes\n def test_weight_preprocessing(self):\n input_dim = 3\n output_dim = 3\n size = 2\n cases = [\n [\n (keras.layers.Bidirectional(keras.layers.SimpleRNN(2))),\n [np.random.random((2, 1)), np.random.random((2, 1))],\n (None, 3, 2),\n ],\n [\n (keras.layers.TimeDistributed(keras.layers.Dense(1))),\n [np.random.random((2, 1)), np.random.random((1,))],\n (None, 3, 2),\n ],\n [\n (keras.layers.Conv1D(output_dim, size, use_bias=False)),\n [np.random.random((output_dim, input_dim, size, 1))],\n (None, 4, input_dim),\n ],\n [\n (keras.layers.Conv2D(output_dim, size,\n use_bias=False, data_format='channels_first')),\n [np.random.random((output_dim, input_dim, size, size))],\n (None, input_dim, 4, 4),\n ],\n [\n (keras.layers.Conv2DTranspose(output_dim, size,\n use_bias=False,\n data_format='channels_first')),\n [np.random.random((output_dim, input_dim, size, size))],\n (None, input_dim, 4, 4),\n ],\n [\n (keras.layers.Conv2DTranspose(output_dim, size,\n use_bias=False,\n data_format='channels_last')),\n [np.random.random((size, size, input_dim, output_dim))],\n (None, 4, 4, input_dim),\n ],\n [\n (keras.layers.Conv3D(output_dim, size,\n use_bias=False, data_format='channels_first')),\n [np.random.random((output_dim, input_dim, size, size, size))],\n (None, input_dim, 4, 4, 4),\n ],\n [\n (keras.layers.GRU(output_dim)),\n [np.random.random((input_dim, output_dim)),\n np.random.random((output_dim, output_dim)),\n np.random.random((output_dim,)),\n np.random.random((input_dim, output_dim)),\n np.random.random((output_dim, output_dim)),\n np.random.random((output_dim,)),\n np.random.random((input_dim, output_dim)),\n np.random.random((output_dim, output_dim)),\n np.random.random((output_dim,))],\n (None, 4, input_dim),\n ],\n [\n (keras.layers.LSTM(output_dim)),\n [np.random.random((input_dim, output_dim)),\n np.random.random((output_dim, output_dim)),\n np.random.random((output_dim,)),\n np.random.random((input_dim, output_dim)),\n np.random.random((output_dim, output_dim)),\n np.random.random((output_dim,)),\n np.random.random((input_dim, output_dim)),\n np.random.random((output_dim, output_dim)),\n np.random.random((output_dim,)),\n np.random.random((input_dim, output_dim)),\n np.random.random((output_dim, output_dim)),\n np.random.random((output_dim,))],\n (None, 4, input_dim),\n ],\n ]\n for layer, weights, input_shape in cases:\n layer.build(input_shape)\n _ = hdf5_format.preprocess_weights_for_loading(\n layer, weights, original_keras_version='1')\n\n model = keras.models.Sequential([keras.layers.Dense(2, input_dim=2)])\n _ = hdf5_format.preprocess_weights_for_loading(\n model, model.weights, original_keras_version='1')\n\n x = keras.Input((2,))\n y = keras.layers.Dense(2)(x)\n model = keras.models.Model(x, y)\n _ = hdf5_format.preprocess_weights_for_loading(\n model, model.weights, original_keras_version='1')\n\n @parameterized.named_parameters(\n ('gru', keras.layers.GRU, {\n 'units': 2,\n 'input_shape': (3, 5)\n }),\n ('gru_with_reset_after', keras.layers.GRU, {\n 'units': 2,\n 'input_shape': (3, 5),\n 'reset_after': True\n }),\n ('lstm', keras.layers.LSTM, {\n 'units': 2,\n 'input_shape': (3, 5)\n }),\n ('cudnngru', keras.layers.CuDNNGRU, {\n 'units': 2,\n 'input_shape': (3, 5)\n }),\n ('cudnnlstm', keras.layers.CuDNNLSTM, {\n 'units': 2,\n 'input_shape': (3, 5)\n }))\n def test_preprocess_weights_for_loading_rnn_should_be_idempotent(\n self, layer_class, layer_args):\n with self.cached_session():\n layer = layer_class(**layer_args)\n layer.build(input_shape=layer_args.get('input_shape'))\n weights1 = layer.get_weights()\n weights2 = hdf5_format.preprocess_weights_for_loading(\n layer, weights1)\n _ = [\n self.assertAllClose(x, y, rtol=1e-05)\n for (x, y) in zip(weights1, weights2)\n ]\n\n @test_util.run_in_graph_and_eager_modes\n def test_sequential_weight_loading(self):\n if h5py is None:\n return\n\n temp_dir = self.get_temp_dir()\n self.addCleanup(shutil.rmtree, temp_dir)\n h5_path = os.path.join(temp_dir, 'test.h5')\n\n num_hidden = 5\n input_dim = 3\n batch_size = 5\n num_classes = 2\n\n with self.cached_session():\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(num_hidden, input_dim=input_dim))\n model.add(keras.layers.Dense(num_classes))\n\n x = np.random.random((batch_size, input_dim))\n ref_y = model.predict(x)\n\n model.save_weights(h5_path)\n\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(num_hidden, input_dim=input_dim))\n model.add(keras.layers.Dense(num_classes))\n model.load_weights(h5_path)\n y = model.predict(x)\n\n self.assertAllClose(y, ref_y)\n\n @test_util.run_in_graph_and_eager_modes\n def test_nested_model_weight_loading(self):\n if h5py is None:\n return\n\n temp_dir = self.get_temp_dir()\n self.addCleanup(shutil.rmtree, temp_dir)\n h5_path = os.path.join(temp_dir, 'test.h5')\n\n num_hidden = 5\n input_dim = 3\n batch_size = 5\n num_classes = 2\n\n with self.cached_session():\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(num_hidden, input_dim=input_dim))\n model.add(keras.layers.Dense(num_classes))\n\n nested_model = keras.models.Sequential()\n nested_model.add(keras.layers.Dense(num_hidden, input_dim=num_classes))\n nested_model.add(keras.layers.Dense(num_classes))\n model.add(nested_model)\n\n x = np.random.random((batch_size, input_dim))\n ref_y = model.predict(x)\n\n model.save_weights(h5_path)\n\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(num_hidden, input_dim=input_dim))\n model.add(keras.layers.Dense(num_classes))\n nested_model = keras.models.Sequential()\n nested_model.add(keras.layers.Dense(num_hidden, input_dim=num_classes))\n nested_model.add(keras.layers.Dense(num_classes))\n model.add(nested_model)\n model.load_weights(h5_path)\n y = model.predict(x)\n\n self.assertAllClose(y, ref_y)\n\n @test_util.run_in_graph_and_eager_modes\n def test_sequential_weight_loading_group_name_with_incorrect_length(self):\n if h5py is None:\n return\n\n temp_dir = self.get_temp_dir()\n self.addCleanup(shutil.rmtree, temp_dir)\n h5_path = os.path.join(temp_dir, 'test.h5')\n\n num_hidden = 5\n input_dim = 3\n num_classes = 2\n with self.cached_session():\n ref_model = keras.models.Sequential()\n ref_model.add(keras.layers.Dense(num_hidden, input_dim=input_dim,\n name='d1'))\n ref_model.add(keras.layers.Dense(num_classes, name='d2'))\n ref_model.compile(loss=keras.losses.MSE,\n optimizer=keras.optimizers.RMSprop(lr=0.0001),\n metrics=[keras.metrics.categorical_accuracy])\n\n f_ref_model = h5py.File(h5_path, 'w')\n hdf5_format.save_weights_to_hdf5_group(f_ref_model, ref_model.layers)\n\n f_model = h5py.File(h5_path, 'r')\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(num_hidden, use_bias=False,\n input_dim=input_dim, name='d1'))\n model.add(keras.layers.Dense(num_classes, name='d2'))\n model.compile(loss=keras.losses.MSE,\n optimizer=keras.optimizers.RMSprop(lr=0.0001),\n metrics=[keras.metrics.categorical_accuracy])\n with self.assertRaisesRegexp(ValueError,\n r'Layer #0 \\(named \\\"d1\\\"\\) expects 1 '\n r'weight\\(s\\), but the saved weights have 2 '\n r'element\\(s\\)\\.'):\n hdf5_format.load_weights_from_hdf5_group_by_name(f_model, model.layers)\n\n @test_util.run_deprecated_v1\n def test_sequential_weight_loading_group_name_with_incorrect_shape(self):\n if h5py is None:\n return\n\n temp_dir = self.get_temp_dir()\n self.addCleanup(shutil.rmtree, temp_dir)\n h5_path = os.path.join(temp_dir, 'test.h5')\n\n num_hidden = 5\n input_dim = 3\n num_classes = 2\n with self.cached_session():\n ref_model = keras.models.Sequential()\n ref_model.add(keras.layers.Dense(num_hidden, input_dim=input_dim,\n name='d1'))\n ref_model.add(keras.layers.Dense(num_classes, name='d2'))\n ref_model.compile(loss=keras.losses.MSE,\n optimizer=keras.optimizers.RMSprop(lr=0.0001),\n metrics=[keras.metrics.categorical_accuracy])\n\n f_ref_model = h5py.File(h5_path, 'w')\n hdf5_format.save_weights_to_hdf5_group(f_ref_model, ref_model.layers)\n\n f_model = h5py.File(h5_path, 'r')\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(num_hidden + 5, input_dim=input_dim,\n name='d1'))\n model.add(keras.layers.Dense(num_classes, name='d2'))\n model.compile(loss=keras.losses.MSE,\n optimizer=keras.optimizers.RMSprop(lr=0.0001),\n metrics=[keras.metrics.categorical_accuracy])\n with self.assertRaisesRegexp(ValueError,\n r'Layer #0 \\(named \"d1\"\\), weight '\n r'<tf\\.Variable \\'d1_1\\/kernel:0\\' '\n r'shape=\\(3, 10\\) dtype=float32> has '\n r'shape \\(3, 10\\), but the saved weight has '\n r'shape \\(3, 5\\)\\.'):\n hdf5_format.load_weights_from_hdf5_group_by_name(f_model, model.layers)\n\n\nclass TestWholeModelSaving(test.TestCase):\n\n @test_util.run_v1_only('b/120994067')\n def test_sequential_model_saving(self):\n if h5py is None:\n self.skipTest('h5py required to run this test')\n\n with self.cached_session():\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(2, input_shape=(3,)))\n model.add(keras.layers.RepeatVector(3))\n model.add(keras.layers.TimeDistributed(keras.layers.Dense(3)))\n model.compile(\n loss=keras.losses.MSE,\n optimizer=keras.optimizers.RMSprop(lr=0.0001),\n metrics=[\n keras.metrics.categorical_accuracy,\n keras.metrics.CategoricalCrossentropy(\n name='cce', label_smoothing=constant_op.constant(0.2)),\n ],\n weighted_metrics=[\n keras.metrics.categorical_crossentropy,\n keras.metrics.CategoricalCrossentropy(\n name='cce', label_smoothing=constant_op.constant(0.2)),\n ],\n sample_weight_mode='temporal')\n\n x = np.random.random((1, 3))\n y = np.random.random((1, 3, 3))\n model.train_on_batch(x, y)\n\n out = model.predict(x)\n fd, fname = tempfile.mkstemp('.h5')\n keras.models.save_model(model, fname)\n\n new_model = keras.models.load_model(fname)\n os.close(fd)\n os.remove(fname)\n\n out2 = new_model.predict(x)\n self.assertAllClose(out, out2, atol=1e-05)\n\n # test that new updates are the same with both models\n x = np.random.random((1, 3))\n y = np.random.random((1, 3, 3))\n model.train_on_batch(x, y)\n new_model.train_on_batch(x, y)\n\n x = np.random.random((1, 3))\n y = np.random.random((1, 3, 3))\n eval_out = model.evaluate(x, y)\n eval_out2 = new_model.evaluate(x, y)\n self.assertArrayNear(eval_out, eval_out2, 0.001)\n\n out = model.predict(x)\n out2 = new_model.predict(x)\n\n # TODO(b/120930751) This tolerance should be 1e-05,\n # very concerning that its not.\n self.assertAllClose(out, out2, atol=1e-03)\n\n @test_util.run_deprecated_v1\n def test_sequential_model_saving_without_input_shape(self):\n if h5py is None:\n self.skipTest('h5py required to run this test')\n\n with self.cached_session():\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(2))\n model.add(keras.layers.RepeatVector(3))\n model.add(keras.layers.TimeDistributed(keras.layers.Dense(3)))\n model.compile(\n loss=keras.losses.MSE,\n optimizer=keras.optimizers.RMSprop(lr=0.0001),\n metrics=[\n keras.metrics.categorical_accuracy,\n keras.metrics.CategoricalAccuracy()\n ],\n weighted_metrics=[\n keras.metrics.categorical_accuracy,\n keras.metrics.CategoricalAccuracy()\n ],\n sample_weight_mode='temporal')\n x = np.random.random((1, 3))\n y = np.random.random((1, 3, 3))\n model.train_on_batch(x, y)\n\n out = model.predict(x)\n fd, fname = tempfile.mkstemp('.h5', dir=self.get_temp_dir())\n model.save(fname)\n\n new_model = keras.models.load_model(fname)\n os.close(fd)\n os.remove(fname)\n\n out2 = new_model.predict(x)\n self.assertAllClose(out, out2, atol=1e-05)\n\n def test_sequential_model_saving_without_compile(self):\n if h5py is None:\n self.skipTest('h5py required to run this test')\n\n with self.cached_session():\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(2, input_shape=(3,)))\n model.add(keras.layers.RepeatVector(3))\n model.add(keras.layers.TimeDistributed(keras.layers.Dense(3)))\n\n x = np.random.random((1, 3))\n out = model.predict(x)\n fd, fname = tempfile.mkstemp('.h5')\n\n # Save the model without any compilation or training.\n keras.models.save_model(model, fname)\n\n new_model = keras.models.load_model(fname)\n os.close(fd)\n os.remove(fname)\n\n out2 = new_model.predict(x)\n self.assertAllClose(out, out2, atol=1e-05)\n\n @test_util.run_deprecated_v1\n def test_sequential_model_saving_2(self):\n if h5py is None:\n self.skipTest('h5py required to run this test')\n\n with self.cached_session():\n # test with custom optimizer, loss\n\n class CustomOp(keras.optimizers.RMSprop):\n pass\n\n def custom_loss(y_true, y_pred):\n return keras.losses.mse(y_true, y_pred)\n\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(2, input_shape=(3,)))\n model.add(keras.layers.Dense(3))\n model.compile(loss=custom_loss, optimizer=CustomOp(), metrics=['acc'])\n\n x = np.random.random((1, 3))\n y = np.random.random((1, 3))\n model.train_on_batch(x, y)\n\n out = model.predict(x)\n fd, fname = tempfile.mkstemp('.h5')\n keras.models.save_model(model, fname)\n\n model = keras.models.load_model(\n fname,\n custom_objects={'CustomOp': CustomOp,\n 'custom_loss': custom_loss})\n os.close(fd)\n os.remove(fname)\n\n out2 = model.predict(x)\n self.assertAllClose(out, out2, atol=1e-05)\n\n @test_util.run_deprecated_v1\n def test_functional_model_saving(self):\n if h5py is None:\n self.skipTest('h5py required to run this test')\n\n with self.cached_session():\n inputs = keras.layers.Input(shape=(3,))\n x = keras.layers.Dense(2)(inputs)\n output = keras.layers.Dense(3)(x)\n\n model = keras.models.Model(inputs, output)\n model.compile(\n loss=keras.losses.MSE,\n optimizer=keras.optimizers.RMSprop(lr=0.0001),\n metrics=[\n keras.metrics.categorical_accuracy,\n keras.metrics.CategoricalAccuracy()\n ],\n weighted_metrics=[\n keras.metrics.categorical_accuracy,\n keras.metrics.CategoricalAccuracy()\n ])\n x = np.random.random((1, 3))\n y = np.random.random((1, 3))\n model.train_on_batch(x, y)\n\n out = model.predict(x)\n fd, fname = tempfile.mkstemp('.h5')\n keras.models.save_model(model, fname)\n\n model = keras.models.load_model(fname)\n os.close(fd)\n os.remove(fname)\n\n out2 = model.predict(x)\n self.assertAllClose(out, out2, atol=1e-05)\n\n def test_saving_without_compilation(self):\n if h5py is None:\n self.skipTest('h5py required to run this test')\n\n with self.cached_session():\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(2, input_shape=(3,)))\n model.add(keras.layers.Dense(3))\n model.compile(loss='mse', optimizer='sgd', metrics=['acc'])\n\n fd, fname = tempfile.mkstemp('.h5')\n keras.models.save_model(model, fname)\n model = keras.models.load_model(fname)\n os.close(fd)\n os.remove(fname)\n\n def test_saving_with_tf_optimizer(self):\n if h5py is None:\n self.skipTest('h5py required to run this test')\n\n with self.cached_session():\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(2, input_shape=(3,)))\n model.add(keras.layers.Dense(3))\n model.compile(loss='mse',\n optimizer=training_module.AdadeltaOptimizer(0.1),\n metrics=['acc'])\n\n fd, fname = tempfile.mkstemp('.h5')\n keras.models.save_model(model, fname)\n model = keras.models.load_model(fname)\n os.close(fd)\n os.remove(fname)\n\n def test_saving_right_after_compilation(self):\n if h5py is None:\n self.skipTest('h5py required to run this test')\n\n with self.cached_session():\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(2, input_shape=(3,)))\n model.add(keras.layers.Dense(3))\n model.compile(loss='mse', optimizer='sgd', metrics=['acc'])\n model._make_train_function()\n\n fd, fname = tempfile.mkstemp('.h5')\n keras.models.save_model(model, fname)\n model = keras.models.load_model(fname)\n os.close(fd)\n os.remove(fname)\n\n def test_saving_lambda_numpy_array_arguments(self):\n with self.cached_session():\n if h5py is None:\n self.skipTest('h5py required to run this test')\n\n mean = np.random.random((4, 2, 3))\n std = np.abs(np.random.random((4, 2, 3))) + 1e-5\n inputs = keras.layers.Input(shape=(4, 2, 3))\n output = keras.layers.Lambda(lambda image, mu, std: (image - mu) / std,\n arguments={'mu': mean, 'std': std})(inputs)\n model = keras.models.Model(inputs, output)\n model.compile(loss='mse', optimizer='sgd', metrics=['acc'])\n\n fd, fname = tempfile.mkstemp('.h5')\n keras.models.save_model(model, fname)\n\n model = keras.models.load_model(fname)\n os.close(fd)\n os.remove(fname)\n\n self.assertAllClose(mean, model.layers[1].arguments['mu'])\n self.assertAllClose(std, model.layers[1].arguments['std'])\n\n def test_saving_model_with_long_layer_names(self):\n if h5py is None:\n self.skipTest('h5py required to run this test')\n\n with self.cached_session():\n # This layer name will make the `layers_name` HDF5 attribute blow\n # out of proportion. Note that it fits into the internal HDF5\n # attribute memory limit on its own but because h5py converts\n # the list of layer names into numpy array, which uses the same\n # amout of memory for every item, it increases the memory\n # requirements substantially.\n x = keras.Input(shape=(2,), name='input_' + ('x' * (2**15)))\n f = x\n for i in range(4):\n f = keras.layers.Dense(2, name='dense_%d' % (i,))(f)\n model = keras.Model(inputs=[x], outputs=[f])\n model.compile(\n 'adam', loss=keras.losses.MeanSquaredError(), metrics=['acc'])\n\n x = np.random.random((1, 2))\n y = np.random.random((1, 2))\n model.train_on_batch(x, y)\n out = model.predict(x)\n\n fd, fname = tempfile.mkstemp('.h5')\n keras.models.save_model(model, fname)\n model = keras.models.load_model(fname)\n\n # Check that the HDF5 files contains chunked array\n # of layer names.\n with h5py.File(fname, 'r') as h5file:\n num_names_arrays = len([attr for attr in h5file['model_weights'].attrs\n if attr.startswith('layer_names')])\n # The chunking of layer names array should have happened.\n self.assertGreater(num_names_arrays, 0)\n out2 = model.predict(x)\n self.assertAllClose(out, out2, atol=1e-05)\n\n # Cleanup\n os.close(fd)\n os.remove(fname)\n\n def test_saving_model_with_long_weights_names(self):\n if h5py is None:\n self.skipTest('h5py required to run this test')\n\n with self.cached_session():\n x = keras.Input(shape=(2,), name='nested_model_input')\n f = x\n for i in range(4):\n f = keras.layers.Dense(2, name='nested_model_dense_%d' % (i,))(f)\n # This layer name will make the `weights_name`\n # HDF5 attribute blow out of proportion.\n f = keras.layers.Dense(2, name='nested_model_output' + ('x' * (2**14)))(f)\n nested_model = keras.Model(inputs=[x], outputs=[f], name='nested_model')\n\n x = keras.Input(shape=(2,), name='outer_model_input')\n f = nested_model(x)\n f = keras.layers.Dense(2, name='outer_model_output')(f)\n\n model = keras.Model(inputs=[x], outputs=[f])\n model.compile(loss='mse', optimizer='adam', metrics=['acc'])\n\n x = np.random.random((1, 2))\n y = np.random.random((1, 2))\n model.train_on_batch(x, y)\n out = model.predict(x)\n\n fd, fname = tempfile.mkstemp('.h5')\n keras.models.save_model(model, fname)\n model = keras.models.load_model(fname)\n\n # Check that the HDF5 files contains chunked array\n # of weight names.\n with h5py.File(fname, 'r') as h5file:\n num_weight_arrays = len(\n [attr for attr in h5file['model_weights']['nested_model'].attrs\n if attr.startswith('weight_names')])\n # The chunking of layer names array should have happened.\n self.assertGreater(num_weight_arrays, 0)\n out2 = model.predict(x)\n self.assertAllClose(out, out2, atol=1e-05)\n\n # Cleanup\n os.close(fd)\n os.remove(fname)\n\n @test_util.run_deprecated_v1\n def test_model_saving_to_pre_created_h5py_file(self):\n if h5py is None:\n self.skipTest('h5py required to run this test')\n\n with self.cached_session():\n inputs = keras.Input(shape=(3,))\n x = keras.layers.Dense(2)(inputs)\n outputs = keras.layers.Dense(3)(x)\n\n model = keras.Model(inputs, outputs)\n model.compile(\n loss=keras.losses.MSE,\n optimizer=keras.optimizers.Adam(),\n metrics=[\n keras.metrics.categorical_accuracy,\n keras.metrics.CategoricalAccuracy()\n ])\n x = np.random.random((1, 3))\n y = np.random.random((1, 3))\n model.train_on_batch(x, y)\n\n out = model.predict(x)\n fd, fname = tempfile.mkstemp('.h5')\n with h5py.File(fname, mode='r+') as h5file:\n keras.models.save_model(model, h5file)\n loaded_model = keras.models.load_model(h5file)\n out2 = loaded_model.predict(x)\n self.assertAllClose(out, out2, atol=1e-05)\n\n # Test non-default options in h5\n with h5py.File('_', driver='core',\n backing_store=False) as h5file:\n keras.models.save_model(model, h5file)\n loaded_model = keras.models.load_model(h5file)\n out2 = loaded_model.predict(x)\n self.assertAllClose(out, out2, atol=1e-05)\n\n # Cleanup\n os.close(fd)\n os.remove(fname)\n\n def test_saving_constant_initializer_with_numpy(self):\n if h5py is None:\n self.skipTest('h5py required to run this test')\n\n with self.cached_session():\n model = keras.models.Sequential()\n model.add(\n keras.layers.Dense(\n 2,\n input_shape=(3,),\n kernel_initializer=keras.initializers.Constant(np.ones((3, 2)))))\n model.add(keras.layers.Dense(3))\n model.compile(loss='mse', optimizer='sgd', metrics=['acc'])\n fd, fname = tempfile.mkstemp('.h5')\n keras.models.save_model(model, fname)\n model = keras.models.load_model(fname)\n os.close(fd)\n os.remove(fname)\n\n def test_primitive_attrs_contain_no_extraneous_strings(self):\n if h5py is None:\n self.skipTest('h5py required to run this test')\n\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(1, input_shape=[2]))\n fname = os.path.join(self.get_temp_dir(), 'model.h5')\n model.save(fname)\n\n h5file = h5py.File(fname, 'r')\n self.assertRegexpMatches(\n h5file.attrs['keras_version'], r'^[\\d]+\\.[\\d]+\\.[\\S]+$')\n\n\nclass SubclassedModel(training.Model):\n\n def __init__(self):\n super(SubclassedModel, self).__init__()\n self.x_layer = keras.layers.Dense(3)\n self.b_layer = keras.layers.Dense(1)\n\n def call(self, a):\n return self.b_layer(self.x_layer(a))\n\n\nclass TestWeightSavingAndLoadingTFFormat(test.TestCase):\n\n def test_keras_optimizer_warning(self):\n graph = ops.Graph()\n with graph.as_default(), self.session(graph):\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(2, input_shape=(3,)))\n model.add(keras.layers.Dense(3))\n model.compile(loss='mse', optimizer=optimizers.Adam(), metrics=['acc'])\n model._make_train_function()\n temp_dir = self.get_temp_dir()\n prefix = os.path.join(temp_dir, 'ckpt')\n with test.mock.patch.object(logging, 'warning') as mock_log:\n model.save_weights(prefix)\n self.assertRegexpMatches(\n str(mock_log.call_args),\n 'Keras optimizer')\n\n @test_util.run_in_graph_and_eager_modes\n def test_tensorflow_format_overwrite(self):\n with self.cached_session() as session:\n model = SubclassedModel()\n temp_dir = self.get_temp_dir()\n prefix = os.path.join(temp_dir, 'ckpt')\n\n x = constant_op.constant(np.random.random((3, 2)), dtype=dtypes.float32)\n executing_eagerly = context.executing_eagerly()\n model(x) # pylint: disable=not-callable\n if not executing_eagerly:\n session.run([v.initializer for v in model.variables])\n model.save_weights(prefix, save_format='tensorflow')\n model.save_weights(prefix, save_format='tensorflow', overwrite=True)\n with self.assertRaises(EOFError):\n # Indirectly tests that the user is prompted\n model.save_weights(prefix, save_format='tensorflow', overwrite=False)\n\n def test_no_default_session(self):\n with ops.Graph().as_default():\n self.assertFalse(ops.get_default_session())\n data = np.random.random((1000, 32)).astype(np.float32)\n labels = np.random.random((1000, 10)).astype(np.float32)\n\n model = keras.models.Sequential([\n keras.layers.Dense(10, activation='softmax'),\n keras.layers.Dense(10, activation='softmax')])\n\n model.compile(optimizer=training_module.RMSPropOptimizer(0.001),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n model.fit(data, labels)\n fname = os.path.join(self.get_temp_dir(), 'weights', 'ckpt')\n model.save_weights(fname)\n model.load_weights(fname)\n\n def test_no_graph_pollution(self):\n with context.graph_mode():\n graph = ops.Graph()\n with graph.as_default(), self.session(graph) as session:\n model = SubclassedModel()\n temp_dir = self.get_temp_dir()\n prefix = os.path.join(temp_dir, 'ckpt')\n\n x = constant_op.constant(np.random.random((3, 2)), dtype=dtypes.float32)\n model(x) # pylint: disable=not-callable\n session.run([v.initializer for v in model.variables])\n model.save_weights(prefix, save_format='tensorflow')\n op_count = len(graph.get_operations())\n model.save_weights(prefix, save_format='tensorflow')\n self.assertEqual(len(graph.get_operations()), op_count)\n\n model.load_weights(prefix)\n op_count = len(graph.get_operations())\n model.load_weights(prefix)\n self.assertEqual(len(graph.get_operations()), op_count)\n\n def _weight_loading_test_template(self, make_model_fn):\n with self.cached_session():\n model = make_model_fn()\n model.compile(\n loss='mse',\n optimizer=training_module.RMSPropOptimizer(0.1),\n metrics=['acc', keras.metrics.CategoricalAccuracy()])\n temp_dir = self.get_temp_dir()\n prefix = os.path.join(temp_dir, 'ckpt')\n train_x = np.random.random((3, 2))\n train_y = np.random.random((3,))\n x = constant_op.constant(train_x, dtype=dtypes.float32)\n\n model.train_on_batch(train_x, train_y)\n model.save_weights(prefix, save_format='tf')\n ref_y_before_train = model.predict(train_x)\n model.train_on_batch(train_x, train_y)\n ref_y_after_train = model.predict(train_x)\n for v in model.variables:\n self.evaluate(\n v.assign(random_ops.random_normal(shape=array_ops.shape(v))))\n\n self.addCleanup(shutil.rmtree, temp_dir)\n\n model.load_weights(prefix)\n self.assertAllClose(ref_y_before_train, self.evaluate(model(x)))\n\n # Test restore-on-create if this is a subclassed Model (graph Networks\n # will have already created their variables).\n load_model = make_model_fn()\n load_model.load_weights(prefix)\n self.assertAllClose(\n ref_y_before_train,\n self.evaluate(load_model(x)))\n load_model = make_model_fn()\n load_model.load_weights(prefix)\n # We need to run some of the restore ops for predict(), but not all\n # variables have been created yet (optimizer slot variables). Tests\n # incremental restore.\n load_model.predict(train_x)\n load_model.compile(\n loss='mse',\n optimizer=training_module.RMSPropOptimizer(0.1),\n metrics=['acc', keras.metrics.CategoricalAccuracy()])\n load_model.train_on_batch(train_x, train_y)\n self.assertAllClose(ref_y_after_train, self.evaluate(load_model(x)))\n\n @test_util.run_in_graph_and_eager_modes\n def test_weight_loading_graph_model(self):\n def _make_graph_model():\n a = keras.layers.Input(shape=(2,))\n x = keras.layers.Dense(3)(a)\n b = keras.layers.Dense(1)(x)\n return keras.models.Model(a, b)\n\n self._weight_loading_test_template(_make_graph_model)\n\n @test_util.run_in_graph_and_eager_modes\n def test_weight_loading_subclassed_model(self):\n self._weight_loading_test_template(SubclassedModel)\n\n def _new_layer_weight_loading_test_template(\n self, first_model_fn, second_model_fn, restore_init_fn):\n with self.cached_session() as session:\n model = first_model_fn()\n temp_dir = self.get_temp_dir()\n prefix = os.path.join(temp_dir, 'ckpt')\n\n x = constant_op.constant(np.random.random((3, 2)), dtype=dtypes.float32)\n executing_eagerly = context.executing_eagerly()\n ref_y_tensor = model(x)\n if not executing_eagerly:\n session.run([v.initializer for v in model.variables])\n ref_y = self.evaluate(ref_y_tensor)\n model.save_weights(prefix)\n self.assertEqual(\n prefix,\n checkpoint_management.latest_checkpoint(temp_dir))\n for v in model.variables:\n self.evaluate(\n v.assign(random_ops.random_normal(shape=array_ops.shape(v))))\n\n self.addCleanup(shutil.rmtree, temp_dir)\n\n second_model = second_model_fn()\n second_model.load_weights(prefix)\n second_model(x)\n self.evaluate(restore_init_fn(second_model))\n second_model.save_weights(prefix)\n # Check that the second model's checkpoint loads into the original model\n model.load_weights(prefix)\n y = self.evaluate(model(x))\n self.assertAllClose(ref_y, y)\n\n @test_util.run_in_graph_and_eager_modes\n def test_weight_loading_graph_model_added_layer(self):\n def _save_graph_model():\n a = keras.layers.Input(shape=(2,))\n x = keras.layers.Dense(3, name='first')(a)\n b = keras.layers.Dense(1, name='second')(x)\n return keras.models.Model(a, b)\n def _restore_graph_model():\n a = keras.layers.Input(shape=(2,))\n x = keras.layers.Dense(3, name='first')(a)\n y = keras.layers.Dense(1, name='second')(x)\n b = keras.layers.Dense(3, name='secondjr')(y)\n return keras.models.Model(a, b)\n def _restore_init_fn(restore_model):\n return [v.initializer for v in restore_model.layers[-1].variables]\n\n self._new_layer_weight_loading_test_template(\n _save_graph_model, _restore_graph_model,\n _restore_init_fn)\n\n @test_util.run_in_graph_and_eager_modes\n def test_weight_loading_graph_model_added_no_weight_layer(self):\n def _save_graph_model():\n a = keras.layers.Input(shape=(2,))\n x = keras.layers.Dense(3, name='first')(a)\n b = keras.layers.Dense(1, name='second')(x)\n return keras.models.Model(a, b)\n def _restore_graph_model():\n a = keras.layers.Input(shape=(2,))\n x = keras.layers.Dense(3, name='first')(a)\n y = keras.layers.Dropout(rate=0.1)(x)\n b = keras.layers.Dense(1, name='second')(y)\n return keras.models.Model(a, b)\n def _restore_init_fn(restore_model):\n del restore_model # unused\n return []\n\n self._new_layer_weight_loading_test_template(\n _save_graph_model, _restore_graph_model,\n _restore_init_fn)\n\n @test_util.run_in_graph_and_eager_modes\n def test_weight_loading_subclassed_model_added_layer(self):\n\n class SubclassedModelRestore(training.Model):\n\n def __init__(self):\n super(SubclassedModelRestore, self).__init__()\n self.x_layer = keras.layers.Dense(3)\n self.y_layer = keras.layers.Dense(3)\n self.b_layer = keras.layers.Dense(1)\n\n def call(self, a):\n return self.b_layer(self.y_layer(self.x_layer(a)))\n\n def _restore_init_fn(restore_model):\n return [v.initializer for v in restore_model.y_layer.variables]\n\n self._new_layer_weight_loading_test_template(\n SubclassedModel, SubclassedModelRestore,\n _restore_init_fn)\n\n @test_util.run_in_graph_and_eager_modes\n def test_incompatible_checkpoint(self):\n save_path = trackable.Checkpoint().save(\n os.path.join(self.get_temp_dir(), 'ckpt'))\n m = keras.Model()\n with self.assertRaisesRegexp(AssertionError, 'Nothing to load'):\n m.load_weights(save_path)\n m.dense = keras.layers.Dense(2)\n m.dense(constant_op.constant([[1.]]))\n with self.assertRaisesRegexp(\n AssertionError, 'Nothing except the root object matched'):\n m.load_weights(save_path)\n\n @test_util.run_in_graph_and_eager_modes\n def test_directory_passed(self):\n m = keras.Model()\n v = m.add_weight(name='v', shape=[])\n self.evaluate(v.assign(42.))\n prefix = os.path.join(self.get_temp_dir(), '{}'.format(ops.uid()), 'ckpt/')\n m.save_weights(prefix)\n self.evaluate(v.assign(2.))\n m.load_weights(prefix)\n self.assertEqual(42., self.evaluate(v))\n\n @test_util.run_in_graph_and_eager_modes\n def test_relative_path(self):\n m = keras.Model()\n v = m.add_weight(name='v', shape=[])\n os.chdir(self.get_temp_dir())\n\n prefix = 'ackpt'\n self.evaluate(v.assign(42.))\n m.save_weights(prefix)\n self.assertTrue(file_io.file_exists('ackpt.index'))\n self.evaluate(v.assign(1.))\n m.load_weights(prefix)\n self.assertEqual(42., self.evaluate(v))\n\n prefix = 'subdir/ackpt'\n self.evaluate(v.assign(43.))\n m.save_weights(prefix)\n self.assertTrue(file_io.file_exists('subdir/ackpt.index'))\n self.evaluate(v.assign(2.))\n m.load_weights(prefix)\n self.assertEqual(43., self.evaluate(v))\n\n prefix = 'ackpt/'\n self.evaluate(v.assign(44.))\n m.save_weights(prefix)\n self.assertTrue(file_io.file_exists('ackpt/.index'))\n self.evaluate(v.assign(3.))\n m.load_weights(prefix)\n self.assertEqual(44., self.evaluate(v))\n\n @test_util.run_in_graph_and_eager_modes\n def test_nonexistant_prefix_directory(self):\n m = keras.Model()\n v = m.add_weight(name='v', shape=[])\n self.evaluate(v.assign(42.))\n prefix = os.path.join(self.get_temp_dir(), '{}'.format(ops.uid()), 'bckpt')\n m.save_weights(prefix)\n self.evaluate(v.assign(2.))\n m.load_weights(prefix)\n self.assertEqual(42., self.evaluate(v))\n\nif __name__ == '__main__':\n test.main()\n"
]
| [
[
"tensorflow.python.tpu.ops.tpu_ops.load_tpu_embedding_adam_parameters",
"tensorflow.python.tpu.ops.tpu_ops.retrieve_tpu_embedding_stochastic_gradient_descent_parameters",
"tensorflow.python.ops.state_ops.assign",
"tensorflow.python.tpu.tpu_system_metadata._query_tpu_system_metadata",
"tensorflow.python.ops.array_ops.expand_dims",
"tensorflow.python.framework.ops.device",
"tensorflow.python.tpu.tpu_system_metadata.master_job",
"tensorflow.python.framework.ops.colocate_with",
"tensorflow.python.ops.array_ops.concat",
"tensorflow.python.ops.init_ops.constant_initializer",
"tensorflow.python.tpu.ops.tpu_ops.retrieve_tpu_embedding_adagrad_parameters",
"tensorflow.python.tpu.ops.tpu_ops.retrieve_tpu_embedding_adam_parameters",
"tensorflow.core.protobuf.tpu.tpu_embedding_configuration_pb2.TPUEmbeddingConfiguration",
"tensorflow.python.ops.init_ops.zeros_initializer",
"tensorflow.python.ops.partitioned_variables.fixed_size_partitioner",
"tensorflow.python.ops.array_ops.zeros",
"tensorflow.python.platform.tf_logging.debug",
"tensorflow.python.tpu.ops.tpu_ops.enqueue_tpu_embedding_sparse_tensor_batch",
"tensorflow.python.tpu.ops.tpu_ops.load_tpu_embedding_adagrad_parameters",
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.tpu.ops.tpu_ops.load_tpu_embedding_stochastic_gradient_descent_parameters"
],
[
"tensorflow.python.eager.context.graph_mode",
"tensorflow.python.keras.optimizers.Adam",
"tensorflow.python.keras.layers.Dense",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.keras.losses.MeanSquaredError",
"numpy.random.random",
"tensorflow.python.platform.test.main",
"tensorflow.python.keras.layers.Conv1D",
"tensorflow.python.training.checkpoint_management.latest_checkpoint",
"tensorflow.python.keras.models.Sequential",
"tensorflow.python.keras.layers.GRU",
"tensorflow.python.keras.models.load_model",
"tensorflow.python.training.training.RMSPropOptimizer",
"tensorflow.python.keras.saving.hdf5_format.preprocess_weights_for_loading",
"tensorflow.python.keras.layers.Conv2D",
"tensorflow.python.keras.layers.Conv2DTranspose",
"tensorflow.python.keras.saving.hdf5_format.save_weights_to_hdf5_group",
"tensorflow.python.keras.saving.hdf5_format.load_weights_from_hdf5_group_by_name",
"tensorflow.python.keras.losses.mse",
"tensorflow.python.keras.metrics.CategoricalAccuracy",
"tensorflow.python.keras.layers.RepeatVector",
"tensorflow.python.keras.layers.LSTM",
"tensorflow.python.framework.ops.get_default_session",
"tensorflow.python.framework.test_util.run_v1_only",
"tensorflow.python.training.training.AdadeltaOptimizer",
"tensorflow.python.keras.models.Model",
"tensorflow.python.keras.models.save_model",
"tensorflow.python.framework.ops.Graph",
"tensorflow.python.training.tracking.util.Checkpoint",
"tensorflow.python.keras.layers.Dropout",
"tensorflow.python.lib.io.file_io.file_exists",
"tensorflow.python.keras.Input",
"tensorflow.python.keras.layers.Conv3D",
"tensorflow.python.platform.test.mock.patch.object",
"tensorflow.python.keras.Model",
"tensorflow.python.keras.layers.SimpleRNN",
"tensorflow.python.keras.layers.Input",
"numpy.ones",
"tensorflow.python.framework.constant_op.constant",
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.framework.ops.uid",
"tensorflow.python.keras.layers.Lambda",
"tensorflow.python.keras.optimizers.RMSprop"
]
]
|
bnonni/Python | [
"9ebd18caa4e2d805028b557e8b77ea65a9ee1a3d"
]
| [
"Machine_Learning/Project/Bryan/P1/MCROC.py"
]
| [
"#!/usr/bin/env python3\nimport gc\nimport warnings\nimport gc, sys, re, os, math\nfrom time import strptime, mktime\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import *\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.svm import *\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.metrics import confusion_matrix, classification_report, roc_curve, roc_auc_score, auc, accuracy_score\n\ndef calc_multi_class_roc_auc(X_train, y_train, X_test, y_test, **kwargs):\n for k,v in kwargs.items():\n model = kwargs['model']\n tuner = kwargs['tuner']\n tuner_val = kwargs['tuner_val']\n dec = kwargs['dec']\n labels = kwargs['labels']\n \n y_train_bin = label_binarize(y_train, classes=labels)\n n_classes = y_train_bin.shape[1]\n y_test_bin = label_binarize(y_test, classes=labels)\n\n clf = OneVsRestClassifier(AdaBoostClassifier())\n y_score = clf.fit(X_train, y_train_bin).decision_function(X_test)\n\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n for i in range(n_classes):\n fpr[i], tpr[i], _ = roc_curve(y_test_bin[:, i], y_score[:, i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n\n fpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(y_test_bin.ravel(), y_score.ravel())\n roc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n \n \n plt.figure()\n plt.plot(fpr[\"micro\"], tpr[\"micro\"], label=f'{model} Micro-Avg Area: {round(roc_auc[\"micro\"], 4)}')\n for i in range(n_classes):\n plt.plot(fpr[i], tpr[i], label=f'{model} Area: {round(roc_auc[i], 4)}')\n if tuner_val == None:\n plt.title(f'{model} ROC Curve, Label {labels[i]}')\n else:\n plt.title(f'{model} ROC Curve, Label {labels[i]}, {tuner}={tuner_val}')\n plt.plot([0, 1], [0, 1], label='tpr-fpr line')\n plt.xlabel('fpr')\n plt.ylabel('tpr')\n plt.legend()\n plt.show()\n \n \n \n\n\"\"\"\ndef calcMultiClassROCAUC(X_train, y_train, X_test, y_test, **kwargs):\n for k,v in kwargs.items():\n model = kwargs['model']\n tuner = kwargs['tuner']\n tuner_val = kwargs['tuner_val']\n dec = kwargs['dec']\n label_len = kwargs['label_len']\n labels = kwargs['labels']\n \n y_bin = label_binarize(y_test, classes=labels)\n\n clf = OneVsRestClassifier(OneVsRestClassifier(SVC(kernel='linear', probability=True, random_state=0)))\n y_score = clf.fit(X_train, y_train).decision_function(X_test)\n\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n for i in range(label_len):\n fpr[i], tpr[i], _ = roc_curve(y_bin[:, i], y_score)\n roc_auc[i] = auc(fpr[i], tpr[i])\n\n fpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(y_test.ravel(), y_score.ravel())\n roc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n\n\n\n plt.figure()\n plt.plot(fpr[\"micro\"], tpr[\"micro\"], label=f'{model} micro-average ROC curve (area = {roc_auc[\"micro\"]})')\n for i in range(label_len):\n if (tuner == '') or (tuner_val == None):\n plt.plot(fpr[i], tpr[i], label=f'{model} ROC curve, Label {i} (area = {roc_auc[i]})')\n else:\n plt.plot(fpr[i], tpr[i], label=f'{model} ROC curve, Label {i}, {tuner}={tuner_val}, Label {i} (area = {roc_auc[i]})')\n plt.plot([0, 1], [0, 1], label='tpr-fpr line')\n plt.xlabel('fpr')\n plt.ylabel('tpr')\n plt.legend()\n plt.show()\n \"\"\""
]
| [
[
"sklearn.ensemble.AdaBoostClassifier",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"sklearn.metrics.auc",
"sklearn.metrics.roc_curve"
]
]
|
astrockragh/IceCube | [
"eba09e9f9a3c351dbf05496821bcd7d29ac0261c"
]
| [
"from_config/run_trainings.py"
]
| [
"import os, sys, tqdm, json, shutil, glob, argparse\r\n\r\nimport os.path as osp\r\n\r\nfrom tensorflow.keras.backend import clear_session\r\nimport tensorflow as tf\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' \r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"-f\", \"--f\", type=str, required=False)\r\nparser.add_argument(\"-gpu\", \"--gpu\", type=str, required=False)\r\nparser.add_argument(\"-cpus\", \"--cpus\", type=str, required=False)\r\nargs = parser.parse_args()\r\n\r\nif args.gpu!='all':\r\n os.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu\r\ngpu_devices = tf.config.list_physical_devices('GPU') \r\n\r\nif len(gpu_devices) > 0:\r\n print(\"GPU detected\")\r\n for i in range(len(gpu_devices)):\r\n tf.config.experimental.set_memory_growth(gpu_devices[i], True)\r\n\r\nexp0_folder = str(args.f)\r\nif args.cpus!='all':\r\n os.environ['TF_NUM_INTRAOP_THREADS'] = args.cpus\r\nSHUTDOWN = False\r\n##########################################################\r\n# Loop over JSON files and train models # \r\n##########################################################\r\n\r\n# Generate list over experiments to run\r\nfrom dev.utils import list_experiments, clean_done, check_dataset\r\nfrom dev.train_script import train_model\r\nclean_done(exp0_folder)\r\nexp_folder, exp_list = list_experiments(exp0_folder)\r\n\r\nprint(f\"Starting process with {len(exp_list)} experiments\")\r\nprint(exp_list)\r\n# Loop over the experiments\r\nfor i, experiment in enumerate(exp_list):\r\n\r\n # Load construction dictionary from json file\r\n with open(osp.join(exp_folder, experiment)) as file:\r\n construct_dict = json.load(file)\r\n construct_dict['experiment_name']=experiment[:-5]\r\n\r\n # data_exists=check_dataset(construct_dict['data_params']['database'], construct_dict['data_params']['muon'],\\\r\n # construct_dict['data_params']['n_data'], construct_dict['data_params']['graph_construction'])\r\n # if data_exists:\r\n # print('No data construction required')\r\n # construct_dict['data_params']['restart']=False\r\n\r\n\r\n print(f\"Starting experiment from {experiment[:-5]}\")\r\n\r\n epochexit=train_model(construct_dict)\r\n print(f'Exited training after {epochexit} epochs')\r\n shutil.move(osp.join(exp_folder, experiment), osp.join(exp0_folder+\"/done\", experiment))\r\n print(f\"Experiment {experiment[:-5]} done \\t {experiment}: {i + 1} / {len(exp_list)}\")\r\n\r\n\r\n\r\n\r\n clear_session()\r\n\r\n# if SHUTDOWN == True:\r\n# os.system(\"shutdown -h\")\r\n\r\n # Create a script to go through and test the performance\r\n # test_model(model = construct_dict['Experiment'], data = instructions_to_dataset_name(construct_dict))\r\n \r\n\r\n\r\n\r\n\r\n# We can setup a shutdown maybe\r\n#os.system(\"shutdown -h 5\")\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n\r\n\r\n"
]
| [
[
"tensorflow.config.list_physical_devices",
"tensorflow.config.experimental.set_memory_growth",
"tensorflow.keras.backend.clear_session"
]
]
|
andrevks/Document-Forgery-Detection | [
"77dcde3867732a55cd0f4604627d7bf67a5e79a5"
]
| [
"app/ImageObject.py"
]
| [
"from PIL import Image\n# import scipy.misc\nimport imageio \nfrom math import pow\nimport numpy as np\nimport builtins\nfrom tqdm import tqdm, trange\nimport time\n\nimport Container\nimport Blocks\n\n\nclass ImageObject(object):\n \"\"\"\n Object to contains a single image, then detects a fraud in it\n \"\"\"\n\n def __init__(self, imageDirectory, imageName, blockDimension, outputDirectory):\n \"\"\"\n Constructor to initialize the algorithm's parameters\n :param imageDirectory: direktori file citra\n :param imageName: nama file citra\n :param blockDimension: ukuran blok dimensi (ex:32, 64, 128)\n :param outputDirectory: direktori untuk hasil deteksi\n :return: None\n \"\"\"\n\n print (imageName)\n print (\"Step 1 of 4: Object and variable initialization\")\n\n # image parameter\n self.imageOutputDirectory = outputDirectory\n self.imagePath = imageName\n self.imageData = Image.open(imageDirectory + imageName)\n self.imageWidth, self.imageHeight = self.imageData.size # height = vertical, width = horizontal\n\n if self.imageData.mode != 'L': # L means grayscale\n self.isThisRGBImage = True\n self.imageData = self.imageData.convert('RGB')\n RGBImagePixels = self.imageData.load()\n self.imageGrayscale = self.imageData.convert(\n 'L') # creates a grayscale version of current image to be used later\n GrayscaleImagePixels = self.imageGrayscale.load()\n\n #?\n for yCoordinate in range(0, self.imageHeight):\n for xCoordinate in range(0, self.imageWidth):\n redPixelValue, greenPixelValue, bluePixelValue = RGBImagePixels[xCoordinate, yCoordinate]\n GrayscaleImagePixels[xCoordinate, yCoordinate] = int(0.299 * redPixelValue) + int(\n 0.587 * greenPixelValue) + int(0.114 * bluePixelValue)\n else:\n self.isThisRGBImage = False\n self.imageData = self.imageData.convert('L')\n\n # algorithm's parameters from the first paper\n self.N = self.imageWidth * self.imageHeight\n self.blockDimension = blockDimension\n self.b = self.blockDimension * self.blockDimension\n self.Nb = (self.imageWidth - self.blockDimension + 1) * (self.imageHeight - self.blockDimension + 1)\n self.Nn = 2 # amount of neighboring block to be evaluated\n self.Nf = 188 # minimum treshold of the offset's frequency\n self.Nd = 50 # minimum treshold of the offset's magnitude\n\n # algorithm's parameters from the second paper\n self.P = (1.80, 1.80, 1.80, 0.0125, 0.0125, 0.0125, 0.0125)\n self.t1 = 2.80\n self.t2 = 0.02\n\n print((self.Nb, self.isThisRGBImage))\n\n # container initialization to later contains several data\n self.featuresContainer = Container.Container()\n self.blockPairContainer = Container.Container()\n self.offsetDictionary = {}\n\n def run(self):\n \"\"\"\n Run the created algorithm\n :return: None\n \"\"\"\n\n # time logging (optional, for evaluation purpose)\n startTimestamp = time.time()\n self.compute()\n timestampAfterComputing = time.time()\n self.sort()\n timestampAfterSorting = time.time()\n self.analyze()\n timestampAfterAnalyze = time.time()\n imageResultPath = self.reconstruct()\n timestampAfterImageCreation = time.time()\n\n print((\"Computing time :\", timestampAfterComputing - startTimestamp, \"second\"))\n print((\"Sorting time :\", timestampAfterSorting - timestampAfterComputing, \"second\"))\n print((\"Analyzing time :\", timestampAfterAnalyze - timestampAfterSorting, \"secon\"))\n print((\"Image creation :\", timestampAfterImageCreation - timestampAfterAnalyze, \"second\"))\n\n totalRunningTimeInSecond = timestampAfterImageCreation - startTimestamp\n totalMinute, totalSecond = divmod(totalRunningTimeInSecond, 60)\n totalHour, totalMinute = divmod(totalMinute, 60)\n print((\"Total time : %d:%02d:%02d second\" % (totalHour, totalMinute, totalSecond), '\\n'))\n return imageResultPath\n\n def compute(self):\n \"\"\"\n To compute the characteristic features of image block\n :return: None\n \"\"\"\n print (\"Step 2 of 4: Computing characteristic features\")\n\n imageWidthOverlap = self.imageWidth - self.blockDimension\n imageHeightOverlap = self.imageHeight - self.blockDimension\n\n if self.isThisRGBImage:\n for i in tqdm(list(range(0, imageWidthOverlap + 1, 1))):\n for j in range(0, imageHeightOverlap + 1, 1):\n imageBlockRGB = self.imageData.crop((i, j, i + self.blockDimension, j + self.blockDimension))\n imageBlockGrayscale = self.imageGrayscale.crop(\n (i, j, i + self.blockDimension, j + self.blockDimension))\n imageBlock = Blocks.Blocks(imageBlockGrayscale, imageBlockRGB, i, j, self.blockDimension)\n self.featuresContainer.addBlock(imageBlock.computeBlock())\n else:\n for i in range(imageWidthOverlap + 1):\n for j in range(imageHeightOverlap + 1):\n imageBlockGrayscale = self.imageData.crop((i, j, i + self.blockDimension, j + self.blockDimension))\n imageBlock = Blocks.Blocks(imageBlockGrayscale, None, i, j, self.blockDimension)\n self.featuresContainer.addBlock(imageBlock.computeBlock())\n\n def sort(self):\n \"\"\"\n To sort the container's elements\n :return: None\n \"\"\"\n self.featuresContainer.sortFeatures()\n\n def analyze(self):\n \"\"\"\n To analyze pairs of image blocks\n :return: None\n \"\"\"\n print (\"Step 3 of 4:Pairing image blocks\")\n z = 0\n time.sleep(0.1)\n featureContainerLength = self.featuresContainer.getLength()\n for i in tqdm(list(range(featureContainerLength))):\n for j in range(i + 1, featureContainerLength):\n result = self.isValid(i, j)\n if result[0]:\n self.addDict(self.featuresContainer.container[i][0], self.featuresContainer.container[j][0],\n result[1])\n z += 1\n else:\n break\n\n def isValid(self, firstBlock, secondBlock):\n \"\"\"\n To check the validity of the image block pairs and each of the characteristic features,\n also compute its offset, magnitude, and absolut value.\n :param firstBlock: the first block\n :param secondBlock: the second block\n :return: is the pair of i and j valid?\n \"\"\"\n\n if abs(firstBlock - secondBlock) < self.Nn:\n iFeature = self.featuresContainer.container[firstBlock][1]\n jFeature = self.featuresContainer.container[secondBlock][1]\n\n # check the validity of characteristic features according to the second paper\n if abs(iFeature[0] - jFeature[0]) < self.P[0]:\n if abs(iFeature[1] - jFeature[1]) < self.P[1]:\n if abs(iFeature[2] - jFeature[2]) < self.P[2]:\n if abs(iFeature[3] - jFeature[3]) < self.P[3]:\n if abs(iFeature[4] - jFeature[4]) < self.P[4]:\n if abs(iFeature[5] - jFeature[5]) < self.P[5]:\n if abs(iFeature[6] - jFeature[6]) < self.P[6]:\n if abs(iFeature[0] - jFeature[0]) + abs(iFeature[1] - jFeature[1]) + abs(\n iFeature[2] - jFeature[2]) < self.t1:\n if abs(iFeature[3] - jFeature[3]) + abs(iFeature[4] - jFeature[4]) + abs(\n iFeature[5] - jFeature[5]) + abs(\n iFeature[6] - jFeature[6]) < self.t2:\n\n # compute the pair's offset\n iCoordinate = self.featuresContainer.container[firstBlock][0]\n jCoordinate = self.featuresContainer.container[secondBlock][0]\n\n # Non Absolute Robust Detection Method\n offset = (\n iCoordinate[0] - jCoordinate[0], iCoordinate[1] - jCoordinate[1])\n\n # compute the pair's magnitude\n magnitude = np.sqrt(pow(offset[0], 2) + pow(offset[1], 2))\n if magnitude >= self.Nd:\n return 1, offset\n return 0,\n\n def addDict(self, firstCoordinate, secondCoordinate, pairOffset):\n \"\"\"\n Add a pair of coordinate and its offset to the dictionary\n \"\"\"\n if pairOffset in self.offsetDictionary:\n self.offsetDictionary[pairOffset].append(firstCoordinate)\n self.offsetDictionary[pairOffset].append(secondCoordinate)\n else:\n self.offsetDictionary[pairOffset] = [firstCoordinate, secondCoordinate]\n\n def reconstruct(self):\n \"\"\"\n Reconstruct the image according to the fraud detectionr esult\n \"\"\"\n print (\"Step 4 of 4: Image reconstruction\")\n\n # create an array as the canvas of the final image\n groundtruthImage = np.zeros((self.imageHeight, self.imageWidth))\n linedImage = np.array(self.imageData.convert('RGB'))\n\n for key in sorted(self.offsetDictionary, key=lambda key: builtins.len(self.offsetDictionary[key]),\n reverse=True):\n if self.offsetDictionary[key].__len__() < self.Nf * 2:\n break\n print((key, self.offsetDictionary[key].__len__()))\n for i in range(self.offsetDictionary[key].__len__()):\n # The original image (grayscale)\n for j in range(self.offsetDictionary[key][i][1],\n self.offsetDictionary[key][i][1] + self.blockDimension):\n for k in range(self.offsetDictionary[key][i][0],\n self.offsetDictionary[key][i][0] + self.blockDimension):\n groundtruthImage[j][k] = 255\n\n # creating a line edge from the original image (for the visual purpose)\n for xCoordinate in range(2, self.imageHeight - 2):\n for yCordinate in range(2, self.imageWidth - 2):\n if groundtruthImage[xCoordinate, yCordinate] == 255 and \\\n (groundtruthImage[xCoordinate + 1, yCordinate] == 0 or groundtruthImage[\n xCoordinate - 1, yCordinate] == 0 or\n groundtruthImage[xCoordinate, yCordinate + 1] == 0 or groundtruthImage[\n xCoordinate, yCordinate - 1] == 0 or\n groundtruthImage[xCoordinate - 1, yCordinate + 1] == 0 or groundtruthImage[\n xCoordinate + 1, yCordinate + 1] == 0 or\n groundtruthImage[xCoordinate - 1, yCordinate - 1] == 0 or groundtruthImage[\n xCoordinate + 1, yCordinate - 1] == 0):\n\n # creating the edge line, respectively left-upper, right-upper, left-down, right-down\n if groundtruthImage[xCoordinate - 1, yCordinate] == 0 and \\\n groundtruthImage[xCoordinate, yCordinate - 1] == 0 and \\\n groundtruthImage[xCoordinate - 1, yCordinate - 1] == 0:\n linedImage[xCoordinate - 2:xCoordinate, yCordinate, 1] = 255\n linedImage[xCoordinate, yCordinate - 2:yCordinate, 1] = 255\n linedImage[xCoordinate - 2:xCoordinate, yCordinate - 2:yCordinate, 1] = 255\n elif groundtruthImage[xCoordinate + 1, yCordinate] == 0 and \\\n groundtruthImage[xCoordinate, yCordinate - 1] == 0 and \\\n groundtruthImage[xCoordinate + 1, yCordinate - 1] == 0:\n linedImage[xCoordinate + 1:xCoordinate + 3, yCordinate, 1] = 255\n linedImage[xCoordinate, yCordinate - 2:yCordinate, 1] = 255\n linedImage[xCoordinate + 1:xCoordinate + 3, yCordinate - 2:yCordinate, 1] = 255\n elif groundtruthImage[xCoordinate - 1, yCordinate] == 0 and \\\n groundtruthImage[xCoordinate, yCordinate + 1] == 0 and \\\n groundtruthImage[xCoordinate - 1, yCordinate + 1] == 0:\n linedImage[xCoordinate - 2:xCoordinate, yCordinate, 1] = 255\n linedImage[xCoordinate, yCordinate + 1:yCordinate + 3, 1] = 255\n linedImage[xCoordinate - 2:xCoordinate, yCordinate + 1:yCordinate + 3, 1] = 255\n elif groundtruthImage[xCoordinate + 1, yCordinate] == 0 and \\\n groundtruthImage[xCoordinate, yCordinate + 1] == 0 and \\\n groundtruthImage[xCoordinate + 1, yCordinate + 1] == 0:\n linedImage[xCoordinate + 1:xCoordinate + 3, yCordinate, 1] = 255\n linedImage[xCoordinate, yCordinate + 1:yCordinate + 3, 1] = 255\n linedImage[xCoordinate + 1:xCoordinate + 3, yCordinate + 1:yCordinate + 3, 1] = 255\n\n # creating the straigh line, respectively upper, down, left, right line\n elif groundtruthImage[xCoordinate, yCordinate + 1] == 0:\n linedImage[xCoordinate, yCordinate + 1:yCordinate + 3, 1] = 255\n elif groundtruthImage[xCoordinate, yCordinate - 1] == 0:\n linedImage[xCoordinate, yCordinate - 2:yCordinate, 1] = 255\n elif groundtruthImage[xCoordinate - 1, yCordinate] == 0:\n linedImage[xCoordinate - 2:xCoordinate, yCordinate, 1] = 255\n elif groundtruthImage[xCoordinate + 1, yCordinate] == 0:\n linedImage[xCoordinate + 1:xCoordinate + 3, yCordinate, 1] = 255\n\n timeStamp = time.strftime(\"%Y%m%d_%H%M%S\")\n # scipy.misc.imsave(self.imageOutputDirectory + timeStamp + \"_\" + self.imagePath, groundtruthImage)\n # scipy.misc.imsave(self.imageOutputDirectory + timeStamp + \"_lined_\" + self.imagePath, linedImage)\n print(\"Writing image to specifed file...\")\n imageio.imwrite(self.imageOutputDirectory + timeStamp + \"_\" + self.imagePath, groundtruthImage)\n print(f'saved: {self.imageOutputDirectory + timeStamp + \"_\" + self.imagePath}')\n imageio.imwrite(self.imageOutputDirectory + timeStamp + \"_lined_\" + self.imagePath, linedImage)\n print(f'saved: {self.imageOutputDirectory + timeStamp + \"_lined_\" + self.imagePath}')\n\n return self.imageOutputDirectory + timeStamp + \"_lined_\" + self.imagePath\n"
]
| [
[
"numpy.zeros"
]
]
|
ntoxeg/ignite | [
"11928a3b02eacaed1f312c225434195adf9e5082"
]
| [
"examples/gan/dcgan.py"
]
| [
"from __future__ import print_function\n\nimport argparse\nimport os\nimport random\nimport warnings\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.utils.data as data\n\nfrom ignite.contrib.handlers import ProgressBar\nfrom ignite.engine import Engine, Events\nfrom ignite.handlers import ModelCheckpoint, Timer\nfrom ignite.metrics import RunningAverage\n\ntry:\n import torchvision.datasets as dset\n import torchvision.transforms as transforms\n import torchvision.utils as vutils\n\nexcept ImportError:\n raise ImportError(\"Please install torchvision to run this example, for example \"\n \"via conda by running 'conda install -c pytorch torchvision'. \")\n\n\nPRINT_FREQ = 100\nFAKE_IMG_FNAME = 'fake_sample_epoch_{:04d}.png'\nREAL_IMG_FNAME = 'real_sample_epoch_{:04d}.png'\nLOGS_FNAME = 'logs.tsv'\nPLOT_FNAME = 'plot.svg'\nSAMPLES_FNAME = 'samples.svg'\nCKPT_PREFIX = 'networks'\n\n\nclass Net(nn.Module):\n \"\"\" A base class for both generator and the discriminator.\n Provides a common weight initialization scheme.\n\n \"\"\"\n\n def weights_init(self):\n for m in self.modules():\n classname = m.__class__.__name__\n\n if 'Conv' in classname:\n m.weight.data.normal_(0.0, 0.02)\n\n elif 'BatchNorm' in classname:\n m.weight.data.normal_(1.0, 0.02)\n m.bias.data.fill_(0)\n\n def forward(self, x):\n return x\n\n\nclass Generator(Net):\n \"\"\" Generator network.\n\n Args:\n nf (int): Number of filters in the second-to-last deconv layer\n \"\"\"\n\n def __init__(self, z_dim, nf):\n super(Generator, self).__init__()\n\n self.net = nn.Sequential(\n\n # input is Z, going into a convolution\n nn.ConvTranspose2d(in_channels=z_dim, out_channels=nf * 8, kernel_size=4, stride=1, padding=0, bias=False),\n nn.BatchNorm2d(nf * 8),\n nn.ReLU(inplace=True),\n\n # state size. (nf*8) x 4 x 4\n nn.ConvTranspose2d(in_channels=nf * 8, out_channels=nf * 4, kernel_size=4, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(nf * 4),\n nn.ReLU(inplace=True),\n\n # state size. (nf*4) x 8 x 8\n nn.ConvTranspose2d(in_channels=nf * 4, out_channels=nf * 2, kernel_size=4, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(nf * 2),\n nn.ReLU(inplace=True),\n\n # state size. (nf*2) x 16 x 16\n nn.ConvTranspose2d(in_channels=nf * 2, out_channels=nf, kernel_size=4, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(nf),\n nn.ReLU(inplace=True),\n\n # state size. (nf) x 32 x 32\n nn.ConvTranspose2d(in_channels=nf, out_channels=3, kernel_size=4, stride=2, padding=1, bias=False),\n nn.Tanh()\n\n # state size. (nc) x 64 x 64\n )\n\n self.weights_init()\n\n def forward(self, x):\n return self.net(x)\n\n\nclass Discriminator(Net):\n \"\"\" Discriminator network.\n\n Args:\n nf (int): Number of filters in the first conv layer.\n \"\"\"\n\n def __init__(self, nf):\n super(Discriminator, self).__init__()\n\n self.net = nn.Sequential(\n\n # input is (nc) x 64 x 64\n nn.Conv2d(in_channels=3, out_channels=nf, kernel_size=4, stride=2, padding=1, bias=False),\n nn.LeakyReLU(0.2, inplace=True),\n\n # state size. (nf) x 32 x 32\n nn.Conv2d(in_channels=nf, out_channels=nf * 2, kernel_size=4, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(nf * 2),\n nn.LeakyReLU(0.2, inplace=True),\n\n # state size. (nf*2) x 16 x 16\n nn.Conv2d(in_channels=nf * 2, out_channels=nf * 4, kernel_size=4, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(nf * 4),\n nn.LeakyReLU(0.2, inplace=True),\n\n # state size. (nf*4) x 8 x 8\n nn.Conv2d(in_channels=nf * 4, out_channels=nf * 8, kernel_size=4, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(nf * 8),\n nn.LeakyReLU(0.2, inplace=True),\n\n # state size. (nf*8) x 4 x 4\n nn.Conv2d(in_channels=nf * 8, out_channels=1, kernel_size=4, stride=1, padding=0, bias=False),\n nn.Sigmoid()\n )\n\n self.weights_init()\n\n def forward(self, x):\n output = self.net(x)\n return output.view(-1, 1).squeeze(1)\n\n\ndef check_manual_seed(seed):\n \"\"\" If manual seed is not specified, choose a random one and communicate it to the user.\n\n \"\"\"\n\n seed = seed or random.randint(1, 10000)\n random.seed(seed)\n torch.manual_seed(seed)\n\n print('Using manual seed: {seed}'.format(seed=seed))\n\n\ndef check_dataset(dataset, dataroot):\n \"\"\"\n\n Args:\n dataset (str): Name of the dataset to use. See CLI help for details\n dataroot (str): root directory where the dataset will be stored.\n\n Returns:\n dataset (data.Dataset): torchvision Dataset object\n\n \"\"\"\n to_rgb = transforms.Lambda(lambda img: img.convert('RGB'))\n resize = transforms.Resize(64)\n crop = transforms.CenterCrop(64)\n to_tensor = transforms.ToTensor()\n normalize = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n\n if dataset in {'imagenet', 'folder', 'lfw'}:\n dataset = dset.ImageFolder(root=dataroot, transform=transforms.Compose([resize,\n crop,\n to_tensor,\n normalize]))\n\n elif dataset == 'lsun':\n dataset = dset.LSUN(root=dataroot, classes=['bedroom_train'], transform=transforms.Compose([resize,\n crop,\n to_tensor,\n normalize]))\n\n elif dataset == 'cifar10':\n dataset = dset.CIFAR10(root=dataroot, download=True, transform=transforms.Compose([resize,\n to_tensor,\n normalize]))\n\n elif dataset == 'mnist':\n dataset = dset.MNIST(root=dataroot, download=True, transform=transforms.Compose([to_rgb,\n resize,\n to_tensor,\n normalize]))\n\n elif dataset == 'fake':\n dataset = dset.FakeData(size=256, image_size=(3, 64, 64), transform=to_tensor)\n\n else:\n raise RuntimeError(\"Invalid dataset name: {}\".format(dataset))\n\n return dataset\n\n\ndef main(dataset, dataroot,\n z_dim, g_filters, d_filters,\n batch_size, epochs,\n learning_rate, beta_1,\n saved_G, saved_D,\n seed,\n n_workers, device,\n alpha, output_dir):\n\n # seed\n check_manual_seed(seed)\n\n # netowrks\n netG = Generator(z_dim, g_filters).to(device)\n netD = Discriminator(d_filters).to(device)\n\n # criterion\n bce = nn.BCELoss()\n\n # optimizers\n optimizerG = optim.Adam(netG.parameters(), lr=learning_rate, betas=(beta_1, 0.999))\n optimizerD = optim.Adam(netD.parameters(), lr=learning_rate, betas=(beta_1, 0.999))\n\n # data\n dataset = check_dataset(dataset, dataroot)\n loader = data.DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=n_workers, drop_last=True)\n\n # load pre-trained models\n if saved_G:\n netG.load_state_dict(torch.load(saved_G))\n\n if saved_D:\n netD.load_state_dict(torch.load(saved_D))\n\n # misc\n real_labels = torch.ones(batch_size, device=device)\n fake_labels = torch.zeros(batch_size, device=device)\n fixed_noise = torch.randn(batch_size, z_dim, 1, 1, device=device)\n\n def get_noise():\n return torch.randn(batch_size, z_dim, 1, 1, device=device)\n\n # The main function, processing a batch of examples\n def step(engine, batch):\n\n # unpack the batch. It comes from a dataset, so we have <images, labels> pairs. Discard labels.\n real, _ = batch\n real = real.to(device)\n\n # -----------------------------------------------------------\n # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))\n netD.zero_grad()\n\n # train with real\n output = netD(real)\n errD_real = bce(output, real_labels)\n D_x = output.mean().item()\n\n errD_real.backward()\n\n # get fake image from generator\n noise = get_noise()\n fake = netG(noise)\n\n # train with fake\n output = netD(fake.detach())\n errD_fake = bce(output, fake_labels)\n D_G_z1 = output.mean().item()\n\n errD_fake.backward()\n\n # gradient update\n errD = errD_real + errD_fake\n optimizerD.step()\n\n # -----------------------------------------------------------\n # (2) Update G network: maximize log(D(G(z)))\n netG.zero_grad()\n\n # Update generator. We want to make a step that will make it more likely that discriminator outputs \"real\"\n output = netD(fake)\n errG = bce(output, real_labels)\n D_G_z2 = output.mean().item()\n\n errG.backward()\n\n # gradient update\n optimizerG.step()\n\n return {\n 'errD': errD.item(),\n 'errG': errG.item(),\n 'D_x': D_x,\n 'D_G_z1': D_G_z1,\n 'D_G_z2': D_G_z2\n }\n\n # ignite objects\n trainer = Engine(step)\n checkpoint_handler = ModelCheckpoint(output_dir, CKPT_PREFIX, save_interval=1, n_saved=10, require_empty=False)\n timer = Timer(average=True)\n\n # attach running average metrics\n monitoring_metrics = ['errD', 'errG', 'D_x', 'D_G_z1', 'D_G_z2']\n RunningAverage(alpha=alpha, output_transform=lambda x: x['errD']).attach(trainer, 'errD')\n RunningAverage(alpha=alpha, output_transform=lambda x: x['errG']).attach(trainer, 'errG')\n RunningAverage(alpha=alpha, output_transform=lambda x: x['D_x']).attach(trainer, 'D_x')\n RunningAverage(alpha=alpha, output_transform=lambda x: x['D_G_z1']).attach(trainer, 'D_G_z1')\n RunningAverage(alpha=alpha, output_transform=lambda x: x['D_G_z2']).attach(trainer, 'D_G_z2')\n\n # attach progress bar\n pbar = ProgressBar()\n pbar.attach(trainer, metric_names=monitoring_metrics)\n\n @trainer.on(Events.ITERATION_COMPLETED)\n def print_logs(engine):\n if (engine.state.iteration - 1) % PRINT_FREQ == 0:\n fname = os.path.join(output_dir, LOGS_FNAME)\n columns = engine.state.metrics.keys()\n values = [str(round(value, 5)) for value in engine.state.metrics.values()]\n\n with open(fname, 'a') as f:\n if f.tell() == 0:\n print('\\t'.join(columns), file=f)\n print('\\t'.join(values), file=f)\n\n message = '[{epoch}/{max_epoch}][{i}/{max_i}]'.format(epoch=engine.state.epoch,\n max_epoch=epochs,\n i=(engine.state.iteration % len(loader)),\n max_i=len(loader))\n for name, value in zip(columns, values):\n message += ' | {name}: {value}'.format(name=name, value=value)\n\n pbar.log_message(message)\n\n # adding handlers using `trainer.on` decorator API\n @trainer.on(Events.EPOCH_COMPLETED)\n def save_fake_example(engine):\n fake = netG(fixed_noise)\n path = os.path.join(output_dir, FAKE_IMG_FNAME.format(engine.state.epoch))\n vutils.save_image(fake.detach(), path, normalize=True)\n\n # adding handlers using `trainer.on` decorator API\n @trainer.on(Events.EPOCH_COMPLETED)\n def save_real_example(engine):\n img, y = engine.state.batch\n path = os.path.join(output_dir, REAL_IMG_FNAME.format(engine.state.epoch))\n vutils.save_image(img, path, normalize=True)\n\n # adding handlers using `trainer.add_event_handler` method API\n trainer.add_event_handler(event_name=Events.EPOCH_COMPLETED, handler=checkpoint_handler,\n to_save={\n 'netG': netG,\n 'netD': netD\n })\n\n # automatically adding handlers via a special `attach` method of `Timer` handler\n timer.attach(trainer, start=Events.EPOCH_STARTED, resume=Events.ITERATION_STARTED,\n pause=Events.ITERATION_COMPLETED, step=Events.ITERATION_COMPLETED)\n\n # adding handlers using `trainer.on` decorator API\n @trainer.on(Events.EPOCH_COMPLETED)\n def print_times(engine):\n pbar.log_message('Epoch {} done. Time per batch: {:.3f}[s]'.format(engine.state.epoch, timer.value()))\n timer.reset()\n\n # adding handlers using `trainer.on` decorator API\n @trainer.on(Events.EPOCH_COMPLETED)\n def create_plots(engine):\n try:\n import matplotlib as mpl\n mpl.use('agg')\n\n import numpy as np\n import pandas as pd\n import matplotlib.pyplot as plt\n\n except ImportError:\n warnings.warn('Loss plots will not be generated -- pandas or matplotlib not found')\n\n else:\n df = pd.read_csv(os.path.join(output_dir, LOGS_FNAME), delimiter='\\t')\n x = np.arange(1, engine.state.iteration + 1, PRINT_FREQ)\n _ = df.plot(x=x, subplots=True, figsize=(20, 20))\n _ = plt.xlabel('Iteration number')\n fig = plt.gcf()\n path = os.path.join(output_dir, PLOT_FNAME)\n\n fig.savefig(path)\n\n # adding handlers using `trainer.on` decorator API\n @trainer.on(Events.EXCEPTION_RAISED)\n def handle_exception(engine, e):\n if isinstance(e, KeyboardInterrupt) and (engine.state.iteration > 1):\n engine.terminate()\n warnings.warn('KeyboardInterrupt caught. Exiting gracefully.')\n\n create_plots(engine)\n checkpoint_handler(engine, {\n 'netG_exception': netG,\n 'netD_exception': netD\n })\n\n else:\n raise e\n\n # Setup is done. Now let's run the training\n trainer.run(loader, epochs)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--dataset',\n required=True, choices={'cifar10', 'lsun', 'imagenet', 'folder', 'lfw', 'fake', 'mnist'},\n help='Type of the dataset to be used.')\n\n parser.add_argument('--dataroot',\n required=True,\n help='path to dataset')\n\n parser.add_argument('--workers',\n type=int, default=2,\n help='number of data loading workers')\n\n parser.add_argument('--batch-size',\n type=int, default=64,\n help='input batch size')\n\n parser.add_argument('--z-dim',\n type=int, default=100,\n help='size of the latent z vector')\n\n parser.add_argument('--g-filters',\n type=int, default=64,\n help='Number of filters in the second-to-last generator deconv layer')\n\n parser.add_argument('--d-filters',\n type=int, default=64,\n help='Number of filters in first discriminator conv layer')\n\n parser.add_argument('--epochs',\n type=int, default=25,\n help='number of epochs to train for')\n\n parser.add_argument('--lr',\n type=float, default=0.0002,\n help='learning rate')\n\n parser.add_argument('--beta-1',\n type=float, default=0.5,\n help='beta_1 for adam')\n\n parser.add_argument('--no-cuda',\n action='store_true',\n help='disables cuda')\n\n parser.add_argument('--saved-G',\n default='',\n help=\"path to pickled generator (to continue training)\")\n\n parser.add_argument('--saved-D',\n default='',\n help=\"path to pickled discriminator (to continue training)\")\n\n parser.add_argument('--output-dir',\n default='.',\n help='directory to output images and model checkpoints')\n\n parser.add_argument('--seed',\n type=int,\n help='manual seed')\n\n parser.add_argument('--alpha',\n type=float, default=0.98,\n help='smoothing constant for exponential moving averages')\n\n args = parser.parse_args()\n dev = 'cpu' if (not torch.cuda.is_available() or args.no_cuda) else 'cuda:0'\n\n try:\n os.makedirs(args.output_dir)\n except FileExistsError:\n if (not os.path.isdir(args.output_dir)) or (len(os.listdir(args.output_dir)) > 0):\n raise FileExistsError(\"Please provide a path to a non-existing or empty directory.\")\n\n main(dataset=args.dataset, dataroot=args.dataroot,\n z_dim=args.z_dim, g_filters=args.g_filters, d_filters=args.d_filters,\n batch_size=args.batch_size, epochs=args.epochs,\n learning_rate=args.lr, beta_1=args.beta_1,\n saved_D=args.saved_D, saved_G=args.saved_G,\n seed=args.seed,\n device=dev, n_workers=args.workers,\n alpha=args.alpha, output_dir=args.output_dir)\n"
]
| [
[
"torch.nn.BatchNorm2d",
"torch.nn.LeakyReLU",
"torch.ones",
"torch.cuda.is_available",
"matplotlib.pyplot.gcf",
"torch.load",
"torch.nn.ConvTranspose2d",
"torch.manual_seed",
"numpy.arange",
"torch.utils.data.DataLoader",
"torch.nn.BCELoss",
"torch.zeros",
"matplotlib.use",
"torch.nn.Tanh",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.nn.Sigmoid",
"matplotlib.pyplot.xlabel",
"torch.randn"
]
]
|
evgenyneu/tarpan | [
"34a5dd8d98b09341e28946ef6aa03da03e62cf1c"
]
| [
"tarpan/shared/histogram.py"
]
| [
"\"\"\"Make histograms of posterior parameter distributions\"\"\"\n\nfrom dataclasses import dataclass\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport seaborn as sns\nfrom tarpan.shared.info_path import InfoPath, get_info_path\nfrom tarpan.shared.summary import SummaryParams, sample_summary\nfrom tarpan.shared.param_names import filter_param_names\n\n\n@dataclass\nclass HistogramParams:\n title: str = None # Plot's title\n max_plot_pages: int = 4 # Maximum number of plots to generate.\n num_plot_rows: int = 4 # Number of rows (subplots) in a plot.\n ncols: int = 2 # Number of columns in the plot.\n\n hist_color = \"#00a6ff\" # Fill color for histogram bars\n hist_edge_color = \"#FFFFFF\" # Edge color for the histogram bars\n\n # Colors and line styles for KDE lines of the error bars (HPDIs)\n # Sorted from largerst smallest HPDI values\n kde_colors = ['#FF9922', '#6666FF', '#44FF55']\n kde_line_styles = ['dotted', 'solid', '-.']\n\n\ndef save_histogram(samples, param_names=None,\n info_path=InfoPath(),\n histogram_params=HistogramParams(),\n summary_params=SummaryParams()):\n \"\"\"\n Make histograms for the parameters from posterior destribution.\n\n Parameters\n -----------\n\n samples : Panda's DataFrame\n\n Each column contains samples from posterior distribution.\n\n param_names : list of str\n\n Names of the parameters for plotting. If None, all will be plotted.\n \"\"\"\n\n info_path.set_codefile()\n df_summary, table = sample_summary(df=samples)\n\n save_histogram_from_summary(samples, df_summary,\n param_names=param_names,\n info_path=info_path,\n histogram_params=histogram_params,\n summary_params=summary_params)\n\n\ndef save_histogram_from_summary(samples, summary, param_names=None,\n info_path=InfoPath(),\n histogram_params=HistogramParams(),\n summary_params=SummaryParams()):\n \"\"\"\n Make histograms for the parameters from posterior destribution.\n\n Parameters\n -----------\n\n samples : Panda's DataFrame\n\n Each column contains samples from posterior distribution.\n\n summary : Panda's DataFrame\n\n Summary information about each column.\n\n param_names : list of str\n\n Names of the parameters for plotting. If None, all will be plotted.\n \"\"\"\n\n info_path = InfoPath(**info_path.__dict__)\n\n figures_and_axes = make_histograms(\n samples, summary, param_names=param_names,\n params=histogram_params,\n summary_params=summary_params)\n\n base_name = info_path.base_name or \"histogram\"\n info_path.extension = info_path.extension or 'pdf'\n\n for i, figure_and_axis in enumerate(figures_and_axes):\n info_path.base_name = f'{base_name}_{i + 1:02d}'\n plot_path = get_info_path(info_path)\n fig = figure_and_axis[0]\n fig.savefig(plot_path, dpi=info_path.dpi)\n plt.close(fig)\n\n\ndef make_histogram_one_page(i_start, samples, summary, param_names,\n params: HistogramParams,\n summary_params=SummaryParams()):\n \"\"\"\n Make a single file with histograms for the parameters\n from posterior destribution.\n \"\"\"\n\n nrows = math.ceil((len(param_names) - i_start) / params.ncols)\n\n if nrows > params.num_plot_rows:\n nrows = params.num_plot_rows\n\n ncols = params.ncols\n fig_height = 4 * nrows\n fig_width = 12\n\n # Special case: if there is just one parameter show a plot with one column\n if len(param_names) == 1:\n ncols = 1\n fig_width /= 2\n\n fig, ax = plt.subplots(\n nrows=nrows,\n ncols=ncols, figsize=(fig_width, fig_height),\n squeeze=False)\n\n axes = ax.flatten()\n\n for i_axis, ax in enumerate(axes):\n i_param = i_start + i_axis\n\n if i_param >= len(param_names):\n break\n\n parameter = param_names[i_param]\n param_samples = samples[parameter]\n data = summary.loc[parameter]\n\n # Exclude extreme outliers from the samples\n # to avoid the blow-up of the x-axis range\n inner_range = np.percentile(param_samples, [0.5, 99.5])\n\n samples_for_kde = param_samples[(param_samples > inner_range[0])\n & (param_samples < inner_range[1])]\n\n sns.distplot(samples_for_kde, kde=False, norm_hist=True, ax=ax,\n hist_kws={\n \"color\": params.hist_color,\n \"zorder\": 1,\n \"edgecolor\": params.hist_edge_color,\n \"linewidth\": 1,\n \"alpha\": 1})\n\n # Show KDEs for the error bars (HPDIs)\n # -----------\n\n hpdis = sorted(summary_params.hpdi_percent(), reverse=True)\n\n for i, hpdi in enumerate(hpdis):\n start = f'{hpdi}CI-'\n end = f'{hpdi}CI+'\n\n # KDE plot\n sns.kdeplot(samples_for_kde, shade=False,\n clip=[data[start], data[end]],\n label=f'{hpdi}% HPDI', ax=ax, legend=None,\n color=params.kde_colors[i],\n linestyle=params.kde_line_styles[i],\n linewidth=2)\n\n if i == len(hpdis) - 1:\n # Show shade under KDE for the last error bar\n sns.kdeplot(samples_for_kde, shade=True,\n clip=[data[start], data[end]],\n color=\"#000000\",\n label='_nolegend_', alpha=0.2,\n zorder=10,\n ax=ax, legend=None,\n linewidth=2)\n\n ax.axvline(x=data['Mean'], label='Mean', linewidth=1.5,\n linestyle='dashed', color='#33AA66')\n\n ax.axvline(x=data['Mode'], label='Mode', linewidth=1.5,\n color='#FF66AA')\n\n ax.set_xlabel(parameter)\n\n # Do not draw the axes for non-existing plots\n for ax in axes[len(param_names):]:\n ax.axis('off')\n\n handles, labels = axes[0].get_legend_handles_labels()\n fig.legend(handles, labels, loc='upper center', mode='expand',\n ncol=len(labels))\n\n fig.tight_layout(rect=[0, 0, 1, 0.95])\n\n return (fig, ax)\n\n\ndef make_histograms(samples, summary, param_names=None,\n params=HistogramParams(),\n summary_params=SummaryParams()):\n \"\"\"\n Make multiple files with\n histograms for the parameters from posterior destribution.\n\n Parameters\n -----------\n\n samples : Panda's DataFrame\n\n Each column contains samples from posterior distribution.\n\n summary : Panda's DataFrame\n\n Summary information about each column.\n\n param_names : list of str\n\n Names of the parameters for plotting. If None, all will be plotted.\n \"\"\"\n param_names = filter_param_names(samples.columns, param_names)\n\n # Total number of plots\n n_plots = math.ceil(math.ceil(len(param_names) / params.ncols) /\n params.num_plot_rows)\n\n if n_plots > params.max_plot_pages:\n print((\n f'Showing only first {params.max_plot_pages} '\n f'pages out of {n_plots} of histogram.'\n 'Consider specifying \"param_names\".'))\n\n n_plots = params.max_plot_pages\n\n if n_plots < 1:\n n_plots = 1\n\n figures_and_axes = []\n\n # Make multiple traceplots\n for i_plot in range(n_plots):\n fig, ax = make_histogram_one_page(\n i_start=i_plot * params.num_plot_rows * params.ncols,\n samples=samples,\n summary=summary,\n param_names=param_names,\n params=params,\n summary_params=summary_params)\n\n figures_and_axes.append([fig, ax])\n\n return figures_and_axes\n"
]
| [
[
"numpy.percentile",
"matplotlib.pyplot.close",
"matplotlib.pyplot.subplots"
]
]
|
hplgit/fem-book | [
"c23099715dc3cb72e7f4d37625e6f9614ee5fc4e"
]
| [
"doc/.src/book/exer/tanh_sines.py"
]
| [
"import sys, os\nsys.path.insert(0, os.path.join(os.pardir, 'src'))\nimport sympy as sym\nfrom approx1D import least_squares_orth, comparison_plot\nimport matplotlib.pyplot as plt\n\nx = sym.Symbol('x')\n\n# Naive approach: (not utilizing the fact that i+1 computations can\n# make use of i computations)\ndef naive(f, s, Omega, N=10):\n psi = []\n for i in range(N+1):\n psi.append(sym.sin((2*i+1)*x))\n u, c = least_squares_orth(f, psi, Omega, symbolic=False)\n comparison_plot(f, u, Omega, 'tmp_sin%02dx' % i,\n legend_loc='upper left', show=True)\n\n# Efficient approach: compute just the matrix diagonal\ndef efficient(f, s, Omega, N=10):\n u = 0\n for i in range(N+1):\n psi = [sym.sin((2*i+1)*x)]\n next_term, c = least_squares_orth(f, psi, Omega, False)\n u = u + next_term\n comparison_plot(f, u, Omega, 'tmp_sin%02dx' % i,\n legend_loc='upper left', show=False,\n plot_title='s=%g, i=%d' % (s, i))\n\nif __name__ == '__main__':\n s = 20 # steepness\n f = sym.tanh(s*(x-sym.pi))\n from math import pi\n Omega = [0, 2*pi] # sym.pi did not work here\n efficient(f, s, Omega, N=10)\n # Make movie\n # avconv/ffmpeg skips frames, use convert instead (few files)\n cmd = 'convert -delay 200 tmp_sin*.png tanh_sines_approx.gif'\n os.system(cmd)\n # Make static plots, 3 figures on 2 lines\n for ext in 'pdf', 'png':\n cmd = 'doconce combine_images %s -3 ' % ext\n cmd += 'tmp_sin00x tmp_sin01x tmp_sin02x tmp_sin04x '\n cmd += 'tmp_sin07x tmp_sin10x tanh_sines_approx'\n os.system(cmd)\n plt.show()\n"
]
| [
[
"matplotlib.pyplot.show"
]
]
|
SunshineJunFu/360Project | [
"93fe3517de5937466dde602741514fa6ca0898d7"
]
| [
"fov_mask.py"
]
| [
"\r\nimport numpy as np\r\nimport cv2\r\n\r\nimport torch\r\nfrom cupy.cuda import function\r\nfrom pynvrtc.compiler import Program\r\nfrom collections import namedtuple\r\n\r\nkernel = \"\"\"\r\n\r\nextern \"C\"\r\n\r\n__global__ void img_fov(float* fov_angle, float* vector_x, float* vector_y, float* pointCenter, float* img_size, float* img)\r\n{\r\n\t//1. 计算线程ID\r\n int x = blockDim.x * blockIdx.x + threadIdx.x;\r\n int y = blockDim.y * blockIdx.y + threadIdx.y;\r\n\r\n float face_size_x = tan(fov_angle[0]/2);\r\n float face_size_y = tan(fov_angle[1]/2);\r\n\r\n\t//2. 输入输出的图片尺寸\r\n float sizeoutx = img_size[0];\r\n float sizeouty = img_size[1];\r\n\r\n\tif(x<sizeoutx && y<sizeouty)\r\n\t{\r\n\r\n \t//1. 求ERP中某点(x,y)的经纬度\r\n float lonERP = x * 2 * 3.1415926 / sizeoutx - 3.1415926;\r\n float latERP = 3.1415926/2 - y * 3.1415926 / sizeouty;\r\n\r\n\t\t//2. 计算笛卡尔坐标系的坐标\r\n float pointERP[3];\r\n pointERP[0] = cos(latERP) * cos(lonERP);\r\n\t pointERP[1] = cos(latERP) * sin(lonERP);\r\n pointERP[2] = sin(latERP);\r\n\r\n\t\t//3. 求该点与球心的直线 与 视点与球心的直线的夹角 cos(theta)\r\n float angle = pointERP[0] * pointCenter[0] + pointERP[1] * pointCenter[1] + pointERP[2] * pointCenter[2];\r\n\r\n\t\t//4. 超过半个平面\r\n if (angle < 0)\r\n return;\r\n\r\n\t\t//5. 求该店在且片面上的坐标\r\n pointERP[0] /= angle;\r\n pointERP[1] /= angle;\r\n pointERP[2] /= angle;\r\n\r\n\t\t//6. 视点与该点的连线\r\n pointERP[0] -= pointCenter[0];\r\n pointERP[1] -= pointCenter[1];\r\n pointERP[2] -= pointCenter[2];\r\n\r\n\t\t//7. 求在切平面下x,y轴的投影\r\n\r\n float plane_x = pointERP[0] * vector_x[0] + pointERP[1] * vector_x[1] + pointERP[2] * vector_x[2];\r\n float plane_y = pointERP[0] * vector_y[0] + pointERP[1] * vector_y[1] + pointERP[2] * vector_y[2];\r\n\r\n\t\t//8.判断是否在切平面内\r\n if (plane_x <= face_size_x && plane_x >= -face_size_x)\r\n plane_x += face_size_x;\r\n else\r\n plane_x = -1;\r\n\r\n if (plane_y <= face_size_y && plane_y >= -face_size_y)\r\n plane_y += face_size_y;\r\n else\r\n plane_y = -1;\r\n\r\n if(plane_x < 0 || plane_y <0)\r\n return;\r\n else\r\n {\r\n img[int((y* sizeoutx + x) +0)] = 255.0; \r\n }\r\n\t}\r\n\r\n}\r\n\"\"\"\r\n\r\nprogram = Program(kernel, 'img_fov.cu')\r\nptx = program.compile()\r\n\r\nm = function.Module()\r\n\r\nm.load(bytes(ptx.encode()))\r\n\r\ndef generate_fov_mask(viewport_lat, viewport_lon, img_in_Width, img_in_Height):\r\n\r\n\t# field of vision #\r\n\r\n fov_angle = np.array([120 * np.pi / 180, 120 * np.pi / 180]).astype(np.float32)\r\n\r\n img_size = np.array([img_in_Width, img_in_Height]).astype(np.float32) # WxH\r\n\r\n # basic vector\r\n vector_x = np.array([-np.sin(viewport_lon), np.cos(viewport_lon), 0]).astype(np.float32).reshape(3, 1)\r\n\r\n vector_y = np.array([np.sin(viewport_lat) * np.cos(viewport_lon),\r\n np.sin(viewport_lat) * np.sin(viewport_lon),\r\n - np.cos(viewport_lat)]).astype(np.float32).reshape(3, 1)\r\n pos_c= np.array([np.cos(viewport_lat) * np.cos(viewport_lon),\r\n np.cos(viewport_lat) * np.sin(viewport_lon),\r\n np.sin(viewport_lat)]).astype(np.float32).reshape(3, 1)\r\n\r\n\t# 2. transfer to cuda #\r\n vector_x = torch.from_numpy(vector_x).float().cuda()\r\n\r\n vector_y =torch.from_numpy(vector_y).float().cuda()\r\n\r\n fov_angle = torch.from_numpy(fov_angle).float().cuda()\r\n\r\n img_size = torch.from_numpy(img_size).float().cuda()\r\n\r\n img = torch.zeros((img_in_Height,img_in_Width)).float().cuda()\r\n\r\n pos_c = torch.from_numpy(pos_c).float().cuda()\r\n\r\n\r\n f = m.get_function('img_fov')\r\n\r\n Stream = namedtuple('Stream', ['ptr'])\r\n\t\r\n s = Stream(ptr=torch.cuda.current_stream().cuda_stream)\r\n\r\n f(grid=((img_in_Width-32)//32+1,(img_in_Height-32)//32+1,1), block=(32,32,1), args=[fov_angle.data_ptr(), vector_x.data_ptr(), vector_y.data_ptr(), pos_c.data_ptr(), img_size.data_ptr(), img.data_ptr()], stream=s)\r\n\r\n return img\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n\ta = generate_fov_mask(50*np.pi/180, 0, 3840, 1920)\r\n\r\n\tprint(a.shape)\r\n\r\n\tcv2.imwrite('a.png',a.cpu().numpy())\r\n\r\n\r\n\r\n\r\n"
]
| [
[
"torch.zeros",
"numpy.array",
"numpy.sin",
"torch.cuda.current_stream",
"torch.from_numpy",
"numpy.cos"
]
]
|
marcelflygare/pyod | [
"89865d8fbf714c22c8237147e20bab38d825f390"
]
| [
"pyod/test/test_data.py"
]
| [
"# -*- coding: utf-8 -*-\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\n\nimport unittest\nfrom sklearn.utils.testing import assert_equal\n# noinspection PyProtectedMember\nfrom sklearn.utils.testing import assert_allclose\nfrom sklearn.utils.testing import assert_less_equal\nfrom sklearn.utils.testing import assert_raises\n\nimport numpy as np\n\n# temporary solution for relative imports in case pyod is not installed\n# if pyod is installed, no need to use the following line\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\n\nfrom utils.data import generate_data\nfrom utils.data import evaluate_print\nfrom utils.data import get_outliers_inliers\nfrom utils.data import check_consistent_shape\n\n\nclass TestData(unittest.TestCase):\n def setUp(self):\n self.n_train = 1000\n self.n_test = 500\n self.contamination = 0.1\n\n self.value_lists = [0.1, 0.3, 0.2, -2, 1.5, 0, 1, -1, -0.5, 11]\n\n def test_data_generate(self):\n X_train, y_train, X_test, y_test = \\\n generate_data(n_train=self.n_train,\n n_test=self.n_test,\n contamination=self.contamination)\n\n assert_equal(y_train.shape[0], X_train.shape[0])\n assert_equal(y_test.shape[0], X_test.shape[0])\n\n assert_less_equal(self.n_train - X_train.shape[0], 1)\n assert_equal(X_train.shape[1], 2)\n\n assert_less_equal(self.n_test - X_test.shape[0], 1)\n assert_equal(X_test.shape[1], 2)\n\n out_perc = np.sum(y_train) / self.n_train\n assert_allclose(self.contamination, out_perc, atol=0.01)\n\n out_perc = np.sum(y_test) / self.n_test\n assert_allclose(self.contamination, out_perc, atol=0.01)\n\n def test_data_generate2(self):\n X_train, y_train, X_test, y_test = \\\n generate_data(n_train=self.n_train,\n n_test=self.n_test,\n n_features=3,\n contamination=self.contamination)\n assert_allclose(X_train.shape, (self.n_train, 3))\n assert_allclose(X_test.shape, (self.n_test, 3))\n\n def test_data_generate3(self):\n X_train, y_train, X_test, y_test = \\\n generate_data(n_train=self.n_train,\n n_test=self.n_test,\n n_features=2,\n contamination=self.contamination,\n random_state=42)\n\n X_train2, y_train2, X_test2, y_test2 = \\\n generate_data(n_train=self.n_train,\n n_test=self.n_test,\n n_features=2,\n contamination=self.contamination,\n random_state=42)\n\n assert_allclose(X_train, X_train2)\n assert_allclose(X_test, X_test2)\n assert_allclose(y_train, y_train2)\n assert_allclose(y_test, y_test2)\n\n def test_evaluate_print(self):\n X_train, y_train, X_test, y_test = generate_data(\n n_train=self.n_train,\n n_test=self.n_test,\n contamination=self.contamination)\n evaluate_print('dummy', y_train, y_train * 0.1)\n\n def test_get_outliers_inliers(self):\n X_train, y_train = generate_data(\n n_train=self.n_train, train_only=True,\n contamination=self.contamination)\n\n X_outliers, X_inliers = get_outliers_inliers(X_train, y_train)\n\n inlier_index = int(self.n_train * (1 - self.contamination))\n\n assert_allclose(X_train[0:inlier_index, :], X_inliers)\n assert_allclose(X_train[inlier_index:, :], X_outliers)\n\n def test_check_consistent_shape(self):\n X_train, y_train, X_test, y_test = generate_data(\n n_train=self.n_train,\n n_test=self.n_test,\n contamination=self.contamination)\n\n X_train_n, y_train_n, X_test_n, y_test_n, y_train_pred_n, y_test_pred_n \\\n = check_consistent_shape(X_train, y_train, X_test, y_test,\n y_train, y_test)\n\n assert_allclose(X_train_n, X_train)\n assert_allclose(y_train_n, y_train)\n assert_allclose(X_test_n, X_test)\n assert_allclose(y_test_n, y_test)\n assert_allclose(y_train_pred_n, y_train)\n assert_allclose(y_test_pred_n, y_test)\n\n # test shape difference\n with assert_raises(ValueError):\n check_consistent_shape(X_train, y_train, y_train, y_test,\n y_train, y_test)\n\n def tearDown(self):\n pass\n\n if __name__ == '__main__':\n unittest.main()\n"
]
| [
[
"numpy.sum",
"sklearn.utils.testing.assert_less_equal",
"sklearn.utils.testing.assert_allclose",
"sklearn.utils.testing.assert_equal",
"sklearn.utils.testing.assert_raises"
]
]
|
harshmehta227/AMLP | [
"4a1d13bc5a2f04885a6854f552d67335a2ef228f"
]
| [
"Categorical_Variables/US-Adult-Census/src/ohe_logres.py"
]
| [
"import time\nimport pandas as pd\n\nfrom sklearn import linear_model\nfrom sklearn import metrics\nfrom sklearn import preprocessing\n\n\ndef run(fold):\n # load the full training data with folds\n df = pd.read_csv(\"../input/adult_folds.csv\")\n # list of numerical columns\n num_cols = [\n \"fnlwgt\",\n \"age\",\n \"capital.gain\",\n \"capital.loss\",\n \"hours.per.week\"\n ]\n # drop numerical columns\n df = df.drop(num_cols, axis=1)\n # map targets to 0s and 1s\n target_mapping = {\n \"<=50K\": 0,\n \">50K\": 1\n }\n df.loc[:, \"income\"] = df.income.map(target_mapping)\n # all columns are features except income and kfold columns\n features = [\n f for f in df.columns if f not in (\"kfold\", \"income\")\n ]\n # fill all NaN values with NONE\n # note that I am converting all columns to \"strings\"\n # it doesnt matter because all are categories\n for col in features:\n df.loc[:, col] = df[col].astype(str).fillna(\"NONE\")\n\n # get training data using folds\n df_train = df[df.kfold != fold].reset_index(drop=True)\n # get validation data using folds\n df_valid = df[df.kfold == fold].reset_index(drop=True)\n # initialize OneHotEncoder from scikit-learn\n ohe = preprocessing.OneHotEncoder()\n # fit ohe on training + validation features\n full_data = pd.concat(\n [df_train[features], df_valid[features]],\n axis=0\n )\n ohe.fit(full_data[features])\n # transform training data\n x_train = ohe.transform(df_train[features])\n # transform validation data\n x_valid = ohe.transform(df_valid[features])\n # initialize Logistic Regression model\n model = linear_model.LogisticRegression()\n # fit model on training data (ohe)\n model.fit(x_train, df_train.income.values)\n # predict on validation data\n # we need the probability values as we are calculating AUC\n # we will use the probability of 1s\n valid_preds = model.predict_proba(x_valid)[:, 1]\n # get roc auc score\n auc = metrics.roc_auc_score(df_valid.income.values, valid_preds)\n # print auc\n print(f\"Fold = {fold}, AUC = {auc}\")\n\n\nif __name__ == \"__main__\":\n start_time = time.time()\n\n for fold_ in range(5):\n run(fold_)\n\n end_time = time.time() - start_time\n\n print(f\"----{end_time} seconds----\")\n\n# Results:\n# Fold = 0, AUC = 0.867126088803909\n# Fold = 1, AUC = 0.875327907255135\n# Fold = 2, AUC = 0.8761559956203355\n# Fold = 3, AUC = 0.8898685042888514\n# Fold = 4, AUC = 0.882478787935077\n# ----9.53763723373413 seconds----"
]
| [
[
"sklearn.linear_model.LogisticRegression",
"pandas.concat",
"pandas.read_csv",
"sklearn.preprocessing.OneHotEncoder",
"sklearn.metrics.roc_auc_score"
]
]
|
philtsmith570/Linear-Regression-Lazy-Programmer | [
"03357ab98155bf73b8f1d2fd53255cc16bea2333"
]
| [
"Linear Regression LP/linear_regression_class/generate_2d.py"
]
| [
"# generates 2-dimensional data for linear regression analysis\n#\n# notes for this course can be found at:\n# https://deeplearningcourses.com/c/data-science-linear-regression-in-python\n# https://www.udemy.com/data-science-linear-regression-in-python\n\nfrom __future__ import print_function, division\nfrom builtins import range\n# Note: you may need to update your version of future\n# sudo pip install -U future\n\n\n\nimport numpy as np\n\nN = 100\nw = np.array([2, 3])\nwith open('data_2d.csv', 'w') as f:\n X = np.random.uniform(low=0, high=100, size=(N,2))\n Y = np.dot(X, w) + 1 + np.random.normal(scale=5, size=N)\n for i in range(N):\n f.write(\"%s,%s,%s\\n\" % (X[i,0], X[i,1], Y[i]))\n"
]
| [
[
"numpy.random.normal",
"numpy.array",
"numpy.random.uniform",
"numpy.dot"
]
]
|
ekrembakay/COMP5327-FinalProject | [
"f6b03e10fddd8898caf9597237b0c8b222614566"
]
| [
"FinalProject/main.py"
]
| [
"import os\nimport numpy as np\nfrom keras.preprocessing.text import Tokenizer\nfrom numpy import array\nfrom numpy import argmax\nfrom numpy import array_equal\nfrom keras.utils import to_categorical\nfrom keras.models import Model\nfrom keras.layers import Input\nfrom keras.layers import LSTM\nfrom keras.layers import Dense\nfrom keras.callbacks import EarlyStopping\nfrom keras.preprocessing.sequence import pad_sequences\nfrom Source import rnnmodel\n\nif __name__ == '__main__':\n n_features = 200 + 1\n\n model, infenc, infdec = rnnmodel.define_models(n_features, n_features, 400)\n model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n input_data, output_data = rnnmodel.load_data()\n tokenizer = Tokenizer(num_words=10000)\n tokenizer.fit_on_texts(input_data)\n\n X1, y = rnnmodel.get_dataset(input_data, output_data, n_features, 10, tokenizer)\n X1_train, X1_test, y_train, y_test = rnnmodel.split_test(X1, y, test_size=0.3)\n\n X2_train = rnnmodel.decoder_input(y_train)\n X2_test = rnnmodel.decoder_input(y_test)\n\n early_stop = EarlyStopping(monitor='val_loss', mode='min', verbose=1)\n\n history = model.fit([X1_train, X2_train], y_train, epochs=100, batch_size=1, validation_data=([X1_test, X2_test], y_test))\n\n new_data = []\n with open(os.path.join(os.getcwd(), \"Source/predict.txt\")) as f:\n new_data.append(f.read())\n tokenizer.fit_on_texts(new_data)\n new_data = tokenizer.texts_to_sequences(new_data)\n X_new = []\n for i in range(len(new_data)):\n for j in range(len(new_data[i])):\n X_new.append(to_categorical(new_data[i][j], num_classes=n_features))\n\n X_new = np.array(X_new)\n X_new = X_new[0:10]\n X_new = X_new.reshape(int(10 / 10), 10, n_features)\n\n target = rnnmodel.predict_sequence(infenc, infdec, X_new, 10, n_features)\n\n yhat = [rnnmodel.one_hot_decode(target)]\n text = tokenizer.sequences_to_texts(yhat)\n print(new_data)\n print(text)\n #print(text)"
]
| [
[
"numpy.array"
]
]
|
ckohnke/discretize | [
"f414dd7ee7c5ba9a141cb2c37d4b71fdc531eae8"
]
| [
"tests/base/test_tensor_boundary.py"
]
| [
"import numpy as np\nimport unittest\nimport discretize\nfrom pymatsolver import Solver\n\nMESHTYPES = [\"uniformTensorMesh\"]\n\n\ndef getxBCyBC_CC(mesh, alpha, beta, gamma):\n \"\"\"\n This is a subfunction generating mixed-boundary condition:\n\n .. math::\n\n \\nabla \\cdot \\vec{j} = -\\nabla \\cdot \\vec{j}_s = q\n\n \\rho \\vec{j} = -\\nabla \\phi \\phi\n\n \\alpha \\phi + \\beta \\frac{\\partial \\phi}{\\partial r} = \\gamma \\ at \\ r\n = \\partial \\Omega\n\n xBC = f_1(\\alpha, \\beta, \\gamma)\n yBC = f(\\alpha, \\beta, \\gamma)\n\n Computes xBC and yBC for cell-centered discretizations\n \"\"\"\n\n if mesh.dim == 1: # 1D\n if len(alpha) != 2 or len(beta) != 2 or len(gamma) != 2:\n raise Exception(\"Lenght of list, alpha should be 2\")\n fCCxm, fCCxp = mesh.cellBoundaryInd\n nBC = fCCxm.sum() + fCCxp.sum()\n h_xm, h_xp = mesh.gridCC[fCCxm], mesh.gridCC[fCCxp]\n\n alpha_xm, beta_xm, gamma_xm = alpha[0], beta[0], gamma[0]\n alpha_xp, beta_xp, gamma_xp = alpha[1], beta[1], gamma[1]\n\n # h_xm, h_xp = mesh.gridCC[fCCxm], mesh.gridCC[fCCxp]\n h_xm, h_xp = mesh.hx[0], mesh.hx[-1]\n\n a_xm = gamma_xm / (0.5 * alpha_xm - beta_xm / h_xm)\n b_xm = (0.5 * alpha_xm + beta_xm / h_xm) / (0.5 * alpha_xm - beta_xm / h_xm)\n a_xp = gamma_xp / (0.5 * alpha_xp - beta_xp / h_xp)\n b_xp = (0.5 * alpha_xp + beta_xp / h_xp) / (0.5 * alpha_xp - beta_xp / h_xp)\n\n xBC_xm = 0.5 * a_xm\n xBC_xp = 0.5 * a_xp / b_xp\n yBC_xm = 0.5 * (1.0 - b_xm)\n yBC_xp = 0.5 * (1.0 - 1.0 / b_xp)\n\n xBC = np.r_[xBC_xm, xBC_xp]\n yBC = np.r_[yBC_xm, yBC_xp]\n\n elif mesh.dim == 2: # 2D\n if len(alpha) != 4 or len(beta) != 4 or len(gamma) != 4:\n raise Exception(\"Lenght of list, alpha should be 4\")\n\n fxm, fxp, fym, fyp = mesh.faceBoundaryInd\n nBC = fxm.sum() + fxp.sum() + fxm.sum() + fxp.sum()\n\n alpha_xm, beta_xm, gamma_xm = alpha[0], beta[0], gamma[0]\n alpha_xp, beta_xp, gamma_xp = alpha[1], beta[1], gamma[1]\n alpha_ym, beta_ym, gamma_ym = alpha[2], beta[2], gamma[2]\n alpha_yp, beta_yp, gamma_yp = alpha[3], beta[3], gamma[3]\n\n # h_xm, h_xp = mesh.gridCC[fCCxm,0], mesh.gridCC[fCCxp,0]\n # h_ym, h_yp = mesh.gridCC[fCCym,1], mesh.gridCC[fCCyp,1]\n\n h_xm = mesh.hx[0] * np.ones_like(alpha_xm)\n h_xp = mesh.hx[-1] * np.ones_like(alpha_xp)\n h_ym = mesh.hy[0] * np.ones_like(alpha_ym)\n h_yp = mesh.hy[-1] * np.ones_like(alpha_yp)\n\n a_xm = gamma_xm / (0.5 * alpha_xm - beta_xm / h_xm)\n b_xm = (0.5 * alpha_xm + beta_xm / h_xm) / (0.5 * alpha_xm - beta_xm / h_xm)\n a_xp = gamma_xp / (0.5 * alpha_xp - beta_xp / h_xp)\n b_xp = (0.5 * alpha_xp + beta_xp / h_xp) / (0.5 * alpha_xp - beta_xp / h_xp)\n\n a_ym = gamma_ym / (0.5 * alpha_ym - beta_ym / h_ym)\n b_ym = (0.5 * alpha_ym + beta_ym / h_ym) / (0.5 * alpha_ym - beta_ym / h_ym)\n a_yp = gamma_yp / (0.5 * alpha_yp - beta_yp / h_yp)\n b_yp = (0.5 * alpha_yp + beta_yp / h_yp) / (0.5 * alpha_yp - beta_yp / h_yp)\n\n xBC_xm = 0.5 * a_xm\n xBC_xp = 0.5 * a_xp / b_xp\n yBC_xm = 0.5 * (1.0 - b_xm)\n yBC_xp = 0.5 * (1.0 - 1.0 / b_xp)\n xBC_ym = 0.5 * a_ym\n xBC_yp = 0.5 * a_yp / b_yp\n yBC_ym = 0.5 * (1.0 - b_ym)\n yBC_yp = 0.5 * (1.0 - 1.0 / b_yp)\n\n sortindsfx = np.argsort(\n np.r_[np.arange(mesh.nFx)[fxm], np.arange(mesh.nFx)[fxp]]\n )\n sortindsfy = np.argsort(\n np.r_[np.arange(mesh.nFy)[fym], np.arange(mesh.nFy)[fyp]]\n )\n\n xBC_x = np.r_[xBC_xm, xBC_xp][sortindsfx]\n xBC_y = np.r_[xBC_ym, xBC_yp][sortindsfy]\n yBC_x = np.r_[yBC_xm, yBC_xp][sortindsfx]\n yBC_y = np.r_[yBC_ym, yBC_yp][sortindsfy]\n\n xBC = np.r_[xBC_x, xBC_y]\n yBC = np.r_[yBC_x, yBC_y]\n\n elif mesh.dim == 3: # 3D\n if len(alpha) != 6 or len(beta) != 6 or len(gamma) != 6:\n raise Exception(\"Lenght of list, alpha should be 6\")\n # fCCxm,fCCxp,fCCym,fCCyp,fCCzm,fCCzp = mesh.cellBoundaryInd\n fxm, fxp, fym, fyp, fzm, fzp = mesh.faceBoundaryInd\n nBC = fxm.sum() + fxp.sum() + fxm.sum() + fxp.sum()\n\n alpha_xm, beta_xm, gamma_xm = alpha[0], beta[0], gamma[0]\n alpha_xp, beta_xp, gamma_xp = alpha[1], beta[1], gamma[1]\n alpha_ym, beta_ym, gamma_ym = alpha[2], beta[2], gamma[2]\n alpha_yp, beta_yp, gamma_yp = alpha[3], beta[3], gamma[3]\n alpha_zm, beta_zm, gamma_zm = alpha[4], beta[4], gamma[4]\n alpha_zp, beta_zp, gamma_zp = alpha[5], beta[5], gamma[5]\n\n # h_xm, h_xp = mesh.gridCC[fCCxm,0], mesh.gridCC[fCCxp,0]\n # h_ym, h_yp = mesh.gridCC[fCCym,1], mesh.gridCC[fCCyp,1]\n # h_zm, h_zp = mesh.gridCC[fCCzm,2], mesh.gridCC[fCCzp,2]\n\n h_xm = mesh.hx[0] * np.ones_like(alpha_xm)\n h_xp = mesh.hx[-1] * np.ones_like(alpha_xp)\n h_ym = mesh.hy[0] * np.ones_like(alpha_ym)\n h_yp = mesh.hy[-1] * np.ones_like(alpha_yp)\n h_zm = mesh.hz[0] * np.ones_like(alpha_zm)\n h_zp = mesh.hz[-1] * np.ones_like(alpha_zp)\n\n a_xm = gamma_xm / (0.5 * alpha_xm - beta_xm / h_xm)\n b_xm = (0.5 * alpha_xm + beta_xm / h_xm) / (0.5 * alpha_xm - beta_xm / h_xm)\n a_xp = gamma_xp / (0.5 * alpha_xp - beta_xp / h_xp)\n b_xp = (0.5 * alpha_xp + beta_xp / h_xp) / (0.5 * alpha_xp - beta_xp / h_xp)\n\n a_ym = gamma_ym / (0.5 * alpha_ym - beta_ym / h_ym)\n b_ym = (0.5 * alpha_ym + beta_ym / h_ym) / (0.5 * alpha_ym - beta_ym / h_ym)\n a_yp = gamma_yp / (0.5 * alpha_yp - beta_yp / h_yp)\n b_yp = (0.5 * alpha_yp + beta_yp / h_yp) / (0.5 * alpha_yp - beta_yp / h_yp)\n\n a_zm = gamma_zm / (0.5 * alpha_zm - beta_zm / h_zm)\n b_zm = (0.5 * alpha_zm + beta_zm / h_zm) / (0.5 * alpha_zm - beta_zm / h_zm)\n a_zp = gamma_zp / (0.5 * alpha_zp - beta_zp / h_zp)\n b_zp = (0.5 * alpha_zp + beta_zp / h_zp) / (0.5 * alpha_zp - beta_zp / h_zp)\n\n xBC_xm = 0.5 * a_xm\n xBC_xp = 0.5 * a_xp / b_xp\n yBC_xm = 0.5 * (1.0 - b_xm)\n yBC_xp = 0.5 * (1.0 - 1.0 / b_xp)\n xBC_ym = 0.5 * a_ym\n xBC_yp = 0.5 * a_yp / b_yp\n yBC_ym = 0.5 * (1.0 - b_ym)\n yBC_yp = 0.5 * (1.0 - 1.0 / b_yp)\n xBC_zm = 0.5 * a_zm\n xBC_zp = 0.5 * a_zp / b_zp\n yBC_zm = 0.5 * (1.0 - b_zm)\n yBC_zp = 0.5 * (1.0 - 1.0 / b_zp)\n\n sortindsfx = np.argsort(\n np.r_[np.arange(mesh.nFx)[fxm], np.arange(mesh.nFx)[fxp]]\n )\n sortindsfy = np.argsort(\n np.r_[np.arange(mesh.nFy)[fym], np.arange(mesh.nFy)[fyp]]\n )\n sortindsfz = np.argsort(\n np.r_[np.arange(mesh.nFz)[fzm], np.arange(mesh.nFz)[fzp]]\n )\n\n xBC_x = np.r_[xBC_xm, xBC_xp][sortindsfx]\n xBC_y = np.r_[xBC_ym, xBC_yp][sortindsfy]\n xBC_z = np.r_[xBC_zm, xBC_zp][sortindsfz]\n\n yBC_x = np.r_[yBC_xm, yBC_xp][sortindsfx]\n yBC_y = np.r_[yBC_ym, yBC_yp][sortindsfy]\n yBC_z = np.r_[yBC_zm, yBC_zp][sortindsfz]\n\n xBC = np.r_[xBC_x, xBC_y, xBC_z]\n yBC = np.r_[yBC_x, yBC_y, yBC_z]\n\n return xBC, yBC\n\n\nclass Test1D_InhomogeneousMixed(discretize.tests.OrderTest):\n name = \"1D - Mixed\"\n meshTypes = MESHTYPES\n meshDimension = 1\n expectedOrders = 2\n meshSizes = [4, 8, 16, 32]\n\n def getError(self):\n # Test function\n def phi_fun(x):\n return np.cos(np.pi * x)\n\n def j_fun(x):\n return np.pi * np.sin(np.pi * x)\n\n def phi_deriv(x):\n return -j_fun(x)\n\n def q_fun(x):\n return (np.pi ** 2) * np.cos(np.pi * x)\n\n xc_ana = phi_fun(self.M.gridCC)\n q_ana = q_fun(self.M.gridCC)\n j_ana = j_fun(self.M.gridFx)\n\n # Get boundary locations\n vecN = self.M.vectorNx\n vecC = self.M.vectorCCx\n\n # Setup Mixed B.C (alpha, beta, gamma)\n alpha_xm, alpha_xp = 1.0, 1.0\n beta_xm, beta_xp = 1.0, 1.0\n alpha = np.r_[alpha_xm, alpha_xp]\n beta = np.r_[beta_xm, beta_xp]\n vecN = self.M.vectorNx\n vecC = self.M.vectorCCx\n phi_bc = phi_fun(vecN[[0, -1]])\n phi_deriv_bc = phi_deriv(vecN[[0, -1]])\n gamma = alpha * phi_bc + beta * phi_deriv_bc\n x_BC, y_BC = getxBCyBC_CC(self.M, alpha, beta, gamma)\n\n sigma = np.ones(self.M.nC)\n Mfrho = self.M.getFaceInnerProduct(1.0 / sigma)\n MfrhoI = self.M.getFaceInnerProduct(1.0 / sigma, invMat=True)\n V = discretize.utils.sdiag(self.M.vol)\n Div = V * self.M.faceDiv\n P_BC, B = self.M.getBCProjWF_simple()\n q = q_fun(self.M.gridCC)\n M = B * self.M.aveCC2F\n G = Div.T - P_BC * discretize.utils.sdiag(y_BC) * M\n # Mrhoj = D.T V phi + P_BC*discretize.utils.sdiag(y_BC)*M phi - P_BC*x_BC\n rhs = V * q + Div * MfrhoI * P_BC * x_BC\n A = Div * MfrhoI * G\n\n if self.myTest == \"xc\":\n # TODO: fix the null space\n Ainv = Solver(A)\n xc = Ainv * rhs\n err = np.linalg.norm((xc - xc_ana), np.inf)\n else:\n NotImplementedError\n return err\n\n def test_order(self):\n print(\"==== Testing Mixed boudary conduction for CC-problem ====\")\n self.name = \"1D\"\n self.myTest = \"xc\"\n self.orderTest()\n\n\nclass Test2D_InhomogeneousMixed(discretize.tests.OrderTest):\n name = \"2D - Mixed\"\n meshTypes = MESHTYPES\n meshDimension = 2\n expectedOrders = 2\n meshSizes = [4, 8, 16, 32]\n\n def getError(self):\n # Test function\n def phi_fun(x):\n return np.cos(np.pi * x[:, 0]) * np.cos(np.pi * x[:, 1])\n\n def j_funX(x):\n return +np.pi * np.sin(np.pi * x[:, 0]) * np.cos(np.pi * x[:, 1])\n\n def j_funY(x):\n return +np.pi * np.cos(np.pi * x[:, 0]) * np.sin(np.pi * x[:, 1])\n\n def phideriv_funX(x):\n return -j_funX(x)\n\n def phideriv_funY(x):\n return -j_funY(x)\n\n def q_fun(x):\n return +2 * (np.pi ** 2) * phi_fun(x)\n\n xc_ana = phi_fun(self.M.gridCC)\n q_ana = q_fun(self.M.gridCC)\n jX_ana = j_funX(self.M.gridFx)\n jY_ana = j_funY(self.M.gridFy)\n j_ana = np.r_[jX_ana, jY_ana]\n\n # Get boundary locations\n fxm, fxp, fym, fyp = self.M.faceBoundaryInd\n gBFxm = self.M.gridFx[fxm, :]\n gBFxp = self.M.gridFx[fxp, :]\n gBFym = self.M.gridFy[fym, :]\n gBFyp = self.M.gridFy[fyp, :]\n\n # Setup Mixed B.C (alpha, beta, gamma)\n alpha_xm = np.ones_like(gBFxm[:, 0])\n alpha_xp = np.ones_like(gBFxp[:, 0])\n beta_xm = np.ones_like(gBFxm[:, 0])\n beta_xp = np.ones_like(gBFxp[:, 0])\n alpha_ym = np.ones_like(gBFym[:, 1])\n alpha_yp = np.ones_like(gBFyp[:, 1])\n beta_ym = np.ones_like(gBFym[:, 1])\n beta_yp = np.ones_like(gBFyp[:, 1])\n\n phi_bc_xm, phi_bc_xp = phi_fun(gBFxm), phi_fun(gBFxp)\n phi_bc_ym, phi_bc_yp = phi_fun(gBFym), phi_fun(gBFyp)\n\n phiderivX_bc_xm = phideriv_funX(gBFxm)\n phiderivX_bc_xp = phideriv_funX(gBFxp)\n phiderivY_bc_ym = phideriv_funY(gBFym)\n phiderivY_bc_yp = phideriv_funY(gBFyp)\n\n def gamma_fun(alpha, beta, phi, phi_deriv):\n return alpha * phi + beta * phi_deriv\n\n gamma_xm = gamma_fun(alpha_xm, beta_xm, phi_bc_xm, phiderivX_bc_xm)\n gamma_xp = gamma_fun(alpha_xp, beta_xp, phi_bc_xp, phiderivX_bc_xp)\n gamma_ym = gamma_fun(alpha_ym, beta_ym, phi_bc_ym, phiderivY_bc_ym)\n gamma_yp = gamma_fun(alpha_yp, beta_yp, phi_bc_yp, phiderivY_bc_yp)\n\n alpha = [alpha_xm, alpha_xp, alpha_ym, alpha_yp]\n beta = [beta_xm, beta_xp, beta_ym, beta_yp]\n gamma = [gamma_xm, gamma_xp, gamma_ym, gamma_yp]\n\n x_BC, y_BC = getxBCyBC_CC(self.M, alpha, beta, gamma)\n\n sigma = np.ones(self.M.nC)\n Mfrho = self.M.getFaceInnerProduct(1.0 / sigma)\n MfrhoI = self.M.getFaceInnerProduct(1.0 / sigma, invMat=True)\n V = discretize.utils.sdiag(self.M.vol)\n Div = V * self.M.faceDiv\n P_BC, B = self.M.getBCProjWF_simple()\n q = q_fun(self.M.gridCC)\n M = B * self.M.aveCC2F\n G = Div.T - P_BC * discretize.utils.sdiag(y_BC) * M\n rhs = V * q + Div * MfrhoI * P_BC * x_BC\n A = Div * MfrhoI * G\n\n if self.myTest == \"xc\":\n Ainv = Solver(A)\n xc = Ainv * rhs\n err = np.linalg.norm((xc - xc_ana), np.inf)\n else:\n NotImplementedError\n return err\n\n def test_order(self):\n print(\"==== Testing Mixed boudary conduction for CC-problem ====\")\n self.name = \"2D\"\n self.myTest = \"xc\"\n self.orderTest()\n\n\nclass Test3D_InhomogeneousMixed(discretize.tests.OrderTest):\n name = \"3D - Mixed\"\n meshTypes = MESHTYPES\n meshDimension = 3\n expectedOrders = 2\n meshSizes = [4, 8, 16]\n\n def getError(self):\n # Test function\n def phi_fun(x):\n return (\n np.cos(np.pi * x[:, 0])\n * np.cos(np.pi * x[:, 1])\n * np.cos(np.pi * x[:, 2])\n )\n\n def j_funX(x):\n return (\n np.pi\n * np.sin(np.pi * x[:, 0])\n * np.cos(np.pi * x[:, 1])\n * np.cos(np.pi * x[:, 2])\n )\n\n def j_funY(x):\n return (\n np.pi\n * np.cos(np.pi * x[:, 0])\n * np.sin(np.pi * x[:, 1])\n * np.cos(np.pi * x[:, 2])\n )\n\n def j_funZ(x):\n return (\n np.pi\n * np.cos(np.pi * x[:, 0])\n * np.cos(np.pi * x[:, 1])\n * np.sin(np.pi * x[:, 2])\n )\n\n def phideriv_funX(x):\n return -j_funX(x)\n\n def phideriv_funY(x):\n return -j_funY(x)\n\n def phideriv_funZ(x):\n return -j_funZ(x)\n\n def q_fun(x):\n return 3 * (np.pi ** 2) * phi_fun(x)\n\n xc_ana = phi_fun(self.M.gridCC)\n q_ana = q_fun(self.M.gridCC)\n jX_ana = j_funX(self.M.gridFx)\n jY_ana = j_funY(self.M.gridFy)\n j_ana = np.r_[jX_ana, jY_ana, jY_ana]\n\n # Get boundary locations\n fxm, fxp, fym, fyp, fzm, fzp = self.M.faceBoundaryInd\n gBFxm = self.M.gridFx[fxm, :]\n gBFxp = self.M.gridFx[fxp, :]\n gBFym = self.M.gridFy[fym, :]\n gBFyp = self.M.gridFy[fyp, :]\n gBFzm = self.M.gridFz[fzm, :]\n gBFzp = self.M.gridFz[fzp, :]\n\n # Setup Mixed B.C (alpha, beta, gamma)\n alpha_xm = np.ones_like(gBFxm[:, 0])\n alpha_xp = np.ones_like(gBFxp[:, 0])\n beta_xm = np.ones_like(gBFxm[:, 0])\n beta_xp = np.ones_like(gBFxp[:, 0])\n alpha_ym = np.ones_like(gBFym[:, 1])\n alpha_yp = np.ones_like(gBFyp[:, 1])\n beta_ym = np.ones_like(gBFym[:, 1])\n beta_yp = np.ones_like(gBFyp[:, 1])\n alpha_zm = np.ones_like(gBFzm[:, 2])\n alpha_zp = np.ones_like(gBFzp[:, 2])\n beta_zm = np.ones_like(gBFzm[:, 2])\n beta_zp = np.ones_like(gBFzp[:, 2])\n\n phi_bc_xm, phi_bc_xp = phi_fun(gBFxm), phi_fun(gBFxp)\n phi_bc_ym, phi_bc_yp = phi_fun(gBFym), phi_fun(gBFyp)\n phi_bc_zm, phi_bc_zp = phi_fun(gBFzm), phi_fun(gBFzp)\n\n phiderivX_bc_xm = phideriv_funX(gBFxm)\n phiderivX_bc_xp = phideriv_funX(gBFxp)\n phiderivY_bc_ym = phideriv_funY(gBFym)\n phiderivY_bc_yp = phideriv_funY(gBFyp)\n phiderivY_bc_zm = phideriv_funZ(gBFzm)\n phiderivY_bc_zp = phideriv_funZ(gBFzp)\n\n def gamma_fun(alpha, beta, phi, phi_deriv):\n return alpha * phi + beta * phi_deriv\n\n gamma_xm = gamma_fun(alpha_xm, beta_xm, phi_bc_xm, phiderivX_bc_xm)\n gamma_xp = gamma_fun(alpha_xp, beta_xp, phi_bc_xp, phiderivX_bc_xp)\n gamma_ym = gamma_fun(alpha_ym, beta_ym, phi_bc_ym, phiderivY_bc_ym)\n gamma_yp = gamma_fun(alpha_yp, beta_yp, phi_bc_yp, phiderivY_bc_yp)\n gamma_zm = gamma_fun(alpha_zm, beta_zm, phi_bc_zm, phiderivY_bc_zm)\n gamma_zp = gamma_fun(alpha_zp, beta_zp, phi_bc_zp, phiderivY_bc_zp)\n\n alpha = [alpha_xm, alpha_xp, alpha_ym, alpha_yp, alpha_zm, alpha_zp]\n beta = [beta_xm, beta_xp, beta_ym, beta_yp, beta_zm, beta_zp]\n gamma = [gamma_xm, gamma_xp, gamma_ym, gamma_yp, gamma_zm, gamma_zp]\n\n x_BC, y_BC = getxBCyBC_CC(self.M, alpha, beta, gamma)\n\n sigma = np.ones(self.M.nC)\n Mfrho = self.M.getFaceInnerProduct(1.0 / sigma)\n MfrhoI = self.M.getFaceInnerProduct(1.0 / sigma, invMat=True)\n V = discretize.utils.sdiag(self.M.vol)\n Div = V * self.M.faceDiv\n P_BC, B = self.M.getBCProjWF_simple()\n q = q_fun(self.M.gridCC)\n M = B * self.M.aveCC2F\n G = Div.T - P_BC * discretize.utils.sdiag(y_BC) * M\n rhs = V * q + Div * MfrhoI * P_BC * x_BC\n A = Div * MfrhoI * G\n\n if self.myTest == \"xc\":\n # TODO: fix the null space\n Ainv = Solver(A)\n xc = Ainv * rhs\n err = np.linalg.norm((xc - xc_ana), np.inf)\n else:\n NotImplementedError\n return err\n\n def test_order(self):\n print(\"==== Testing Mixed boudary conduction for CC-problem ====\")\n self.name = \"3D\"\n self.myTest = \"xc\"\n self.orderTest()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
]
| [
[
"numpy.sin",
"numpy.ones_like",
"numpy.linalg.norm",
"numpy.ones",
"numpy.arange",
"numpy.cos"
]
]
|
warlicks/Real_Estate_Data | [
"137dc53a24a878cb96ec5132be6e81196902aec1"
]
| [
"python/neighborhood_stats.py"
]
| [
"# Import Libriaries\n###############################################################################\nimport urllib\nimport xml.etree.ElementTree as et\nimport pandas as pd\n\n# Define Global Variable\n###############################################################################\ntrulia = 'http://api.trulia.com/webservices.php?' # Set Trulia URL\n\n# Define function to call trulia API and parse the retruned XML\n###############################################################################\ndef neighborhood_stats(neighborhoodid, start_date, end_date, api_key):\n\n\t# Set Up URL for API Call\n\turl = trulia + urllib.urlencode({'library':'TruliaStats', 'function':'getNeighborhoodStats', 'neighborhoodId':neighborhoodid, 'startDate':start_date, 'endDate':end_date, 'apikey':api_key}) # Create url\n\n\t# Connect to API\n\tpage = urllib.urlopen(url) \n\txml_string = page.read()\n\n\t# Create dictionary for storage of parsed xml\n\toutput = {\"date\":[], \"neighborhoodid\":[], \"type\":[], \"properties\":[], \"medianPrice\":[], \"avgPrice\":[]}\n\n\t# Convert the data returned from api to XML\n\txml_element = et.fromstring(xml_string) # Create to Element from string\n\txml_tree = et.ElementTree(xml_element) # Convert Element to Element Tree\n\n\t# Parse the XML\n\tdata_node = xml_tree.findall(\".//listingStat\")\n\n\tfor records in data_node:\n\t\trecord_date = records.find(\"weekEndingDate\").text # Extract record date\n\t\t\t\n\t\tcategories = records.findall(\".//subcategory\") # Find all subcategory for the given weekend date\n \n\t\tfor category in categories:\n\t\t\toutput[\"date\"].append(record_date) \n\n\t\t\toutput[\"neighborhoodid\"].append(neighborhoodid)\n\n\t\t\ttp = category.find(\"type\").text\n\t\t\toutput[\"type\"].append(tp)\n\n\t\t\tprop = category.find(\"numberOfProperties\").text\n\t\t\toutput[\"properties\"].append(prop)\n\n\t\t\tmedian = category.find(\"medianListingPrice\").text\n\t\t\toutput[\"medianPrice\"].append(median)\n \n\t\t\tavg = category.find(\"averageListingPrice\").text\n\t\t\toutput[\"avgPrice\"].append(avg)\n\n\tdata_frame = pd.DataFrame(output) # Convert to a data frame for easy import in R\n\treturn data_frame"
]
| [
[
"pandas.DataFrame"
]
]
|
SparkJiao/LARCH | [
"93e2e103ff5e134f5a7d3501b46f510167fb99d5"
]
| [
"models/gat_layer.py"
]
| [
"import torch\nimport torch.nn.functional as F\nfrom torch import nn\n\n\nclass GraphAttentionLayer(nn.Module):\n \"\"\"\n Simple GAT layer, similar to https://arxiv.org/abs/1710.10903\n \"\"\"\n\n def __init__(self, in_features, out_features, dropout, alpha, concat=True, residual=False):\n super(GraphAttentionLayer, self).__init__()\n self.dropout = dropout\n self.in_features = in_features\n self.out_features = out_features\n self.alpha = alpha\n self.concat = concat\n self.residual = residual\n\n self.seq_transformation = nn.Conv1d(in_features, out_features, kernel_size=1, stride=1, bias=False)\n if self.residual:\n self.proj_residual = nn.Conv1d(in_features, out_features, kernel_size=1, stride=1)\n self.f_1 = nn.Conv1d(out_features, 1, kernel_size=1, stride=1)\n self.f_2 = nn.Conv1d(out_features, 1, kernel_size=1, stride=1)\n self.bias = nn.Parameter(torch.zeros(out_features, dtype=torch.float), requires_grad=True)\n\n self.leakyrelu = nn.LeakyReLU(self.alpha)\n\n def forward(self, input: torch.Tensor, adj):\n # Too harsh to use the same dropout. TODO add another dropout\n # input = F.dropout(input, self.dropout, training=self.training)\n\n seq = input.transpose(0, 1).unsqueeze(0)\n seq_fts = self.seq_transformation(seq)\n\n f_1 = self.f_1(seq_fts)\n f_2 = self.f_2(seq_fts)\n logits = (torch.transpose(f_1, 2, 1) + f_2).squeeze(0)\n coefs = F.softmax(self.leakyrelu(logits) + adj, dim=1)\n\n seq_fts = F.dropout(torch.transpose(seq_fts.squeeze(0), 0, 1), self.dropout, training=self.training)\n coefs = F.dropout(coefs, self.dropout, training=self.training)\n\n ret = torch.mm(coefs, seq_fts) + self.bias\n\n if self.residual:\n if seq.size()[-1] != ret.size()[-1]:\n ret += torch.transpose(self.proj_residual(seq).squeeze(0), 0, 1)\n else:\n ret += input\n\n if self.concat:\n return F.elu(ret)\n else:\n return ret\n\n def __repr__(self):\n return self.__class__.__name__ + ' (' + str(self.in_features) + ' -> ' + str(self.out_features) + ')'\n\n\nclass GATLayer(nn.Module):\n \"\"\"\n Simple GAT layer, similar to https://arxiv.org/abs/1710.10903\n \"\"\"\n\n def __init__(self, in_features, head_num, dropout, alpha, concat=True, residual=False):\n super().__init__()\n # self.dropout = dropout\n self.in_features = in_features\n self.alpha = alpha\n self.concat = concat\n self.residual = residual\n\n self.n_head = head_num\n self.d_head = in_features // self.n_head\n self.d_model = self.n_head * self.d_head\n self.seq_transform = nn.Linear(in_features, self.d_model, bias=False)\n\n self.attn_transform1 = nn.Linear(self.d_head, 1, bias=False)\n self.attn_transform2 = nn.Linear(self.d_head, 1, bias=False)\n\n self.attn_output = nn.Linear(self.d_model, self.in_features)\n\n if dropout > 0:\n self.dropout = nn.Dropout(dropout)\n else:\n self.dropout = lambda x: x\n\n self.leakyrelu = nn.LeakyReLU(self.alpha)\n\n def forward(self, input: torch.Tensor, adj):\n # Too harsh to use the same dropout. TODO add another dropout\n # input = F.dropout(input, self.dropout, training=self.training)\n\n seq_len = input.size(0)\n\n seq = self.seq_transform(input).view(seq_len, self.n_head, self.d_head)\n\n # (n_head, seq_len)\n score1 = self.attn_transform1(seq).squeeze(-1).transpose(0, 1).contiguous()\n score2 = self.attn_transform2(seq).squeeze(-1).transpose(0, 1).contiguous()\n\n scores = score1[:, :, None] + score2[:, None, :]\n\n # seq1 = seq.unsqueeze(1).expand(-1, seq_len, -1).reshape(seq_len, seq_len, self.n_head, self.d_head)\n # seq2 = seq.unsqueeze(0).expand(seq_len, -1, -1).reshape(seq_len, seq_len, self.n_head, self.d_head)\n #\n # seq_mat = torch.cat([seq1, seq2], dim=-1).reshape(seq_len * seq_len, self.n_head, self.d_head * 2)\n # scores = self.attn_transform(seq_mat).view(seq_len, seq_len, self.n_head).permute(2, 0, 1)\n scores = self.leakyrelu(scores)\n alpha = torch.softmax(scores + (1 - adj).unsqueeze(0) * -65500.0, dim=-1)\n alpha = self.dropout(alpha)\n\n # seq = seq.view(seq_len, self.n_head, self.d_head)\n hidden = torch.einsum(\"hij,jhd->ihd\", alpha, seq).reshape(seq_len, self.d_model)\n hidden = self.attn_output(hidden)\n\n if self.residual:\n hidden = hidden + input\n\n if self.concat:\n return F.elu(hidden)\n else:\n return hidden\n\n def __repr__(self):\n return self.__class__.__name__ + ' (' + str(self.in_features) + ' -> ' + str(self.out_features) + ')'\n\n"
]
| [
[
"torch.nn.Linear",
"torch.zeros",
"torch.nn.Dropout",
"torch.einsum",
"torch.nn.Conv1d",
"torch.nn.functional.dropout",
"torch.nn.LeakyReLU",
"torch.nn.functional.elu",
"torch.mm",
"torch.transpose"
]
]
|
cherepaha/PyDDM | [
"9ef36fd0cdf0c7926340f1bef3e18fe921bc8f21"
]
| [
"ddm/sample.py"
]
| [
"# Copyright 2018 Max Shinn <[email protected]>\n# 2018 Norman Lam <[email protected]>\n# \n# This file is part of PyDDM, and is available under the MIT license.\n# Please see LICENSE.txt in the root directory for more information.\n\nimport numpy as np\nimport itertools\n\nfrom paranoid.types import NDArray, Number, List, String, Self, Positive, Positive0, Range, Natural0, Unchecked, Dict, Maybe, Nothing\nfrom paranoid.decorators import *\nfrom .models.paranoid_types import Conditions\n\n@paranoidclass\nclass Sample(object):\n \"\"\"Describes a sample from some (empirical or simulated) distribution.\n\n Similarly to Solution, this is a glorified container for three\n items: a list of correct reaction times, a list of error reaction\n times, and the number of undecided trials. Each can have\n different properties associated with it, known as \"conditions\"\n elsewhere in this codebase. This is to specifiy the experimental\n parameters of the trial, to allow fitting of stimuli by (for\n example) color or intensity.\n\n To specify conditions, pass a keyword argument to the constructor.\n The name should be the name of the property, and the value should\n be a tuple of length two or three. The first element of the tuple\n should be a list of length equal to the number of correct trials,\n and the second should be equal to the number of error trials. If\n there are any undecided trials, the third argument should\n contain a list of length equal to `undecided`.\n\n Optionally, additional data can be associated with each\n independent data point. These should be passed as keyword\n arguments, where the keyword name is the property and the value is\n a tuple. The tuple should have either two or three elements: the\n first two should be lists of properties for the correct and error\n reaction times, where the properties correspond to reaction times\n in the correct or error lists. Optionally, a third list of length\n equal to the number of undecided trials gives a list of conditions\n for these trials. If multiple properties are passed as keyword\n arguments, the ordering of the undecided properties (in addition\n to those of the correct and error distributions) will correspond\n to one another.\n \"\"\"\n @classmethod\n def _test(cls, v):\n # Most testing is done in the constructor and the data is read\n # only, so this isn't strictly necessary\n assert type(v) is cls\n assert v.corr in NDArray(d=1, t=Number), \"sample_corr not a numpy array, it is \" + str(type(v.corr))\n assert v.err in NDArray(d=1, t=Number), \"sample_err not a numpy array, it is \" + str(type(v.err))\n assert v.undecided in Natural0(), \"undecided not a natural number\"\n for k,val in v.conditions.items():\n # Make sure shape and type are correct\n assert k, \"Invalid key\"\n assert isinstance(val, tuple)\n assert len(val) in [2, 3]\n assert val[0] in NDArray(d=1)\n assert val[1] in NDArray(d=1)\n assert len(val[0]) == len(v.corr)\n assert len(val[1]) == len(v.err)\n if len(val) == 3:\n assert len(val[2]) == v.undecided\n assert val[2] in NDArray(d=1)\n else:\n assert v.undecided == 0\n @staticmethod\n def _generate():\n aa = lambda x : np.asarray(x)\n yield Sample(aa([.1, .2, .3]), aa([.2, .3, .4]), undecided=0)\n yield Sample(aa([.1, .2, .3]), aa([]), undecided=0)\n yield Sample(aa([]), aa([.2, .3, .4]), undecided=0)\n yield Sample(aa([.1, .2, .3]), aa([.2, .3, .4]), undecided=5)\n \n def __init__(self, sample_corr, sample_err, undecided=0, **kwargs):\n assert sample_corr in NDArray(d=1, t=Number), \"sample_corr not a numpy array, it is \" + str(type(sample_corr))\n assert sample_err in NDArray(d=1, t=Number), \"sample_err not a numpy array, it is \" + str(type(sample_err))\n assert undecided in Natural0(), \"undecided not a natural number\"\n self.corr = sample_corr\n self.err = sample_err\n self.undecided = undecided\n # Values should not change\n self.corr.flags.writeable = False\n self.err.flags.writeable = False\n # Make sure the kwarg parameters/conditions are in the correct\n # format\n for k,v in kwargs.items():\n # Make sure shape and type are correct\n assert k, \"Invalid key\"\n assert isinstance(v, tuple)\n assert len(v) in [2, 3]\n assert v[0] in NDArray(d=1)\n assert v[1] in NDArray(d=1)\n assert len(v[0]) == len(self.corr)\n assert len(v[1]) == len(self.err)\n # Make read-only\n v[0].flags.writeable = False\n v[1].flags.writeable = False\n if len(v) == 3:\n assert len(v[2]) == undecided\n else:\n assert undecided == 0\n self.conditions = kwargs\n def __len__(self):\n \"\"\"The number of samples\"\"\"\n return len(self.corr) + len(self.err) + self.undecided\n def __iter__(self):\n \"\"\"Iterate through each reaction time, with no regard to whether it was a correct or error trial.\"\"\"\n return np.concatenate([self.corr, self.err]).__iter__()\n def __eq__(self, other):\n if not np.allclose(self.corr, other.corr) or \\\n not np.allclose(self.err, other.err) or \\\n self.undecided != other.undecided:\n return False\n for k in self.conditions:\n if k not in other.conditions:\n return False\n if np.issubdtype(self.conditions[k][0].dtype, np.floating) and \\\n np.issubdtype(self.conditions[k][0].dtype, np.floating):\n compare_func = np.allclose\n else:\n compare_func = lambda x,y: np.all(x == y)\n if not compare_func(self.conditions[k][0], other.conditions[k][0]) or \\\n not compare_func(self.conditions[k][1], other.conditions[k][1]):\n return False\n if len(self.conditions[k]) == 3 and \\\n len(other.conditions[k]) == 3 and \\\n not compare_func(self.conditions[k][2], other.conditions[k][2]):\n return False\n return True\n def __add__(self, other):\n assert sorted(self.conditions.keys()) == sorted(other.conditions.keys()), \"Canot add with unlike conditions\"\n corr = np.concatenate([self.corr, other.corr])\n err = np.concatenate([self.err, other.err])\n undecided = self.undecided + other.undecided\n conditions = {}\n for k in self.conditions.keys():\n sc = self.conditions\n oc = other.conditions\n bothc = np.concatenate([sc[k][0], oc[k][0]])\n bothe = np.concatenate([sc[k][1], oc[k][1]])\n bothn = np.concatenate([sc[k][2] if len(sc[k]) == 3 else [],\n oc[k][2] if len(oc[k]) == 3 else []])\n conditions[k] = (bothc, bothe, bothn)\n return Sample(corr, err, undecided, **conditions)\n @staticmethod\n @accepts(NDArray(d=2, t=Number), List(String))\n @returns(Self)\n @requires('data.shape[1] >= 2')\n @requires('set(list(data[:,1])) - {0, 1} == set()')\n @requires('all(data[:,0].astype(\"float\") == data[:,0])')\n @requires('data.shape[1] - 2 == len(column_names)')\n @ensures('len(column_names) == len(return.condition_names())')\n def from_numpy_array(data, column_names):\n \"\"\"Generate a Sample object from a numpy array.\n \n `data` should be an n x m array (n rows, m columns) where\n m>=2. The first column should be the response times, and the\n second column should be whether the trial was correct or an\n error (1 == correct, 0 == error). Any remaining columns\n should be conditions. `column_names` should be a list of\n length m of strings indicating the names of the conditions.\n The order of the names should correspond to the order of the\n columns. This function does not yet work with undecided\n trials.\n \"\"\"\n c = data[:,1].astype(bool)\n nc = (1-data[:,1]).astype(bool)\n def pt(x): # Pythonic types\n arr = np.asarray(x)\n if np.all(arr == np.round(arr)):\n arr = arr.astype(int)\n return arr\n\n conditions = {k: (pt(data[c,i+2]), pt(data[nc,i+2]), np.asarray([])) for i,k in enumerate(column_names)}\n return Sample(pt(data[c,0]), pt(data[nc,0]), 0, **conditions)\n @staticmethod\n @accepts(Unchecked, String, String) # TODO change unchecked to pandas\n @returns(Self)\n @requires('df.shape[1] >= 2')\n @requires('rt_column_name in df')\n @requires('correct_column_name in df')\n @requires('not np.any(df.isnull())')\n @requires('len(np.setdiff1d(df[correct_column_name], [0, 1])) == 0')\n @requires('all(df[rt_column_name].astype(\"float\") == df[rt_column_name])')\n @ensures('len(df) == len(return)')\n def from_pandas_dataframe(df, rt_column_name, correct_column_name):\n \"\"\"Generate a Sample object from a pandas dataframe.\n \n `df` should be a pandas array. `rt_column_name` and\n `correct_column_name` should be strings, and `df` should\n contain columns by these names. The column with the name\n `rt_column_name` should be the response times, and the column\n with the name `correct_column_name` should be whether the\n trial was correct or an error (1 == correct, 0 == error). Any\n remaining columns should be conditions. This function does\n not yet work with undecided trials.\n \"\"\"\n if np.mean(df[rt_column_name]) > 50:\n print(\"Warning: RTs should be specified in seconds, not milliseconds\")\n c = df[correct_column_name].astype(bool)\n nc = (1-df[correct_column_name]).astype(bool)\n def pt(x): # Pythonic types\n arr = np.asarray(x)\n if np.all(arr == np.round(arr)):\n arr = arr.astype(int)\n return arr\n\n column_names = [e for e in df.columns if not e in [rt_column_name, correct_column_name]]\n conditions = {k: (pt(df[c][k]), pt(df[nc][k]), np.asarray([])) for k in column_names}\n return Sample(pt(df[c][rt_column_name]), pt(df[nc][rt_column_name]), 0, **conditions)\n def items(self, correct):\n \"\"\"Iterate through the reaction times.\n\n This takes only one argument: a boolean `correct`, true if we\n want to iterate through the correct trials, and false if we\n want to iterate through the error trials. \n\n For each iteration, a two-tuple is returned. The first\n element is the reaction time, the second is a dictionary\n containing the conditions associated with that reaction time.\n\n If you just want the list of RTs, you can directly iterate\n through \"sample.corr\" and \"sample.err\".\n \"\"\"\n return _Sample_Iter_Wraper(self, correct=correct)\n @accepts(Self)\n @returns(Self)\n def subset(self, **kwargs):\n \"\"\"Subset the data by filtering based on specified properties.\n\n Each keyword argument should be the name of a property. These\n keyword arguments may have one of three values:\n\n - A list: For each element in the returned subset, the\n specified property is in this list of values.\n - A function: For each element in the returned subset, the\n specified property causes the function to evaluate to True.\n - Anything else: Each element in the returned subset must have\n this value for the specified property.\n\n Return a sample object representing the filtered sample.\n \"\"\"\n mask_corr = np.ones(len(self.corr)).astype(bool)\n mask_err = np.ones(len(self.err)).astype(bool)\n mask_undec = np.ones(self.undecided).astype(bool)\n for k,v in kwargs.items():\n if hasattr(v, '__call__'):\n mask_corr = np.logical_and(mask_corr, [v(i) for i in self.conditions[k][0]])\n mask_err = np.logical_and(mask_err, [v(i) for i in self.conditions[k][1]])\n mask_undec = np.asarray([], dtype=bool) if self.undecided == 0 else np.logical_and(mask_undec, [v(i) for i in self.conditions[k][2]])\n elif hasattr(v, '__contains__'):\n mask_corr = np.logical_and(mask_corr, [i in v for i in self.conditions[k][0]])\n mask_err = np.logical_and(mask_err, [i in v for i in self.conditions[k][1]])\n mask_undec = np.asarray([], dtype=bool) if self.undecided == 0 else np.logical_and(mask_undec, [i in v for i in self.conditions[k][2]])\n else:\n mask_corr = np.logical_and(mask_corr, v == self.conditions[k][0])\n mask_err = np.logical_and(mask_err, v == self.conditions[k][1])\n mask_undec = np.asarray([], dtype=bool) if self.undecided == 0 else np.logical_and(mask_undec, v == self.conditions[k][2])\n for k,v in self.conditions.items():\n assert len(v[0]) == len(mask_corr)\n assert len(v[1]) == len(mask_err)\n assert mask_corr.dtype == bool\n if len(v) == 3:\n assert len(v[2]) == len(mask_undec)\n v[2][mask_undec] if len(v) == 3 else np.asarray([])\n filtered_conditions = {k : (v[0][mask_corr.astype(bool)],\n v[1][mask_err.astype(bool)],\n (v[2][mask_undec.astype(bool)] if len(v) == 3 else np.asarray([])))\n for k,v in self.conditions.items()}\n return Sample(self.corr[mask_corr],\n self.err[mask_err],\n sum(mask_undec),\n **filtered_conditions)\n @accepts(Self)\n @returns(List(String))\n def condition_names(self):\n \"\"\"The names of conditions which hold some non-zero value in this sample.\"\"\"\n return list(self.conditions.keys())\n @accepts(Self, String)\n @requires('cond in self.condition_names()')\n @returns(List(Unchecked))\n def condition_values(self, cond):\n \"\"\"The values of a condition that have at least one element in the sample.\n\n `cond` is the name of the condition from which to get the\n observed values. Returns a list of these values.\n \"\"\"\n cs = self.conditions\n cvs = set(cs[cond][0]).union(set(cs[cond][1]))\n if len(cs[cond]) == 3:\n cvs = cvs.union(set(cs[cond][2]))\n return sorted(list(cvs))\n @accepts(Self, Maybe(List(String)))\n @returns(List(Conditions))\n def condition_combinations(self, required_conditions=None):\n \"\"\"Get all values for set conditions and return every combination of them.\n\n Since PDFs of solved models in general depend on all of the\n conditions, this returns a list of dictionaries. The keys of\n each dictionary are the names of conditions, and the value is\n a particular value held by at least one element in the sample.\n Each list contains all possible combinations of condition values.\n\n If `required_conditions` is iterable, only the conditions with\n names found within `required_conditions` will be included.\n \"\"\"\n cs = self.conditions\n conditions = []\n names = self.condition_names()\n if required_conditions is not None:\n names = [n for n in names if n in required_conditions]\n for c in names:\n conditions.append(list(set(cs[c][0]).union(set(cs[c][1]))))\n combs = []\n for p in itertools.product(*conditions):\n if len(self.subset(**dict(zip(names, p)))) != 0:\n combs.append(dict(zip(names, p)))\n if len(combs) == 0: # Generally not needed since iterools.product does this\n return [{}]\n return combs\n\n @staticmethod\n @accepts(dt=Positive, T_dur=Positive)\n @returns(NDArray(d=1, t=Positive0))\n #@requires('T_dur/dt < 1e5') # Too large of a number\n def t_domain(dt=.01, T_dur=2):\n \"\"\"The times that corresponds with pdf/cdf_corr/err parameters (their support).\"\"\"\n return np.linspace(0, T_dur, int(T_dur/dt)+1)\n\n @accepts(Self, dt=Positive, T_dur=Positive)\n @returns(NDArray(d=1, t=Positive0))\n #@requires('T_dur/dt < 1e5') # Too large of a number\n @ensures('len(return) == len(self.t_domain(dt=dt, T_dur=T_dur))')\n def pdf_corr(self, dt=.01, T_dur=2):\n \"\"\"The correct component of the joint PDF.\"\"\"\n return np.histogram(self.corr, bins=int(T_dur/dt)+1, range=(0-dt/2, T_dur+dt/2))[0]/len(self)/dt # dt/2 terms are for continuity correction\n\n @accepts(Self, dt=Positive, T_dur=Positive)\n @returns(NDArray(d=1, t=Positive0))\n #@requires('T_dur/dt < 1e5') # Too large of a number\n @ensures('len(return) == len(self.t_domain(dt=dt, T_dur=T_dur))')\n def pdf_err(self, dt=.01, T_dur=2):\n \"\"\"The error (incorrect) component of the joint PDF.\"\"\"\n return np.histogram(self.err, bins=int(T_dur/dt)+1, range=(0-dt/2, T_dur+dt/2))[0]/len(self)/dt # dt/2 terms are for continuity correction\n\n @accepts(Self, dt=Positive, T_dur=Positive)\n @returns(NDArray(d=1, t=Positive0))\n #@requires('T_dur/dt < 1e5') # Too large of a number\n @ensures('len(return) == len(self.t_domain(dt=dt, T_dur=T_dur))')\n def cdf_corr(self, dt=.01, T_dur=2):\n \"\"\"The correct component of the joint CDF.\"\"\"\n return np.cumsum(self.pdf_corr(dt=dt, T_dur=T_dur))*dt\n\n @accepts(Self, dt=Positive, T_dur=Positive)\n @returns(NDArray(d=1, t=Positive0))\n @ensures('len(return) == len(self.t_domain(dt=dt, T_dur=T_dur))')\n def cdf_err(self, dt=.01, T_dur=2):\n \"\"\"The error (incorrect) component of the joint CDF.\"\"\"\n return np.cumsum(self.pdf_err(dt=dt, T_dur=T_dur))*dt\n\n @accepts(Self)\n @returns(Range(0, 1))\n @requires(\"len(self) > 0\")\n def prob_correct(self):\n \"\"\"The probability of selecting the right response.\"\"\"\n return len(self.corr)/len(self)\n\n @accepts(Self)\n @returns(Range(0, 1))\n @requires(\"len(self) > 0\")\n def prob_error(self):\n \"\"\"The probability of selecting the incorrect (error) response.\"\"\"\n return len(self.err)/len(self)\n\n @accepts(Self)\n @returns(Range(0, 1))\n @requires(\"len(self) > 0\")\n def prob_undecided(self):\n \"\"\"The probability of selecting neither response (undecided).\"\"\"\n return self.undecided/len(self)\n\n @accepts(Self)\n @returns(Range(0, 1))\n @requires(\"len(self) > 0\")\n def prob_correct_forced(self):\n \"\"\"The probability of selecting the correct response if a response is forced.\"\"\"\n return self.prob_correct() + self.prob_undecided()/2.\n\n @accepts(Self)\n @returns(Range(0, 1))\n @requires(\"len(self) > 0\")\n def prob_error_forced(self):\n \"\"\"The probability of selecting the incorrect response if a response is forced.\"\"\"\n return self.prob_error() + self.prob_undecided()/2.\n\n @accepts(Self)\n @requires(\"len(self.corr) > 0\")\n @returns(Positive0)\n def mean_decision_time(self):\n \"\"\"The mean decision time in the correct trials.\"\"\"\n return np.mean(self.corr)\n\nclass _Sample_Iter_Wraper(object):\n \"\"\"Provide an iterator for sample objects.\n\n `sample_obj` is the Sample which we plan to iterate. `correct`\n should be either True (to iterate through correct responses) or\n False (to iterate through error responses).\n\n Each step of the iteration returns a two-tuple, where the first\n element is the reaction time, and the second element is a\n dictionary of conditions.\n \"\"\"\n def __init__(self, sample_obj, correct):\n self.sample = sample_obj\n self.i = 0\n self.correct = correct\n if self.correct:\n self.rt = self.sample.corr\n self.ind = 0\n elif not self.correct:\n self.rt = self.sample.err\n self.ind = 1\n def __iter__(self):\n return self\n def __next__(self):\n if self.i == len(self.rt):\n raise StopIteration\n self.i += 1\n return (self.rt[self.i-1], {k : self.sample.conditions[k][self.ind][self.i-1] for k in self.sample.conditions.keys()})\n \n"
]
| [
[
"numpy.concatenate",
"numpy.asarray",
"numpy.round",
"numpy.ones",
"numpy.mean",
"numpy.logical_and",
"numpy.allclose",
"numpy.all",
"numpy.issubdtype"
]
]
|
jpnm561/HAR-UP | [
"04243d1e22d1aaac10aaa403604fc7965b6d4c47"
]
| [
"CameraOF_files/resizeOF.py"
]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 11 14:27:56 2019\n\n@author: José Pablo\n\"\"\"\n\nfrom PIL import Image\nimport numpy as np\nfrom numpy import genfromtxt\nimport os\nfrom createFolder import createFolder\nfrom progressBar import progressBar\nimport sys\n\n#A function to replace dashes in the timestamps with colons\ndef tstGT(st):\n st = st.replace('_',':')\n return st[:-6]\n\n#A function to make a 20x20 resize to csv containing the image features\ndef resCSV(file):\n #An image is generated from the csv file\n g = open(file,'r')\n temp = genfromtxt(g, delimiter = ',')\n g.close()\n arr = np.array(temp,dtype=np.float32)\n rzero = np.min(arr)\n arr = arr + np.abs(rzero)\n r255 = np.amax(arr)\n if r255 != 0:\n fcon = 255/r255\n arr = arr*fcon\n img = Image.fromarray(arr).convert('RGB') \n img = img.resize((20, 20), Image.ANTIALIAS)\n img.load()\n data = np.asarray( img, dtype=np.float32)\n narr = []\n for i in range(0,20):\n #rows\n tmp = []\n for j in range(0,20):\n #columns\n tmp.append(data[i][j][0])\n narr.append(tmp)\n return narr\n\n#A function to get the magnitude from each change, from v and u\ndef sqrd(arru, arrv):\n tmp1 = np.square(arru,dtype=np.float32)\n tmp2 = np.square(arru,dtype=np.float32)\n tmp = np.add(tmp1,tmp2,dtype=np.float32)\n arrf = np.sqrt(tmp,dtype=np.float32)\n return(arrf)\n\ndef camOF_joiner(gral,\n rs_path,\n n_sub=[1,17],\n n_act=[1,11],\n n_trl=[1,3],\n n_cam=[1,2]):\n cmr = []\n interrupt = False\n for cam in n_cam:\n cmr.append('Camera'+str(cam)+'_OF_UZ//')\n for i in range(n_sub[0],n_sub[1]+1):\n if interrupt:\n break\n sub = 'Subject' + str(i)\n print(sub)\n for j in range(n_act[0],n_act[1]+1):\n if interrupt:\n break\n act = 'Activity' + str(j)\n print('S'+str(i)+'--'+act)\n for k in range(n_trl[0],n_trl[1]+1):\n if interrupt:\n break\n trl = 'Trial' + str(k)\n print('S'+str(i)+'-A'+str(j)+'--'+trl)\n path = gral+sub+'//'+act+'//'+trl+'//'+sub+act+trl+cmr[0]\n #path = gral+trl+'//'+sub+act+trl+cmr[0]\n path2 = gral+sub+'//'+act+'//'+trl+'//'+sub+act+trl+cmr[1]\n if os.path.exists(path) and os.path.exists(path2):\n files = os.listdir(path)\n files2 = os.listdir(path2)\n if len(files)==len(files2):\n p = 0\n n_path = rs_path+sub+'//'+act+'//'\n createFolder(n_path)\n n_file = sub+act+trl+'CameraResizedOF_notag.csv'\n print('----------Writing...')\n w = open(n_path+n_file,'w')\n try:\n w.write('Timestamp')\n for z in range(n_cam[0],n_cam[1]+1):\n for q in range(0,20):\n for r in range(0,20):\n w.write(',C'+str(z)+'('+str(q)+';'+str(r)+')')\n w.write(',Subject,Activity,Trial')\n print('------------Joining ' + str(len(files)) + ' files')\n while p < len(files):\n if p % 2 == 0:\n npath = path + files[p]\n npath2 = path2 + files[p]\n tst = tstGT(files[p])\n arr1 = resCSV(npath)\n sar1 = resCSV(npath2)\n p+=1\n npath = path + files[p]\n npath2 = path2 + files[p]\n arr2 = resCSV(npath)\n sar2 = resCSV(npath2)\n arrf = sqrd(arr1,arr2)\n sarf = sqrd(sar1,sar2)\n w.write('\\n'+tst)\n for q in range(0,20):\n for r in range(0,20):\n w.write(','+str(arrf[i][j]))\n for q in range(0,20):\n for r in range(0,20):\n w.write(','+str(sarf[i][j]))\n w.write(','+str(i)+','+str(j)+','+str(k))\n progressBar('-------------Progress',p,len(files),width=2)\n p+=1\n except KeyboardInterrupt:\n print(\"\\nThe program has been interrupted.\")\n interrupt = True\n except Exception as e:\n print('-----------Unexpected error: ' + str(e))\n w.close()\n if not interrupt:\n print('\\n------------'+n_file+' has been successfully created.' )\n else:\n print('------------Images from paths ' + path +' and ' +path2 + ' do not fit')\n\ndef main():\n OF_path = ''\n resize_path = ''\n camOF_joiner(OF_path,resize_path)\n print('End of task')\n \nif __name__ == \"__main__\":\n main()\n"
]
| [
[
"numpy.square",
"numpy.array",
"numpy.add",
"numpy.asarray",
"numpy.genfromtxt",
"numpy.min",
"numpy.amax",
"numpy.sqrt",
"numpy.abs"
]
]
|
arpita221b/Hacktoberfest-2k19-1 | [
"6f682ea2226a8ce6f5a913da9ecdafff7a9fa5bd"
]
| [
"machineLearning/KNN/knn.py"
]
| [
"\"\"\"\r\nA knn classifier predicts which class a point p should belong to. To do this we loop through\r\nall the points and find the distance of p from each point. We then sort these\r\nindices ie., we get an array with the sorted indices(find_nearest_neighbours).\r\nWe then select the first k of these indices and find to which class do majority \r\nof the k points lie using the majority votes function. knn_predict returns this\r\nclass\r\n\r\n\"\"\" \r\nimport numpy as np\r\n\r\ndef distance(p1,p2):\r\n \"\"\" \r\n Returns the eucledian distance between two points p1 and p2.\r\n \"\"\"\r\n #TODO\r\n\r\n\r\n\r\ndef majority_votes(votes):\r\n \"\"\"\r\n Votes is a list.\r\n Returns the vote (in votes) with maximum counts and a random maximum in case of a tie.\r\n Constructs the count of votes as a dictionary with keys as the votes and \r\n values as the counts of the votes. You may use library functions like mode in scipy.stats.mstats or write your own code.\r\n \"\"\"\r\n #TODO\r\n\r\n\r\ndef find_nearest_neighbours(p, points, k=5):\r\n \"\"\")\r\n Find k nearest neighbours of p and return their indices\r\n p : Point to classify\r\n points : List of predictors\r\n \"\"\"\r\n #Finding nearest neighbours- pseudocode\r\n #loop over all the points\r\n # find the distance between p and every other point\r\n # sort the distances and return thek nearest points\r\n\r\n #TODO\r\n \r\n\r\n#classes to which the k points belong is given by outcomes\r\ndef knn_predict(p, points, outcomes, k=5):\r\n \"\"\"\r\n Use find_nearest_neighbors and majority_votes to predict the class to which the class p belongs\r\n p : Point to classify\r\n points : List of predictors\r\n outcomes : List Containing the possible outcomes/targets.\r\n \"\"\"\r\n #TODO\r\n\r\n\r\n\r\n### kNN on the iris dataset ###\r\n\r\n## Load the IRIS dataset.\r\nfrom sklearn import datasets\r\niris = datasets.load_iris()\r\n\r\npredictors = iris.data\r\noutcomes = iris.target\r\n\r\n## Using sklearn's KNN Classifier ##\r\n\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nknn = KNeighborsClassifier(n_neighbors = 5)\r\nknn.fit(predictors, outcomes)\r\nsk_predictions = knn.predict(predictors)\r\n\r\n\r\n## Using the classifier we built\r\nmy_predictions = np.array([knn_predict(p, predictors, outcomes, k=5) for p in predictors])\r\n\r\n\r\n# Test and compare our model\r\n\r\nnp.mean(my_predictions == sk_predictions)\r\n\r\nnp.mean(my_predictions == outcomes)\r\n\r\nnp.mean(sk_predictions == outcomes)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n "
]
| [
[
"sklearn.neighbors.KNeighborsClassifier",
"numpy.mean",
"sklearn.datasets.load_iris"
]
]
|
kekedan/PhotoWakeUpHMR | [
"d78b091ed320669efb0cd0a828891d655e7d1620"
]
| [
"PhotoWakeUpDepthMaps.py"
]
| [
"\"\"\"\nDemo of HMR.\n\nNote that HMR requires the bounding box of the person in the image. The best performance is obtained when max length of the person in the image is roughly 150px. \n\nWhen only the image path is supplied, it assumes that the image is centered on a person whose length is roughly 150px.\nAlternatively, you can supply output of the openpose to figure out the bbox and the right scale factor.\n\nSample usage:\n\n# On images on a tightly cropped image around the person\npython -m demo --img_path data/im1963.jpg\npython -m demo --img_path data/coco1.png\n\n# On images, with openpose output\npython -m demo --img_path data/random.jpg --json_path data/random_keypoints.json\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nfrom absl import flags\nimport numpy as np\n\nimport json\n\nimport cv2\n\nimport skimage.io as io\nimport tensorflow as tf\n\nfrom src.util import depthRenderer as vis_util\nfrom src.util import image as img_util\nfrom src.util import openpose as op_util\nimport src.config\nfrom src.RunModel import RunModel\n\n\ndef visualize(img, proc_param, joints, verts, cam, img_path):\n \"\"\"\n Renders the result in original image coordinate frame.\n \"\"\"\n cam_for_render, vert_shifted, joints_orig = vis_util.get_original(\n proc_param, verts, cam, joints, img_size=img.shape[:2])\n\n folder = '/'.join(img_path.split('/')[0:-1])\n print(\"FOLDER!!!!!!!!!!!\")\n print(folder)\n\n # Render results\n config = flags.FLAGS\n config(sys.argv)\n # Using pre-trained model, change this to use your own.\n config.load_path = src.config.PRETRAINED_MODEL\n\n config.batch_size = 1\n renderer = vis_util.SMPLRenderer(face_path=config.smpl_face_path)\n\n # skel_img = vis_util.draw_skeleton(img, joints_orig)\n # rend_img_overlay = renderer(\n # vert_shifted, cam=cam_for_render, img=img, do_alpha=True)\n rend_img = renderer(\n vert_shifted, cam=cam_for_render, img_size=img.shape[:2])\n # rend_img_vp1 = renderer.rotated(\n # vert_shifted, 60, cam=cam_for_render, img_size=img.shape[:2])\n rend_img_vp2 = renderer.rotated(\n vert_shifted, 180, cam=cam_for_render, img_size=img.shape[:2])\n\n depthMapPath = folder + '/depthMap.png'\n print(\"Saving Depth Map to:\")\n print(depthMapPath)\n\n cv2.imwrite(depthMapPath, rend_img)\n # cv2.imshow('Depth Map',rend_img) \n # cv2.waitKey(0)\n\n depthMapPath = folder + '/depthMapBack.png'\n print(\"Saving Depth Map to:\")\n print(depthMapPath) \n\n cv2.imwrite(depthMapPath, rend_img_vp2)\n # cv2.imshow('Depth Map',rend_img_vp2) \n # cv2.waitKey(0)\n\n # cv2.destroyAllWindows() \n\n # import matplotlib.pyplot as plt\n\n # plt.ion()\n\n # plt.figure(1)\n # plt.clf()\n # plt.subplot(231)\n # plt.imshow(img)\n # plt.title('input')\n # plt.axis('off')\n # plt.subplot(232)\n # plt.imshow(skel_img)\n # plt.title('joint projection')\n # plt.axis('off')\n # plt.subplot(233)\n # plt.imshow(rend_img_overlay)\n # plt.title('3D Mesh overlay')\n # plt.axis('off')\n # plt.subplot(234)\n # plt.imshow(rend_img)\n # plt.title('3D mesh')\n # plt.axis('off')\n # plt.subplot(235)\n # plt.imshow(rend_img_vp1)\n # plt.title('diff vp')\n # plt.axis('off')\n # plt.subplot(236)\n # plt.imshow(rend_img_vp2)\n # plt.title('diff vp')\n # plt.axis('off')\n # plt.draw()\n # plt.show()\n\n\n # import ipdb\n # ipdb.set_trace()\n\n\ndef preprocess_image(img_path, json_path=None):\n img = io.imread(img_path)\n if img.shape[2] == 4:\n img = img[:, :, :3]\n\n if json_path is None:\n if np.max(img.shape[:2]) != config.img_size:\n print('Resizing so the max image size is %d..' % config.img_size)\n scale = (float(config.img_size) / np.max(img.shape[:2]))\n else:\n scale = 1.\n center = np.round(np.array(img.shape[:2]) / 2).astype(int)\n # image center in (x,y)\n center = center[::-1]\n else:\n scale, center = op_util.get_bbox(json_path)\n\n crop, proc_param = img_util.scale_and_crop(img, scale, center,\n config.img_size)\n\n # Normalize image to [-1, 1]\n crop = 2 * ((crop / 255.) - 0.5)\n\n return crop, proc_param, img\n\n\ndef main(img_path, json_path=None):\n sess = tf.Session()\n model = RunModel(config, sess=sess)\n\n input_img, proc_param, img = preprocess_image(img_path, json_path)\n # Add batch dimension: 1 x D x D x 3\n input_img = np.expand_dims(input_img, 0)\n\n joints, verts, cams, joints3d, theta = model.predict(\n input_img, get_theta=True)\n\n visualize(img, proc_param, joints[0], verts[0], cams[0], img_path)\n\n #print(theta)\n theta_out = theta.tolist()\n with open('results/HMR_value_out.json', 'w') as outfile: \n\t json.dump([theta_out], outfile)\n\nif __name__ == '__main__':\n config = flags.FLAGS\n config(sys.argv)\n # Using pre-trained model, change this to use your own.\n config.load_path = src.config.PRETRAINED_MODEL\n\n config.batch_size = 1\n\n renderer = vis_util.SMPLRenderer(face_path=config.smpl_face_path)\n\n main(config.img_path, config.json_path)\n"
]
| [
[
"numpy.max",
"numpy.array",
"tensorflow.Session",
"numpy.expand_dims"
]
]
|
deephog/BASNet | [
"7770bc69f00b2bb7421c6ea7b26f38f6ca02082f"
]
| [
"wandb/run-20210618_113342-dapqogt7/files/code/basnet_train.py"
]
| [
"import torch\nimport torchvision\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\nimport torch.optim as optim\nimport wandb\nimport torchvision.transforms as standard_transforms\n\nimport numpy as np\nimport sys\nimport glob\nimport time\n\nfrom data_loader import Rescale\nfrom data_loader import RescaleT\nfrom data_loader import RandomCrop, OtherTrans\nfrom data_loader import CenterCrop\nfrom data_loader import ToTensor\nfrom data_loader import ToTensorLab\nfrom data_loader import SalObjDataset\nfrom data import get_loader\n\nfrom skimage import io\n\nfrom model import BASNet\n\nimport pytorch_ssim\nimport pytorch_iou\nimport os\n# ------- 1. define loss function --------\n\nbce_loss = nn.BCELoss(size_average=True)\nssim_loss = pytorch_ssim.SSIM(window_size=11,size_average=True)\niou_loss = pytorch_iou.IOU(size_average=True)\n\nhyperparameter_defaults = {\n \"gpu\": '0',\n \"learning_rate\": 1e-4,\n \"lr_decay\": 0,\n \"epochs\": 1000,\n \"batch_size\": 2,\n \"checkpoint\": False,\n \"load_pretrained\": True,\n \"trainsize\": 416,\n \"model_dir\": \"./saved_models/basnet_bsi_random_fr0.2_pb_0.2/\"\n}\n\nrun = wandb.init(project='basnet_refine', config=hyperparameter_defaults, save_code='on', mode='online', reinit=True)\nconfig = run.config\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = config.gpu\ndef bce_ssim_loss(pred,target):\n\n bce_out = bce_loss(pred,target)\n ssim_out = 1 - ssim_loss(pred,target)\n iou_out = iou_loss(pred,target)\n\n loss = bce_out + ssim_out + iou_out\n\n return loss\n\ndef muti_bce_loss_fusion(d0, d1, d2, d3, d4, d5, d6, d7, labels_v):\n\n loss0 = bce_ssim_loss(d0,labels_v)\n loss1 = bce_ssim_loss(d1,labels_v)\n loss2 = bce_ssim_loss(d2,labels_v)\n loss3 = bce_ssim_loss(d3,labels_v)\n loss4 = bce_ssim_loss(d4,labels_v)\n loss5 = bce_ssim_loss(d5,labels_v)\n loss6 = bce_ssim_loss(d6,labels_v)\n loss7 = bce_ssim_loss(d7,labels_v)\n #ssim0 = 1 - ssim_loss(d0,labels_v)\n\n # iou0 = iou_loss(d0,labels_v)\n #loss = torch.pow(torch.mean(torch.abs(labels_v-d0)),2)*(5.0*loss0 + loss1 + loss2 + loss3 + loss4 + loss5) #+ 5.0*lossa\n loss = loss0 + loss1 + loss2 + loss3 + loss4 + loss5 + loss6 + loss7#+ 5.0*lossa\n # print(\"l0: %3f, l1: %3f, l2: %3f, l3: %3f, l4: %3f, l5: %3f, l6: %3f\\n\"%(loss0.data[0],loss1.data[0],loss2.data[0],loss3.data[0],loss4.data[0],loss5.data[0],loss6.data[0]))\n # print(\"BCE: l1:%3f, l2:%3f, l3:%3f, l4:%3f, l5:%3f, la:%3f, all:%3f\\n\"%(loss1.data[0],loss2.data[0],loss3.data[0],loss4.data[0],loss5.data[0],lossa.data[0],loss.data[0]))\n #print(\"\\r l0: %3f, l1: %3f, l2: %3f, l3: %3f, l4: %3f, l5: %3f\" % (loss1.item(), loss2.item(), loss3.item(), loss4.item(), loss5.item(), loss6.item()))\n return loss0, loss\n\n\n# ------- 2. set the directory of training dataset --------\n\ndata_dir = '/home/hypevr/Desktop/data/projects/data/combined_human/'\ntra_image_dir = 'train/image/'\ntra_label_dir = 'train/mask/'\n\nte_image_dir = 'val/image/'\nte_label_dir = 'val/mask/'\n\n# tra_image_dir = 'dummy_img/'\n# tra_label_dir = 'dummy_gt/'\n#\n# te_image_dir = 'dummy_img/'\n# te_label_dir = 'dummy_gt/'\n\nimage_ext = '.jpg'\nlabel_ext = '.jpg'\n\nmodel_dir = config.model_dir\n\n##############################\ncheckpoint = config.checkpoint\nload_pretrained = config.load_pretrained\n#############################\n\nif checkpoint:\n checkpoint_dir = model_dir + 'basnet_' + str(checkpoint) + '.pth'\n\nif load_pretrained:\n checkpoint_dir = './saved_models/basnet_bsi/basnet.pth'\n\nepoch_num = config.epochs\nbatch_size_train = config.batch_size\nbatch_size_val = config.batch_size\ntrain_num = 0\nval_num = 0\n\ntra_img_name_list = glob.glob(data_dir + tra_image_dir + '*' + image_ext)\nte_img_name_list = glob.glob(data_dir + te_image_dir + '*' + image_ext)\n\ntra_lbl_name_list = []\nte_lbl_name_list = []\n\n\nfor img_path in tra_img_name_list:\n img_name = img_path.split(\"/\")[-1]\n\n aaa = img_name.split(\".\")\n bbb = aaa[0:-1]\n imidx = bbb[0]\n for i in range(1,len(bbb)):\n imidx = imidx + \".\" + bbb[i]\n\n tra_lbl_name_list.append(data_dir + tra_label_dir + imidx + label_ext)\n\nfor img_path in te_img_name_list:\n img_name = img_path.split(\"/\")[-1]\n\n aaa = img_name.split(\".\")\n bbb = aaa[0:-1]\n imidx = bbb[0]\n for i in range(1,len(bbb)):\n imidx = imidx + \".\" + bbb[i]\n\n te_lbl_name_list.append(data_dir + te_label_dir + imidx + label_ext)\n\nprint(\"---\")\nprint(\"train images: \", len(tra_img_name_list))\nprint(\"train labels: \", len(tra_lbl_name_list))\nprint(\"test images: \", len(te_img_name_list))\nprint(\"test labels: \", len(te_lbl_name_list))\nprint(\"---\")\n\ntrain_num = len(tra_img_name_list)\nval_num = len(te_img_name_list)\n\n\n# salobj_dataset = SalObjDataset(\n# img_name_list=tra_img_name_list,\n# lbl_name_list=tra_lbl_name_list,\n# img_transform=transforms.Compose([OtherTrans()]),\n# transform=transforms.Compose([\n# RescaleT(512),\n# RandomCrop(352),\n# ToTensorLab(flag=0),\n# ]))\n#\n# salobj_dataset_te = SalObjDataset(\n# img_name_list=te_img_name_list,\n# lbl_name_list=te_lbl_name_list,\n# transform=transforms.Compose([\n# RescaleT(352),\n# #RandomCrop(224),\n# ToTensorLab(flag=0),\n# ]))\n#salobj_dataloader = DataLoader(salobj_dataset, batch_size=batch_size_train, shuffle=True, num_workers=1)\n#salobj_dataloader_te = DataLoader(salobj_dataset_te, batch_size=1, shuffle=False, num_workers=1)\nback_dir = '/home/hypevr/Desktop/data/projects/background/image/'\n\nsalobj_dataloader = get_loader(data_dir+tra_image_dir, data_dir+tra_label_dir, batchsize=config.batch_size, trainsize=config.trainsize, fake_back_rate=0.2, back_dir=back_dir, pure_back_rate=0.2)\nsalobj_dataloader_te = get_loader(data_dir+te_image_dir, data_dir+te_label_dir, batchsize=config.batch_size, trainsize=config.trainsize, fake_back_rate=0, back_dir=None)\n\n# ------- 3. define model --------\n# define the net\nnet = BASNet(3, 1)\nif torch.cuda.is_available():\n net.cuda()\n\nif checkpoint or load_pretrained:\n net.load_state_dict(torch.load(checkpoint_dir))\n\ntorch.cuda.empty_cache()\n# ------- 4. define optimizer --------\nprint(\"---define optimizer...\")\noptimizer = optim.Adam(net.parameters(), lr=config.learning_rate, betas=(0.9, 0.999), eps=1e-08, weight_decay=config.lr_decay)\n\n# ------- 5. training process --------\nprint(\"---start training...\")\nite_num = 0\nrunning_loss = 0.0\nrunning_tar_loss = 0.0\nite_num4val = 0\n\nfor epoch in range(0, epoch_num):\n if checkpoint:\n epoch += checkpoint\n\n net.train()\n start_time = time.time()\n\n for i, data in enumerate(salobj_dataloader):\n if not i == 0:\n sys.stdout.write(\"\\033[F\")\n sys.stdout.write(\"\\033[K\")\n\n ite_num = ite_num + 1\n ite_num4val = ite_num4val + 1\n\n inputs, labels = data\n\n # print(inputs.shape)\n #\n # io.imsave('temp.jpg', inputs[0, 0, :, :]*255)\n # io.imsave('temp.png', labels[0, 0, :, :]*255)\n # input('wait')\n\n inputs = inputs.type(torch.FloatTensor)\n labels = labels.type(torch.FloatTensor)\n\n # wrap them in Variable\n if torch.cuda.is_available():\n inputs_v, labels_v = Variable(inputs.cuda(), requires_grad=False), Variable(labels.cuda(),\n requires_grad=False)\n else:\n inputs_v, labels_v = Variable(inputs, requires_grad=False), Variable(labels, requires_grad=False)\n\n # y zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n d0, d1, d2, d3, d4, d5, d6, d7 = net(inputs_v)#\n loss0, loss = muti_bce_loss_fusion(d0, d1, d2, d3, d4, d5, d6, d7, labels_v) #loss2\n\n loss.backward()\n optimizer.step()\n\n # # print statistics\n running_loss += loss.item()\n running_tar_loss += loss0.item()\n\n # del temporary outputs and loss\n del d0, loss#d1, d2, d3, d4, d5, loss2, loss\n\n print(\"[epoch: %3d/%3d, batch: %5d/%5d, ite: %d] train loss: %3f, tar: %3f , time_lapse: %3f\" % (\n epoch + 1, epoch_num, (i + 1) * batch_size_train, train_num, ite_num, running_loss / ite_num4val,\n running_tar_loss / ite_num4val, time.time()-start_time))\n\n wandb.log({'epochs': epoch,\n 'train_loss': float(running_tar_loss / ite_num4val),\n })\n\n if epoch % 2 == 1: # save model every 2000 iterations\n # basnet_bsi_itr_%d_train_%3f_tar_%3f.pth basnet_time.pth\n # torch.save(net.state_dict(), model_dir + \"basnet_bsi_itr_%d_train_%3f_tar_%3f.pth\" % (ite_num, running_loss / ite_num4val, running_tar_loss / ite_num4val))\n\n net.eval()\n ind_v = 0\n running_loss_v = 0.0\n running_tar_loss_v = 0.0\n for i, data in enumerate(salobj_dataloader_te):\n if not i == 0:\n sys.stdout.write(\"\\033[F\")\n sys.stdout.write(\"\\033[K\")\n ind_v += 1\n inputs, labels = data\n\n inputs = inputs.type(torch.FloatTensor)\n labels = labels.type(torch.FloatTensor)\n\n # wrap them in Variable\n if torch.cuda.is_available():\n inputs_v, labels_v = Variable(inputs.cuda(), requires_grad=False), Variable(labels.cuda(),\n requires_grad=False)\n else:\n inputs_v, labels_v = Variable(inputs, requires_grad=False), Variable(labels, requires_grad=False)\n\n d0, d1, d2, d3, d4, d5, d6, d7 = net(inputs_v)#\n loss0, loss = muti_bce_loss_fusion(d0, d1, d2, d3, d4, d5, d6, d7, labels_v)#d1, d2, d3, d4, d5,\n\n running_loss_v += loss.item()\n running_tar_loss_v += loss0.item()\n\n print(\"(Validation Phase) [epoch: %3d/%3d, batch: %5d/%5d, ite: %d] train loss: %3f, tar: %3f \" % (\n epoch + 1, epoch_num, (i + 1) * batch_size_val, val_num, ind_v, running_loss_v / ind_v,\n running_tar_loss_v / ind_v))\n # # print statistics\n\n del d0, loss #d1, d2, d3, d4, d5, loss2,\n\n torch.save(net.state_dict(), model_dir + \"basnet_%d.pth\" % (epoch))\n #running_loss = 0.0\n #running_tar_loss = 0.0\n net.train() # resume train\n #ite_num4val = 0\n wandb.log({\n 'val_loss': float(running_tar_loss_v / ind_v)\n })\n\n # sys.stdout.write(\"\\033[F\")\n # sys.stdout.write(\"\\033[F\")\n # sys.stdout.write(\"\\033[F\")\n\n\nprint('-------------Congratulations! Training Done!!!-------------')\n"
]
| [
[
"torch.autograd.Variable",
"torch.cuda.empty_cache",
"torch.cuda.is_available",
"torch.nn.BCELoss",
"torch.load"
]
]
|
sn6uv/sympy | [
"5b149c2f72847e4785c65358b09d99b29f101dd5"
]
| [
"sympy/physics/quantum/qubit.py"
]
| [
"\"\"\"Qubits for quantum computing.\n\nTodo:\n* Finish implementing measurement logic. This should include POVM.\n* Update docstrings.\n* Update tests.\n\"\"\"\n\nimport math\n\nfrom sympy import Integer, log, Mul, Add, Pow, conjugate\nfrom sympy.core.basic import sympify\nfrom sympy.matrices.matrices import Matrix, zeros\nfrom sympy.printing.pretty.stringpict import prettyForm\n\n\nfrom sympy.physics.quantum.hilbert import ComplexSpace\nfrom sympy.physics.quantum.state import Ket, Bra, State\n\nfrom sympy.physics.quantum.qexpr import QuantumError\nfrom sympy.physics.quantum.represent import represent\nfrom sympy.physics.quantum.matrixutils import (\n numpy_ndarray, scipy_sparse_matrix\n)\nfrom sympy.mpmath.libmp.libintmath import bitcount\n\n__all__ = [\n 'Qubit',\n 'QubitBra',\n 'IntQubit',\n 'IntQubitBra',\n 'qubit_to_matrix',\n 'matrix_to_qubit',\n 'matrix_to_density',\n 'measure_all',\n 'measure_partial',\n 'measure_partial_oneshot',\n 'measure_all_oneshot'\n]\n\n#-----------------------------------------------------------------------------\n# Qubit Classes\n#-----------------------------------------------------------------------------\n\nclass QubitState(State):\n \"\"\"Base class for Qubit and QubitBra.\"\"\"\n\n #-------------------------------------------------------------------------\n # Initialization/creation\n #-------------------------------------------------------------------------\n\n @classmethod\n def _eval_args(cls, args):\n # If we are passed a QubitState or subclass, we just take its qubit\n # values directly.\n if len(args) == 1 and isinstance(args[0], QubitState):\n return args[0].qubit_values\n\n # Turn strings into tuple of strings\n if len(args) == 1 and isinstance(args[0], basestring):\n args = tuple(args[0])\n\n args = sympify(args)\n\n # Validate input (must have 0 or 1 input)\n for element in args:\n if not (element == 1 or element == 0):\n raise ValueError(\"Qubit values must be 0 or 1, got: %r\" % element)\n return args\n\n @classmethod\n def _eval_hilbert_space(cls, args):\n return ComplexSpace(2)**len(args)\n\n #-------------------------------------------------------------------------\n # Properties\n #-------------------------------------------------------------------------\n\n @property\n def dimension(self):\n \"\"\"The number of Qubits in the state.\"\"\"\n return len(self.qubit_values)\n\n @property\n def nqubits(self):\n return self.dimension\n\n @property\n def qubit_values(self):\n \"\"\"Returns the values of the qubits as a tuple.\"\"\"\n return self.label\n\n #-------------------------------------------------------------------------\n # Special methods\n #-------------------------------------------------------------------------\n\n def __len__(self):\n return self.dimension\n\n def __getitem__(self, bit):\n return self.qubit_values[int(self.dimension-bit-1)]\n\n #-------------------------------------------------------------------------\n # Utility methods\n #-------------------------------------------------------------------------\n\n def flip(self, *bits):\n \"\"\"Flip the bit(s) given.\"\"\"\n newargs = list(self.qubit_values)\n for i in bits:\n bit = int(self.dimension-i-1)\n if newargs[bit] == 1:\n newargs[bit] = 0\n else:\n newargs[bit] = 1\n return self.__class__(*tuple(newargs))\n\n\nclass Qubit(QubitState, Ket):\n \"\"\"A multi-qubit ket in the computational (z) basis.\n\n We use the normal convention that the least significant qubit is on the\n right, so ``|00001>`` has a 1 in the least significant qubit.\n\n Parameters\n ==========\n\n values : list, str\n The qubit values as a list of ints ([0,0,0,1,1,]) or a string ('011').\n\n Examples\n ========\n\n Create a qubit in a couple of different ways and look at their attributes:\n\n >>> from sympy.physics.quantum.qubit import Qubit\n >>> Qubit(0,0,0)\n |000>\n >>> q = Qubit('0101')\n >>> q\n |0101>\n\n >>> q.nqubits\n 4\n >>> len(q)\n 4\n >>> q.dimension\n 4\n >>> q.qubit_values\n (0, 1, 0, 1)\n\n We can flip the value of an individual qubit:\n\n >>> q.flip(1)\n |0111>\n\n We can take the dagger of a Qubit to get a bra:\n\n >>> from sympy.physics.quantum.dagger import Dagger\n >>> Dagger(q)\n <0101|\n >>> type(Dagger(q))\n <class 'sympy.physics.quantum.qubit.QubitBra'>\n\n Inner products work as expected:\n\n >>> ip = Dagger(q)*q\n >>> ip\n <0101|0101>\n >>> ip.doit()\n 1\n \"\"\"\n\n\n @classmethod\n def dual_class(self):\n return QubitBra\n\n def _eval_innerproduct_QubitBra(self, bra, **hints):\n if self.label == bra.label:\n return Integer(1)\n else:\n return Integer(0)\n\n def _represent_default_basis(self, **options):\n return self._represent_ZGate(None, **options)\n\n def _represent_ZGate(self, basis, **options):\n \"\"\"Represent this qubits in the computational basis (ZGate).\n \"\"\"\n format = options.get('format', 'sympy')\n n = 1\n definite_state = 0\n for it in reversed(self.qubit_values):\n definite_state += n*it\n n = n*2\n result = [0]*(2**self.dimension)\n result[int(definite_state)] = 1\n if format == 'sympy':\n return Matrix(result)\n elif format == 'numpy':\n import numpy as np\n return np.matrix(result, dtype='complex').transpose()\n elif format == 'scipy.sparse':\n from scipy import sparse\n return sparse.csr_matrix(result, dtype='complex').transpose()\n\n def _eval_trace(self, bra, **kwargs):\n indices = kwargs.get('indices', [])\n\n #sort index list to begin trace from most-significant\n #qubit\n sorted_idx = list(indices)\n if len(sorted_idx) == 0:\n sorted_idx = range(0, self.nqubits)\n sorted_idx.sort()\n\n #trace out for each of index\n new_mat = self*bra\n for i in xrange(len(sorted_idx)-1, -1, -1):\n # start from tracing out from leftmost qubit\n new_mat = self._reduced_density(new_mat, int(sorted_idx[i]))\n\n if (len(sorted_idx) == self.nqubits):\n #in case full trace was requested\n return new_mat[0]\n else:\n return matrix_to_density(new_mat)\n\n def _reduced_density(self, matrix, qubit, **options):\n \"\"\"Compute the reduced density matrix by tracing out one qubit.\n The qubit argument should be of type python int, since it is used\n in bit operations\n \"\"\"\n def find_index_that_is_projected(j, k, qubit):\n bit_mask = 2**qubit - 1\n return ((j >> qubit) << (1 + qubit)) + (j & bit_mask) + (k << qubit)\n\n old_matrix = represent(matrix, **options)\n old_size = old_matrix.cols\n #we expect the old_size to be even\n new_size = old_size//2\n new_matrix = Matrix().zeros(new_size)\n\n for i in xrange(new_size):\n for j in xrange(new_size):\n for k in xrange(2):\n col = find_index_that_is_projected(j, k, qubit)\n row = find_index_that_is_projected(i, k, qubit)\n new_matrix[i,j] += old_matrix[row,col]\n\n return new_matrix\n\nclass QubitBra(QubitState, Bra):\n \"\"\"A multi-qubit bra in the computational (z) basis.\n\n We use the normal convention that the least significant qubit is on the\n right, so ``|00001>`` has a 1 in the least significant qubit.\n\n Parameters\n ==========\n\n values : list, str\n The qubit values as a list of ints ([0,0,0,1,1,]) or a string ('011').\n\n See also\n ========\n\n Qubit: Examples using qubits\n\n \"\"\"\n @classmethod\n def dual_class(self):\n return Qubit\n\n\nclass IntQubitState(QubitState):\n \"\"\"A base class for qubits that work with binary representations.\"\"\"\n\n @classmethod\n def _eval_args(cls, args):\n # The case of a QubitState instance\n if len(args) == 1 and isinstance(args[0], QubitState):\n return QubitState._eval_args(args)\n # For a single argument, we construct the binary representation of\n # that integer with the minimal number of bits.\n if len(args) == 1 and args[0] > 1:\n #rvalues is the minimum number of bits needed to express the number\n rvalues = reversed(xrange(bitcount(abs(args[0]))))\n qubit_values = [(args[0]>>i)&1 for i in rvalues]\n return QubitState._eval_args(qubit_values)\n # For two numbers, the second number is the number of bits\n # on which it is expressed, so IntQubit(0,5) == |00000>.\n elif len(args) == 2 and args[1] > 1:\n need = bitcount(abs(args[0]))\n if args[1] < need:\n raise ValueError('cannot represent %s with %s bits' % (args[0], args[1]))\n qubit_values = [(args[0]>>i)&1 for i in reversed(range(args[1]))]\n return QubitState._eval_args(qubit_values)\n else:\n return QubitState._eval_args(args)\n\n def as_int(self):\n \"\"\"Return the numerical value of the qubit.\"\"\"\n number = 0\n n = 1\n for i in reversed(self.qubit_values):\n number += n*i\n n = n<<1\n return number\n\n def _print_label(self, printer, *args):\n return str(self.as_int())\n\n def _print_label_pretty(self, printer, *args):\n label = self._print_label(printer, *args)\n return prettyForm(label)\n\n _print_label_repr = _print_label\n _print_label_latex = _print_label\n\n\nclass IntQubit(IntQubitState, Qubit):\n \"\"\"A qubit ket that store integers as binary numbers in qubit values.\n\n The differences between this class and ``Qubit`` are:\n\n * The form of the constructor.\n * The qubit values are printed as their corresponding integer, rather\n than the raw qubit values. The internal storage format of the qubit\n values in the same as ``Qubit``.\n\n Parameters\n ==========\n\n values : int, tuple\n If a single argument, the integer we want to represent in the qubit\n values. This integer will be represented using the fewest possible\n number of qubits. If a pair of integers, the first integer gives the\n integer to represent in binary form and the second integer gives\n the number of qubits to use.\n\n Examples\n ========\n\n Create a qubit for the integer 5:\n\n >>> from sympy.physics.quantum.qubit import IntQubit\n >>> from sympy.physics.quantum.qubit import Qubit\n >>> q = IntQubit(5)\n >>> q\n |5>\n\n We can also create an ``IntQubit`` by passing a ``Qubit`` instance.\n\n >>> q = IntQubit(Qubit('101'))\n >>> q\n |5>\n >>> q.as_int()\n 5\n >>> q.nqubits\n 3\n >>> q.qubit_values\n (1, 0, 1)\n\n We can go back to the regular qubit form.\n\n >>> Qubit(q)\n |101>\n \"\"\"\n @classmethod\n def dual_class(self):\n return IntQubitBra\n\n\nclass IntQubitBra(IntQubitState, QubitBra):\n \"\"\"A qubit bra that store integers as binary numbers in qubit values.\"\"\"\n\n @classmethod\n def dual_class(self):\n return IntQubit\n\n\n#-----------------------------------------------------------------------------\n# Qubit <---> Matrix conversion functions\n#-----------------------------------------------------------------------------\n\n\ndef matrix_to_qubit(matrix):\n \"\"\"Convert from the matrix repr. to a sum of Qubit objects.\n\n Parameters\n ----------\n matrix : Matrix, numpy.matrix, scipy.sparse\n The matrix to build the Qubit representation of. This works with\n sympy matrices, numpy matrices and scipy.sparse sparse matrices.\n\n Examples\n --------\n\n Represent a state and then go back to its qubit form:\n\n >>> from sympy.physics.quantum.qubit import matrix_to_qubit, Qubit\n >>> from sympy.physics.quantum.gate import Z\n >>> from sympy.physics.quantum.represent import represent\n >>> q = Qubit('01')\n >>> matrix_to_qubit(represent(q))\n |01>\n \"\"\"\n # Determine the format based on the type of the input matrix\n format = 'sympy'\n if isinstance(matrix, numpy_ndarray):\n format = 'numpy'\n if isinstance(matrix, scipy_sparse_matrix):\n format = 'scipy.sparse'\n\n # Make sure it is of correct dimensions for a Qubit-matrix representation.\n # This logic should work with sympy, numpy or scipy.sparse matrices.\n if matrix.shape[0] == 1:\n mlistlen = matrix.shape[1]\n nqubits = log(mlistlen, 2)\n ket = False\n cls = QubitBra\n elif matrix.shape[1] == 1:\n mlistlen = matrix.shape[0]\n nqubits = log(mlistlen, 2)\n ket = True\n cls = Qubit\n else:\n raise QuantumError(\n 'Matrix must be a row/column vector, got %r' % matrix\n )\n if not isinstance(nqubits, Integer):\n raise QuantumError('Matrix must be a row/column vector of size '\n '2**nqubits, got: %r' % matrix)\n # Go through each item in matrix, if element is non-zero, make it into a\n # Qubit item times the element.\n result = 0\n for i in range(mlistlen):\n if ket:\n element = matrix[i,0]\n else:\n element = matrix[0,i]\n if format == 'numpy' or format == 'scipy.sparse':\n element = complex(element)\n if element != 0.0:\n # Form Qubit array; 0 in bit-locations where i is 0, 1 in\n # bit-locations where i is 1\n qubit_array = [int(i & (1<<x) != 0) for x in range(nqubits)]\n qubit_array.reverse()\n result = result + element*cls(*qubit_array)\n\n # If sympy simplified by pulling out a constant coefficient, undo that.\n if isinstance(result, (Mul,Add,Pow)):\n result = result.expand()\n\n return result\n\ndef matrix_to_density(mat):\n \"\"\"\n Works by finding the eigenvectors and eigenvalues of the matrix.\n We know we can decompose rho by doing:\n sum(EigenVal*|Eigenvect><Eigenvect|)\n \"\"\"\n from sympy.physics.quantum.density import Density\n eigen = mat.eigenvects()\n args = [[matrix_to_qubit(Matrix([vector,])), x[0]] for x in eigen for vector in x[2] if x[0] != 0]\n if (len(args) == 0):\n return 0\n else:\n return Density(*args)\n\ndef qubit_to_matrix(qubit, format='sympy'):\n \"\"\"Coverts an Add/Mul of Qubit objects into it's matrix representation\n\n This function is the inverse of ``matrix_to_qubit`` and is a shorthand\n for ``represent(qubit)``.\n \"\"\"\n return represent(qubit, format=format)\n\n\n#-----------------------------------------------------------------------------\n# Measurement\n#-----------------------------------------------------------------------------\n\n\ndef measure_all(qubit, format='sympy', normalize=True):\n \"\"\"Perform an ensemble measurement of all qubits.\n\n Parameters\n ==========\n\n qubit : Qubit, Add\n The qubit to measure. This can be any Qubit or a linear combination\n of them.\n format : str\n The format of the intermediate matrices to use. Possible values are\n ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is\n implemented.\n\n Returns\n =======\n\n result : list\n A list that consists of primitive states and their probabilities.\n\n Examples\n ========\n\n >>> from sympy.physics.quantum.qubit import Qubit, measure_all\n >>> from sympy.physics.quantum.gate import H, X, Y, Z\n >>> from sympy.physics.quantum.qapply import qapply\n\n >>> c = H(0)*H(1)*Qubit('00')\n >>> c\n H(0)*H(1)*|00>\n >>> q = qapply(c)\n >>> measure_all(q)\n [(|00>, 1/4), (|01>, 1/4), (|10>, 1/4), (|11>, 1/4)]\n \"\"\"\n m = qubit_to_matrix(qubit, format)\n\n if format == 'sympy':\n results = []\n\n if normalize:\n m = m.normalized()\n\n size = max(m.shape) # Max of shape to account for bra or ket\n nqubits = int(math.log(size)/math.log(2))\n for i in range(size):\n if m[i] != 0.0:\n results.append(\n (Qubit(IntQubit(i, nqubits)), m[i]*conjugate(m[i]))\n )\n return results\n else:\n raise NotImplementedError(\n \"This function can't handle non-sympy matrix formats yet\"\n )\n\n\ndef measure_partial(qubit, bits, format='sympy', normalize=True):\n \"\"\"Perform a partial ensemble measure on the specifed qubits.\n\n Parameters\n ==========\n\n qubits : Qubit\n The qubit to measure. This can be any Qubit or a linear combination\n of them.\n bits : tuple\n The qubits to measure.\n format : str\n The format of the intermediate matrices to use. Possible values are\n ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is\n implemented.\n\n Returns\n =======\n\n result : list\n A list that consists of primitive states and their probabilities.\n\n Examples\n ========\n\n >>> from sympy.physics.quantum.qubit import Qubit, measure_partial\n >>> from sympy.physics.quantum.gate import H, X, Y, Z\n >>> from sympy.physics.quantum.qapply import qapply\n\n >>> c = H(0)*H(1)*Qubit('00')\n >>> c\n H(0)*H(1)*|00>\n >>> q = qapply(c)\n >>> measure_partial(q, (0,))\n [(sqrt(2)*|00>/2 + sqrt(2)*|10>/2, 1/2), (sqrt(2)*|01>/2 + sqrt(2)*|11>/2, 1/2)]\n \"\"\"\n m = qubit_to_matrix(qubit, format)\n\n if isinstance(bits, (int, Integer)):\n bits = (int(bits),)\n\n if format == 'sympy':\n if normalize:\n m = m.normalized()\n\n possible_outcomes = _get_possible_outcomes(m, bits)\n\n # Form output from function.\n output = []\n for outcome in possible_outcomes:\n # Calculate probability of finding the specified bits with\n # given values.\n prob_of_outcome = 0\n prob_of_outcome += (outcome.H*outcome)[0]\n\n # If the output has a chance, append it to output with found\n # probability.\n if prob_of_outcome != 0:\n if normalize:\n next_matrix = matrix_to_qubit(outcome.normalized())\n else:\n next_matrix = matrix_to_qubit(outcome)\n\n output.append((\n next_matrix,\n prob_of_outcome\n ))\n\n return output\n else:\n raise NotImplementedError(\n \"This function can't handle non-sympy matrix formats yet\"\n )\n\n\ndef measure_partial_oneshot(qubit, bits, format='sympy'):\n \"\"\"Perform a partial oneshot measurement on the specified qubits.\n\n A oneshot measurement is equivalent to performing a measurement on a\n quantum system. This type of measurement does not return the probabilities\n like an ensemble measurement does, but rather returns *one* of the\n possible resulting states. The exact state that is returned is determined\n by picking a state randomly according to the ensemble probabilities.\n\n Parameters\n ----------\n qubits : Qubit\n The qubit to measure. This can be any Qubit or a linear combination\n of them.\n bits : tuple\n The qubits to measure.\n format : str\n The format of the intermediate matrices to use. Possible values are\n ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is\n implemented.\n\n Returns\n -------\n result : Qubit\n The qubit that the system collapsed to upon measurement.\n \"\"\"\n import random\n m = qubit_to_matrix(qubit, format)\n\n if format == 'sympy':\n m = m.normalized()\n possible_outcomes = _get_possible_outcomes(m, bits)\n\n # Form output from function\n random_number = random.random()\n total_prob = 0\n for outcome in possible_outcomes:\n # Calculate probability of finding the specified bits\n # with given values\n total_prob += (outcome.H*outcome)[0]\n if total_prob >= random_number:\n return matrix_to_qubit(outcome.normalized())\n else:\n raise NotImplementedError(\n \"This function can't handle non-sympy matrix formats yet\"\n )\n\n\ndef _get_possible_outcomes(m, bits):\n \"\"\"Get the possible states that can be produced in a measurement.\n\n Parameters\n ----------\n m : Matrix\n The matrix representing the state of the system.\n bits : tuple, list\n Which bits will be measured.\n\n Returns\n -------\n result : list\n The list of possible states which can occur given this measurement.\n These are un-normalized so we can derive the probability of finding\n this state by taking the inner product with itself\n \"\"\"\n\n # This is filled with loads of dirty binary tricks...You have been warned\n\n size = max(m.shape) # Max of shape to account for bra or ket\n nqubits = int(math.log(size,2)+.1) # Number of qubits possible\n\n # Make the output states and put in output_matrices, nothing in them now.\n # Each state will represent a possible outcome of the measurement\n # Thus, output_matrices[0] is the matrix which we get when all measured\n # bits return 0. and output_matrices[1] is the matrix for only the 0th\n # bit being true\n output_matrices = []\n for i in range(1<<len(bits)):\n output_matrices.append(zeros(2**nqubits, 1))\n\n # Bitmasks will help sort how to determine possible outcomes.\n # When the bit mask is and-ed with a matrix-index,\n # it will determine which state that index belongs to\n bit_masks = []\n for bit in bits:\n bit_masks.append(1<<bit)\n\n # Make possible outcome states\n for i in range(2**nqubits):\n trueness = 0 # This tells us to which output_matrix this value belongs\n # Find trueness\n for j in range(len(bit_masks)):\n if i&bit_masks[j]:\n trueness += j+1\n # Put the value in the correct output matrix\n output_matrices[trueness][i] = m[i]\n return output_matrices\n\n\ndef measure_all_oneshot(qubit, format='sympy'):\n \"\"\"Perform a oneshot ensemble measurement on all qubits.\n\n A oneshot measurement is equivalent to performing a measurement on a\n quantum system. This type of measurement does not return the probabilities\n like an ensemble measurement does, but rather returns *one* of the\n possible resulting states. The exact state that is returned is determined\n by picking a state randomly according to the ensemble probabilities.\n\n Parameters\n ----------\n qubits : Qubit\n The qubit to measure. This can be any Qubit or a linear combination\n of them.\n format : str\n The format of the intermediate matrices to use. Possible values are\n ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is\n implemented.\n\n Returns\n -------\n result : Qubit\n The qubit that the system collapsed to upon measurement.\n \"\"\"\n import random\n m = qubit_to_matrix(qubit)\n\n if format == 'sympy':\n m = m.normalized()\n random_number = random.random()\n total = 0\n result = 0\n for i in m:\n total += i*i.conjugate()\n if total > random_number:\n break\n result += 1\n return Qubit(IntQubit(result, int(math.log(max(m.shape),2)+.1)))\n else:\n raise NotImplementedError(\n \"This function can't handle non-sympy matrix formats yet\"\n )\n"
]
| [
[
"numpy.matrix",
"scipy.sparse.csr_matrix"
]
]
|
simonlindgren/GetOldTweets3 | [
"05744c7c2dfec11d5de65971a0add478cecab41f"
]
| [
"sql2csv.py"
]
| [
"#!/usr/bin/env python3\n\n'''\nREAD SQLITE3 DB INTO CSV\nSimon Lindgren\n200220\n'''\n\nimport sqlite3\nimport pandas as pd\nimport glob\n\ndef main():\n print(\"\\nEnter the name of a database file, located in this directory.\")\n dbs = glob.glob(\"*.db\")\n print(\"You have these to choose from:\")\n print([i for i in dbs])\n print(\"\\n\")\n dbname = input(\": \")\n print(\"This script assumes that there is a table named 'tweets' inside your database.\")\n sql2csv(dbname)\n print(\"Successfully written csv!\")\n \ndef sql2csv(dbname):\n with sqlite3.connect(dbname) as conn:\n tweets_df = pd.read_sql_query(\"SELECT * from tweets\", conn)\n tweets_df = tweets_df.replace({'\\n': ' '}, regex=True) # remove linebreaks in the dataframe\n tweets_df = tweets_df.replace({'\\t': ' '}, regex=True) # remove tabs in the dataframe\n tweets_df = tweets_df.replace({'\\r': ' '}, regex=True) # remove carriage return in the dataframe\n tweets_df.to_csv(dbname.split(\".\")[0] + \".csv\", index = False)\n \nif __name__ == '__main__':\n main()\n"
]
| [
[
"pandas.read_sql_query"
]
]
|
jcoreyes/erl | [
"43f4e8407967749f5364106163f3c5335eb7dc83"
]
| [
"rlkit/core/batch_rl_algorithm_modenv.py"
]
| [
"from collections import OrderedDict\n\nfrom rlkit.core.timer import timer\n\nfrom rlkit.core import logger\nfrom rlkit.data_management.replay_buffer import ReplayBuffer\nfrom rlkit.misc import eval_util\nfrom rlkit.samplers.data_collector.path_collector import PathCollector\nfrom rlkit.core.rl_algorithm import BaseRLAlgorithm\nimport numpy as np\n\ndef linear_schedule(start, end, current):\n return float(current) / (end - start)\n\nclass BatchRLAlgorithmModEnv(BaseRLAlgorithm):\n def __init__(\n self,\n batch_size,\n max_path_length,\n num_eval_steps_per_epoch,\n num_expl_steps_per_train_loop,\n num_trains_per_train_loop,\n mod_env_epoch_schedule,\n env_class,\n env_mod_params,\n env_mod_dist,\n lifelong,\n num_train_loops_per_epoch=1,\n min_num_steps_before_training=0,\n *args,\n **kwargs\n ):\n\n super().__init__(*args, **kwargs)\n self.batch_size = batch_size\n self.max_path_length = max_path_length\n self.num_eval_steps_per_epoch = num_eval_steps_per_epoch\n self.num_trains_per_train_loop = num_trains_per_train_loop\n self.num_train_loops_per_epoch = num_train_loops_per_epoch\n self.num_expl_steps_per_train_loop = num_expl_steps_per_train_loop\n self.min_num_steps_before_training = min_num_steps_before_training\n\n self.lifelong = lifelong\n self.mod_env_epoch_schedule = mod_env_epoch_schedule\n self.env_class = env_class\n self.env_mod_params = env_mod_params\n self.env_mod_dist = env_mod_dist\n\n def _train(self):\n if self.lifelong:\n return self._train_lifelong()\n else:\n return self._train_batch()\n\n def _train_lifelong(self):\n done = (self.epoch == self.num_epochs)\n if done:\n return OrderedDict(), done\n\n self.training_mode(False)\n if self.min_num_steps_before_training > 0 and self.epoch == 0:\n self.expl_data_collector.collect_new_steps(\n self.max_path_length,\n self.min_num_steps_before_training,\n discard_incomplete_paths=False,\n )\n init_expl_paths = self.expl_data_collector.get_epoch_paths()\n self.replay_buffer.add_paths(init_expl_paths)\n self.expl_data_collector.end_epoch(-1)\n\n num_trains_per_expl_step = self.num_trains_per_train_loop // self.num_expl_steps_per_train_loop\n timer.start_timer('evaluation sampling')\n if self.epoch % self._eval_epoch_freq == 0:\n self.eval_data_collector.collect_new_paths(\n self.max_path_length,\n self.num_eval_steps_per_epoch,\n discard_incomplete_paths=True,\n )\n timer.stop_timer('evaluation sampling')\n\n if not self._eval_only:\n for _ in range(self.num_train_loops_per_epoch):\n for _ in range(self.num_expl_steps_per_train_loop):\n timer.start_timer('exploration sampling', unique=False)\n self.expl_data_collector.collect_new_steps(\n self.max_path_length,\n 1, # num steps\n discard_incomplete_paths=False,\n )\n timer.stop_timer('exploration sampling')\n\n timer.start_timer('training', unique=False)\n self.training_mode(True)\n for _ in range(num_trains_per_expl_step):\n train_data = self.replay_buffer.random_batch(\n self.batch_size)\n self.trainer.train(train_data)\n timer.stop_timer('training')\n self.training_mode(False)\n\n timer.start_timer('replay buffer data storing', unique=False)\n new_expl_paths = self.expl_data_collector.get_epoch_paths()\n self.replay_buffer.add_paths(new_expl_paths)\n timer.stop_timer('replay buffer data storing')\n\n log_stats = self._get_diagnostics()\n\n return log_stats, False\n\n def _train_batch(self):\n done = (self.epoch == self.num_epochs)\n if done:\n return OrderedDict(), done\n\n if self.epoch == 0 and self.min_num_steps_before_training > 0:\n init_expl_paths = self.expl_data_collector.collect_new_paths(\n self.max_path_length,\n self.min_num_steps_before_training,\n discard_incomplete_paths=False,\n )\n self.replay_buffer.add_paths(init_expl_paths)\n self.expl_data_collector.end_epoch(-1)\n\n timer.start_timer('evaluation sampling')\n if self.epoch % self._eval_epoch_freq == 0:\n self.eval_data_collector.collect_new_paths(\n self.max_path_length,\n self.num_eval_steps_per_epoch,\n discard_incomplete_paths=True,\n )\n timer.stop_timer('evaluation sampling')\n\n if not self._eval_only:\n for _ in range(self.num_train_loops_per_epoch):\n timer.start_timer('exploration sampling', unique=False)\n new_env_mod_parms = dict()\n if self.env_mod_dist:\n current = max(1, self.epoch / (self.mod_env_epoch_schedule * self.num_epochs))\n for k, v in self.env_mod_params.items():\n lbound, ubound = v\n low = current + (1.0 - current) * lbound\n high = current + (1.0 - current) * ubound\n new_env_mod_parms[k] = np.random.uniform(low, high)\n\n else:\n current = max(1, self.epoch / (self.mod_env_epoch_schedule * self.num_epochs))\n for k, v in self.env_mod_params.items():\n new_env_mod_parms[k] = 1.0 * current + (1.0 - current) * v\n self.expl_data_collector._env = self.env_class(new_env_mod_parms)\n\n new_expl_paths = self.expl_data_collector.collect_new_paths(\n self.max_path_length,\n self.num_expl_steps_per_train_loop,\n discard_incomplete_paths=False,\n )\n timer.stop_timer('exploration sampling')\n\n timer.start_timer('replay buffer data storing', unique=False)\n self.replay_buffer.add_paths(new_expl_paths)\n timer.stop_timer('replay buffer data storing')\n\n timer.start_timer('training', unique=False)\n for _ in range(self.num_trains_per_train_loop):\n train_data = self.replay_buffer.random_batch(self.batch_size)\n self.trainer.train(train_data)\n timer.stop_timer('training')\n log_stats = self._get_diagnostics()\n return log_stats, False\n"
]
| [
[
"numpy.random.uniform"
]
]
|
modyharshit23/trax | [
"2e6783a4674209b57482ec41e1c533a420aa6fe6"
]
| [
"trax/rl/space_serializer.py"
]
| [
"# coding=utf-8\n# Copyright 2019 The Trax Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Serialization of elements of Gym spaces into discrete sequences.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport copy\n\nfrom absl import logging\nimport gin\nimport gym\nimport numpy as np\n\n\nclass SpaceSerializer(object):\n \"\"\"Base class for Gym space serializers.\n\n Attrs:\n space_type: (type) Gym space class that this SpaceSerializer corresponds\n to. Should be defined in subclasses.\n representation_length: (int) Number of symbols in the representation of\n every element of the space.\n significance_map: (np.ndarray) Integer array of the same size as the\n discrete representation, where elements describe the significance of\n symbols, e.g. in fixed-precision encoding. 0 is the most significant\n symbol, 1 the second most significant etc.\n \"\"\"\n\n space_type = None\n representation_length = None\n significance_map = None\n\n def __init__(self, space, vocab_size):\n \"\"\"Creates a SpaceSerializer.\n\n Subclasses should retain the signature.\n\n Args:\n space: (gym.Space) Gym space of type self.space_type.\n vocab_size: (int) Number of symbols in the vocabulary.\n \"\"\"\n assert isinstance(space, self.space_type)\n self._space = space\n self._vocab_size = vocab_size\n\n def serialize(self, data):\n \"\"\"Serializes a batch of space elements into discrete sequences.\n\n Should be defined in subclasses.\n\n Args:\n data: A batch of batch_size elements of the Gym space to be serialized.\n\n Returns:\n int32 array of shape (batch_size, self.representation_length).\n \"\"\"\n raise NotImplementedError\n\n def deserialize(self, representation):\n \"\"\"Deserializes a batch of discrete sequences into space elements.\n\n Should be defined in subclasses.\n\n Args:\n representation: int32 Numpy array of shape\n (batch_size, self.representation_length) to be deserialized.\n\n Returns:\n A batch of batch_size deserialized elements of the Gym space.\n \"\"\"\n raise NotImplementedError\n\n\ndef create(space, vocab_size):\n \"\"\"Creates a SpaceSerializer for the given Gym space.\"\"\"\n return {\n gym.spaces.Box: BoxSpaceSerializer,\n gym.spaces.Discrete: DiscreteSpaceSerializer,\n gym.spaces.MultiDiscrete: MultiDiscreteSpaceSerializer,\n }[type(space)](space, vocab_size)\n\n\[email protected](blacklist=[\"space\", \"vocab_size\"])\nclass BoxSpaceSerializer(SpaceSerializer):\n \"\"\"Serializer for gym.spaces.Box.\n\n Assumes that the space is bounded. Internally rescales it to the [0, 1]\n interval and uses a fixed-precision encoding.\n \"\"\"\n\n space_type = gym.spaces.Box\n\n def __init__(self, space, vocab_size, precision=2, max_range=(-100.0, 100.0)):\n self._precision = precision\n\n # Some gym envs (e.g. CartPole) have unreasonably high bounds for\n # observations. We clip so we can represent them.\n bounded_space = copy.copy(space)\n (min_low, max_high) = max_range\n bounded_space.low = np.maximum(space.low, min_low)\n bounded_space.high = np.minimum(space.high, max_high)\n if (not np.allclose(bounded_space.low, space.low) or\n not np.allclose(bounded_space.high, space.high)):\n logging.warning(\n \"Space limits %s, %s out of bounds %s. Clipping to %s, %s.\",\n str(space.low), str(space.high), str(max_range),\n str(bounded_space.low), str(bounded_space.high)\n )\n\n super(BoxSpaceSerializer, self).__init__(bounded_space, vocab_size)\n\n def serialize(self, data):\n array = data\n batch_size = array.shape[0]\n array = (array - self._space.low) / (self._space.high - self._space.low)\n digits = []\n for digit_index in range(-1, -self._precision - 1, -1):\n threshold = self._vocab_size ** digit_index\n digit = np.array(array / threshold).astype(np.int32)\n # For the corner case of x == high.\n digit[digit == self._vocab_size] -= 1\n digits.append(digit)\n array -= digit * threshold\n digits = np.stack(digits, axis=-1)\n return np.reshape(digits, (batch_size, -1))\n\n def deserialize(self, representation):\n digits = representation\n batch_size = digits.shape[0]\n digits = np.reshape(digits, (batch_size, -1, self._precision))\n array = np.zeros(digits.shape[:-1])\n for digit_index_in_seq in range(self._precision):\n digit_index = -digit_index_in_seq - 1\n array += self._vocab_size ** digit_index * digits[..., digit_index_in_seq]\n array = np.reshape(array, (batch_size,) + self._space.shape)\n return array * (self._space.high - self._space.low) + self._space.low\n\n @property\n def representation_length(self):\n return self._precision * self._space.low.size\n\n @property\n def significance_map(self):\n return np.reshape(np.broadcast_to(\n np.arange(self._precision), self._space.shape + (self._precision,)), -1)\n\n\nclass DiscreteSpaceSerializer(SpaceSerializer):\n \"\"\"Serializer for gym.spaces.Discrete.\n\n Assumes that the size of the space fits in the number of symbols.\n \"\"\"\n\n space_type = gym.spaces.Discrete\n representation_length = 1\n\n def __init__(self, space, vocab_size):\n super(DiscreteSpaceSerializer, self).__init__(space, vocab_size)\n assert space.n <= vocab_size, (\n \"Discrete space size should fit in the number of symbols.\")\n\n def serialize(self, data):\n return np.reshape(data, (-1, 1)).astype(np.int32)\n\n def deserialize(self, representation):\n return np.reshape(representation, -1)\n\n @property\n def significance_map(self):\n return np.zeros(1, dtype=np.int32)\n\n\nclass MultiDiscreteSpaceSerializer(SpaceSerializer):\n \"\"\"Serializer for gym.spaces.MultiDiscrete.\n\n Assumes that the number of categories in each dimension fits in the number of\n symbols.\n \"\"\"\n\n space_type = gym.spaces.MultiDiscrete\n\n def __init__(self, space, vocab_size):\n super(MultiDiscreteSpaceSerializer, self).__init__(space, vocab_size)\n assert np.max(space.nvec) <= vocab_size, (\n \"MultiDiscrete maximum number of categories should fit in the number \"\n \"of symbols.\"\n )\n\n def serialize(self, data):\n return data.astype(np.int32)\n\n def deserialize(self, representation):\n return representation\n\n @property\n def representation_length(self):\n return len(self._space.nvec)\n\n @property\n def significance_map(self):\n return np.zeros(self.representation_length, dtype=np.int32)\n"
]
| [
[
"numpy.max",
"numpy.array",
"numpy.reshape",
"numpy.zeros",
"numpy.minimum",
"numpy.allclose",
"numpy.stack",
"numpy.arange",
"numpy.maximum"
]
]
|
spectralDNS/mpi4pt-fft | [
"ac510f8398f138bb860ed9f2580343e8b98cf799"
]
| [
"tests/test_io.py"
]
| [
"import functools\nimport os\nfrom mpi4py import MPI\nimport numpy as np\nfrom mpi4py_fft import PFFT, HDF5File, NCFile, newDistArray, generate_xdmf\n\nN = (12, 13, 14, 15)\ncomm = MPI.COMM_WORLD\n\nex = {True: 'c', False: 'r'}\n\nwriter = {'hdf5': functools.partial(HDF5File, mode='w'),\n 'netcdf4': functools.partial(NCFile, mode='w')}\nreader = {'hdf5': functools.partial(HDF5File, mode='r'),\n 'netcdf4': functools.partial(NCFile, mode='r')}\nending = {'hdf5': '.h5', 'netcdf4': '.nc'}\n\ndef remove_if_exists(filename):\n try:\n os.remove(filename)\n except OSError:\n pass\n\ndef test_2D(backend, forward_output):\n if backend == 'netcdf4':\n assert forward_output is False\n T = PFFT(comm, (N[0], N[1]))\n for i, domain in enumerate([None, ((0, np.pi), (0, 2*np.pi)),\n (np.arange(N[0], dtype=float)*1*np.pi/N[0],\n np.arange(N[1], dtype=float)*2*np.pi/N[1])]):\n for rank in range(3):\n filename = \"\".join(('test2D_{}{}{}'.format(ex[i == 0], ex[forward_output], rank),\n ending[backend]))\n if backend == 'netcdf4':\n remove_if_exists(filename)\n u = newDistArray(T, forward_output=forward_output, val=1, rank=rank)\n hfile = writer[backend](filename, domain=domain)\n assert hfile.backend() == backend\n hfile.write(0, {'u': [u]})\n hfile.write(1, {'u': [u]})\n u.write(hfile, 'u', 2)\n if rank > 0:\n hfile.write(0, {'u': [u]}, as_scalar=True)\n hfile.write(1, {'u': [u]}, as_scalar=True)\n u.write(hfile, 'u', 2, as_scalar=True)\n u.write('t'+filename, 'u', 0)\n u.write('t'+filename, 'u', 0, [slice(None), 3])\n\n if not forward_output and backend == 'hdf5' and comm.Get_rank() == 0:\n generate_xdmf(filename)\n generate_xdmf(filename, order='visit')\n\n u0 = newDistArray(T, forward_output=forward_output, rank=rank)\n read = reader[backend](filename)\n read.read(u0, 'u', step=0)\n u0.read(filename, 'u', 2)\n u0.read(read, 'u', 2)\n assert np.allclose(u0, u)\n if backend == 'netcdf4': # Test opening file in mode 'a' when not existing\n remove_if_exists('nctesta.nc')\n _ = NCFile('nctesta.nc', domain=domain, mode='a')\n T.destroy()\n\ndef test_3D(backend, forward_output):\n if backend == 'netcdf4':\n assert forward_output is False\n T = PFFT(comm, (N[0], N[1], N[2]))\n d0 = ((0, np.pi), (0, 2*np.pi), (0, 3*np.pi))\n d1 = (np.arange(N[0], dtype=float)*1*np.pi/N[0],\n np.arange(N[1], dtype=float)*2*np.pi/N[1],\n np.arange(N[2], dtype=float)*3*np.pi/N[2])\n for i, domain in enumerate([None, d0, d1]):\n for rank in range(3):\n filename = ''.join(('test_{}{}{}'.format(ex[i == 0], ex[forward_output], rank),\n ending[backend]))\n if backend == 'netcdf4':\n remove_if_exists('uv'+filename)\n remove_if_exists('v'+filename)\n\n u = newDistArray(T, forward_output=forward_output, rank=rank)\n v = newDistArray(T, forward_output=forward_output, rank=rank)\n h0file = writer[backend]('uv'+filename, domain=domain)\n h1file = writer[backend]('v'+filename, domain=domain)\n u[:] = np.random.random(u.shape)\n v[:] = 2\n for k in range(3):\n h0file.write(k, {'u': [u,\n (u, [slice(None), slice(None), 4]),\n (u, [5, 5, slice(None)])],\n 'v': [v,\n (v, [slice(None), 6, slice(None)])]})\n h1file.write(k, {'v': [v,\n (v, [slice(None), 6, slice(None)]),\n (v, [6, 6, slice(None)])]})\n # One more time with same k\n h0file.write(k, {'u': [u,\n (u, [slice(None), slice(None), 4]),\n (u, [5, 5, slice(None)])],\n 'v': [v,\n (v, [slice(None), 6, slice(None)])]})\n h1file.write(k, {'v': [v,\n (v, [slice(None), 6, slice(None)]),\n (v, [6, 6, slice(None)])]})\n\n if rank > 0:\n for k in range(3):\n u.write('uv'+filename, 'u', k, as_scalar=True)\n u.write('uv'+filename, 'u', k, [slice(None), slice(None), 4], as_scalar=True)\n u.write('uv'+filename, 'u', k, [5, 5, slice(None)], as_scalar=True)\n v.write('uv'+filename, 'v', k, as_scalar=True)\n v.write('uv'+filename, 'v', k, [slice(None), 6, slice(None)], as_scalar=True)\n\n if not forward_output and backend == 'hdf5' and comm.Get_rank() == 0:\n generate_xdmf('uv'+filename)\n generate_xdmf('v'+filename, periodic=False)\n generate_xdmf('v'+filename, periodic=(True, True, True))\n generate_xdmf('v'+filename, order='visit')\n\n u0 = newDistArray(T, forward_output=forward_output, rank=rank)\n read = reader[backend]('uv'+filename)\n read.read(u0, 'u', step=0)\n assert np.allclose(u0, u)\n read.read(u0, 'v', step=0)\n assert np.allclose(u0, v)\n T.destroy()\n\ndef test_4D(backend, forward_output):\n if backend == 'netcdf4':\n assert forward_output is False\n T = PFFT(comm, (N[0], N[1], N[2], N[3]))\n d0 = ((0, np.pi), (0, 2*np.pi), (0, 3*np.pi), (0, 4*np.pi))\n d1 = (np.arange(N[0], dtype=float)*1*np.pi/N[0],\n np.arange(N[1], dtype=float)*2*np.pi/N[1],\n np.arange(N[2], dtype=float)*3*np.pi/N[2],\n np.arange(N[3], dtype=float)*4*np.pi/N[3]\n )\n for i, domain in enumerate([None, d0, d1]):\n for rank in range(3):\n filename = \"\".join(('h5test4_{}{}{}'.format(ex[i == 0], ex[forward_output], rank),\n ending[backend]))\n if backend == 'netcdf4':\n remove_if_exists('uv'+filename)\n u = newDistArray(T, forward_output=forward_output, rank=rank)\n v = newDistArray(T, forward_output=forward_output, rank=rank)\n h0file = writer[backend]('uv'+filename, domain=domain)\n u[:] = np.random.random(u.shape)\n v[:] = 2\n for k in range(3):\n h0file.write(k, {'u': [u, (u, [slice(None), 4, slice(None), slice(None)])],\n 'v': [v, (v, [slice(None), slice(None), 5, 6])]})\n\n if not forward_output and backend == 'hdf5' and comm.Get_rank() == 0:\n generate_xdmf('uv'+filename)\n\n u0 = newDistArray(T, forward_output=forward_output, rank=rank)\n read = reader[backend]('uv'+filename)\n read.read(u0, 'u', step=0)\n assert np.allclose(u0, u)\n read.read(u0, 'v', step=0)\n assert np.allclose(u0, v)\n T.destroy()\n\nif __name__ == '__main__':\n #pylint: disable=unused-import\n skip = {'hdf5': False, 'netcdf4': False}\n try:\n import h5py\n except ImportError:\n skip['hdf5'] = True\n try:\n import netCDF4\n except ImportError:\n skip['netcdf4'] = True\n for bnd in ('hdf5', 'netcdf4'):\n if not skip[bnd]:\n forw_output = [False]\n if bnd == 'hdf5':\n forw_output.append(True)\n for kind in forw_output:\n test_3D(bnd, kind)\n test_2D(bnd, kind)\n if bnd == 'hdf5':\n test_4D(bnd, kind)\n"
]
| [
[
"numpy.allclose",
"numpy.arange",
"numpy.random.random"
]
]
|
alfred100p/PettingZoo | [
"2f5188608d5b4fc9c64297d7cddd4be57423dc6b"
]
| [
"pettingzoo/butterfly/cooperative_pong/cooperative_pong.py"
]
| [
"import os\nimport numpy as np\nimport gym\nfrom gym.utils import seeding\nfrom .cake_paddle import CakePaddle, RENDER_RATIO\nfrom .manual_control import manual_control\nfrom pettingzoo import AECEnv\nfrom pettingzoo.utils import wrappers\nfrom pettingzoo.utils.agent_selector import agent_selector\nfrom pettingzoo.utils.conversions import parallel_wrapper_fn\nos.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = 'hide'\nimport pygame\nfrom gym.utils import EzPickle\n\nKERNEL_WINDOW_LENGTH = 2\n\n\ndef deg_to_rad(deg):\n return deg * np.pi / 180\n\n\ndef get_flat_shape(width, height):\n return int(width * height / (KERNEL_WINDOW_LENGTH * KERNEL_WINDOW_LENGTH))\n\n\ndef original_obs_shape(screen_width, screen_height):\n return (int(screen_height * 2 / KERNEL_WINDOW_LENGTH), int(screen_width * 2 / (KERNEL_WINDOW_LENGTH)), 1)\n\n\ndef get_valid_angle(randomizer):\n # generates an angle in [0, 2*np.pi) that\n # excludes (90 +- ver_deg_range), (270 +- ver_deg_range), (0 +- hor_deg_range), (180 +- hor_deg_range)\n # (65, 115), (245, 295), (170, 190), (0, 10), (350, 360)\n ver_deg_range = 25\n hor_deg_range = 10\n a1 = deg_to_rad(90 - ver_deg_range)\n b1 = deg_to_rad(90 + ver_deg_range)\n a2 = deg_to_rad(270 - ver_deg_range)\n b2 = deg_to_rad(270 + ver_deg_range)\n c1 = deg_to_rad(180 - hor_deg_range)\n d1 = deg_to_rad(180 + hor_deg_range)\n c2 = deg_to_rad(360 - hor_deg_range)\n d2 = deg_to_rad(0 + hor_deg_range)\n\n angle = 0\n while ((angle > a1 and angle < b1) or (angle > a2 and angle < b2) or (angle > c1 and angle < d1) or (angle > c2) or (angle < d2)):\n angle = 2 * np.pi * randomizer.rand()\n\n return angle\n\n\ndef get_small_random_value(randomizer):\n # generates a small random value between [0, 1/100)\n return (1 / 100) * randomizer.rand()\n\n\nclass PaddleSprite(pygame.sprite.Sprite):\n def __init__(self, dims, speed):\n self.surf = pygame.Surface(dims)\n self.rect = self.surf.get_rect()\n self.speed = speed\n\n def reset(self):\n pass\n\n def draw(self, screen):\n pygame.draw.rect(screen, (255, 255, 255), self.rect)\n\n def update(self, area, action):\n # action: 1 - up, 2 - down\n movepos = [0, 0]\n if action > 0:\n if action == 1:\n movepos[1] = movepos[1] - self.speed\n elif action == 2:\n movepos[1] = movepos[1] + self.speed\n\n # make sure the players stay inside the screen\n newpos = self.rect.move(movepos)\n if area.contains(newpos):\n self.rect = newpos\n\n def process_collision(self, b_rect, dx, dy, b_speed, paddle_type):\n '''\n\n Parameters\n ----------\n b_rect : Ball rect\n dx, dy : Ball speed along single axis\n b_speed : Ball speed\n\n Returns\n -------\n is_collision: 1 if ball collides with paddle\n b_rect: new ball rect\n b_speed: new ball speed\n\n '''\n if paddle_type == 1:\n if self.rect.colliderect(b_rect):\n is_collision = True\n if dx < 0:\n b_rect.left = self.rect.right\n b_speed[0] = -b_speed[0]\n # top or bottom edge\n elif dy > 0:\n b_rect.bottom = self.rect.top\n b_speed[1] = -b_speed[1]\n elif dy < 0:\n b_rect.top = self.rect.bottom\n b_speed[1] = -b_speed[1]\n return is_collision, b_rect, b_speed\n elif paddle_type == 2:\n if self.rect.colliderect(b_rect):\n is_collision = True\n if dx > 0:\n b_rect.right = self.rect.left\n b_speed[0] = -b_speed[0]\n # top or bottom edge\n elif dy > 0:\n b_rect.bottom = self.rect.top\n b_speed[1] = -b_speed[1]\n elif dy < 0:\n b_rect.top = self.rect.bottom\n b_speed[1] = -b_speed[1]\n return is_collision, b_rect, b_speed\n return False, b_rect, b_speed\n\n\nclass BallSprite(pygame.sprite.Sprite):\n def __init__(self, randomizer, dims, speed, bounce_randomness=False):\n self.surf = pygame.Surface(dims)\n self.rect = self.surf.get_rect()\n self.speed_val = speed\n self.speed = [int(self.speed_val * np.cos(np.pi / 4)), int(self.speed_val * np.sin(np.pi / 4))]\n self.bounce_randomness = bounce_randomness\n self.done = False\n self.hit = False\n self.randomizer = randomizer\n\n def update2(self, area, p0, p1):\n (speed_x, speed_y) = self.speed\n done_x, done_y = False, False\n if self.speed[0] != 0:\n done_x = self.move_single_axis(self.speed[0], 0, area, p0, p1)\n if self.speed[1] != 0:\n done_y = self.move_single_axis(0, self.speed[1], area, p0, p1)\n return (done_x or done_y)\n\n def move_single_axis(self, dx, dy, area, p0, p1):\n # move ball rect\n self.rect.x += dx\n self.rect.y += dy\n\n if not area.contains(self.rect):\n # bottom wall\n if dy > 0:\n self.rect.bottom = area.bottom\n self.speed[1] = -self.speed[1]\n # top wall\n elif dy < 0:\n self.rect.top = area.top\n self.speed[1] = -self.speed[1]\n # right or left walls\n else:\n return True\n self.speed[0] = -self.speed[0]\n\n else:\n # Do ball and bat collide?\n # add some randomness\n r_val = 0\n if self.bounce_randomness:\n r_val = get_small_random_value(self.randomizer)\n\n # ball in left half of screen\n if self.rect.center[0] < area.center[0]:\n is_collision, self.rect, self.speed = p0.process_collision(self.rect, dx, dy, self.speed, 1)\n if is_collision:\n self.speed = [self.speed[0] + np.sign(self.speed[0]) * r_val, self.speed[1] + np.sign(self.speed[1]) * r_val]\n # ball in right half\n else:\n is_collision, self.rect, self.speed = p1.process_collision(self.rect, dx, dy, self.speed, 2)\n if is_collision:\n self.speed = [self.speed[0] + np.sign(self.speed[0]) * r_val, self.speed[1] + np.sign(self.speed[1]) * r_val]\n\n return False\n\n def draw(self, screen):\n # screen.blit(self.surf, self.rect)\n pygame.draw.rect(screen, (255, 255, 255), self.rect)\n\n\nclass CooperativePong:\n def __init__(self, randomizer, ball_speed=9, left_paddle_speed=12, right_paddle_speed=12, cake_paddle=True, max_cycles=900, bounce_randomness=False):\n super(CooperativePong, self).__init__()\n\n pygame.init()\n self.num_agents = 2\n\n # Display screen\n self.s_width, self.s_height = 960 // RENDER_RATIO, 560 // RENDER_RATIO\n self.screen = pygame.Surface((self.s_width, self.s_height)) # (960, 720) # (640, 480) # (100, 200)\n self.area = self.screen.get_rect()\n\n # define action and observation spaces\n self.action_space = [gym.spaces.Discrete(3) for _ in range(self.num_agents)]\n original_shape = original_obs_shape(self.s_width, self.s_height)\n original_color_shape = (original_shape[0], original_shape[1], 3)\n self.observation_space = [gym.spaces.Box(low=0, high=255, shape=(original_color_shape), dtype=np.uint8) for _ in range(self.num_agents)]\n # define the global space of the environment or state\n self.state_space = gym.spaces.Box(low=0, high=255, shape=((self.s_height, self.s_width, 3)), dtype=np.uint8)\n\n self.renderOn = False\n\n # set speed\n self.speed = [ball_speed, left_paddle_speed, right_paddle_speed]\n\n self.max_cycles = max_cycles\n\n # paddles\n self.p0 = PaddleSprite((20 // RENDER_RATIO, 80 // RENDER_RATIO), left_paddle_speed)\n if cake_paddle:\n self.p1 = CakePaddle(right_paddle_speed)\n else:\n self.p1 = PaddleSprite((20 // RENDER_RATIO, 100 // RENDER_RATIO), right_paddle_speed)\n\n self.agents = [\"paddle_0\", \"paddle_1\"] # list(range(self.num_agents))\n\n # ball\n self.ball = BallSprite(randomizer, (20 // RENDER_RATIO, 20 // RENDER_RATIO), ball_speed, bounce_randomness)\n self.randomizer = randomizer\n\n self.reinit()\n\n def reinit(self):\n self.rewards = dict(zip(self.agents, [0.0] * len(self.agents)))\n self.dones = dict(zip(self.agents, [False] * len(self.agents)))\n self.infos = dict(zip(self.agents, [{}] * len(self.agents)))\n self.score = 0\n\n def reset(self):\n # reset ball and paddle init conditions\n self.ball.rect.center = self.area.center\n # set the direction to an angle between [0, 2*np.pi)\n angle = get_valid_angle(self.randomizer)\n # angle = deg_to_rad(89)\n self.ball.speed = [int(self.ball.speed_val * np.cos(angle)), int(self.ball.speed_val * np.sin(angle))]\n\n self.p0.rect.midleft = self.area.midleft\n self.p1.rect.midright = self.area.midright\n self.p0.reset()\n self.p1.reset()\n self.p0.speed = self.speed[1]\n self.p1.speed = self.speed[2]\n\n self.done = False\n\n self.num_frames = 0\n\n self.reinit()\n\n self.draw()\n\n def close(self):\n if self.renderOn:\n pygame.event.pump()\n pygame.display.quit()\n self.renderOn = False\n\n def enable_render(self):\n self.screen = pygame.display.set_mode(self.screen.get_size())\n self.renderOn = True\n self.draw()\n\n def render(self, mode='human'):\n if not self.renderOn and mode == \"human\":\n # sets self.renderOn to true and initializes display\n self.enable_render()\n\n observation = np.array(pygame.surfarray.pixels3d(self.screen))\n if mode == \"human\":\n pygame.display.flip()\n return np.transpose(observation, axes=(1, 0, 2)) if mode == \"rgb_array\" else None\n\n def observe(self):\n observation = np.array(pygame.surfarray.pixels3d(self.screen))\n observation = np.rot90(observation, k=3) # now the obs is laid out as H, W as rows and cols\n observation = np.fliplr(observation) # laid out in the correct order\n return observation\n\n def state(self):\n '''\n Returns an observation of the global environment\n '''\n state = pygame.surfarray.pixels3d(self.screen).copy()\n state = np.rot90(state, k=3)\n state = np.fliplr(state)\n return state\n\n def draw(self):\n pygame.draw.rect(self.screen, (0, 0, 0), self.area)\n self.p0.draw(self.screen)\n self.p1.draw(self.screen)\n self.ball.draw(self.screen)\n\n def step(self, action, agent):\n\n # update p0, p1 accordingly\n # action: 0: do nothing,\n # action: 1: p[i] move up\n # action: 2: p[i] move down\n if agent == self.agents[0]:\n self.rewards = {a: 0 for a in self.agents}\n self.p0.update(self.area, action)\n elif agent == self.agents[1]:\n self.p1.update(self.area, action)\n\n # do the rest if not done\n if not self.done:\n # update ball position\n self.done = self.ball.update2(self.area, self.p0, self.p1)\n\n # do the miscellaneous stuff after the last agent has moved\n # reward is the length of time ball is in play\n reward = 0\n # ball is out-of-bounds\n if self.done:\n reward = -100\n self.score += reward\n if not self.done:\n self.num_frames += 1\n # scaling reward so that the max reward is 100\n reward = 100 / self.max_cycles\n self.score += reward\n if self.num_frames == self.max_cycles:\n self.done = True\n\n for ag in self.agents:\n self.rewards[ag] = reward / self.num_agents\n self.dones[ag] = self.done\n self.infos[ag] = {}\n\n if self.renderOn:\n pygame.event.pump()\n self.draw()\n\n\ndef env(**kwargs):\n env = raw_env(**kwargs)\n env = wrappers.AssertOutOfBoundsWrapper(env)\n env = wrappers.OrderEnforcingWrapper(env)\n return env\n\n\nparallel_env = parallel_wrapper_fn(env)\n\n\nclass raw_env(AECEnv, EzPickle):\n # class env(MultiAgentEnv):\n metadata = {'render.modes': ['human', \"rgb_array\"], 'name': \"cooperative_pong_v3\"}\n\n def __init__(self, **kwargs):\n EzPickle.__init__(self, **kwargs)\n self._kwargs = kwargs\n\n self.seed()\n\n self.agents = self.env.agents[:]\n self.possible_agents = self.agents[:]\n self._agent_selector = agent_selector(self.agents)\n self.agent_selection = self._agent_selector.reset()\n # spaces\n self.action_spaces = dict(zip(self.agents, self.env.action_space))\n self.observation_spaces = dict(zip(self.agents, self.env.observation_space))\n self.state_space = self.env.state_space\n # dicts\n self.observations = {}\n self.rewards = self.env.rewards\n self.dones = self.env.dones\n self.infos = self.env.infos\n\n self.score = self.env.score\n\n # def convert_to_dict(self, list_of_list):\n # return dict(zip(self.agents, list_of_list))\n def seed(self, seed=None):\n self.randomizer, seed = seeding.np_random(seed)\n self.env = CooperativePong(self.randomizer, **self._kwargs)\n\n def reset(self):\n self.env.reset()\n self.agents = self.possible_agents[:]\n self.agent_selection = self._agent_selector.reset()\n self.rewards = self.env.rewards\n self._cumulative_rewards = {a: 0 for a in self.agents}\n self.dones = self.env.dones\n self.infos = self.env.infos\n\n def observe(self, agent):\n obs = self.env.observe()\n return obs\n\n def state(self):\n state = self.env.state()\n return state\n\n def close(self):\n self.env.close()\n\n def render(self, mode='human'):\n return self.env.render(mode)\n\n def step(self, action):\n if self.dones[self.agent_selection]:\n return self._was_done_step(action)\n agent = self.agent_selection\n if not self.action_spaces[agent].contains(action):\n raise Exception('Action for agent {} must be in Discrete({}).'\n 'It is currently {}'.format(agent, self.action_spaces[agent].n, action))\n\n self.env.step(action, agent)\n # select next agent and observe\n self.agent_selection = self._agent_selector.next()\n self.rewards = self.env.rewards\n self.dones = self.env.dones\n self.infos = self.env.infos\n\n self.score = self.env.score\n\n self._cumulative_rewards[agent] = 0\n self._accumulate_rewards()\n\n# This was originally created, in full, by Ananth Hari in a different repo, and was\n# added in by Justin Terry (which is why he's shown as the creator in the git history)\n"
]
| [
[
"numpy.rot90",
"numpy.sin",
"numpy.sign",
"numpy.transpose",
"numpy.cos",
"numpy.fliplr"
]
]
|
Corentin-M/Deployment_Notebook_Sagemaker | [
"fd2d8eebf4e837b50bd9243bc2e869dbb424cf75"
]
| [
"Project/serve/predict.py"
]
| [
"import argparse\nimport json\nimport os\nimport pickle\nimport sys\nimport sagemaker_containers\nimport pandas as pd\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.utils.data\n\nfrom model import LSTMClassifier\n\nfrom utils import review_to_words, convert_and_pad\n\ndef model_fn(model_dir):\n \"\"\"Load the PyTorch model from the `model_dir` directory.\"\"\"\n print(\"Loading model.\")\n\n # First, load the parameters used to create the model.\n model_info = {}\n model_info_path = os.path.join(model_dir, 'model_info.pth')\n with open(model_info_path, 'rb') as f:\n model_info = torch.load(f)\n\n print(\"model_info: {}\".format(model_info))\n\n # Determine the device and construct the model.\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model = LSTMClassifier(model_info['embedding_dim'], model_info['hidden_dim'], model_info['vocab_size'])\n\n # Load the store model parameters.\n model_path = os.path.join(model_dir, 'model.pth')\n with open(model_path, 'rb') as f:\n model.load_state_dict(torch.load(f))\n\n # Load the saved word_dict.\n word_dict_path = os.path.join(model_dir, 'word_dict.pkl')\n with open(word_dict_path, 'rb') as f:\n model.word_dict = pickle.load(f)\n\n model.to(device).eval()\n\n print(\"Done loading model.\")\n return model\n\ndef input_fn(serialized_input_data, content_type):\n print('Deserializing the input data.')\n if content_type == 'text/plain':\n data = serialized_input_data.decode('utf-8')\n return data\n raise Exception('Requested unsupported ContentType in content_type: ' + content_type)\n\ndef output_fn(prediction_output, accept):\n print('Serializing the generated output.')\n return str(prediction_output)\n\ndef predict_fn(input_data, model):\n print('Inferring sentiment of input data.')\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n \n if model.word_dict is None:\n raise Exception('Model has not been loaded properly, no word_dict.')\n \n # TODO: Process input_data so that it is ready to be sent to our model.\n # You should produce two variables:\n # data_X - A sequence of length 500 which represents the converted review\n # data_len - The length of the review\n\n data_X, data_len = convert_and_pad(model.word_dict, review_to_words(input_data))\n\n # Using data_X and data_len we construct an appropriate input tensor. Remember\n # that our model expects input data of the form 'len, review[500]'.\n data_pack = np.hstack((data_len, data_X))\n data_pack = data_pack.reshape(1, -1)\n \n data = torch.from_numpy(data_pack)\n data = data.to(device)\n\n # Make sure to put the model into evaluation mode\n model.eval()\n\n # TODO: Compute the result of applying the model to the input data. The variable `result` should\n # be a numpy array which contains a single integer which is either 1 or 0\n \n # Perform forward propagation\n output_data = model.forward(data)\n \n # Copy output_data tensor to host memory\n if torch.cuda.is_available():\n output_data.to('cpu')\n \n # Detach output_data from its computation history and round the value\n result = int(np.round(output_data.detach().numpy()))\n \n return result\n"
]
| [
[
"numpy.hstack",
"torch.cuda.is_available",
"torch.load",
"torch.from_numpy"
]
]
|
gbmxdwmssj/path_planner | [
"53e1d743dc8f780b677a69ea232ee0b9aeacaf5f"
]
| [
"scripts/hori_compar.py"
]
| [
"#!/usr/bin/env python\n\nimport rospy\nimport math\nimport csv\nimport numpy as np\nimport scipy\nfrom scipy import interpolate\nfrom scipy.interpolate import CubicHermiteSpline\nfrom nav_msgs.msg import *\nfrom hybrid_astar.srv import *\nfrom std_msgs.msg import *\nimport pylab as pl\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nfrom geometry_msgs.msg import *\nfrom hybrid_astar.srv import *\nfrom grid_map_msgs.msg import *\nimport time\nimport yaml\nfrom matplotlib.pyplot import MultipleLocator\nimport os\n\n\n\ns_path = None\no_path = None\np_path = None\nele_map = None\nfil_map = None\nstart = None\ngoal = None\nsgn = lambda x: 1 if x > 0 else -1 if x < 0 else 0\n\nele_map_value_range = [-0.5, 1.0]\ngrayscale_range = [0, 254]\nele_meter_range = [0, 198] # m\n\n\n\ndef normalizedHeadingRad(theta_z): # [0, 2pi)\n if theta_z < 0:\n theta_z = theta_z - 2.0 * math.pi * (int)(theta_z / (2.0 * math.pi))\n return 2.0 * math.pi + theta_z\n\n return theta_z - 2.0 * math.pi * (int)(theta_z / (2.0 * math.pi))\n\n\n\ndef sCallback(path):\n global s_path\n s_path = path\n\n\n\ndef oCallback(path):\n global o_path\n o_path = path\n\n\n\ndef pCallback(path):\n global p_path\n p_path = path\n\n\n\ndef eleCallback(map):\n global ele_map\n ele_map = map\n\n\n\ndef filCallback(map):\n global fil_map\n fil_map = map\n\n\n\ndef startCallback(data):\n global start\n start = data\n\n\n\ndef goalCallback(data):\n global goal\n goal = data\n\n\n\ndef getRollPitch(p1, p2, p3):\n a = 1.0 * (p2[1] - p1[1]) * (p3[2] - p1[2]) - (p3[1] - p1[1]) * (p2[2] - p1[2])\n b = 1.0 * (p2[2] - p1[2]) * (p3[0] - p1[0]) - (p3[2] - p1[2]) * (p2[0] - p1[0])\n c = 1.0 * (p2[0] - p1[0]) * (p3[1] - p1[1]) - (p3[0] - p1[0]) * (p2[1] - p1[1])\n roll = sgn(b) * math.acos(c / math.sqrt(b*b+c*c))\n pitch = sgn(a) * math.acos(math.sqrt((b*b+c*c) / (a*a+b*b+c*c)))\n return roll, pitch\n\n\n\ndef getSingleTf(path):\n if path[0].header.frame_id == 'forward':\n print('forward!')\n v_0 = 0.0 # m/s\n a_0 = 2.0 # m/s^2\n v_tra = 3.0\n a_f = -2.0\n v_f = 0.0\n t_f = None\n else:\n print('reverse!')\n v_0 = 0.0 # m/s\n a_0 = -2.0 # m/s^2\n v_tra = -3.0\n a_f = 2.0\n v_f = 0.0\n t_f = None\n\n ## compute the lenght of the path\n l_f = 0.0\n l_list = []\n for i in range(len(path) - 1, 0, -1):\n l_list.append(l_f)\n x = path[i].pose.position.x\n y = path[i].pose.position.y\n dx = path[i-1].pose.position.x - x\n dy = path[i-1].pose.position.y - y\n dis = math.sqrt(dx*dx + dy*dy)\n if v_tra < 0:\n dis = -dis\n l_f = l_f + dis\n\n l_list.append(l_f)\n frac_1 = (v_tra - v_0)*(v_tra - v_0) / (2 * a_0)\n frac_2 = (v_tra - v_f)*(v_tra - v_f) / (2 * a_f)\n t_f = (l_f + frac_1 - frac_2) / v_tra\n print(l_f)\n return t_f\n\n\n\ndef getTf(path):\n if len(path.poses) == 0:\n return\n\n ## division\n single_path = []\n paths = []\n for i in range(len(path.poses) - 1, 0, -1):\n single_path.append(path.poses[i])\n cur_dir = path.poses[i].header.frame_id\n next_dir = path.poses[i-1].header.frame_id\n if cur_dir != next_dir:\n if len(single_path) >= 2:\n paths.append(single_path)\n single_path = []\n single_path.append(path.poses[0])\n if len(single_path) >= 2:\n paths.append(single_path)\n\n t_f = 0.0\n for path in paths:\n t_f += getSingleTf(path)\n\n return t_f\n\n\n\nrospy.init_node('performance', anonymous=True)\nrospy.Subscriber('/sPath', Path, sCallback)\nrospy.Subscriber('/oPath', Path, oCallback)\nrospy.Subscriber('/predicted_path', Path, pCallback)\nrospy.Subscriber('/grid_map_visualization/elevation_grid', OccupancyGrid, eleCallback)\nrospy.Subscriber('/grid_map_filter_demo/filtered_map', GridMap, filCallback)\nrospy.Subscriber('/initialpose', PoseWithCovarianceStamped, startCallback)\nrospy.Subscriber('/move_base_simple/goal', PoseStamped, goalCallback)\nstart_pub = rospy.Publisher('/initialpose', PoseWithCovarianceStamped, queue_size=10, latch=True)\ngoal_pub = rospy.Publisher('/move_base_simple/goal', PoseStamped, queue_size=10, latch=True)\n# print('I waiting for service /euler_from_quaternion...')\n# rospy.wait_for_service('/euler_from_quaternion')\n# print('Service /euler_from_quaternion is availiable!')\n\nmajor_locator=MultipleLocator(0.25)\n\n\n\ninit_ele = None\n# euler_from_quaternion = rospy.ServiceProxy('/euler_from_quaternion', EulerFromQuaternion)\nwhile not rospy.core.is_shutdown():\n\n print('Missing for start or goal...')\n while (start is None or goal is None) and not rospy.core.is_shutdown():\n time.sleep(0.5)\n\n if not rospy.core.is_shutdown():\n print('Launch!')\n xs = []\n ys = []\n eles = []\n ls = []\n l = 0.0\n rolls = []\n pitchs = []\n yaws = []\n W = 1.7\n L = 2.0\n smooth_cost = 0.0\n\n rospy.set_param('/hybrid_astar/s_path_name', '/NoTS_sPath')\n rospy.set_param('/hybrid_astar/occ_thre', 20)\n rospy.set_param('/hybrid_astar/cost_mode', 0)\n rospy.set_param('/hybrid_astar/occ_wei', 2.0)\n start_pub.publish(start)\n goal_pub.publish(goal)\n print('---------- NoTS start! ----------')\n os.system('rosrun hybrid_astar hybrid_astar')\n print('NoTS stop!')\n time.sleep(1.0)\n\n rospy.set_param('/hybrid_astar/s_path_name', '/TS_NoSus_sPath')\n rospy.set_param('/hybrid_astar/occ_thre', 20)\n rospy.set_param('/hybrid_astar/cost_mode', 1)\n rospy.set_param('/hybrid_astar/occ_wei', 0.7)\n print('---------- TS_NoSus start! ----------')\n os.system('rosrun hybrid_astar hybrid_astar')\n print('TS_NoSus stop!')\n time.sleep(1.0)\n\n rospy.set_param('/hybrid_astar/s_path_name', '/TS_Sus_sPath')\n rospy.set_param('/hybrid_astar/occ_thre', 20)\n rospy.set_param('/hybrid_astar/cost_mode', 2)\n rospy.set_param('/hybrid_astar/occ_wei', 5.7)\n print('---------- TS_Sus start! ----------')\n os.system('rosrun hybrid_astar hybrid_astar')\n print('TS_Sus stop!')\n time.sleep(1.0)\n\n start = None\n goal = None\n\n # with open('/home/kai/performance_sheet.csv', 'w', newline='') as t_file:\n # csv_writer = csv.writer(t_file)\n # csv_writer.writerow(['length', l])\n # csv_writer.writerow(['smooth_cost', smooth_cost])\n # csv_writer.writerow(['t_f', t_f])\n\n else:\n print('Shutdown!')\n\nelse:\n print('Shutdown!')\n"
]
| [
[
"matplotlib.pyplot.MultipleLocator"
]
]
|
chie4hao/fgotest | [
"b489957fa90a297390d8ab620a4dc5850f4225d3"
]
| [
"utils.py"
]
| [
"# -*- coding: utf-8 -*- \nimport os\nimport numpy as np\nfrom PIL import Image, ImageGrab\nimport time\nimport matplotlib.pyplot as plt\nimport pytesseract\nimport win32api\nimport win32gui\nimport win32ui\nimport win32con\nfrom ctypes import windll\nimport cv2\n############################鼠标点击使用常数########################################\nX1 = float(1032) #STEP 1\nY1 = float(578)\n################################获取信息的常数################\nX6 = float(1032) \ntem = float(578) \nY6A = float(331/tem)\nY6B = float(487/tem)\nY6C = float(87/tem)\nY6D = float(243/tem)\n\nCARDS_POSITONS = [(float(45/X6), Y6A, float(165/X6), Y6B), (float(250/X6), Y6A, float(370/X6), Y6B),\\\n (float(455/X6), Y6A, float(575/X6), Y6B), (float(660/X6), Y6A, float(780/X6), Y6B),\\\n (float(865/X6), Y6A, float(985/X6), Y6B), (float(275/X6), Y6C, float(395/X6), Y6D),\\\n (float(460/X6), Y6C, float(580/X6), Y6D), (float(645/X6), Y6C, float(765/X6), Y6D)]\n\nBATTLE = (float(850/1025) , float(433/581), float(975/1025) , float(550/581))\nROUND = [float(690/X1), float(6/Y1), float(746/X1), float(34/Y1)] #第几回合\n# END = (float(45/X1), float(340/Y1), float(989/X1), float(442/Y1)) #结束界面判定\nEND = (float(800/X1), float(520/Y1), float(990/X1), float(570/Y1)) #结束界面判定\n\nCHOICE_CHECK_BOX = (float(880/X1), float(516/Y1), 1, 1) #主界面\nCHECK_APPLE_BOX = (float(258/X1), float(96/Y1), float(346/X1), float(193/Y1)) #确认苹果界面\n\n\nBORDER = [40, 55, 0, 0]\n\nBOXS = {\n \"HOME\": CHOICE_CHECK_BOX,\n \"APPLE\": CHECK_APPLE_BOX,\n \"BATTLE\":BATTLE,\n# \"END\": END,\n \"ROUND\": ROUND,\n \"CARDS\": CARDS_POSITONS\n}\n################################对比的常数#########################\npath = os.path.join(os.path.abspath(os.path.dirname(os.path.realpath('__file__'))), \"data\")\nCHECK_POINT = Image.open(os.path.join(path,\"check.png\")) #选关卡图片 用来对比\nCHECK_APPLE = Image.open(os.path.join(path,\"apple.png\")) #吃苹果图片\nBATTLE_SCREEM = Image.open(os.path.join(path,\"battle.png\")) #人物头像,用来确认是否在技能界面\nCHECH_SUPPORT = Image.open(os.path.join(path,\"teasupport.png\"))\nQP_SUPPORT = Image.open(os.path.join(path,\"qpsupport.png\"))\n\n# END_SCREEM = Image.open(os.path.join(path,\"end.png\"))\n# STATE = [\"HOME\", \"APPLE\", \"BATTLE\", \"END\"]\nSTATE = [\"HOME\", \"APPLE\", \"BATTLE\"]\n# IMAGES = {\"HOME\":CHECK_POINT, \"APPLE\":CHECK_APPLE, \"BATTLE\":BATTLE_SCREEM, \"END\": END_SCREEM}\nIMAGES = {\"HOME\":CHECK_POINT, \"APPLE\":CHECK_APPLE, \"BATTLE\":BATTLE_SCREEM}\n\n##################################################################外部方法\ndef True_Type(input):\n if input:\n return False\n else:\n return True\n\ndef show_plot(image):\n plt.figure(\"Image\")\n plt.imshow(image)\n plt.show()\n\ndef Absolute_Position(position, size):\n \"\"\"return Absolute position in image\n \"\"\"\n rp = position*np.array(size*2)\n return rp.astype(np.int32)\n'''\ndef Crop_Border(image):\n \"\"\"crop windows border to get game image\n \"\"\"\n size = image.size\n box = [6, 46, 1286 ,766]\n # box = [BORDER[2], BORDER[0], size[0] - BORDER[3], size[1] - BORDER[1]]\n image = image.crop(box)\n return image\n'''\ndef Crop(image, box):\n \"\"\"crop image using box Relative_Box get image to confirm state\n \"\"\"\n true_box = Absolute_Position(box, list(image.size))\n image = image.crop(true_box)\n return image\n########################################################################################\ndef is_end(image):\n image = np.array(image)\n size = np.size(image)\n energy = np.sum(image)/size\n dark = np.sum(image < 30)/size\n color = np.sum(image > 235)/size\n if dark > 0.8 and color > 0.025:\n print(dark, color)\n return True\n else:\n False\n\ndef getcolor(image):\n COLOR = [\"R\", \"G\", \"B\"]\n image = np.array(image.convert(\"RGB\"))\n c_min = np.min(image, axis=2)\n array = image - np.expand_dims(c_min, axis=2)\n c_max = [np.max(array[:,:,i]) for i in range(3)]\n c_sum = [np.sum(array[:,:,i]) for i in range(3)]\n if (c_max > np.array([230, 230, 230])).any():\n idx = np.argmax(c_sum)\n color = COLOR[idx]\n return color\n else:\n return None\n\ndef Compare(img1, img2, size = (64, 64)):\n img1 = np.array(img1.resize(size).convert(\"RGB\"))/256\n img2 = np.array(img2.resize(size).convert(\"RGB\"))/256\n loss = np.max(np.abs(img1 - img2), axis=2)\n loss = np.sum(loss < 0.2)/(64*64)\n if loss > 0.75:\n return True\n else:\n return False\n######################################################################\ndef getcard(image):\n # image = Crop_Border(image)\n cards = [Crop(image, box) for box in BOXS[\"CARDS\"]]\n cards = [getcolor(card) for card in cards]\n return cards\n\ndef getstate(self, image, s = None):\n # image = Crop_Border(image)\n\n '''\n b = image.getpixel((923, 56))\n print(b)\n print(b==(123,124,124))\n '''\n\n # image.save(\"test.png\")\n if s:\n search_state = s\n else:\n search_state = STATE\n \n for i in search_state:\n img = Crop(image, BOXS[i])\n # img.save(i+\".png\")\n if IMAGES[i]:\n if Compare(img, IMAGES[i]):\n if i == \"APPLE\":\n self.click(49)\n self.click(50)\n time.sleep(1)\n while True:\n image = capture(self.hwnd)\n self.image=image\n if is_support(self.image):\n break\n time.sleep(1)\n if i == \"HOME\":\n self.click(48)\n time.sleep(1)\n return i\n # print(image.getpixel((1006,682)))\n # if image.getpixel((949, 675))==(0xB4,0xAF,0x9E) and image.getpixel((1006,682)) == (0xD2,0xD2,0xD2) and image.getpixel((1059,693))==(0x5A,0x66,0x75) and image.getpixel((1155,685))==(0x2C,0x33,0x68):\n if image.getpixel((912, 59))==(0x8E,0x8E,0x8E) and image.getpixel((923,57)) == (0x8D,0x8D,0x8D) and image.getpixel((911,29))==(0x77,0x77,0x77) and image.getpixel((913,53))==(0x83,0x83,0x83):\n return \"END\"\n elif image.getpixel((273,158))==(0xc3,0x92,0x70) and image.getpixel((282,159))==(0x47,0x42,0x46)\\\n and image.getpixel((282,162))==(0x55,0xe9,0xd3)and image.getpixel((316,162))==(0xfb,0xc6,0x88):\n print(\"REBOOTING\")\n while True:\n windll.user32.SetCursorPos(298,213) #鼠标移动到\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) #左键按下\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)\n time.sleep(3)\n image = capture(self.hwnd)\n if is_comfirm(image):\n print(\"REBOOT SUCCESS\")\n self.click(50)\n break\n elif is_cha(image):\n print(\"click cha\")\n self.click(55)\n break\n\n self.click(90)\n\n elif image.getpixel((832,557))==(0x7c,0x7c,0x7c) and image.getpixel((776,557))==(0x04,0x04,0x04)\\\n and image.getpixel((776,559))==(0x22,0x22,0x22) and image.getpixel((776,560))==(8,8,8)\\\n and image.getpixel((776,567))==(3,3,3) and image.getpixel((842,557))==(0x8d,0x8d,0x8d):\n print(\"network error\")\n self.click(50)\n time.sleep(2)\n elif (i!=\"APPLE\"):\n return False\n image = capture(self.hwnd)\n self.image=image\n s=getstate(self,image)\n return s\n\n\ndef is_support(image):\n # image = Crop_Border(image)\n # print(image.getpixel((859,275)))\n if image.getpixel((843,258))==(21,106,1) and image.getpixel((928,258))==(25,59,116)\\\n and image.getpixel((1013,258))==(123,17,8):\n return True\n return False\n\ndef is_pcards(image):\n # image = Crop_Border(image)\n # print(image.getpixel((859,275)))\n if image.getpixel((1059,59))==(0xff,0xff,0xff) and image.getpixel((1147,680))==(0x0f,0xac,0xd6) and image.getpixel((1180,681))==(0xbd,0xdc,0xfa)and image.getpixel((1212,681))==(0x0d,0x3f,0x64):\n return True\n return False\n\n# 师匠红茶学妹\n'''\nrequire =[\n (51, 326, 96, 126, 172), (129,340, 203, 159, 176), (162,351, 255, 241, 233), (191, 359, 248, 251, 179),\n (57, 288, 216, 158, 249), (80, 266, 69, 31, 67), (143, 260, 167, 77, 77), (190, 286, 195, 222, 118),\n (1138, 343, 0x7E, 0xB2, 0x37), (1160, 332, 0xDF, 0xFF, 0xAD)]\n'''\n'''\nrequire =[\n (51, 326, 103, 134, 173), (129,340, 231, 182, 206), (162,351, 255, 241, 230), (191, 359, 248, 251, 179),\n (57, 288, 216, 158, 249), (80, 266, 62, 22, 71), (143, 260, 156, 59, 59), (190, 286, 195, 222, 118),\n (1138, 343, 0x7E, 0xB2, 0x37), (1160, 332, 0xDF, 0xFF, 0xAD)]\n'''\nrequire =[\n (51, 326, 0x5e, 0x82, 0xb8), (129,340, 0xc6, 0x94, 0xd7), (162,351, 255, 241, 233), (191, 359, 248, 251, 179),\n (57, 288, 216, 158, 249), (80, 266, 0x3d, 0x1a, 0x45), (143, 260, 0xbd, 0x31, 0x38), (190, 286, 195, 222, 118),\n (1138, 343, 0x85, 0xb7, 0x33), (1160, 332, 0xe1, 0xfe, 0xaf)]\n\n'''\n# 蒙娜丽莎\nrequire =[(61,335,73,96,192),(110,353,22,47,72),(130,364,255,189,148),(190,358,254,254,168),\n (1138, 343, 0x7E, 0xB2, 0x37), (1160, 332, 0xDF, 0xFF, 0xAD)]\n'''\ndef Compare_support(img1, img2, size = (64, 64)):\n img1 = np.array(img1.resize(size).convert(\"RGB\"))/256\n img2 = np.array(img2.resize(size).convert(\"RGB\"))/256\n loss = np.max(np.abs(img1 - img2), axis=2)\n loss = np.sum(loss < 0.2)/(64*64)\n if loss > 0.95:\n return True\n else:\n return False\n\ndef is_comfirm(image):\n # image = Crop_Border(image)\n if image.getpixel((736,376))==(0xff,0,0) and image.getpixel((746,555))==(0xdc,0xdd,0xdd)\\\n and image.getpixel((770,560))==(5,5,5)and image.getpixel((898,575))==(0x33,0x33,0x34):\n return True\n return False\n\ndef is_cha(image):\n if image.getpixel((1210,0))==(0x5c,0x5d,0x5d) and image.getpixel((1211,0))==(0xe5,0xe5,0xe5)\\\n and image.getpixel((1213,2))==(0x99,0x99,0x99)and image.getpixel((1213,3))==(0x32,0x32,0x32)\\\n and image.getpixel((1214,2))==(0x7f,0x7f,0x7f):\n return True\n return False\n\ndef is_pool(image):\n if image.getpixel((454,686))==(0x12,0x7a,0xb3) and image.getpixel((458,686))==(0xaf,0xb9,0xc5)\\\n and image.getpixel((475,686))==(0xc7,0xda,0xe0)and image.getpixel((501,686))==(0xd1,0xd5,0xd9)\\\n and image.getpixel((449,361))==(0xf8,0x88,0x39):\n return True\n return False\n\ndef if_pool_re(image):\n print(image.getpixel((200,426)),image.getpixel((200,440)),image.getpixel((200,463)),image.getpixel((203,485)))\n\n if image.getpixel((200,426))==(0x09,0x50,0x6f) and image.getpixel((200,440))==(0x07,0x5a,0x75)\\\n and image.getpixel((200,463))==(0x05,0x5f,0x78)and image.getpixel((203,485))==(0xff,0xff,0xff):\n return True\n return False\n\ndef is_requiresupport(image):\n # return -1\n # image = Crop_Border(image)\n '''\n if image.getpixel((191,359))==(248,251,179) and image.getpixel((190,286))==(195,222,118)\\\n and image.getpixel((1138,343))==(0x7e,0xb2,0x37)and image.getpixel((1160,332))==(0xdf,0xff,0xad):\n box = [51, 326, 208, 370]\n image1 = image.crop(box)\n if Compare_support(image1, QP_SUPPORT):\n return 1\n if image.getpixel((191,559))==(248,251,179) and image.getpixel((190,486))==(195,222,118)\\\n and image.getpixel((1138,543))==(0x7e,0xb2,0x37)and image.getpixel((1160,532))==(0xdf,0xff,0xad):\n box = [51, 526, 208, 570]\n image2 = image.crop(box)\n if Compare_support(image2, QP_SUPPORT):\n return 2\n '''\n '''\n if image.getpixel((191,359))==(248,251,179) and image.getpixel((190,286))==(195,222,118)\\\n and image.getpixel((1138,343))==(0x85,0xb7,0x33) and image.getpixel((1160,332))==(0xe1,0xfe,0xaf):\n # and image.getpixel((1138,343))==(0x7e,0xb2,0x37)and image.getpixel((1160,332))==(0xdf,0xff,0xad):\n \n box = [51, 240, 208, 370]\n image1 = image.crop(box)\n if Compare_support(image1, CHECH_SUPPORT):\n return 1\n if image.getpixel((191,559))==(248,251,179) and image.getpixel((190,486))==(195,222,118)\\\n and image.getpixel((1138,343))==(0x85,0xb7,0x33) and image.getpixel((1160,332))==(0xe1,0xfe,0xaf):\n # and image.getpixel((1138,543))==(0x7e,0xb2,0x37)and image.getpixel((1160,532))==(0xdf,0xff,0xad):\n box = [51, 440, 208, 570]\n image2 = image.crop(box)\n if Compare_support(image2, CHECH_SUPPORT):\n return 2\n '''\n \n # 刷池子cba助战\n if image.getpixel((53,376))==(0xe6,0xbc,0x50) and image.getpixel((62,376))==(0xef,0xcd,0x66)\\\n and image.getpixel((70,288))==(0xd7,0x9e,0xf8) and image.getpixel((114,277))==(0xff,0xff,0xe0)\\\n and image.getpixel((163,275))==(0x80,0x3e,0x70) and image.getpixel((190,286))==(195,222,118) \\\n and image.getpixel((1138,343))==(0x85,0xb7,0x33) and image.getpixel((1160,332))==(0xe1,0xfe,0xaf)\\\n and image.getpixel((191,359))==(248,251,179):\n return 1\n if image.getpixel((53,576))==(0xe6,0xbc,0x50) and image.getpixel((62,576))==(0xef,0xcd,0x66)\\\n and image.getpixel((70,488))==(0xd7,0x9e,0xf8) and image.getpixel((114,477))==(0xff,0xff,0xe0)\\\n and image.getpixel((163,475))==(0x80,0x3e,0x70) and image.getpixel((190,486))==(195,222,118)\\\n and image.getpixel((1138,543))==(0x85,0xb7,0x33) and image.getpixel((1160,532))==(0xe1,0xfe,0xaf)\\\n and image.getpixel((191,559))==(248,251,179): \n return 2\n \n return 0\n '''\n for i in require:\n if image.getpixel((i[0], i[1])) == (i[2], i[3], i[4]):\n print(True)\n else: print(False)\n \n for i in require:\n if image.getpixel((i[0], i[1])) != (i[2], i[3], i[4]):\n flag=2\n break\n if flag == 1:\n return 1\n for i in require:\n if image.getpixel((i[0], i[1]+200)) != (i[2], i[3], i[4]):\n flag=0\n break\n return flag\n '''\n\n'''\ndef is_xuemei(image):\n image = Crop_Border(image)\n if image.getpixel((51, 326))==(172,126,96) and image.getpixel((129,340)) == (176,158,203) and image.getpixel((162,351))==(233,241,255) and image.getpixel((191,359))==(179,251,248):\n return True\n return False\n\ndef is_shijiang(image):\n image = Crop_Border(image)\n if image.getpixel((57, 488))==(249,158,216) and image.getpixel((80,466)) == (67,31,69) and image.getpixel((143,460))==(77,77,167) and image.getpixel((190,486))==(118,222,195):\n return True\n return False\n'''\ndef get_round(image):\n # config = \"--psm 10 digits\"\n # image = Crop_Border(image)\n\n\n # image = Crop(image, BOXS[\"ROUND\"])\n # image = image.convert(\"L\")\n # image.save(\"round.png\")\n # code = pytesseract.image_to_string(image, config=config)[0]\n\n # print(pytesseract.image_to_string(image, config=config))\n\n # round 3 876,29 (255,255,255) 870,16 (250,250,250) 875,18 (255,255,255)\n if image.getpixel((873, 31))==(255,255,255) and image.getpixel((873,15)) == (92,92,92) and image.getpixel((871,17))==(234,234,234) and image.getpixel((867,19))==(200,200,200):\n return 0\n elif image.getpixel((866, 17))==(113,113,113) and image.getpixel((873,16)) == (254,254,254) and image.getpixel((876,22))==(235,235,235) and image.getpixel((873,33))==(214,214,214):\n return 1\n elif image.getpixel((867, 16))==(118,118,118) and image.getpixel((875,16)) == (194,194,194) and image.getpixel((875,27))==(198,198,198) and image.getpixel((867,33))==(174,174,174):\n return 2\n elif image.getpixel((273,158))==(0xc3,0x92,0x70) and image.getpixel((282,159))==(0x47,0x42,0x46)\\\n and image.getpixel((282,162))==(0x55,0xe9,0xd3)and image.getpixel((316,162))==(0xfb,0xc6,0x88):\n return -1\n else:\n return 3\n \ndef capture(hwnd):\n \"\"\"capture applications screem\"\"\"\n # left, top, right, bot = win32gui.GetWindowRect(hwnd)\n # w = (right - left)\n # h = (bot - top)\n # 104,37 106,67 \n # print(hwnd)\n # win32gui.ShowWindow(hwnd,win32con.SW_RESTORE)\n # win32gui.SetForegroundWindow(hwnd)\n game_rect=win32gui.GetWindowRect(hwnd)\n src_image=ImageGrab.grab(game_rect)\n # src_image.save(\"123466.png\")\n '''\n hwndDC = win32gui.GetWindowDC(hwnd)\n mfcDC = win32ui.CreateDCFromHandle(hwndDC)\n saveDC = mfcDC.CreateCompatibleDC()\n saveBitMap = win32ui.CreateBitmap()\n\n\n saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)\n saveDC.SelectObject(saveBitMap)\n\n\n\n result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0)\n bmpinfo = saveBitMap.GetInfo()\n bmpstr = saveBitMap.GetBitmapBits(True)\n im = Image.frombuffer('RGB',(bmpinfo['bmWidth'], bmpinfo['bmHeight']),\n bmpstr, 'raw', 'BGRX', 0, 1)\n\n im.save(\"21234.png\")\n win32gui.DeleteObject(saveBitMap.GetHandle())\n saveDC.DeleteDC()\n mfcDC.DeleteDC()\n win32gui.ReleaseDC(hwnd, hwndDC)\n '''\n # if result == 1:\n # PrintWindow Succeeded\n # im.save(\"test.png\")\n # im.show()\n \n '''\n if w <= 200 or h <= 200:\n raise \"captrue error\"\n ''' \n return src_image\n\nif __name__ == '__main__':\n scrpt = None\n \n"
]
| [
[
"numpy.max",
"numpy.array",
"numpy.sum",
"numpy.min",
"matplotlib.pyplot.figure",
"numpy.argmax",
"numpy.size",
"numpy.abs",
"matplotlib.pyplot.show",
"numpy.expand_dims",
"matplotlib.pyplot.imshow"
]
]
|
cogerk/walk-up-music-scrapper | [
"74df610985e6ff220a605a49933a0655e247caa3"
]
| [
"walkupEnv/lib/python3.6/site-packages/holoviews/plotting/bokeh/annotation.py"
]
| [
"from collections import defaultdict\n\nimport param\nimport numpy as np\nfrom bokeh.models import Span, Arrow, Div as BkDiv\ntry:\n from bokeh.models.arrow_heads import TeeHead, NormalHead\n arrow_start = {'<->': NormalHead, '<|-|>': NormalHead}\n arrow_end = {'->': NormalHead, '-[': TeeHead, '-|>': NormalHead,\n '-': None}\nexcept:\n from bokeh.models.arrow_heads import OpenHead, NormalHead\n arrow_start = {'<->': NormalHead, '<|-|>': NormalHead}\n arrow_end = {'->': NormalHead, '-[': OpenHead, '-|>': NormalHead,\n '-': None}\n\nfrom ...core.util import datetime_types, dimension_sanitizer, basestring\nfrom ...element import HLine\nfrom ..plot import GenericElementPlot\nfrom .element import (ElementPlot, CompositeElementPlot, ColorbarPlot,\n text_properties, line_properties)\nfrom .plot import BokehPlot\nfrom .util import date_to_integer\n\n\nclass TextPlot(ElementPlot):\n\n style_opts = text_properties+['color', 'angle']\n _plot_methods = dict(single='text', batched='text')\n\n def get_data(self, element, ranges, style):\n mapping = dict(x='x', y='y', text='text')\n if self.static_source:\n return dict(x=[], y=[], text=[]), mapping, style\n if self.invert_axes:\n data = dict(x=[element.y], y=[element.x])\n else:\n data = dict(x=[element.x], y=[element.y])\n self._categorize_data(data, ('x', 'y'), element.dimensions())\n data['text'] = [element.text]\n if 'text_align' not in style:\n style['text_align'] = element.halign\n baseline = 'middle' if element.valign == 'center' else element.valign\n if 'text_baseline' not in style:\n style['text_baseline'] = baseline\n if 'text_font_size' not in style:\n style['text_font_size'] = '%dPt' % element.fontsize\n if 'color' in style:\n style['text_color'] = style.pop('color')\n style['angle'] = np.deg2rad(style.get('angle', element.rotation))\n return (data, mapping, style)\n\n def get_batched_data(self, element, ranges=None):\n data = defaultdict(list)\n zorders = self._updated_zorders(element)\n for (key, el), zorder in zip(element.data.items(), zorders):\n style = self.lookup_options(element.last, 'style')\n style = style.max_cycles(len(self.ordering))[zorder]\n eldata, elmapping, style = self.get_data(el, ranges, style)\n for k, eld in eldata.items():\n data[k].extend(eld)\n return data, elmapping, style\n\n def get_extents(self, element, ranges=None):\n return None, None, None, None\n\n\n\nclass LabelsPlot(ColorbarPlot):\n\n color_index = param.ClassSelector(default=None, class_=(basestring, int),\n allow_None=True, doc=\"\"\"\n Index of the dimension from which the color will the drawn\"\"\")\n\n show_legend = param.Boolean(default=False, doc=\"\"\"\n Whether to show legend for the plot.\"\"\")\n\n xoffset = param.Number(default=None, doc=\"\"\"\n Amount of offset to apply to labels along x-axis.\"\"\")\n\n yoffset = param.Number(default=None, doc=\"\"\"\n Amount of offset to apply to labels along x-axis.\"\"\")\n\n style_opts = text_properties + ['cmap', 'angle']\n\n _plot_methods = dict(single='text', batched='text')\n _batched_style_opts = text_properties\n\n def get_data(self, element, ranges, style):\n style = self.style[self.cyclic_index]\n style['angle'] = np.deg2rad(style.get('angle', 0))\n\n dims = element.dimensions()\n coords = (1, 0) if self.invert_axes else (0, 1)\n xdim, ydim, tdim = (dimension_sanitizer(dims[i].name) for i in coords+(2,))\n mapping = dict(x=xdim, y=ydim, text=tdim)\n data = {d: element.dimension_values(d) for d in (xdim, ydim)}\n if self.xoffset is not None:\n data[xdim] = data[xdim] + self.xoffset\n if self.yoffset is not None:\n data[ydim] = data[ydim] + self.yoffset\n data[tdim] = [dims[2].pprint_value(v) for v in element.dimension_values(2)]\n self._categorize_data(data, (xdim, ydim), element.dimensions())\n\n cdim = element.get_dimension(self.color_index)\n if cdim is None:\n return data, mapping, style\n\n cdata, cmapping = self._get_color_data(element, ranges, style, name='text_color')\n data['text_color'] = cdata[dimension_sanitizer(cdim.name)]\n mapping['text_color'] = cmapping['text_color']\n return data, mapping, style\n\n\n\nclass LineAnnotationPlot(ElementPlot):\n\n style_opts = line_properties + ['level']\n\n _plot_methods = dict(single='Span')\n\n def get_data(self, element, ranges, style):\n data, mapping = {}, {}\n dim = 'width' if isinstance(element, HLine) else 'height'\n if self.invert_axes:\n dim = 'width' if dim == 'height' else 'height'\n mapping['dimension'] = dim\n loc = element.data\n if isinstance(loc, datetime_types):\n loc = date_to_integer(loc)\n mapping['location'] = loc\n return (data, mapping, style)\n\n def _init_glyph(self, plot, mapping, properties):\n \"\"\"\n Returns a Bokeh glyph object.\n \"\"\"\n box = Span(level=properties.get('level', 'glyph'), **mapping)\n plot.renderers.append(box)\n return None, box\n\n def get_extents(self, element, ranges=None):\n return None, None, None, None\n\n\n\nclass SplinePlot(ElementPlot):\n \"\"\"\n Draw the supplied Spline annotation (see Spline docstring).\n Does not support matplotlib Path codes.\n \"\"\"\n\n style_opts = line_properties\n _plot_methods = dict(single='bezier')\n\n def get_data(self, element, ranges, style):\n if self.invert_axes:\n data_attrs = ['y0', 'x0', 'cy0', 'cx0', 'cy1', 'cx1', 'y1', 'x1']\n else:\n data_attrs = ['x0', 'y0', 'cx0', 'cy0', 'cx1', 'cy1', 'x1', 'y1']\n verts = np.array(element.data[0])\n inds = np.where(np.array(element.data[1])==1)[0]\n data = {da: [] for da in data_attrs}\n skipped = False\n for vs in np.split(verts, inds[1:]):\n if len(vs) != 4:\n skipped = len(vs) > 1\n continue\n for x, y, xl, yl in zip(vs[:, 0], vs[:, 1], data_attrs[::2], data_attrs[1::2]):\n data[xl].append(x)\n data[yl].append(y)\n if skipped:\n self.warning('Bokeh SplitPlot only support cubic splines, '\n 'unsupported splines were skipped during plotting.')\n data = {da: data[da] for da in data_attrs}\n return (data, dict(zip(data_attrs, data_attrs)), style)\n\n\n\nclass ArrowPlot(CompositeElementPlot):\n\n style_opts = (['arrow_%s' % p for p in line_properties+['size']] + text_properties)\n\n _style_groups = {'arrow': 'arrow', 'label': 'text'}\n\n def get_data(self, element, ranges, style):\n plot = self.state\n label_mapping = dict(x='x', y='y', text='text')\n\n # Compute arrow\n x1, y1 = element.x, element.y\n axrange = plot.x_range if self.invert_axes else plot.y_range\n span = (axrange.end - axrange.start) / 6.\n if element.direction == '^':\n x2, y2 = x1, y1-span\n label_mapping['text_baseline'] = 'top'\n elif element.direction == '<':\n x2, y2 = x1+span, y1\n label_mapping['text_align'] = 'left'\n label_mapping['text_baseline'] = 'middle'\n elif element.direction == '>':\n x2, y2 = x1-span, y1\n label_mapping['text_align'] = 'right'\n label_mapping['text_baseline'] = 'middle'\n else:\n x2, y2 = x1, y1+span\n label_mapping['text_baseline'] = 'bottom'\n arrow_opts = {'x_end': x1, 'y_end': y1,\n 'x_start': x2, 'y_start': y2}\n\n # Define arrowhead\n arrow_opts['arrow_start'] = arrow_start.get(element.arrowstyle, None)\n arrow_opts['arrow_end'] = arrow_end.get(element.arrowstyle, NormalHead)\n\n # Compute label\n if self.invert_axes:\n label_data = dict(x=[y2], y=[x2])\n else:\n label_data = dict(x=[x2], y=[y2])\n label_data['text'] = [element.text]\n return ({'label': label_data},\n {'arrow': arrow_opts, 'label': label_mapping}, style)\n\n def _init_glyph(self, plot, mapping, properties, key):\n \"\"\"\n Returns a Bokeh glyph object.\n \"\"\"\n properties.pop('legend', None)\n if key == 'arrow':\n properties.pop('source')\n arrow_end = mapping.pop('arrow_end')\n arrow_start = mapping.pop('arrow_start')\n start = arrow_start(**properties) if arrow_start else None\n end = arrow_end(**properties) if arrow_end else None\n glyph = Arrow(start=start, end=end, **dict(**mapping))\n else:\n properties = {p if p == 'source' else 'text_'+p: v\n for p, v in properties.items()}\n glyph, _ = super(ArrowPlot, self)._init_glyph(\n plot, mapping, properties, 'text_1')\n plot.renderers.append(glyph)\n return None, glyph\n\n def get_extents(self, element, ranges=None):\n return None, None, None, None\n\n\n\nclass DivPlot(BokehPlot, GenericElementPlot):\n\n height = param.Number(default=300)\n\n width = param.Number(default=300)\n\n finalize_hooks = param.HookList(default=[], doc=\"\"\"\n Optional list of hooks called when finalizing a column.\n The hook is passed the plot object and the displayed\n object, and other plotting handles can be accessed via plot.handles.\"\"\")\n\n _stream_data = False\n\n def __init__(self, element, plot=None, **params):\n super(DivPlot, self).__init__(element, **params)\n self.callbacks = []\n self.handles = {} if plot is None else self.handles['plot']\n\n\n def get_data(self, element, ranges, style):\n return element.data, {}, style\n\n\n def initialize_plot(self, ranges=None, plot=None, plots=None, source=None):\n \"\"\"\n Initializes a new plot object with the last available frame.\n \"\"\"\n # Get element key and ranges for frame\n element = self.hmap.last\n key = self.keys[-1]\n self.current_frame = element\n self.current_key = key\n\n data, _, _ = self.get_data(element, ranges, {})\n div = BkDiv(text=data, width=self.width, height=self.height)\n self.handles['plot'] = div\n self._execute_hooks(element)\n self.drawn = True\n return div\n\n\n def update_frame(self, key, ranges=None, plot=None):\n \"\"\"\n Updates an existing plot with data corresponding\n to the key.\n \"\"\"\n element = self._get_frame(key)\n text, _, _ = self.get_data(element, ranges, {})\n self.handles['plot'].text = text\n"
]
| [
[
"numpy.array",
"numpy.split"
]
]
|
mitramir55/PassivePy | [
"6ffe8d082a40369f226909c84aa97286c6a1edd5"
]
| [
"PassivePyCode/PassivePySrc/PassivePy.py"
]
| [
"import pandas as pd\nimport numpy as np\nimport spacy\nfrom termcolor import colored\nimport regex as re\nfrom itertools import chain \nfrom tqdm import tqdm\nimport tqdm.notebook as tq\nimport os, sys, gc\n\n\ntry: \n from PassivePyCode.PassivePySrc.rules_for_all_passives import create_matcher\n from PassivePyCode.PassivePySrc.rules_for_full_passives import create_matcher_full\n from PassivePyCode.PassivePySrc.rules_for_truncated_passives import create_matcher_truncated\nexcept: \n from PassivePySrc.rules_for_all_passives import create_matcher\n from PassivePySrc.rules_for_full_passives import create_matcher_full\n from PassivePySrc.rules_for_truncated_passives import create_matcher_truncated\n\nclass PassivePyAnalyzer:\n \n \"\"\"\n Get the data from a dataframe.\n\n Clean the dataset based on the given regex patterns.\n Match passive voice sentence level or corpus level.\n save the output to a file\n\n \"\"\"\n def __init__(self, spacy_model = \"en_core_web_lg\"):\n\n \"\"\"\n Create the Detector\n\n n_processses: number of core to use\n batch_size: size of batches of records passed onto the matcher\n regex_patterns: Patterns that should be detected and cleaned from the data\n \n \n \"\"\"\n # os.system('pip install -r https://raw.githubusercontent.com/mitramir55/PassivePy/main/PassivePyCode/PassivePySrc/requirements.txt')\n \n self.nlp, self.matcher = create_matcher(spacy_model)\n self.matcher_t = create_matcher_truncated(self.nlp)\n self.matcher_f = create_matcher_full(self.nlp)\n\n def print_matches(self, sentence, truncated_passive=False, full_passive=False):\n \"\"\"\n prints match span - I removed this from parse_sentence after changing its \n structure. It is used by the author for testing.\n \"\"\"\n doc = self.nlp(sentence)\n if truncated_passive: matches = self.matcher_t(doc)\n elif full_passive:matches = self.matcher_f(doc)\n else: matches = self.matcher(doc)\n\n if matches:\n for id_, s,e in matches:\n match_ = doc[s:e] \n print(match_)\n print(colored('rule: ', 'blue'), self.nlp.vocab.strings[id_])\n else: print('No match.')\n\n\n def parse_sentence(self, sentence):\n \"\"\"\n This function allows us to see the components of a sentence, \n specifically, the POS, DEP, and lemma\n \"\"\"\n doc = self.nlp(sentence)\n\n df_output = pd.DataFrame(\n index=['POS', 'dependency', 'tag', 'lemma']\n )\n\n for token in doc:\n df_output.loc[:, token.text] = [token.pos_,\n token.dep_, token.tag_, token.lemma_]\n \n return df_output\n\n\n def _detect_sents(self, document, batch_size, n_process):\n\n print('Detecting Sentences...')\n\n \"\"\"\n Separates sentences from each other in each record\n and puts them in a list along side the count of sentences in each \n document in another list\n \"\"\"\n document = [corpus.lower() for corpus in document]\n\n all_sentences = []\n count_sents = []\n\n # go through all the records\n m = 0\n for record_doc in self.nlp.pipe(document, batch_size=batch_size, n_process = n_process):\n\n\n sentences = list(record_doc.sents)\n sentences = [str(sentence) if len(sentence)>=2 else 'Not a Sentence' for sentence in sentences] \n\n\n unwanted = []\n for sentence in sentences:\n i = sentences.index(sentence)\n \n \n #...........................joining with the previous one.............................#\n # ones that start with but and their previous record doesn't have dot at its end\n if i!=0:\n if (re.search(r'^ *but', sentence) and not re.search(r'.$', sentences[i-1])) or all((re.search(r'^[A-Z0-9]', word) or re.search(r'^[\\(\\)\\.\\-]', word)) for word in sentence.split()) or re.search(r'^\\(.*\\)[\\.\\!\\,]*', sentence):\n j = 0\n for j in range(1, i):\n if i-j not in unwanted:\n sentences[i-j] = sentences[i-j] + sentences[i]\n unwanted.append(i)\n break\n \n\n #.........................joining with the next one..........................#\n if i != len(sentences)-1:\n\n\n if re.search(r', *$', sentence): # remove the one that's ended with comma\n sentences[i] = ' '.join([sentences[i], sentences[i+1]])\n unwanted.append(i+1)\n\n if re.search(r'\\- *$', sentence): \n # see if it's ended with hyphen then look at the next one\n # if it has and in the beginning, forget about this one and go to the next to analyze the and \n # and not duplicate the process\n if re.search(r'^ *(\\([\\w\\. ]*\\))* *and', sentences[i+1]):\n continue\n else: \n # but if there was no and in the next one,\n # join this with the next\n\n sentences[i] = ' '.join([sentences[i], sentences[i+1]])\n unwanted.append(i+1)\n # see if it ends with and and join it with the \n elif re.search(r'and *$', sentence):\n sentences[i] = ' '.join([sentences[i], sentences[i+1]])\n unwanted.append(i+1)\n\n # end with 'as well as' and join with the next one\n elif re.search(r'((as well as) *)$', sentence):\n sentences[i] = ' '.join([sentences[i], sentences[i+1]])\n unwanted.append(i+1)\n\n # end with the following phrases and join with the next ones\n elif re.search(r'((Exp\\.)|(e\\.g\\.)|(i\\.e\\.))$', sentence):\n sentences[i] = ' '.join([sentences[i], sentences[i+1]])\n unwanted.append(i+1)\n\n\n m+=1\n for index in sorted(set(unwanted), reverse=True):\n del sentences[index]\n\n\n count_sents.append(len(sentences))\n all_sentences.append(sentences) \n\n all_sentences = list(chain.from_iterable(all_sentences))\n # print(f'Total number of sentences = {len(all_sentences)}')\n\n\n return np.array(count_sents, dtype='object'), np.array(all_sentences, dtype='object')\n\n\n def _find_doc_idx(self, count_sents):\n\n \"\"\" finds the indices required for the documents and sentences\"\"\"\n\n m = 1\n sent_indices = []\n doc_indices = []\n for i in count_sents:\n n = 1\n for j in range(i):\n sent_indices.append(n)\n doc_indices.append(m)\n n+=1\n m+=1\n\n return pd.DataFrame(sent_indices), pd.DataFrame(doc_indices)\n\n\n def _add_other_cols(self, df, column_name, count_sents):\n\n \"\"\" creates a dataframe of all the other columns\n with the required number of repetitions for each \"\"\"\n\n # create a list of all the col names\n fields = df.columns.tolist()\n # remove column_name\n del fields[fields.index(column_name)]\n\n other_columns = {}\n # create a df of all the other cols with \n # appropriate number of repetitions\n for col in fields:\n properties = []\n for i in range(len(count_sents)):\n properties.append(count_sents[i]*[df.loc[i, col]])\n \n properties = list(chain.from_iterable(properties))\n other_columns[col] = properties\n\n df_other_cols = pd.DataFrame.from_dict(other_columns)\n\n return df_other_cols \n\n\n def match_text(self, document, truncated_passive=False, full_passive=False):\n\n \"\"\" \n This function finds passive matches in one sample sentence\n \"\"\"\n\n # we don't want to print the usual statements\n with HiddenPrints():\n \n df_output = self.match_corpus_level(\n pd.DataFrame({'text': [document]}), \n column_name='text',\n n_process = 1,\n batch_size = 1000, \n add_other_columns=False,\n truncated_passive=truncated_passive,\n full_passive=full_passive \n )\n\n return df_output\n\n \n def _find_unique_spans(self, doc, truncated_passive=False, full_passive=False) ->list:\n\n \"\"\"\"\n finds matches and checks for overlaps\n \"\"\"\n\n final_matches_i = []\n if truncated_passive: matches_i = self.matcher_t(doc)\n elif full_passive: matches_i = self.matcher_f(doc)\n else: matches_i = self.matcher(doc)\n\n if matches_i:\n spans = [doc[s:e] for id_, s,e in matches_i]\n\n for span in spacy.util.filter_spans(spans):\n final_matches_i.append(str(span))\n return final_matches_i\n\n\n def _find_matches(self, sentences, batch_size, n_process,\n truncated_passive=False, full_passive=False) -> dict:\n\n \"\"\" finds matches from each record \"\"\"\n print(colored('Starting to find passives...', 'green')) \n\n # defining the parameters ---------------------------------------\n # all passives parameters\n all_passives_count = []\n all_passives = []\n binary = []\n\n # full passive parameters\n raw_full_passive_count = []\n full_passive_matches = []\n binary_full_passive = []\n\n # truncated passive parameters\n raw_truncated_passive_count = []\n truncated_passive_matches = []\n binary_truncated_passive = []\n # -----------------------------------------------------------------\n\n\n \n for doc in self.nlp.pipe(sentences, batch_size=batch_size, n_process=n_process):\n\n binary_f = 0\n binary_t = 0\n binary_i = 0\n\n # truncated passive voice ----------------------------------\n if truncated_passive:\n\n truncated_matches_i = self._find_unique_spans(doc, truncated_passive, full_passive=False)\n if truncated_matches_i != []:\n \n # because the truncated version adds one token at the end\n # I will use the main matcher whenever there was a truncated passive\n truncated_matches_i = self._find_unique_spans(doc)\n\n binary_t = 1\n binary_truncated_passive.append(binary_t)\n truncated_passive_matches.append(truncated_matches_i)\n raw_truncated_passive_count.append(len(truncated_matches_i))\n\n # if there were no matches\n else:\n truncated_passive_matches.append(None)\n raw_truncated_passive_count.append(0)\n binary_truncated_passive.append(binary_t)\n\n # full passive voice ----------------------------------------\n if full_passive:\n full_matches_i = self._find_unique_spans(doc, truncated_passive=False, full_passive=True)\n if full_matches_i != []:\n\n binary_f = 1\n full_passive_matches.append(full_matches_i)\n raw_full_passive_count.append(len(full_matches_i))\n binary_full_passive.append(binary_f)\n\n # if there were no matches\n else:\n full_passive_matches.append(None)\n raw_full_passive_count.append(0)\n binary_full_passive.append(binary_f)\n \n # all passive voices ----------------------------------------------\n matches_i = self._find_unique_spans(doc)\n if matches_i != []:\n binary_i = 1\n binary.append(binary_i)\n all_passives.append(matches_i)\n all_passives_count.append(len(matches_i))\n\n # if there were no matches\n else:\n all_passives.append(None)\n all_passives_count.append(0)\n binary.append(binary_i)\n\n\n\n output_dict = {}\n\n # add columns -------------------------------------------------------\n columns = [sentences, all_passives, all_passives_count, binary]\n if full_passive:\n columns += [full_passive_matches, raw_full_passive_count, binary_full_passive]\n\n if truncated_passive: \n columns += [truncated_passive_matches, raw_truncated_passive_count, binary_truncated_passive]\n\n for element in columns:\n # name of variables will be the name of columns \n element_name = [k for k,v in locals().items() if v is element][0]\n output_dict[str(element_name)] = pd.Series(element, dtype='object')\n \n return output_dict\n\n\n def match_sentence_level(self, df, column_name, n_process = 1,\n batch_size = 1000, add_other_columns=True,\n truncated_passive=False, full_passive=False):\n\n \"\"\"\n Parameters\n\n column_name: name of the column with text\n level: whether the user wants corpus level or sentence level results\n n_process: number of cores to use can be any number\n between 1 and the maximum number of cores available\n (set it to -1 to use all the cores available)\n batch_size: give records in batches to the matcher\n record when passed\n add_other_columns: True\\False whether or not to add the other columns \n to the outputted dataframe\n \"\"\"\n \n df = df.reset_index(drop=True)\n # create a list of the column we will process\n document = df.loc[:, column_name].values.tolist()\n\n # seperating sentences\n count_sents, all_sentences = self._detect_sents(document, batch_size, n_process)\n\n # create a df of matches -------------------------------------------\n output_dict = self._find_matches(\n all_sentences, batch_size, n_process,\n truncated_passive, full_passive\n )\n df_output = pd.DataFrame(output_dict)\n\n # find indices required for the final dataset based on the document and sentence index\n sent_indices, doc_indices = self._find_doc_idx(count_sents)\n \n # add indices\n df_output.insert(0, \"docId\", doc_indices)\n df_output.insert(1, \"sentenceId\", sent_indices)\n\n\n # concatenating the results with the initial df -------------------\n if add_other_columns:\n\n other_cols_df = self._add_other_cols(df, column_name, count_sents)\n assert len(other_cols_df) == len(df_output)\n df_final = pd.concat([df_output, other_cols_df], axis = 1)\n\n return df_final\n\n else:\n return df_output\n\n\n def _all_elements_in_one_list(self, series_: pd.Series(list)) -> list:\n \"\"\"\n a function for reducing the size of a series\n \"\"\"\n # output: 1d list\n passive_matches = [val for val in series_ if val!=None]\n passive_matches = list(chain.from_iterable(passive_matches))\n return passive_matches\n\n\n def match_corpus_level(self, df, column_name, n_process = 1,\n batch_size = 1000, add_other_columns=True,\n truncated_passive=False, full_passive=False):\n\n \"\"\"\n finds matches based on sentences in all records\n\n Parameters\n\n column_name: name of the column with text\n level: whether the user wants corpus level or sentence level\n results\n n_process: number of cores to use can be any number\n between 1 and the maximum number of cores available\n (set it to -1 to use all the cores available)\n batch_size: give records in batches to the matcher\n record when passed\n add_other_columns: True\\False whether or not to add the other columns \n to the outputted dataframe\n sentences to the output dataset\n\n passive_sents_count: the percentage of sentences with passive in them\n \"\"\"\n \n df = df.reset_index(drop=True)\n # create a list of the column we will process\n document = df.loc[:, column_name].values.tolist()\n\n\n df_output = self.match_sentence_level(\n df, column_name, n_process,\n batch_size, add_other_columns,\n truncated_passive, full_passive\n )\n\n # declare variables -----------------------------------------\n # full passive\n if full_passive:\n full_passive_matches = []\n full_passive_count = []\n binary_full_passive = []\n full_passive_percentages = []\n full_passive_sents_count = []\n\n # truncated\n if truncated_passive:\n truncated_passive_matches = []\n truncated_passive_count = []\n binary_truncated_passive = []\n truncated_passive_percentages = []\n truncated_passive_sents_count = []\n \n # all passives\n all_passives = []\n passive_count = []\n binary = []\n passive_percentages = []\n passive_sents_count = []\n # -------------------------------------------------------------------\n\n # general\n count_sents = []\n output_dict = {}\n columns = [\n document, count_sents, all_passives, passive_count, \n passive_sents_count, passive_percentages, binary\n ]\n\n # list all the docs\n ids_ = df_output.docId.unique()\n \n\n for i in ids_:\n\n # select all the sentences of a doc\n rows = df_output[df_output['docId'] == i]\n\n # concatenate all the proberties ------------------------------------\n count_sents.append(len(rows))\n\n # all_passives \n count_passive_s = sum(rows.binary)\n passive_sents_count.append(count_passive_s)\n passive_percentages.append(count_passive_s/ len(rows))\n\n # binary will be =1 if there is even one 1 \n if any(rows.binary) == 1: binary.append(1)\n else: binary.append(0)\n\n # put all matches in one list\n all_matches = self._all_elements_in_one_list(rows['all_passives'].values)\n all_passives.append(all_matches)\n passive_count.append(len(all_matches))\n\n \n # full passive\n if full_passive:\n \n count_full_passive_s = sum(rows.binary_full_passive)\n full_passive_sents_count.append(count_full_passive_s)\n full_passive_percentages.append(count_full_passive_s/ len(rows))\n\n # binary will be =1 if there is even one 1 \n if any(rows.binary_full_passive) == 1: binary_full_passive.append(1)\n else: binary_full_passive.append(0)\n\n # put all matches in one list\n full_passives = self._all_elements_in_one_list(rows['full_passive_matches'].values)\n full_passive_matches.append(full_passives)\n full_passive_count.append(len(full_passives))\n\n columns+= [full_passive_matches, full_passive_count, \n full_passive_sents_count, full_passive_percentages, binary_full_passive\n ]\n\n # truncated passive\n if truncated_passive:\n count_truncated_passive_s = sum(rows.binary_truncated_passive)\n truncated_passive_sents_count.append(count_truncated_passive_s)\n truncated_passive_percentages.append(count_truncated_passive_s/ len(rows))\n\n # binary will be =1 if there is even one 1 \n if any(rows.binary_truncated_passive) == 1: binary_truncated_passive.append(1)\n else: binary_truncated_passive.append(0)\n\n # put all matches in one list\n truncated_passives = self._all_elements_in_one_list(rows['truncated_passive_matches'].values)\n truncated_passive_matches.append(truncated_passives)\n truncated_passive_count.append(len(truncated_passives))\n\n columns += [\n truncated_passive_matches, truncated_passive_count,\n truncated_passive_sents_count, truncated_passive_percentages, \n binary_truncated_passive\n ]\n\n\n # put all properties in a df ------------------------------------------------------\n \n for element in columns:\n # name of variables will be the name of columns \n element_name = [ k for k,v in locals().items() if v is element][0]\n output_dict[str(element_name)] = pd.Series(element, dtype='object')\n\n df_output = pd.DataFrame(output_dict)\n \n # add other columns in the initial df -------------------------------------------\n if add_other_columns:\n \n # create a list of all the col names\n fields = df.columns.tolist()\n\n # remove column_name\n del fields[fields.index(column_name)]\n\n assert len(df[fields]) == len(df_output)\n\n df_output = pd.concat([df_output, df[fields]], axis = 1)\n \n return df_output\n\n\n# for stopping the print statements in one sample sentences\nclass HiddenPrints:\n def __enter__(self):\n self._original_stdout = sys.stdout\n sys.stdout = open(os.devnull, 'w')\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n sys.stdout.close()\n sys.stdout = self._original_stdout\n"
]
| [
[
"numpy.array",
"pandas.DataFrame.from_dict",
"pandas.DataFrame",
"pandas.concat",
"pandas.Series"
]
]
|
ZJU-lishuang/C-3-Framework | [
"b3823bb5a54f7dd1885be65e8ada4aed102f1632"
]
| [
"test.py"
]
| [
"from matplotlib import pyplot as plt\n\nimport matplotlib\nimport os\nimport random\nimport torch\nfrom torch.autograd import Variable\nimport torchvision.transforms as standard_transforms\nimport misc.transforms as own_transforms\nimport pandas as pd\n\nfrom models.CC import CrowdCounter\nfrom config import cfg\nfrom misc.utils import *\nimport scipy.io as sio\nfrom PIL import Image, ImageOps\nimport time\n\ntorch.cuda.set_device(0)\ntorch.backends.cudnn.benchmark = True\n\nexp_name = '../UCF-QNRF_results'\nexp_name = '../test_results'\nif not os.path.exists(exp_name):\n os.mkdir(exp_name)\n\nif not os.path.exists(exp_name+'/pred'):\n os.mkdir(exp_name+'/pred')\n\nif not os.path.exists(exp_name+'/gt'):\n os.mkdir(exp_name+'/gt')\n\nmean_std = ([0.452016860247, 0.447249650955, 0.431981861591],[0.23242045939, 0.224925786257, 0.221840232611])\nimg_transform = standard_transforms.Compose([\n standard_transforms.ToTensor(),\n standard_transforms.Normalize(*mean_std)\n ])\nrestore = standard_transforms.Compose([\n own_transforms.DeNormalize(*mean_std),\n standard_transforms.ToPILImage()\n ])\npil_to_tensor = standard_transforms.ToTensor()\n\ndataRoot = '../ProcessedData/MULDATASET/UCF-QNRF-1024x1024/test'\ndataRoot = '../ProcessedData/testimg'\n\n# model_path = './exp/ori12-21_03-16_SHHB_Res50_1e-05/all_ep_41_mae_8.2_mse_13.9.pth'\nmodel_path = '/home/lishuang/Disk/gitlab/traincode/crowd_counting/PyTorch_Pretrained/all_ep_93_mae_68.8_mse_402.4.pth'\n\ndef main():\n \n file_list = [filename for root,dirs,filename in os.walk(dataRoot+'/img/')] \n\n test(file_list[0], model_path)\n \n\ndef test(file_list, model_path):\n\n net = CrowdCounter(cfg.GPU_ID,cfg.NET)\n net.load_state_dict({k.replace('module.',''):v for k,v in torch.load(model_path).items()})\n net.cuda()\n net.eval()\n\n\n f1 = plt.figure(1)\n\n gts = []\n preds = []\n maes = AverageMeter()\n mses = AverageMeter()\n img_num=0\n for filename in file_list:\n print( filename )\n imgname = dataRoot + '/img/' + filename\n filename_no_ext = filename.split('.')[0]\n\n denname = dataRoot + '/den/' + filename_no_ext + '.csv'\n\n den = pd.read_csv(denname, sep=',',header=None).values\n den = den.astype(np.float32, copy=False)\n\n img = Image.open(imgname)\n\n if img.mode == 'L':\n img = img.convert('RGB')\n\n t1 = time.time()\n img = img_transform(img)\n\n gt = np.sum(den)\n with torch.no_grad():\n img = Variable(img[None,:,:,:]).cuda()\n pred_map = net.test_forward(img)\n t2 = time.time()\n print('Done. (%.3fs)' % (t2 - t1))\n sio.savemat(exp_name+'/pred/'+filename_no_ext+'.mat',{'data':pred_map.squeeze().cpu().numpy()/100.})\n sio.savemat(exp_name+'/gt/'+filename_no_ext+'.mat',{'data':den})\n\n pred_map = pred_map.cpu().data.numpy()[0,0,:,:]\n\n\n pred = np.sum(pred_map)/100.0\n pred_map = pred_map/np.max(pred_map+1e-20)\n \n den = den/np.max(den+1e-20)\n\n pred_cnt = pred\n gt_count = gt\n\n maes.update(abs(gt_count - pred_cnt))\n mses.update((gt_count - pred_cnt) * (gt_count - pred_cnt))\n\n mae = maes.avg\n mse = np.sqrt(mses.avg)\n img_num=img_num+1\n if img_num %100 ==0:\n print(\"mae=\", mae, \"mse=\", mse)\n\n\n\n \n den_frame = plt.gca()\n plt.imshow(den, 'jet')\n den_frame.axes.get_yaxis().set_visible(False)\n den_frame.axes.get_xaxis().set_visible(False)\n den_frame.spines['top'].set_visible(False) \n den_frame.spines['bottom'].set_visible(False) \n den_frame.spines['left'].set_visible(False) \n den_frame.spines['right'].set_visible(False) \n plt.savefig(exp_name+'/'+filename_no_ext+'_gt_'+str(int(gt))+'.png',\\\n bbox_inches='tight',pad_inches=0,dpi=150)\n\n plt.close()\n \n # sio.savemat(exp_name+'/'+filename_no_ext+'_gt_'+str(int(gt))+'.mat',{'data':den})\n\n pred_frame = plt.gca()\n plt.imshow(pred_map, 'jet')\n pred_frame.axes.get_yaxis().set_visible(False)\n pred_frame.axes.get_xaxis().set_visible(False)\n pred_frame.spines['top'].set_visible(False) \n pred_frame.spines['bottom'].set_visible(False) \n pred_frame.spines['left'].set_visible(False) \n pred_frame.spines['right'].set_visible(False) \n plt.savefig(exp_name+'/'+filename_no_ext+'_pred_'+str(float(pred))+'.png',\\\n bbox_inches='tight',pad_inches=0,dpi=150)\n\n plt.close()\n\n # sio.savemat(exp_name+'/'+filename_no_ext+'_pred_'+str(float(pred))+'.mat',{'data':pred_map})\n\n diff = den-pred_map\n\n diff_frame = plt.gca()\n plt.imshow(diff, 'jet')\n plt.colorbar()\n diff_frame.axes.get_yaxis().set_visible(False)\n diff_frame.axes.get_xaxis().set_visible(False)\n diff_frame.spines['top'].set_visible(False) \n diff_frame.spines['bottom'].set_visible(False) \n diff_frame.spines['left'].set_visible(False) \n diff_frame.spines['right'].set_visible(False) \n plt.savefig(exp_name+'/'+filename_no_ext+'_diff.png',\\\n bbox_inches='tight',pad_inches=0,dpi=150)\n\n plt.close()\n\n # sio.savemat(exp_name+'/'+filename_no_ext+'_diff.mat',{'data':diff})\n\n print(\"last_mae=\", mae, \"last_mse=\", mse)\n # mae = maes.avg\n # mse = np.sqrt(mses.avg)\n\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n"
]
| [
[
"matplotlib.pyplot.colorbar",
"torch.autograd.Variable",
"matplotlib.pyplot.savefig",
"torch.no_grad",
"matplotlib.pyplot.close",
"pandas.read_csv",
"scipy.io.savemat",
"matplotlib.pyplot.figure",
"torch.cuda.set_device",
"torch.load",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.imshow"
]
]
|
davidefiocco/ipyplot | [
"ff64f4a376e17bf86c6c6fb1d47ee99e50227708"
]
| [
"tests/test_utils.py"
]
| [
"import sys\n\nimport numpy as np\nimport pytest\nimport pandas as pd\n\nsys.path.append(\".\")\nsys.path.append(\"../.\")\nfrom ipyplot._utils import _get_class_representations\n\n\nTEST_OUT_IMAGES = ['a', 'b', 'c']\nTEST_DATA = [\n # images, labels,\n # ignore_list, labels_order,\n # out_images, out_labels\n\n # data type tests\n (\n ['c', 'b', 'a', 'd'], ['3', '2', '1', '3'],\n None, None,\n TEST_OUT_IMAGES, ['1', '2', '3']\n ),\n (\n np.array(['c', 'b', 'a', 'd']), np.array(['3', '2', '1', '3']),\n None, None,\n TEST_OUT_IMAGES, np.array(['1', '2', '3'])\n ),\n (\n pd.Series(['c', 'b', 'a', 'd']), pd.Series(['3', '2', '1', '3']),\n None, None,\n TEST_OUT_IMAGES, pd.Series(['1', '2', '3'])\n ),\n (\n ['c', 'b', 'a', 'd'], [3, 2, 1, 3],\n None, None,\n TEST_OUT_IMAGES, [1, 2, 3]\n ),\n # ignore_list tests\n (\n ['e', 'c', 'b', 'a', 'd'], ['4', '3', '2', '1', '3'],\n ['4'], None,\n TEST_OUT_IMAGES, ['1', '2', '3']\n ),\n (\n ['e', 'c', 'b', 'a', 'd'], [4, 3, 2, 1, 3],\n [4], None,\n TEST_OUT_IMAGES, [1, 2, 3]\n ),\n # labels_order tests\n (\n ['e', 'c', 'b', 'a', 'd'], ['4', '3', '2', '1', '3'],\n None, ['2', '1', '3'],\n ['b', 'a', 'c'], ['2', '1', '3']\n ),\n (\n ['c', 'b', 'a', 'd'], ['3', '2', '1', '3'],\n None, ['2', '1', '4', '3'],\n ['b', 'a', 'c'], ['2', '1', '3']\n ),\n (\n ['e', 'c', 'b', 'a', 'd'], [4, 3, 2, 1, 3],\n None, [2, 1, 3],\n ['b', 'a', 'c'], [2, 1, 3]\n ),\n (\n ['c', 'b', 'a', 'd'], [3, 2, 1, 3],\n None, [2, 1, 4, 3],\n ['b', 'a', 'c'], [2, 1, 3]\n ),\n # labels_order + ignore_list tests\n (\n ['e', 'c', 'b', 'a', 'd'], ['4', '3', '2', '1', '3'],\n ['1'], ['2', '1', '3'],\n ['b', 'c'], ['2', '3']\n ),\n (\n ['c', 'b', 'a', 'd'], ['3', '2', '1', '3'],\n ['1'], ['2', '1', '4', '3'],\n ['b', 'c'], ['2', '3']\n ),\n (\n ['e', 'c', 'b', 'a', 'd'], [4, 3, 2, 1, 3],\n [1], [2, 1, 3],\n ['b', 'c'], [2, 3]\n ),\n (\n ['c', 'b', 'a', 'd'], [3, 2, 1, 3],\n [1], [2, 1, 4, 3],\n ['b', 'c'], [2, 3]\n ),\n]\n\n\[email protected](\n \"images, labels, ignore_labels, labels_order, out_images, out_labels\",\n TEST_DATA)\ndef test_get_class_representations(\n images, labels, ignore_labels, labels_order, out_images, out_labels):\n images, labels = _get_class_representations(\n images,\n labels=labels,\n ignore_labels=ignore_labels,\n labels_order=labels_order)\n assert all(images == out_images)\n assert all(labels == out_labels)\n"
]
| [
[
"numpy.array",
"pandas.Series"
]
]
|
j1a0m0e4sNTU/ML2019SPRING | [
"3d5f1ba8441660e61a0a7cbb0579f67d9b659c77"
]
| [
"hw8_all/model_test.py"
]
| [
"import sys\nimport torch\nimport torch.nn as nn\n\n# simple baseline : about 162435 parameters\n# strong baseline : about 56310 parameters\n\nconv_config = {\n 'base': [16, 64, 'D', 128, 'D', 256, 'D', 512, 'D'],\n 'A': [8, 16, 'D', 16, 16, 16, 'D', 32, 32, 'D', 32, 32, 'D', 64, 64],\n 'B': [16, 16, 16, 'D', 16, 16, 16, 16, 'D', 32, 32, 32, 32, 'D', 64, 64, 64, 64, 'D'],\n 'C': [16, 16, 16, 'D', 16, 16, 16, 'D', 32, 32, 32, 'D', 64, 64, 64, 'D', 128, 128], \n 'D': [32, 32, 32, 'D', 32, 32, 32, 'D', 64, 64, 64, 'D', 128, 128, 128, 'D', 128, 128],\n 'E': [32, 32, 32, 'D', 32, 32, 32, 'D', 32, 32, 32, 'D', 64, 64, 64, 'D', 128],\n 'F': [16, 16, 'D', 32, 32, 'D', 32, 32, 'D', 64, 64, 'D'],\n 'G': [16, 16, 'D', 16, 16, 'D', 32, 32, 'D', 32, 32, 'D']\n}\n\nfc_config = {\n 'base': [512*2*2, 128, 7],\n 'A': [64*2*2, 64, 7], \n 'B': [64*2*2, 128, 7], \n 'C': [128*2*2, 7],\n 'C2': [128*2*2, 32, 7],\n 'F' : [64*2*2, 7], \n 'G' : [32*2*2, 7]\n}\n\ndef conv_layers(config):\n layers = []\n in_planes = 1\n for i, x in enumerate(config) :\n if x == 'D':\n layers.append(nn.MaxPool2d(kernel_size= 2, stride= 2))\n else:\n layers += [\n nn.Conv2d(in_planes, x, 3, 1, 1),\n nn.BatchNorm2d(x), \n nn.ReLU(inplace= True)\n ]\n in_planes = x\n\n layers = nn.Sequential(* layers)\n return layers\n\ndef fc_layers(config):\n layers = []\n for i in range(1, len(config)):\n layers += [\n nn.Linear(config[i - 1], config[i]), \n nn.ReLU(inplace= True),\n nn.Dropout()\n ]\n layers = layers[:-2]\n layers = nn.Sequential(* layers)\n return layers\n\nclass CNN(nn.Module):\n def __init__(self, conv_symbol, fc_symbol):\n super().__init__()\n self.conv_layers = conv_layers(conv_config[conv_symbol])\n self.fc_layers = fc_layers(fc_config[fc_symbol])\n \n def forward(self, inputs):\n out = self.conv_layers(inputs)\n out = out.view(out.size(0), -1)\n out = self.fc_layers(out)\n return out\n\ndef parameter_number(model):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\ndef test():\n batch_size = 8\n images = torch.zeros(batch_size, 1, 44, 44)\n model = CNN(sys.argv[1], sys.argv[2])\n output = model(images)\n\n print('Model parameter number: {}'.format(parameter_number(model)))\n print('Input size: {}'.format(images.size()))\n print('Output size: {}'.format(output.size()))\n\nif __name__ == '__main__':\n test()"
]
| [
[
"torch.nn.Linear",
"torch.zeros",
"torch.nn.Dropout",
"torch.nn.MaxPool2d",
"torch.nn.Sequential",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.Conv2d"
]
]
|
t-aritake/ancestral_atom_learning | [
"1af3451058f31dfdd28289bb05e90bb2ec1d9e5d"
]
| [
"utils/intrinsic_dimension_estimator.py"
]
| [
"# -*- coding: utf-8 -*-\nimport numpy\nimport scipy.cluster.hierarchy\n\n\n# 二分木みたいにルートから追加できないのがちょっと面倒.\n# あとで見直す?\nclass Node(object):\n ''' class to construct clustering tree'''\n def __init__(self):\n self.data = None\n self.left = None\n self.right = None\n self.annotated_distance = None\n\n\n# 全ノードへのアクセス(順番は葉,親の順番で)\ndef traverse(node):\n if node is None:\n return\n for x in traverse(node.left):\n yield x\n for x in traverse(node.right):\n yield x\n yield node\n\n\n# 葉ノードへのアクセス(annotated distanceによる枝刈りも可能)\ndef traverse_leaves(node, thresholding=-1):\n # 自分がNoneなら葉\n if node is None:\n return\n if node.annotated_distance is not None:\n if node.annotated_distance <= thresholding:\n yield node\n return\n for x in traverse_leaves(node.left, thresholding):\n yield x\n for x in traverse_leaves(node.right, thresholding):\n yield x\n if node.left is None and node.right is None:\n yield node\n\n\ndef cluster_dimension(D):\n '''\n Parameters\n ----------\n D : numpy.array\n 1d array of pairwise distance matrix of all items\n The form should be same as the returned value of scipy.spatial.distance.pdist\n\n Returns\n ----------\n int\n estimated cluster dimension\n '''\n\n num_items = 1\n while True:\n if len(D) / num_items * 2 == num_items + 1:\n num_items += 1\n break\n num_items += 1\n D_mat = numpy.zeros(shape=(num_items, num_items))\n D_mat[numpy.triu_indices(num_items, 1)] = D\n\n # items = [[i] for i in range(num_items)]\n items = []\n for i in range(num_items):\n n = Node()\n n.data = [i]\n items.append(n)\n # items = [Node([i]) for i in range(num_items)]\n item_indices = [i for i in range(num_items)]\n link = scipy.cluster.hierarchy.linkage(D, method='complete')\n # annotated_distance = [0 for i in range(num_items)]\n annotated_distance = []\n\n for l in link:\n # item_indices.append(len(items))\n item = Node()\n item.left = items[int(l[0])]\n item.right = items[int(l[1])]\n item.data = item.left.data + item.right.data\n item.annotated_distance = numpy.max(D_mat[item.data][:, item.data])\n items.append(item)\n\n annotated_distance = sorted([item.annotated_distance for item in traverse(items[-1]) if item.annotated_distance is not None])\n\n rmin = 0\n rmax = numpy.max(D_mat)\n # rminは各クラスタの要素数の中央値が1より大きくなるときの値\n for r in annotated_distance:\n data = sorted([len(item.data) for item in traverse_leaves(items[-1], r)])\n if data[len(data) // 2] > 1:\n rmin = r\n break\n\n r_list = []\n leafs_list = []\n\n # TODO: 本当はここはもっと細かく点をとって傾きを求める方法でもよい\n # とりあえずrmin, rmaxの25%, 75%の値でやってる\n rmean = (rmin + rmax) / 2\n rstep = 0.1\n # for r in [(rmin + rmean)/2, (rmean + rmax) / 2]:\n for r in numpy.arange(rmin, rmax, rstep):\n # print(r_prev < link[:, 2])\n data = [len(item.data) for item in traverse_leaves(items[-1], r)]\n r_list.append(r)\n leafs_list.append(len(list(traverse_leaves(items[-1], r))))\n\n x = numpy.log(r_list)\n y = numpy.log(leafs_list)\n a = -(numpy.dot(x, y) - x.sum() * y.sum() / len(x)) / ((x**2).sum() - x.sum()**2/len(x))\n # print(a)\n return a\n # print(numpy.mean(numpy.array(leafs_list) / numpy.array(r_list)))\n # return -(numpy.log(leafs_list[-1]) - numpy.log(leafs_list[0])) / (numpy.log(r_list[-1])-numpy.log(r_list[0]))\n\n\ndef packing_dimension(D, r1=None, r2=None, epsilon=1e-3):\n num_items = 1\n while True:\n if len(D) / num_items * 2 == num_items + 1:\n num_items += 1\n break\n num_items += 1\n D_mat = numpy.zeros(shape=(num_items, num_items))\n D_mat[numpy.triu_indices(num_items, 1)] = D\n D_mat = D_mat + D_mat.T\n\n if r1 is None:\n r1 = numpy.percentile(D, 25)\n if r2 is None:\n r2 = numpy.percentile(D, 75)\n r_list = [r1, r2]\n\n items = numpy.array([i for i in range(num_items)])\n L_list = [[], []] \n for loop in range(1000):\n numpy.random.shuffle(items)\n for k in range(2):\n pack = [items[0], ]\n for i in range(1, num_items):\n if numpy.all(D_mat[i, pack] >= r_list[k]):\n pack.append(items[i])\n L_list[k].append(numpy.log(len(pack)))\n denom = numpy.log(r_list[1]) - numpy.log(r_list[0])\n D_pack = - (numpy.mean(L_list[1]) - numpy.mean(L_list[0])) / denom\n\n criterion = 1.65 * numpy.sqrt(numpy.var(L_list[0]) + numpy.var(L_list[1])) / (numpy.sqrt(loop+1) * denom)\n if loop > 10 and criterion < D_pack * (1 - epsilon) / 2:\n return D_pack\n\n\nif __name__ == '__main__':\n from sklearn import datasets\n import scipy.spatial.distance\n cdim = []\n pdim = []\n # numpy.random.seed(1)\n for i in range(20):\n r=4\n B = numpy.random.normal(size=(10, r))\n B = B / numpy.sum(B, axis=0)\n C = numpy.random.random(size=(r, 10000))\n C = C / numpy.sum(C, axis=0)\n X = numpy.dot(B, C).T\n print(X.shape)\n\n D = scipy.spatial.distance.pdist(X)\n pdim.append(packing_dimension(D))\n cdim.append(cluster_dimension(D))\n print(cdim[-1])\n print(pdim[-1])\n print()\n print(numpy.mean(pdim), numpy.var(pdim))\n print(numpy.mean(cdim), numpy.var(cdim))\n\n # X, color = datasets.samples_generator.make_swiss_roll(n_samples=900)\n # print(X.shape)\n # D = scipy.spatial.distance.pdist(X)\n # print(cluster_dimension(D))\n"
]
| [
[
"numpy.max",
"numpy.random.normal",
"numpy.dot",
"numpy.triu_indices",
"numpy.log",
"numpy.zeros",
"numpy.percentile",
"numpy.sum",
"numpy.random.shuffle",
"numpy.mean",
"numpy.arange",
"numpy.sqrt",
"numpy.all",
"numpy.random.random",
"numpy.var"
]
]
|
zjzh/pynndescent | [
"1e79a3742436bfe4822995de073b500ffedd485c"
]
| [
"pynndescent/distances.py"
]
| [
"# Author: Leland McInnes <[email protected]>\n#\n# License: BSD 3 clause\nimport numpy as np\nimport numba\n\nfrom pynndescent.optimal_transport import (\n allocate_graph_structures,\n initialize_graph_structures,\n initialize_supply,\n initialize_cost,\n network_simplex_core,\n total_cost,\n ProblemStatus,\n sinkhorn_transport_plan,\n)\n\n_mock_identity = np.eye(2, dtype=np.float32)\n_mock_ones = np.ones(2, dtype=np.float32)\n_dummy_cost = np.zeros((2, 2), dtype=np.float64)\n\nFLOAT32_EPS = np.finfo(np.float32).eps\nFLOAT32_MAX = np.finfo(np.float32).max\n\n\[email protected](fastmath=True)\ndef euclidean(x, y):\n r\"\"\"Standard euclidean distance.\n\n .. math::\n D(x, y) = \\\\sqrt{\\sum_i (x_i - y_i)^2}\n \"\"\"\n result = 0.0\n for i in range(x.shape[0]):\n result += (x[i] - y[i]) ** 2\n return np.sqrt(result)\n\n\[email protected](\n [\n \"f4(f4[::1],f4[::1])\",\n numba.types.float32(\n numba.types.Array(numba.types.float32, 1, \"C\", readonly=True),\n numba.types.Array(numba.types.float32, 1, \"C\", readonly=True),\n ),\n ],\n fastmath=True,\n locals={\n \"result\": numba.types.float32,\n \"diff\": numba.types.float32,\n \"dim\": numba.types.intp,\n \"i\": numba.types.uint16,\n },\n)\ndef squared_euclidean(x, y):\n r\"\"\"Squared euclidean distance.\n\n .. math::\n D(x, y) = \\sum_i (x_i - y_i)^2\n \"\"\"\n result = 0.0\n dim = x.shape[0]\n for i in range(dim):\n diff = x[i] - y[i]\n result += diff * diff\n\n return result\n\n\[email protected](fastmath=True)\ndef standardised_euclidean(x, y, sigma=_mock_ones):\n r\"\"\"Euclidean distance standardised against a vector of standard\n deviations per coordinate.\n\n .. math::\n D(x, y) = \\sqrt{\\sum_i \\frac{(x_i - y_i)**2}{v_i}}\n \"\"\"\n result = 0.0\n for i in range(x.shape[0]):\n result += ((x[i] - y[i]) ** 2) / sigma[i]\n\n return np.sqrt(result)\n\n\[email protected](fastmath=True)\ndef manhattan(x, y):\n r\"\"\"Manhattan, taxicab, or l1 distance.\n\n .. math::\n D(x, y) = \\sum_i |x_i - y_i|\n \"\"\"\n result = 0.0\n for i in range(x.shape[0]):\n result += np.abs(x[i] - y[i])\n\n return result\n\n\[email protected](fastmath=True)\ndef chebyshev(x, y):\n r\"\"\"Chebyshev or l-infinity distance.\n\n .. math::\n D(x, y) = \\max_i |x_i - y_i|\n \"\"\"\n result = 0.0\n for i in range(x.shape[0]):\n result = max(result, np.abs(x[i] - y[i]))\n\n return result\n\n\[email protected](fastmath=True)\ndef minkowski(x, y, p=2):\n r\"\"\"Minkowski distance.\n\n .. math::\n D(x, y) = \\left(\\sum_i |x_i - y_i|^p\\right)^{\\frac{1}{p}}\n\n This is a general distance. For p=1 it is equivalent to\n manhattan distance, for p=2 it is Euclidean distance, and\n for p=infinity it is Chebyshev distance. In general it is better\n to use the more specialised functions for those distances.\n \"\"\"\n result = 0.0\n for i in range(x.shape[0]):\n result += (np.abs(x[i] - y[i])) ** p\n\n return result ** (1.0 / p)\n\n\[email protected](fastmath=True)\ndef weighted_minkowski(x, y, w=_mock_ones, p=2):\n r\"\"\"A weighted version of Minkowski distance.\n\n .. math::\n D(x, y) = \\left(\\sum_i w_i |x_i - y_i|^p\\right)^{\\frac{1}{p}}\n\n If weights w_i are inverse standard deviations of graph_data in each dimension\n then this represented a standardised Minkowski distance (and is\n equivalent to standardised Euclidean distance for p=1).\n \"\"\"\n result = 0.0\n for i in range(x.shape[0]):\n result += (w[i] * np.abs(x[i] - y[i])) ** p\n\n return result ** (1.0 / p)\n\n\[email protected](fastmath=True)\ndef mahalanobis(x, y, vinv=_mock_identity):\n result = 0.0\n\n diff = np.empty(x.shape[0], dtype=np.float32)\n\n for i in range(x.shape[0]):\n diff[i] = x[i] - y[i]\n\n for i in range(x.shape[0]):\n tmp = 0.0\n for j in range(x.shape[0]):\n tmp += vinv[i, j] * diff[j]\n result += tmp * diff[i]\n\n return np.sqrt(result)\n\n\[email protected](fastmath=True)\ndef hamming(x, y):\n result = 0.0\n for i in range(x.shape[0]):\n if x[i] != y[i]:\n result += 1.0\n\n return float(result) / x.shape[0]\n\n\[email protected](fastmath=True)\ndef canberra(x, y):\n result = 0.0\n for i in range(x.shape[0]):\n denominator = np.abs(x[i]) + np.abs(y[i])\n if denominator > 0:\n result += np.abs(x[i] - y[i]) / denominator\n\n return result\n\n\[email protected](fastmath=True)\ndef bray_curtis(x, y):\n numerator = 0.0\n denominator = 0.0\n for i in range(x.shape[0]):\n numerator += np.abs(x[i] - y[i])\n denominator += np.abs(x[i] + y[i])\n\n if denominator > 0.0:\n return float(numerator) / denominator\n else:\n return 0.0\n\n\[email protected](fastmath=True)\ndef jaccard(x, y):\n num_non_zero = 0.0\n num_equal = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_non_zero += x_true or y_true\n num_equal += x_true and y_true\n\n if num_non_zero == 0.0:\n return 0.0\n else:\n return float(num_non_zero - num_equal) / num_non_zero\n\n\[email protected](\n [\n \"f4(f4[::1],f4[::1])\",\n numba.types.float32(\n numba.types.Array(numba.types.float32, 1, \"C\", readonly=True),\n numba.types.Array(numba.types.float32, 1, \"C\", readonly=True),\n ),\n ],\n fastmath=True,\n locals={\n \"result\": numba.types.float32,\n \"num_non_zero\": numba.types.float32,\n \"num_equal\": numba.types.float32,\n \"x_true\": numba.types.uint8,\n \"y_true\": numba.types.uint8,\n \"dim\": numba.types.intp,\n \"i\": numba.types.uint16,\n },\n)\ndef alternative_jaccard(x, y):\n num_non_zero = 0.0\n num_equal = 0.0\n dim = x.shape[0]\n for i in range(dim):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_non_zero += x_true or y_true\n num_equal += x_true and y_true\n\n if num_non_zero == 0.0:\n return 0.0\n else:\n return -np.log2(num_equal / num_non_zero)\n\n\[email protected](fastmath=True)\ndef correct_alternative_jaccard(v):\n return 1.0 - pow(2.0, -v)\n\n\[email protected](fastmath=True)\ndef matching(x, y):\n num_not_equal = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_not_equal += x_true != y_true\n\n return float(num_not_equal) / x.shape[0]\n\n\[email protected](fastmath=True)\ndef dice(x, y):\n num_true_true = 0.0\n num_not_equal = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_true_true += x_true and y_true\n num_not_equal += x_true != y_true\n\n if num_not_equal == 0.0:\n return 0.0\n else:\n return num_not_equal / (2.0 * num_true_true + num_not_equal)\n\n\[email protected](fastmath=True)\ndef kulsinski(x, y):\n num_true_true = 0.0\n num_not_equal = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_true_true += x_true and y_true\n num_not_equal += x_true != y_true\n\n if num_not_equal == 0:\n return 0.0\n else:\n return float(num_not_equal - num_true_true + x.shape[0]) / (\n num_not_equal + x.shape[0]\n )\n\n\[email protected](fastmath=True)\ndef rogers_tanimoto(x, y):\n num_not_equal = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_not_equal += x_true != y_true\n\n return (2.0 * num_not_equal) / (x.shape[0] + num_not_equal)\n\n\[email protected](fastmath=True)\ndef russellrao(x, y):\n num_true_true = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_true_true += x_true and y_true\n\n if num_true_true == np.sum(x != 0) and num_true_true == np.sum(y != 0):\n return 0.0\n else:\n return float(x.shape[0] - num_true_true) / (x.shape[0])\n\n\[email protected](fastmath=True)\ndef sokal_michener(x, y):\n num_not_equal = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_not_equal += x_true != y_true\n\n return (2.0 * num_not_equal) / (x.shape[0] + num_not_equal)\n\n\[email protected](fastmath=True)\ndef sokal_sneath(x, y):\n num_true_true = 0.0\n num_not_equal = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_true_true += x_true and y_true\n num_not_equal += x_true != y_true\n\n if num_not_equal == 0.0:\n return 0.0\n else:\n return num_not_equal / (0.5 * num_true_true + num_not_equal)\n\n\[email protected](fastmath=True)\ndef haversine(x, y):\n if x.shape[0] != 2:\n raise ValueError(\"haversine is only defined for 2 dimensional graph_data\")\n sin_lat = np.sin(0.5 * (x[0] - y[0]))\n sin_long = np.sin(0.5 * (x[1] - y[1]))\n result = np.sqrt(sin_lat ** 2 + np.cos(x[0]) * np.cos(y[0]) * sin_long ** 2)\n return 2.0 * np.arcsin(result)\n\n\[email protected](fastmath=True)\ndef yule(x, y):\n num_true_true = 0.0\n num_true_false = 0.0\n num_false_true = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_true_true += x_true and y_true\n num_true_false += x_true and (not y_true)\n num_false_true += (not x_true) and y_true\n\n num_false_false = x.shape[0] - num_true_true - num_true_false - num_false_true\n\n if num_true_false == 0.0 or num_false_true == 0.0:\n return 0.0\n else:\n return (2.0 * num_true_false * num_false_true) / (\n num_true_true * num_false_false + num_true_false * num_false_true\n )\n\n\[email protected](fastmath=True)\ndef cosine(x, y):\n result = 0.0\n norm_x = 0.0\n norm_y = 0.0\n for i in range(x.shape[0]):\n result += x[i] * y[i]\n norm_x += x[i] ** 2\n norm_y += y[i] ** 2\n\n if norm_x == 0.0 and norm_y == 0.0:\n return 0.0\n elif norm_x == 0.0 or norm_y == 0.0:\n return 1.0\n else:\n return 1.0 - (result / np.sqrt(norm_x * norm_y))\n\n\[email protected](\n [\n \"f4(f4[::1],f4[::1])\",\n numba.types.float32(\n numba.types.Array(numba.types.float32, 1, \"C\", readonly=True),\n numba.types.Array(numba.types.float32, 1, \"C\", readonly=True),\n ),\n ],\n fastmath=True,\n locals={\n \"result\": numba.types.float32,\n \"norm_x\": numba.types.float32,\n \"norm_y\": numba.types.float32,\n \"dim\": numba.types.intp,\n \"i\": numba.types.uint16,\n },\n)\ndef alternative_cosine(x, y):\n result = 0.0\n norm_x = 0.0\n norm_y = 0.0\n dim = x.shape[0]\n for i in range(dim):\n result += x[i] * y[i]\n norm_x += x[i] * x[i]\n norm_y += y[i] * y[i]\n\n if norm_x == 0.0 and norm_y == 0.0:\n return 0.0\n elif norm_x == 0.0 or norm_y == 0.0:\n return FLOAT32_MAX\n elif result <= 0.0:\n return FLOAT32_MAX\n else:\n result = np.sqrt(norm_x * norm_y) / result\n return np.log2(result)\n\n\[email protected](\n \"f4(f4[::1],f4[::1])\",\n fastmath=True,\n locals={\n \"result\": numba.types.float32,\n \"dim\": numba.types.intp,\n \"i\": numba.types.uint16,\n },\n)\ndef dot(x, y):\n result = 0.0\n dim = x.shape[0]\n for i in range(dim):\n result += x[i] * y[i]\n\n if result <= 0.0:\n return 1.0\n else:\n return 1.0 - result\n\n\[email protected](\n [\n \"f4(f4[::1],f4[::1])\",\n numba.types.float32(\n numba.types.Array(numba.types.float32, 1, \"C\", readonly=True),\n numba.types.Array(numba.types.float32, 1, \"C\", readonly=True),\n ),\n ],\n fastmath=True,\n locals={\n \"result\": numba.types.float32,\n \"dim\": numba.types.intp,\n \"i\": numba.types.uint16,\n },\n)\ndef alternative_dot(x, y):\n result = 0.0\n dim = x.shape[0]\n for i in range(dim):\n result += x[i] * y[i]\n\n if result <= 0.0:\n return FLOAT32_MAX\n else:\n return -np.log2(result)\n\n\[email protected](fastmath=True)\ndef correct_alternative_cosine(d):\n return 1.0 - pow(2.0, -d)\n\n\[email protected](fastmath=True)\ndef tsss(x, y):\n d_euc_squared = 0.0\n d_cos = 0.0\n norm_x = 0.0\n norm_y = 0.0\n dim = x.shape[0]\n\n for i in range(dim):\n diff = x[i] - y[i]\n d_euc_squared += diff * diff\n d_cos += x[i] * y[i]\n norm_x += x[i] * x[i]\n norm_y += y[i] * y[i]\n\n norm_x = np.sqrt(norm_x)\n norm_y = np.sqrt(norm_y)\n magnitude_difference = np.abs(norm_x - norm_y)\n d_cos /= norm_x * norm_y\n theta = np.arccos(d_cos) + np.radians(10) # Add 10 degrees as an \"epsilon\" to\n # avoid problems\n sector = ((np.sqrt(d_euc_squared) + magnitude_difference) ** 2) * theta\n triangle = norm_x * norm_y * np.sin(theta) / 2.0\n return triangle * sector\n\n\[email protected](fastmath=True)\ndef true_angular(x, y):\n result = 0.0\n norm_x = 0.0\n norm_y = 0.0\n dim = x.shape[0]\n for i in range(dim):\n result += x[i] * y[i]\n norm_x += x[i] * x[i]\n norm_y += y[i] * y[i]\n\n if norm_x == 0.0 and norm_y == 0.0:\n return 0.0\n elif norm_x == 0.0 or norm_y == 0.0:\n return FLOAT32_MAX\n elif result <= 0.0:\n return FLOAT32_MAX\n else:\n result = result / np.sqrt(norm_x * norm_y)\n return 1.0 - (np.arccos(result) / np.pi)\n\n\[email protected](fastmath=True)\ndef true_angular_from_alt_cosine(d):\n return 1.0 - (np.arccos(pow(2.0, -d)) / np.pi)\n\n\[email protected](fastmath=True)\ndef correlation(x, y):\n mu_x = 0.0\n mu_y = 0.0\n norm_x = 0.0\n norm_y = 0.0\n dot_product = 0.0\n\n for i in range(x.shape[0]):\n mu_x += x[i]\n mu_y += y[i]\n\n mu_x /= x.shape[0]\n mu_y /= x.shape[0]\n\n for i in range(x.shape[0]):\n shifted_x = x[i] - mu_x\n shifted_y = y[i] - mu_y\n norm_x += shifted_x ** 2\n norm_y += shifted_y ** 2\n dot_product += shifted_x * shifted_y\n\n if norm_x == 0.0 and norm_y == 0.0:\n return 0.0\n elif dot_product == 0.0:\n return 1.0\n else:\n return 1.0 - (dot_product / np.sqrt(norm_x * norm_y))\n\n\[email protected](\n [\n \"f4(f4[::1],f4[::1])\",\n numba.types.float32(\n numba.types.Array(numba.types.float32, 1, \"C\", readonly=True),\n numba.types.Array(numba.types.float32, 1, \"C\", readonly=True),\n ),\n ],\n fastmath=True,\n locals={\n \"result\": numba.types.float32,\n \"l1_norm_x\": numba.types.float32,\n \"l1_norm_y\": numba.types.float32,\n \"dim\": numba.types.intp,\n \"i\": numba.types.uint16,\n },\n)\ndef hellinger(x, y):\n result = 0.0\n l1_norm_x = 0.0\n l1_norm_y = 0.0\n dim = x.shape[0]\n\n for i in range(dim):\n result += np.sqrt(x[i] * y[i])\n l1_norm_x += x[i]\n l1_norm_y += y[i]\n\n if l1_norm_x == 0 and l1_norm_y == 0:\n return 0.0\n elif l1_norm_x == 0 or l1_norm_y == 0:\n return 1.0\n else:\n return np.sqrt(1 - result / np.sqrt(l1_norm_x * l1_norm_y))\n\n\[email protected](\n [\n \"f4(f4[::1],f4[::1])\",\n numba.types.float32(\n numba.types.Array(numba.types.float32, 1, \"C\", readonly=True),\n numba.types.Array(numba.types.float32, 1, \"C\", readonly=True),\n ),\n ],\n fastmath=True,\n locals={\n \"result\": numba.types.float32,\n \"l1_norm_x\": numba.types.float32,\n \"l1_norm_y\": numba.types.float32,\n \"dim\": numba.types.intp,\n \"i\": numba.types.uint16,\n },\n)\ndef alternative_hellinger(x, y):\n result = 0.0\n l1_norm_x = 0.0\n l1_norm_y = 0.0\n dim = x.shape[0]\n\n for i in range(dim):\n result += np.sqrt(x[i] * y[i])\n l1_norm_x += x[i]\n l1_norm_y += y[i]\n\n if l1_norm_x == 0 and l1_norm_y == 0:\n return 0.0\n elif l1_norm_x == 0 or l1_norm_y == 0:\n return FLOAT32_MAX\n elif result <= 0:\n return FLOAT32_MAX\n else:\n result = np.sqrt(l1_norm_x * l1_norm_y) / result\n return np.log2(result)\n\n\[email protected](fastmath=True)\ndef correct_alternative_hellinger(d):\n return np.sqrt(1.0 - pow(2.0, -d))\n\n\[email protected]()\ndef rankdata(a, method=\"average\"):\n arr = np.ravel(np.asarray(a))\n if method == \"ordinal\":\n sorter = arr.argsort(kind=\"mergesort\")\n else:\n sorter = arr.argsort(kind=\"quicksort\")\n\n inv = np.empty(sorter.size, dtype=np.intp)\n inv[sorter] = np.arange(sorter.size)\n\n if method == \"ordinal\":\n return (inv + 1).astype(np.float64)\n\n arr = arr[sorter]\n obs = np.ones(arr.size, np.bool_)\n obs[1:] = arr[1:] != arr[:-1]\n dense = obs.cumsum()[inv]\n\n if method == \"dense\":\n return dense.astype(np.float64)\n\n # cumulative counts of each unique value\n nonzero = np.nonzero(obs)[0]\n count = np.concatenate((nonzero, np.array([len(obs)], nonzero.dtype)))\n\n if method == \"max\":\n return count[dense].astype(np.float64)\n\n if method == \"min\":\n return (count[dense - 1] + 1).astype(np.float64)\n\n # average method\n return 0.5 * (count[dense] + count[dense - 1] + 1)\n\n\[email protected](fastmath=True)\ndef spearmanr(x, y):\n a = np.column_stack((x, y))\n\n n_vars = a.shape[1]\n\n for i in range(n_vars):\n a[:, i] = rankdata(a[:, i])\n rs = np.corrcoef(a, rowvar=0)\n\n return rs[1, 0]\n\n\[email protected](nogil=True)\ndef kantorovich(x, y, cost=_dummy_cost, max_iter=100000):\n\n row_mask = x != 0\n col_mask = y != 0\n\n a = x[row_mask].astype(np.float64)\n b = y[col_mask].astype(np.float64)\n\n a_sum = a.sum()\n b_sum = b.sum()\n\n # if not isclose(a_sum, b_sum):\n # raise ValueError(\n # \"Kantorovich distance inputs must be valid probability distributions.\"\n # )\n\n a /= a_sum\n b /= b_sum\n\n sub_cost = cost[row_mask, :][:, col_mask]\n\n node_arc_data, spanning_tree, graph = allocate_graph_structures(\n a.shape[0], b.shape[0], False\n )\n initialize_supply(a, -b, graph, node_arc_data.supply)\n initialize_cost(sub_cost, graph, node_arc_data.cost)\n # initialize_cost(cost, graph, node_arc_data.cost)\n init_status = initialize_graph_structures(graph, node_arc_data, spanning_tree)\n if init_status == False:\n raise ValueError(\n \"Kantorovich distance inputs must be valid probability distributions.\"\n )\n solve_status = network_simplex_core(node_arc_data, spanning_tree, graph, max_iter)\n # if solve_status == ProblemStatus.MAX_ITER_REACHED:\n # print(\"WARNING: RESULT MIGHT BE INACCURATE\\nMax number of iteration reached!\")\n if solve_status == ProblemStatus.INFEASIBLE:\n raise ValueError(\n \"Optimal transport problem was INFEASIBLE. Please check \" \"inputs.\"\n )\n elif solve_status == ProblemStatus.UNBOUNDED:\n raise ValueError(\n \"Optimal transport problem was UNBOUNDED. Please check \" \"inputs.\"\n )\n result = total_cost(node_arc_data.flow, node_arc_data.cost)\n\n return result\n\n\[email protected](fastmath=True)\ndef sinkhorn(x, y, cost=_dummy_cost, regularization=1.0):\n row_mask = x != 0\n col_mask = y != 0\n\n a = x[row_mask].astype(np.float64)\n b = y[col_mask].astype(np.float64)\n\n a_sum = a.sum()\n b_sum = b.sum()\n\n a /= a_sum\n b /= b_sum\n\n sub_cost = cost[row_mask, :][:, col_mask]\n\n transport_plan = sinkhorn_transport_plan(\n x, y, cost=sub_cost, regularization=regularization\n )\n dim_i = transport_plan.shape[0]\n dim_j = transport_plan.shape[1]\n result = 0.0\n for i in range(dim_i):\n for j in range(dim_j):\n result += transport_plan[i, j] * cost[i, j]\n\n return result\n\n\[email protected]()\ndef jensen_shannon_divergence(x, y):\n result = 0.0\n l1_norm_x = 0.0\n l1_norm_y = 0.0\n dim = x.shape[0]\n\n for i in range(dim):\n l1_norm_x += x[i]\n l1_norm_y += y[i]\n\n l1_norm_x += FLOAT32_EPS * dim\n l1_norm_y += FLOAT32_EPS * dim\n\n pdf_x = (x + FLOAT32_EPS) / l1_norm_x\n pdf_y = (y + FLOAT32_EPS) / l1_norm_y\n m = 0.5 * (pdf_x + pdf_y)\n\n for i in range(dim):\n result += 0.5 * (\n pdf_x[i] * np.log(pdf_x[i] / m[i]) + pdf_y[i] * np.log(pdf_y[i] / m[i])\n )\n\n return result\n\n\[email protected]()\ndef wasserstein_1d(x, y, p=1):\n x_sum = 0.0\n y_sum = 0.0\n for i in range(x.shape[0]):\n x_sum += x[i]\n y_sum += y[i]\n\n x_cdf = x / x_sum\n y_cdf = y / y_sum\n\n for i in range(1, x_cdf.shape[0]):\n x_cdf[i] += x_cdf[i - 1]\n y_cdf[i] += y_cdf[i - 1]\n\n return minkowski(x_cdf, y_cdf, p)\n\n\[email protected]()\ndef circular_kantorovich(x, y, p=1):\n x_sum = 0.0\n y_sum = 0.0\n for i in range(x.shape[0]):\n x_sum += x[i]\n y_sum += y[i]\n\n x_cdf = x / x_sum\n y_cdf = y / y_sum\n\n for i in range(1, x_cdf.shape[0]):\n x_cdf[i] += x_cdf[i - 1]\n y_cdf[i] += y_cdf[i - 1]\n\n mu = np.median((x_cdf - y_cdf) ** p)\n\n # Now we just want minkowski distance on the CDFs shifted by mu\n result = 0.0\n if p > 2:\n for i in range(x_cdf.shape[0]):\n result += np.abs(x_cdf[i] - y_cdf[i] - mu) ** p\n\n return result ** (1.0 / p)\n\n elif p == 2:\n for i in range(x_cdf.shape[0]):\n val = x_cdf[i] - y_cdf[i] - mu\n result += val * val\n\n return np.sqrt(result)\n\n elif p == 1:\n for i in range(x_cdf.shape[0]):\n result += np.abs(x_cdf[i] - y_cdf[i] - mu)\n\n return result\n\n else:\n raise ValueError(\"Invalid p supplied to Kantorvich distance\")\n\n\[email protected]()\ndef symmetric_kl_divergence(x, y):\n result = 0.0\n l1_norm_x = 0.0\n l1_norm_y = 0.0\n dim = x.shape[0]\n\n for i in range(dim):\n l1_norm_x += x[i]\n l1_norm_y += y[i]\n\n l1_norm_x += FLOAT32_EPS * dim\n l1_norm_y += FLOAT32_EPS * dim\n\n pdf_x = (x + FLOAT32_EPS) / l1_norm_x\n pdf_y = (y + FLOAT32_EPS) / l1_norm_y\n\n for i in range(dim):\n result += pdf_x[i] * np.log(pdf_x[i] / pdf_y[i]) + pdf_y[i] * np.log(\n pdf_y[i] / pdf_x[i]\n )\n\n return result\n\n\nnamed_distances = {\n # general minkowski distances\n \"euclidean\": euclidean,\n \"l2\": euclidean,\n \"sqeuclidean\": squared_euclidean,\n \"manhattan\": manhattan,\n \"taxicab\": manhattan,\n \"l1\": manhattan,\n \"chebyshev\": chebyshev,\n \"linfinity\": chebyshev,\n \"linfty\": chebyshev,\n \"linf\": chebyshev,\n \"minkowski\": minkowski,\n # Standardised/weighted distances\n \"seuclidean\": standardised_euclidean,\n \"standardised_euclidean\": standardised_euclidean,\n \"wminkowski\": weighted_minkowski,\n \"weighted_minkowski\": weighted_minkowski,\n \"mahalanobis\": mahalanobis,\n # Other distances\n \"canberra\": canberra,\n \"cosine\": cosine,\n \"dot\": dot,\n \"correlation\": correlation,\n \"haversine\": haversine,\n \"braycurtis\": bray_curtis,\n \"spearmanr\": spearmanr,\n \"tsss\": tsss,\n \"true_angular\": true_angular,\n # Distribution distances\n \"hellinger\": hellinger,\n \"kantorovich\": kantorovich,\n \"wasserstein\": kantorovich,\n \"wasserstein_1d\": wasserstein_1d,\n \"wasserstein-1d\": wasserstein_1d,\n \"kantorovich-1d\": wasserstein_1d,\n \"kantorovich_1d\": wasserstein_1d,\n \"circular_kantorovich\": circular_kantorovich,\n \"circular_wasserstein\": circular_kantorovich,\n \"sinkhorn\": sinkhorn,\n \"jensen-shannon\": jensen_shannon_divergence,\n \"jensen_shannon\": jensen_shannon_divergence,\n \"symmetric-kl\": symmetric_kl_divergence,\n \"symmetric_kl\": symmetric_kl_divergence,\n \"symmetric_kullback_liebler\": symmetric_kl_divergence,\n # Binary distances\n \"hamming\": hamming,\n \"jaccard\": jaccard,\n \"dice\": dice,\n \"matching\": matching,\n \"kulsinski\": kulsinski,\n \"rogerstanimoto\": rogers_tanimoto,\n \"russellrao\": russellrao,\n \"sokalsneath\": sokal_sneath,\n \"sokalmichener\": sokal_michener,\n \"yule\": yule,\n}\n\n# Some distances have a faster to compute alternative that\n# retains the same ordering of distances. We can compute with\n# this instead, and then correct the final distances when complete.\n# This provides a list of distances that have such an alternative\n# along with the alternative distance function and the correction\n# function to be applied.\nfast_distance_alternatives = {\n \"euclidean\": {\"dist\": squared_euclidean, \"correction\": np.sqrt},\n \"l2\": {\"dist\": squared_euclidean, \"correction\": np.sqrt},\n \"cosine\": {\"dist\": alternative_cosine, \"correction\": correct_alternative_cosine},\n \"dot\": {\"dist\": alternative_dot, \"correction\": correct_alternative_cosine},\n \"true_angular\": {\n \"dist\": alternative_cosine,\n \"correction\": true_angular_from_alt_cosine,\n },\n \"hellinger\": {\n \"dist\": alternative_hellinger,\n \"correction\": correct_alternative_hellinger,\n },\n \"jaccard\": {\"dist\": alternative_jaccard, \"correction\": correct_alternative_jaccard},\n}\n"
]
| [
[
"numpy.arccos",
"numpy.median",
"numpy.finfo",
"numpy.radians",
"numpy.cos",
"numpy.sin",
"numpy.empty",
"numpy.log",
"numpy.arcsin",
"numpy.nonzero",
"numpy.eye",
"numpy.arange",
"numpy.sqrt",
"numpy.column_stack",
"numpy.zeros",
"numpy.corrcoef",
"numpy.log2",
"numpy.asarray",
"numpy.sum",
"numpy.ones",
"numpy.abs"
]
]
|
dvdzhang/uncertainty-baselines | [
"8ce0d7494e5cae0719c1b750da4b61564e536636"
]
| [
"baselines/clinc_intent/bert_utils.py"
]
| [
"# coding=utf-8\n# Copyright 2022 The Uncertainty Baselines Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Utility function for BERT models.\"\"\"\nimport json\nimport re\nfrom typing import Any, Dict, List, Mapping, Optional, Tuple\nfrom absl import logging\n\nimport tensorflow as tf\n\nfrom tensorflow.core.protobuf import trackable_object_graph_pb2 # pylint: disable=g-direct-tensorflow-import\nfrom official.nlp import optimization\nfrom official.nlp.bert import configs\n\n\n\ndef create_config(config_dir: str) -> configs.BertConfig:\n \"\"\"Load a BERT config object from directory.\"\"\"\n with tf.io.gfile.GFile(config_dir) as config_file:\n bert_config = json.load(config_file)\n return configs.BertConfig(**bert_config)\n\n\ndef create_feature_and_label(inputs, feature_size: int):\n \"\"\"Creates features and labels for a BERT model.\"\"\"\n input_token_ids = inputs['features']\n labels = inputs['labels']\n num_tokens = inputs['num_tokens']\n\n input_mask = tf.sequence_mask(num_tokens, feature_size, dtype=tf.int32)\n type_id = tf.sequence_mask(num_tokens, feature_size, dtype=tf.int32)\n features = [input_token_ids, input_mask, type_id]\n\n return features, labels\n\n\ndef create_optimizer(\n initial_lr: float,\n steps_per_epoch: int,\n epochs: int,\n warmup_proportion: float,\n end_lr: float = 0.0,\n optimizer_type: str = 'adamw',\n beta_1: float = 0.9) -> tf.keras.optimizers.Optimizer:\n \"\"\"Creates a BERT optimizer with learning rate schedule.\"\"\"\n num_train_steps = steps_per_epoch * epochs\n num_warmup_steps = int(num_train_steps * warmup_proportion)\n return optimization.create_optimizer(\n initial_lr,\n num_train_steps,\n num_warmup_steps,\n end_lr=end_lr,\n optimizer_type=optimizer_type,\n beta_1=beta_1)\n\n\ndef load_bert_weight_from_ckpt(\n bert_model: tf.keras.Model,\n bert_ckpt_dir: str,\n repl_patterns: Optional[Dict[str, str]] = None\n) -> Tuple[tf.keras.Model, Mapping[str, str], Mapping[str, Any]]:\n \"\"\"Loads checkpoint weights and match to model weights if applicable.\n\n Args:\n bert_model: The BERT Encoder model whose weights to load from checkpoints.\n bert_ckpt_dir: Path to BERT pre-trained checkpoints.\n repl_patterns: A mapping of regex string patterns and their replacements. To\n be used to update checkpoint weight names so they match those in\n bert_model (e.g., via re.sub(pattern, repl, weight_name))\n\n Returns:\n bert_model: The BERT Encoder model with loaded weights.\n names_to_keys: A dict mapping of weight name to checkpoint keys.\n keys_to_weights: A dict mapping of checkpoint keys to weight values.\n \"\"\"\n # Load a dict mapping of weight names to their corresponding checkpoint keys.\n names_to_keys = object_graph_key_mapping(bert_ckpt_dir)\n if repl_patterns:\n # Update weight names so they match those in bert_model\n names_to_keys = {\n update_weight_name(repl_patterns, weight_name): weight_key\n for weight_name, weight_key in names_to_keys.items()\n }\n\n # Load a dict mapping of checkpoint keys to weight values.\n logging.info('Loading weights from checkpoint: %s', bert_ckpt_dir)\n keys_to_weights = load_ckpt_keys_to_weight_mapping(bert_ckpt_dir)\n\n # Arranges the pre-trained weights in the order of model weights.\n init_weight_list = match_ckpt_weights_to_model(bert_model, names_to_keys,\n keys_to_weights)\n\n # Load weights into model.\n bert_model.set_weights(init_weight_list)\n\n return bert_model, names_to_keys, keys_to_weights\n\n\ndef load_ckpt_keys_to_weight_mapping(ckpt_path: str) -> Mapping[str, Any]:\n \"\"\"Loads weight values and their checkpoint keys from BERT checkpoint.\"\"\"\n init_vars = tf.train.list_variables(ckpt_path)\n\n keys_to_weights = {}\n for name, _ in init_vars:\n var = tf.train.load_variable(ckpt_path, name)\n keys_to_weights[name] = var\n\n return keys_to_weights\n\n\ndef match_ckpt_weights_to_model(\n model: tf.keras.Model,\n names_to_keys: Mapping[str, str],\n keys_to_weights: Mapping[str, Any]) -> List[Any]:\n \"\"\"Produces a list of checkpoint weights in the order specified by model.\"\"\"\n init_weight_list = []\n\n for weight in model.weights:\n # Look up weight name in checkpoint weight names.\n weight_name = weight.name.replace(':0', '')\n ckpt_key = names_to_keys.get(weight_name, None)\n\n if ckpt_key:\n init_weight = keys_to_weights[ckpt_key]\n else:\n logging.info(\n '\"%s\" not found in checkpoint. '\n 'Using randomly initialized values.', weight_name)\n init_weight = weight.numpy()\n\n init_weight_list.append(init_weight)\n\n return init_weight_list\n\n\ndef update_weight_name(repl_patterns: Dict[str, str], weight_name: str) -> str:\n \"\"\"Updates weight names according a dictionary of replacement patterns.\"\"\"\n # Create a regular expression from all of the dictionary keys\n regex = re.compile('|'.join(map(re.escape, repl_patterns.keys())))\n\n # For each match, look up the corresponding value in the repl_patterns dict.\n return regex.sub(lambda match: repl_patterns[match.group(0)], weight_name)\n\n\ndef object_graph_key_mapping(checkpoint_path: str) -> Dict[str, str]:\n \"\"\"Return name to key mappings from the checkpoint.\"\"\"\n reader = tf.train.load_checkpoint(checkpoint_path)\n object_graph_string = reader.get_tensor('_CHECKPOINTABLE_OBJECT_GRAPH')\n object_graph_proto = trackable_object_graph_pb2.TrackableObjectGraph()\n object_graph_proto.ParseFromString(object_graph_string)\n names_to_keys = {}\n for node in object_graph_proto.nodes:\n for attribute in node.attributes:\n names_to_keys[attribute.full_name] = attribute.checkpoint_key\n return names_to_keys\n"
]
| [
[
"tensorflow.sequence_mask",
"tensorflow.io.gfile.GFile",
"tensorflow.train.load_variable",
"tensorflow.train.load_checkpoint",
"tensorflow.train.list_variables",
"tensorflow.core.protobuf.trackable_object_graph_pb2.TrackableObjectGraph"
]
]
|
openAGI/datum | [
"2dfc8c62ed1366fd8544b8b25d730d89dfb57d4e"
]
| [
"datum/utils/common_utils.py"
]
| [
"# Copyright 2020 The OpenAGI Datum Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport abc\nimport contextlib\nimport copy\nimport importlib.util as module_util\nimport sys\nfrom itertools import chain\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, no_type_check\n\nimport numpy as np\nfrom tensorflow.python.util import tf_inspect\n\nfrom datum.utils.types_utils import DatumType, ValueType\n\n\ndef load_module(module_name: str, module_path: str) -> object:\n \"\"\"Load python module using a given path; the path can be absolute or relative.\n\n Args:\n module_name: a `str`, name of the module to load\n module_path: a `str`, absolute/relative path of the module to load\n\n Return:\n loaded python module\n \"\"\"\n spec = module_util.spec_from_file_location(module_name, module_path)\n module = module_util.module_from_spec(spec)\n spec.loader.exec_module(module) # type: ignore\n return module\n\n\nclass AttrDict(dict):\n \"\"\"Enables acessing dict items as attributes.\n\n Args:\n args: a `dict` object.\n \"\"\"\n\n # pylint: disable=no-self-argument\n def __init__(__self, *args: Any, **kwargs: Any):\n object.__setattr__(__self, '__parent', kwargs.pop('__parent', None))\n object.__setattr__(__self, '__key', kwargs.pop('__key', None))\n for arg in args:\n if not arg:\n continue\n elif isinstance(arg, dict):\n for key, val in arg.items():\n __self[key] = __self._hook(val)\n elif isinstance(arg, tuple) and (not isinstance(arg[0], tuple)):\n __self[arg[0]] = __self._hook(arg[1])\n else:\n for key, val in iter(arg):\n __self[key] = __self._hook(val)\n\n for key, val in kwargs.items():\n __self[key] = __self._hook(val)\n\n def __setattr__(self, name: str, value: Any) -> None:\n if hasattr(self.__class__, name):\n raise AttributeError(\"'Dict' object attribute \" \"'{0}' is read-only\".format(name))\n else:\n self[name] = value\n\n def __setitem__(self, name: str, value: Any) -> None:\n super(AttrDict, self).__setitem__(name, value)\n try:\n p = object.__getattribute__(self, '__parent')\n key = object.__getattribute__(self, '__key')\n except AttributeError:\n p = None\n key = None\n if p is not None:\n p[key] = self\n object.__delattr__(self, '__parent')\n object.__delattr__(self, '__key')\n\n def __add__(self, other: Any) -> Any:\n if not self.keys():\n return other\n else:\n self_type = type(self).__name__\n other_type = type(other).__name__\n msg = \"unsupported operand type(s) for +: '{}' and '{}'\"\n raise TypeError(msg.format(self_type, other_type))\n\n @classmethod\n def _hook(cls: Any, item: Any) -> Any:\n if isinstance(item, dict):\n return cls(item)\n elif isinstance(item, (list, tuple)):\n return type(item)(cls._hook(elem) for elem in item)\n return item\n\n def __getattr__(self, item: Any) -> Any:\n return self.__getitem__(item)\n\n def __missing__(self, name: str) -> Any:\n return self.__class__(__parent=self, __key=name)\n\n def __delattr__(self, name: str) -> None:\n del self[name]\n\n def to_dict(self) -> Any:\n base = {}\n for key, value in self.items():\n if isinstance(value, type(self)):\n base[key] = value.to_dict()\n elif isinstance(value, (list, tuple)):\n base[key] = type(value)(item.to_dict() if isinstance(item, type(self)) else item\n for item in value)\n else:\n base[key] = value\n return base\n\n def copy(self) -> Any:\n return copy.copy(self)\n\n def deepcopy(self) -> Any:\n return copy.deepcopy(self)\n\n def __deepcopy__(self, memo: Any) -> Any:\n other = self.__class__()\n memo[id(self)] = other\n for key, value in self.items():\n other[copy.deepcopy(key, memo)] = copy.deepcopy(value, memo)\n return other\n\n def update(self, *args: Any, **kwargs: Any) -> None:\n other: Dict[Any, Any] = {}\n if args:\n if len(args) > 1:\n raise TypeError()\n other.update(args[0])\n other.update(kwargs)\n for k, v in other.items():\n if ((k not in self) or (not isinstance(self[k], dict)) or (not isinstance(v, dict))):\n self[k] = v\n else:\n self[k].update(v)\n\n def __getnewargs__(self) -> Any:\n return tuple(self.items())\n\n def __getstate__(self) -> Any:\n return self\n\n def __setstate__(self, state: Any) -> None:\n self.update(state)\n\n def setdefault(self, key: Any, default: Optional[Any] = None) -> Any:\n if key in self:\n return self[key]\n else:\n self[key] = default\n return default\n\n\ndef add_metaclass(metaclass: abc.ABCMeta) -> Callable[[Any], object]:\n \"\"\"Class decorator for creating a class with a metaclass.\n\n This supports creating metaclass with slots variable.\n \"\"\"\n\n def wrapper(cls: Any) -> object:\n orig_vars = cls.__dict__.copy()\n slots = orig_vars.get(\"__slots__\")\n if slots is not None:\n if isinstance(slots, str):\n slots = [slots]\n for slots_var in slots:\n orig_vars.pop(slots_var)\n orig_vars.pop(\"__dict__\", None)\n orig_vars.pop(\"__weakref__\", None)\n if hasattr(cls, \"__qualname__\"):\n orig_vars[\"__qualname__\"] = cls.__qualname__\n return metaclass(cls.__name__, cls.__bases__, orig_vars)\n\n return wrapper\n\n\ndef reraise(prefix: Optional[str] = None, suffix: Optional[str] = None) -> None:\n \"\"\"Reraise an exception with an additional message.\n\n Args:\n prefix: prefix to add to the current exception.\n suffix: suffix to add to the current exception.\n \"\"\"\n exc_type, exc_value, exc_traceback = sys.exc_info()\n prefix = prefix or \"\"\n suffix = \"\\n\" + suffix if suffix else \"\"\n msg = prefix + str(exc_value) + suffix\n six_reraise(exc_type, exc_type(msg), exc_traceback) # type: ignore\n\n\[email protected]\ndef try_reraise(*args: Any, **kwargs: Any) -> Any:\n \"\"\"Reraise an exception with an additional message.\"\"\"\n try:\n yield\n except Exception: # pylint: disable=broad-except\n reraise(*args, **kwargs)\n\n\n@no_type_check\ndef six_reraise(tp, value, tb=None):\n try:\n if value is None:\n value = tp()\n if value.__traceback__ is not tb:\n raise value.with_traceback(tb)\n raise value\n finally:\n value = None\n tb = None\n\n\n@no_type_check\ndef zip_dict(*dicts):\n \"\"\"Iterate over items of dictionaries grouped by their keys.\"\"\"\n for key in set(chain(*dicts)): # set merge all keys\n # Will raise KeyError if the dict don't have the same keys\n yield key, tuple(d[key] for d in dicts)\n\n\ndef item_to_type_and_shape(item: ValueType) -> Tuple[str, List]:\n \"\"\"Datum item to type and shape.\"\"\"\n item = np.array(item)\n\n shape = list(item.shape)\n if item.dtype == np.bool_:\n return 'int', shape\n item = item.flatten()\n if np.issubdtype(item.dtype, np.integer):\n return 'int', shape\n elif np.issubdtype(item.dtype, np.floating):\n return 'float', shape\n elif is_string(item):\n return 'string', check_and_image_shape(item, shape)\n else:\n raise ValueError(f'Unsupported value: {item}.')\n\n\ndef check_and_image_shape(item: ValueType, shape: List) -> List:\n \"\"\"Check whether a string is image filename.\n\n Args:\n item: input string to check.\n\n Returns:\n a list, item shape.\n \"\"\"\n if len(item.shape) > 0:\n item = str(item[0])\n if item.endswith(('.jpg', '.jpeg', '.png')):\n import cv2\n im = cv2.imread(item)\n if im is not None:\n return list(im.shape)\n return shape\n\n\ndef is_string(item: Any) -> bool:\n \"\"\"Check if the object contains string or bytes.\"\"\"\n if isinstance(item, (bytes, bytearray, str)):\n return True\n elif (isinstance(item, (tuple, list)) and all(is_string(x) for x in item)):\n return True\n elif (isinstance(item, np.ndarray) and # binary or unicode\n (item.dtype.kind in (\"U\", \"S\") or item.dtype == object)):\n return True\n return False\n\n\ndef datum_to_type_and_shape(datum: DatumType, sparse_features: Optional[List[str]] = None) -> Dict:\n \"\"\"Get object type and shape from value.\"\"\"\n if not isinstance(datum, dict):\n raise ValueError(f'Input type is not supported, datum: {datum}')\n outputs = {}\n for key, value in datum.items():\n otype, shape = item_to_type_and_shape(value)\n if sparse_features and key in sparse_features:\n outputs[key] = {'type': otype, 'shape': shape, 'dense': False}\n else:\n outputs[key] = {'type': otype, 'shape': shape, 'dense': True}\n return outputs\n\n\nclass memoized_property(property): # pylint: disable=invalid-name\n \"\"\"Descriptor that mimics @property but caches output in member variable.\"\"\"\n\n @no_type_check\n def __get__(self, obj, objtype=None):\n # See https://docs.python.org/3/howto/descriptor.html#properties\n if obj is None:\n return self\n if self.fget is None:\n raise AttributeError(\"unreadable attribute\")\n attr = \"__cached_\" + self.fget.__name__\n cached = getattr(obj, attr, None)\n if cached is None:\n cached = self.fget(obj)\n setattr(obj, attr, cached)\n return cached\n\n\ndef deserialize_object(identifier: Any,\n module_objects: Dict,\n printable_module_name: str = 'object') -> object:\n \"\"\"Deserialize object using name.\n\n Args:\n identifier: a string or function.\n module_objects: modules global objects.\n printable_module_name: name of the module,\n\n Returns:\n deserialized class.\n\n Raises:\n ValueError: if identifier does not exist or not supported.\n \"\"\"\n if identifier is None:\n return None\n\n if isinstance(identifier, str):\n obj = module_objects.get(identifier)\n if obj is None:\n raise ValueError('Unknown ' + printable_module_name + ':' + identifier)\n return obj\n elif tf_inspect.isfunction(identifier):\n return identifier\n else:\n raise ValueError(f'Could not interpret serialized {printable_module_name}:{identifier}')\n"
]
| [
[
"numpy.array",
"tensorflow.python.util.tf_inspect.isfunction",
"numpy.issubdtype"
]
]
|
Iota87/texthero | [
"f3e3acec1ffab3436f38419f87058f2693e3da7e"
]
| [
"tests/test_representation.py"
]
| [
"import pandas as pd\nimport numpy as np\nfrom texthero import representation\nfrom texthero import preprocessing\n\nfrom . import PandasTestCase\n\nimport doctest\nimport unittest\nimport string\nimport math\nimport warnings\nfrom parameterized import parameterized\n\n\n\"\"\"\nTest doctest\n\"\"\"\n\n\ndef load_tests(loader, tests, ignore):\n tests.addTests(doctest.DocTestSuite(representation))\n return tests\n\n\n\"\"\"\nHelper functions for the tests.\n\"\"\"\n\n\ndef _tfidf(term, corpus, document_index):\n idf = (\n math.log((1 + len(corpus)) / (1 + len([doc for doc in corpus if term in doc])))\n + 1\n )\n tfidf_value = idf * corpus[document_index].count(term)\n return tfidf_value\n\n\n\"\"\"\nTest functions in representation module in a\nparameterized way.\n\"\"\"\n\n\n# Define valid inputs / outputs / indexes for different functions.\ns_not_tokenized = pd.Series([\"This is not tokenized!\"])\ns_tokenized = pd.Series([[\"Test\", \"Test\", \"TEST\", \"!\"], [\"Test\", \"?\", \".\", \".\"]])\ns_tokenized_with_noncontinuous_index = pd.Series(\n [[\"Test\", \"Test\", \"TEST\", \"!\"], [\"Test\", \"?\", \".\", \".\"]], index=[5, 7]\n)\n\ns_tokenized_output_index = pd.MultiIndex.from_tuples(\n [(0, \"!\"), (0, \"TEST\"), (0, \"Test\"), (1, \".\"), (1, \"?\"), (1, \"Test\")],\n)\n\ns_tokenized_output_noncontinuous_index = pd.MultiIndex.from_tuples(\n [(5, \"!\"), (5, \"TEST\"), (5, \"Test\"), (7, \".\"), (7, \"?\"), (7, \"Test\")],\n)\n\ns_tokenized_output_min_df_index = pd.MultiIndex.from_tuples([(0, \"Test\"), (1, \"Test\")],)\n\n\ntest_cases_vectorization = [\n # format: [function_name, function, correct output for tokenized input above, dtype of output]\n [\"count\", representation.count, [1, 1, 2, 2, 1, 1], \"int\"],\n [\n \"term_frequency\",\n representation.term_frequency,\n [0.125, 0.125, 0.250, 0.250, 0.125, 0.125],\n \"float\",\n ],\n [\n \"tfidf\",\n representation.tfidf,\n [_tfidf(x[1], s_tokenized, x[0]) for x in s_tokenized_output_index],\n \"float\",\n ],\n]\n\ntest_cases_vectorization_min_df = [\n # format: [function_name, function, correct output for tokenized input above, dtype of output]\n [\"count\", representation.count, [2, 1], \"int\"],\n [\"term_frequency\", representation.term_frequency, [0.666667, 0.333333], \"float\",],\n [\"tfidf\", representation.tfidf, [2.0, 1.0], \"float\",],\n]\n\n\nclass AbstractRepresentationTest(PandasTestCase):\n \"\"\"\n Class for representation test cases. Most tests are\n parameterized, some are implemented individually\n (e.g. to test a formula manually).\n \"\"\"\n\n \"\"\"\n Vectorization.\n \"\"\"\n\n @parameterized.expand(test_cases_vectorization)\n def test_vectorization_simple(\n self, name, test_function, correct_output_values, int_or_float\n ):\n if int_or_float == \"int\":\n s_true = pd.Series(\n correct_output_values, index=s_tokenized_output_index, dtype=\"int\"\n ).astype(pd.SparseDtype(np.int64, 0))\n else:\n s_true = pd.Series(\n correct_output_values, index=s_tokenized_output_index, dtype=\"float\"\n ).astype(pd.SparseDtype(\"float\", np.nan))\n result_s = test_function(s_tokenized)\n\n pd.testing.assert_series_equal(s_true, result_s)\n\n @parameterized.expand(test_cases_vectorization)\n def test_vectorization_noncontinuous_index_kept(\n self, name, test_function, correct_output_values, int_or_float\n ):\n if int_or_float == \"int\":\n s_true = pd.Series(\n correct_output_values,\n index=s_tokenized_output_noncontinuous_index,\n dtype=\"int\",\n ).astype(pd.SparseDtype(np.int64, 0))\n else:\n s_true = pd.Series(\n correct_output_values,\n index=s_tokenized_output_noncontinuous_index,\n dtype=\"float\",\n ).astype(pd.SparseDtype(\"float\", np.nan))\n\n result_s = test_function(s_tokenized_with_noncontinuous_index)\n\n pd.testing.assert_series_equal(s_true, result_s)\n\n @parameterized.expand(test_cases_vectorization_min_df)\n def test_vectorization_min_df(\n self, name, test_function, correct_output_values, int_or_float\n ):\n if int_or_float == \"int\":\n s_true = pd.Series(\n correct_output_values,\n index=s_tokenized_output_min_df_index,\n dtype=\"int\",\n ).astype(pd.SparseDtype(np.int64, 0))\n else:\n s_true = pd.Series(\n correct_output_values,\n index=s_tokenized_output_min_df_index,\n dtype=\"float\",\n ).astype(pd.SparseDtype(\"float\", np.nan))\n\n result_s = test_function(s_tokenized, min_df=2)\n\n pd.testing.assert_series_equal(s_true, result_s)\n\n @parameterized.expand(test_cases_vectorization)\n def test_vectorization_not_tokenized_yet_warning(self, name, test_function, *args):\n with self.assertWarns(DeprecationWarning): # check raise warning\n test_function(s_not_tokenized)\n\n @parameterized.expand(test_cases_vectorization)\n def test_vectorization_arguments_to_sklearn(self, name, test_function, *args):\n try:\n test_function(s_not_tokenized, max_features=1, min_df=1, max_df=1.0)\n except TypeError:\n self.fail(\"Sklearn arguments not handled correctly.\")\n\n \"\"\"\n Individual / special tests.\n \"\"\"\n\n def test_tfidf_formula(self):\n s = pd.Series([\"Hi Bye\", \"Test Bye Bye\"])\n s = preprocessing.tokenize(s)\n s_true_index = pd.MultiIndex.from_tuples(\n [(0, \"Bye\"), (0, \"Hi\"), (1, \"Bye\"), (1, \"Test\")],\n )\n s_true = pd.Series(\n [_tfidf(x[1], s, x[0]) for x in s_true_index], index=s_true_index\n ).astype(\"Sparse\")\n\n self.assertEqual(representation.tfidf(s), s_true)\n\n \"\"\"\n flatten.\n \"\"\"\n\n def test_flatten(self):\n index = pd.MultiIndex.from_tuples(\n [(\"doc0\", \"Word1\"), (\"doc0\", \"Word3\"), (\"doc1\", \"Word2\")],\n )\n s = pd.Series([3, np.nan, 4], index=index)\n\n s_true = pd.Series(\n [[3.0, 0.0, np.nan], [0.0, 4.0, 0.0]], index=[\"doc0\", \"doc1\"],\n )\n\n pd.testing.assert_series_equal(\n representation.flatten(s), s_true, check_names=False\n )\n\n def test_flatten_fill_missing_with(self):\n index = pd.MultiIndex.from_tuples(\n [(\"doc0\", \"Word1\"), (\"doc0\", \"Word3\"), (\"doc1\", \"Word2\")],\n )\n s = pd.Series([3, np.nan, 4], index=index)\n\n s_true = pd.Series(\n [[3.0, \"FILLED\", np.nan], [\"FILLED\", 4.0, \"FILLED\"]],\n index=[\"doc0\", \"doc1\"],\n )\n\n pd.testing.assert_series_equal(\n representation.flatten(s, fill_missing_with=\"FILLED\"),\n s_true,\n check_names=False,\n )\n\n def test_flatten_missing_row(self):\n # Simulating a row with no features, so it's completely missing from\n # the representation series.\n index = pd.MultiIndex.from_tuples(\n [(\"doc0\", \"Word1\"), (\"doc0\", \"Word3\"), (\"doc1\", \"Word2\")],\n )\n s = pd.Series([3, np.nan, 4], index=index)\n\n s_true = pd.Series(\n [[3.0, 0.0, np.nan], [0.0, 4.0, 0.0], [0.0, 0.0, 0.0]],\n index=[\"doc0\", \"doc1\", \"doc2\"],\n )\n\n pd.testing.assert_series_equal(\n representation.flatten(s, index=s_true.index), s_true, check_names=False\n )\n"
]
| [
[
"pandas.testing.assert_series_equal",
"pandas.MultiIndex.from_tuples",
"pandas.SparseDtype",
"pandas.Series"
]
]
|
osu-xai/abp | [
"cd83eaa2810a1c5350c849303d61639576c0bb0d"
]
| [
"abp/adaptives/mb_ts/adaptive_archive_1l.py"
]
| [
"import logging\nimport time\nimport random\nimport pickle\nimport os\nfrom sys import maxsize\nfrom collections import OrderedDict\n\nimport torch\nfrom tensorboardX import SummaryWriter\nfrom baselines.common.schedules import LinearSchedule\nimport numpy as np\nfrom copy import deepcopy\n\nfrom abp.utils import clear_summary_path\nfrom abp.models import DQNModel\n# TODO: Generalize it\nfrom abp.examples.pysc2.tug_of_war.models_mb.transition_model import TransModel\nfrom abp.utils.search_tree import Node\n\nlogger = logging.getLogger('root')\nuse_cuda = torch.cuda.is_available()\nFloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor\nLongTensor = torch.cuda.LongTensor if use_cuda else torch.LongTensor\nIntTensor = torch.cuda.IntTensor if use_cuda else torch.IntTensor\nByteTensor = torch.cuda.ByteTensor if use_cuda else torch.ByteTensor\nTensor = FloatTensor\n\nbuilding_types = {\n 'Marine': 0,\n 'Viking': 1,\n 'Colossus': 2,\n 'Pylon': 3\n}\nclass MBTSAdaptive(object):\n \"\"\"Adaptive which uses the Model base Tree search algorithm\"\"\"\n\n def __init__(self, name, state_length, network_config, reinforce_config, models_path, env, player = 1):\n super(MBTSAdaptive, self).__init__()\n self.name = name\n #self.choices = choices\n self.network_config = network_config\n self.reinforce_config = reinforce_config\n self.explanation = False\n self.state_length = state_length\\\n \n # Global\n self.steps = 0\n self.episode = 0\n self.transition_model_HP = TransModel(state_length, 2)\n self.transition_model_unit = TransModel(state_length, 6)\n self.value_model = DQNModel(self.name + \"_eval\", self.network_config, use_cuda)\n self.load_model(models_path)\n self.env = env\n self.player = player\n \n self.index_hp = np.array([4, 9])\n self.index_units = np.array(range(11, 17))\n \n self.look_forward_step = 1\n \n # Generalize it \n self.load_model(models_path)\n self.eval_mode()\n self.normalization_array = np.array([30, 30, 30, 30, 2000,\n 30, 30, 30, 30, 2000,\n 1500, 60, 60, 60, 60, 60, 60])\n\n self.reset()\n \n def reward_func(self, state, next_states):\n# print(\"reward func\")\n# print(state.shape, next_states.shape)\n# for n_s in next_states:\n# print(\"===================================\")\n# print(state.tolist())\n# print(n_s.tolist())\n# # print(state, next_states)\n# print(next_states[:, self.index_hp] > 2000)\n next_states[next_states > 2000] = 2000\n \n rewards = (next_states - state.reshape(-1,))[:, self.index_hp]\n rewards[rewards > 0] = 1\n rewards[:, 1] *= -1\n rewards = np.sum(rewards, axis = 1)\n# print(rewards)\n# input()\n return rewards\n \n \n def eval_mode(self):\n self.value_model.eval_mode()\n self.transition_model_HP.eval_mode()\n self.transition_model_unit.eval_mode()\n \n def load_model(self, models_path):\n HP_state_dict = torch.load(models_path + 'transition_model_HP.pt')\n unit_state_dict = torch.load(models_path + 'transition_model_unit.pt')\n# print(HP_state_dict.model)\n new_HP_state_dict = OrderedDict()\n new_unit_state_dict = OrderedDict()\n \n for old_key_value_hp, old_key_value_unit in zip(list(HP_state_dict.items()), list(unit_state_dict.items())):\n new_key_hp, new_value_hp = \"module.\" + old_key_value_hp[0], old_key_value_hp[1]\n new_key_unit, new_value_unit = \"module.\" + old_key_value_unit[0], old_key_value_unit[1]\n# print(new_key_hp, new_key_unit)\n# print(old_key_hp, old_key_unit)\n new_HP_state_dict[new_key_hp] = new_value_hp\n new_unit_state_dict[new_key_unit] = new_value_unit\n \n \n self.transition_model_HP.load_weight(new_HP_state_dict)\n # TODO: get unit transition model\n self.transition_model_unit.load_weight(new_unit_state_dict)\n self.value_model.load_weight(torch.load(models_path + 'value_model.pt'))\n\n def predict(self, state, minerals_enemy):\n # Get actions of self\n root = Node('root', state)\n parents = [root]\n if self.player == 1:\n fifo_self = self.env.fifo_player_1\n fifo_enemy = self.env.fifo_player_2\n else:\n fifo_self = self.env.fifo_player_2\n fifo_enemy = self.env.fifo_player_1\n \n leaf_node = []\n leaf_node_states = []\n leaf_fifo = []\n for i in range(self.look_forward_step):\n for n in parents:\n next_states, next_fifo_self, length_enemy_action = self.expand_node(n, minerals_enemy, fifo_self, fifo_enemy)\n if i == (self.look_forward_step - 1):\n next_states = self.same_self_action_block(next_states, length_enemy_action)\n children = self.same_self_action_block(np.array(n.children), length_enemy_action)\n leaf_node_states.append(next_states)\n leaf_fifo.append(next_fifo_self)\n leaf_node.append(children)\n \n \n# print(len(leaf_node_states[0]), len(leaf_fifo[0]), len(leaf_node[0]))\n# input()\n if self.look_forward_step == 0:\n self.rollout_root([parents[0].state], parents, [fifo_self])\n else:\n for lns, ln, ff in zip(leaf_node_states, leaf_node, leaf_fifo):\n self.rollout(lns, ln, ff)\n \n# print(root.best_reward)\n# action, _ = self.value_model.predict(state, 0, False)\n# print(root.best_action)\n return root.best_action\n\n def same_self_action_block(self, states_or_nodes, length_enemy_action):\n return np.array(np.split(states_or_nodes, length_enemy_action))\n \n def rollout(self, states, nodes, ffs):\n all_min_q_value = []\n for s_block, n_block, ff in zip(states, nodes, ffs):\n# print(s.tolist(),n.parent.best_reward,ff)\n# input()\n s_b = []\n for s in s_block:\n actions_self = self.env.get_big_A(s[self.env.miner_index])\n com_s, _ = self.combine_sa(s, actions_self, ff, is_enemy = False)\n # for cs in com_s:\n # print(cs.tolist())\n # input()\n # com_s_old, _ = self.combine_sa_old(s, actions_self, ff, is_enemy = False)\n # assert sum(sum(com_s_old == com_s)) == com_s_old.shape[0] * com_s_old.shape[1], print(com_s_old == com_s)\n com_s = self.env.normalization(com_s)\n s_b.append(com_s)\n s_b = np.vstack(s_b)\n# print(s_b.shape)\n# input()\n q_values_block = FloatTensor(self.value_model.predict_batch(Tensor(s_b))[1]).view(-1)\n# print(q_values)\n# input()\n min_q_value, _ = q_values_block.min(0)\n all_min_q_value.append(min_q_value)\n# print(all_min_q_value)\n max_q_value, choice = FloatTensor(all_min_q_value).max(0)\n if nodes[0][0].parent is not None:\n parent = nodes[0][0].parent\n else:\n parent = nodes[0][0]\n parent.best_reward = parent.reward + max_q_value\n parent.best_action = self.env.get_big_A(parent.state[self.env.miner_index])[choice]\n self.reward_brack_prop(parent)\n# print(\"mbts:\")\n# print(parent.best_reward)\n# print(parent.best_action)\n# input()\n \n def rollout_root(self, states, nodes, ffs):\n for s, n, ff in zip(states, nodes, ffs):\n actions_self = self.env.get_big_A(s[self.env.miner_index])\n com_s, _ = self.combine_sa(s, actions_self, ff, is_enemy = False)\n com_s = self.env.normalization(com_s)\n q_values = FloatTensor(self.value_model.predict_batch(Tensor(com_s))[1]).view(-1)\n max_q_value, choice = q_values.max(0)\n n.best_reward = n.reward + max_q_value\n n.best_action = actions_self[choice]\n# print(\"sadq:\")\n# print(n.reward + max_q_value)\n# print(actions_self[choice])\n# input()\n def normalization(self, state):\n return state / self.normalization_array\n \n def expand_node(self, parent, mineral_enemy, fifo_self, fifo_enemy):\n # TODO: check the state change or not ,if yes deepcopy for the reward func state\n state = deepcopy(parent.state)\n parent_name = parent.name\n actions_self = self.env.get_big_A(state[self.env.miner_index])\n actions_enemy = self.env.get_big_A(mineral_enemy)\n \n after_states, after_fifo_self, after_state_actions_self = self.get_after_states(state, actions_self, actions_enemy, fifo_self, fifo_enemy)\n next_states = self.get_next_states(after_states)\n \n rewards = self.reward_func(state, next_states)\n \n all_sub_nodes = []\n best_reward = float('-inf')\n best_node = None\n best_action = None\n# print(after_state_actions_self)\n for i, (n_s, reward, action) in enumerate(zip(next_states, rewards, after_state_actions_self)):\n# print(n_s.tolist(), reward, action)\n# input()\n child = Node(parent_name + '_' + str(i + 1), n_s, reward = reward, parent = parent, parent_action = action)\n parent.add_child(child, action)\n \n if best_reward < reward:\n best_reward = reward\n best_node = child\n best_action = action\n parent.best_action = best_action\n self.reward_brack_prop(best_node)\n \n return next_states, after_fifo_self, len(actions_self)\n \n def reward_brack_prop(self, node):\n if node.name == \"root\":\n return\n parent = node.parent\n if node.best_reward > parent.best_reward:\n parent.best_child = node\n parent.best_reward = node.best_reward\n parent.best_action = node.parent_action\n self.reward_brack_prop(parent)\n return\n \n def action_ranking(self, q_state, k):\n # TODO\n pass\n \n def reset(self):\n self.current_reward = 0\n self.total_reward = 0\n\n def get_next_states(self, after_state):\n next_HPs = self.transition_model_HP.predict_batch(FloatTensor(self.normalization(after_state)))\n next_units = self.transition_model_unit.predict_batch(FloatTensor(self.normalization(after_state)))\n \n after_state[:, self.index_hp] = next_HPs.cpu().detach().numpy()\n after_state[:, self.index_units] = next_units.round().cpu().detach().numpy()\n \n return after_state\n \n def get_after_states(self, state, actions_self, actions_enemy, fifo_self, fifo_enemy):\n # Faster combination way\n \n after_states_self, after_fifo_self = self.combine_sa(state, actions_self, fifo_self, is_enemy = False)\n# print(len(actions_self), len(after_fifo_self))\n# after_states_self = self.imply_mineral_by_action(after_states_self, actions_self)\n# for af, ff in zip(after_states_self, after_fifo_self):\n# print(af.tolist(), ff)\n after_states = np.zeros((len(actions_self) * len(actions_enemy), after_states_self.shape[1]))\n# print(after_states.shape)\n# idx = 0\n after_state_actions_self = np.zeros((len(actions_self) * len(actions_enemy), actions_self.shape[1]))\n# after_state_fifo_self = []\n for i, a_s_s in enumerate(after_states_self):\n a_s, _ = self.combine_sa(a_s_s, actions_enemy, fifo_enemy, is_enemy = True)\n# print(a_s.shape)\n after_states[i * len(actions_enemy) : (i + 1)* len(actions_enemy)] = a_s\n \n after_state_actions_self[i * len(actions_enemy) : (i + 1)* len(actions_enemy)] = np.repeat(actions_self[i].reshape((1,-1)), len(actions_enemy), axis = 0).copy()\n# for _ in range(len(actions_enemy)):\n# after_state_fifo_self.append(deepcopy(after_fifo_self[i]))\n# print(after_states[:, building_types['Pylon']])\n# print(\"*********\")\n# print(len(after_states), len(after_fifo_self), len(actions_enemy))\n after_states[:, self.env.miner_index] += after_states[:, building_types['Pylon']] * 50 + 100\n# idx += 1\n# print(idx)\n# for a_s in after_states:\n# print(a_s.tolist())\n \n return after_states, after_fifo_self, after_state_actions_self\n \n# def combine_sa_old(self, de_s, actions, fifo, is_enemy):\n# # Change that if the index is changed, generalize it later\n# if not is_enemy:\n# building_index = range(0, 4)\n# else:\n# building_index = range(5, 9)\n \n# fifo = np.array(fifo)\n# s = np.repeat(de_s.reshape((1,-1)), len(actions), axis = 0)\n# fifo_array = np.repeat(fifo.reshape((1,-1)), len(actions), axis = 0)\n \n# actions = np.array(actions)\n# s[:,building_index] += actions\n \n# # Get rid of the building from the candidate after_states until no exceeders to match the FIFO behavior\n# for building_type in fifo:\n# # Get the count of building of the candidate after_state\n# count_of_bulding = s[:, building_index].sum(axis = 1)\n# array_of_indices_of_exceeders = count_of_bulding > self.env.building_limiation\n \n# if sum(array_of_indices_of_exceeders) <= 0:\n# break\n# # print(s.shape)\n# s[array_of_indices_of_exceeders, building_type] -= 1\n \n# # Get all the fifo for each branch\n# fifo_array[array_of_indices_of_exceeders, :-1] = fifo_array[array_of_indices_of_exceeders, 1:]\n# fifo_array[array_of_indices_of_exceeders, 1:] = building_type\n \n# if not is_enemy: \n# s[:, self.env.miner_index] -= np.sum(self.env.maker_cost_np * actions, axis = 1)\n# return s, fifo_array\n\n def combine_sa(self, de_s, actions, fifo, is_enemy):\n if not is_enemy:\n building_index = list(range(0, 4))\n else:\n building_index = list(range(5, 9))\n fifo_list = []\n for _ in range(len(actions)):\n fifo_list.append(deepcopy(fifo))\n s = np.repeat(de_s.reshape((1,-1)), len(actions), axis = 0)\n actions = actions.reshape(-1, 4)\n for idx_a, action in enumerate(actions):\n# print(action)\n for a, num in enumerate(action):\n for _ in range(int(num)):\n s[idx_a][building_index[a]] += 1\n fifo_list[idx_a].append(building_index[a])\n if len(fifo_list[idx_a]) > 30:\n s[idx_a][building_index[fifo_list[idx_a][0]]] -= 1\n del fifo_list[idx_a][0]\n if not is_enemy: \n s[:, self.env.miner_index] -= np.sum(self.env.maker_cost_np * actions, axis = 1)\n return s, fifo_list\n \n def imply_mineral_by_action(self, mineral, action):\n mineral -= np.sum(self.env.maker_cost_np * action)\n return mineral\n \n def imply_after_mineral(self, state):\n state[env.miner_index] += state[building_types['Pylon']] * 50 + 100\n return state\n\n"
]
| [
[
"numpy.array",
"numpy.sum",
"numpy.split",
"torch.cuda.is_available",
"torch.load",
"numpy.vstack"
]
]
|
Lingesh2311/Python-Projects | [
"9916cf580dff165a7348f52efd274c743961381d",
"9916cf580dff165a7348f52efd274c743961381d"
]
| [
"Financial Projects/LeakyGANLongTextGeneration/encode.py",
"Employee Sentiment Analysis & Topic Modelling/initial.py"
]
| [
"from functools import reduce\r\nimport numpy as np\r\nimport pickle\r\n\r\ndef text_to_tensor(filePath):\r\n \"\"\"\r\n Read text from file\r\n \"\"\"\r\n with open(filePath, 'r') as f:\r\n lines = f.readlines()\r\n f.close()\r\n corpus = []\r\n for l in lines:\r\n l = l.strip().split(' ') #strip removes blank spaces from both sides\r\n if len(l) < 28:\r\n corpus.append(l)\r\n \"\"\"\r\n Get all words used in text\r\n \"\"\"\r\n vocab = []\r\n for p in corpus:\r\n vocab.extend(p) #save all into a single list\r\n vocab = list(set(vocab)) #save only unique characters\r\n for i in range(len(vocab)):\r\n if vocab[i] == \"<R>\":\r\n break\r\n del vocab[i]\r\n vocab.append(\"<R>\") #we only need one <R> not several\r\n\r\n \"\"\"\r\n Encode text into a LongTensor\r\n \"\"\"\r\n corpus_num = []\r\n for p in corpus:\r\n corpus_num.append(list(map(lambda x: vocab.index(x) + 1, p)))\r\n corpus_data = np.array(corpus_data)\r\n\r\n \"\"\"\r\n Save preprocessed file\r\n \"\"\"\r\n np.save(\"corpus\", corpus_data) #save the training corpus data, where words are represented as numbers(their index in vocab array)\r\n f = open(\"chars.pkl\", \"wb\") #this is in a sense table of keys\r\n pickle.dump(vocab, f)\r\n\r\n\r\ndef tensor_to_text(input_x, vocab):\r\n #vocab will convert some integer into a word\r\n poem = []\r\n sen_len = 5\r\n for index, x in enumerate(input_x):\r\n if index != 0:\r\n if index % sen_len == 0:\r\n poem.append(\"\\n\")\r\n poem.append(vocab[x-1]) #x-1 because when encoding we added one\r\n poem_ = \"\"\r\n poem_ = reduce((lambda x, y:x + y), poem) # just add strings\r\n print(poem_) #to see\r\n return poem_",
"import pandas as pd\r\n\r\ndef initial(): \r\n path = 'data/train.csv'\r\n df = pd.read_csv(path)\r\n print(df.head(5))\r\n\r\n for col in df.columns:\r\n print(f'Column {col} contains: {len(df[col].unique())} values')\r\n\r\n ratings = df.columns[10:]\r\n for rat in ratings:\r\n print(f\"{rat} : {sorted(df[rat].unique())}\")\r\n return df\r\n\r\n\r\nif __name__ == \"__main__\":\r\n initial()"
]
| [
[
"numpy.array",
"numpy.save"
],
[
"pandas.read_csv"
]
]
|
YHJYH/Machine_Learning | [
"0e86f0a5de0b8f280924c68e83ca1e817d7878e9",
"0e86f0a5de0b8f280924c68e83ca1e817d7878e9"
]
| [
"projects/Multi Task Learning/code/mmoe/data_loader.py",
"projects/Multi Task Learning/code/single_task/data_loader.py"
]
| [
"import torchvision.transforms as transforms\nfrom PIL import Image, ImageDraw, ImageFont\nfrom torch.utils.data import Dataset, DataLoader\n\nimport h5py\nimport math\nimport numpy as np\nfrom tqdm import tqdm\n\ndef load_data(root_path, batch_size=16, num_workers=2): \n transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n \n\n img_path = root_path+'/images.h5'\n img_h5 = h5py.File(img_path , 'r', swmr=True)\n img_key = list(img_h5.keys())[0]\n imgs = img_h5[img_key]\n\n label_type = ['binary', 'bboxes', 'masks']\n label_path = [root_path+'/'+label_type[i]+'.h5' for i in range(len(label_type))]\n label_h5 = [h5py.File(label_path[i] , 'r', swmr=True) for i in range(len(label_path))]\n label_key = [list(label_h5[i].keys())[0] for i in range(len(label_path))]\n labels = [label_h5[i][label_key[i]] for i in range(len(label_type))]\n\n dataset = MyDataset(imgs, labels, len(label_type), transform)\n dataloader = DataLoader(dataset, batch_size = 16, shuffle=True, num_workers=num_workers)\n return dataset, dataloader\n\nclass MyDataset(Dataset):\n def __init__(self, images, labels, num_label, transform):\n super(MyDataset, self).__init__()\n self.transform = transform\n self.imgs = images\n self.labels = labels\n self.num_label = num_label\n\n def __getitem__(self, index):\n image = self.imgs[index]\n label = [self.labels[i][index] for i in range(self.num_label)]\n return self.transform(np.array(image, dtype=np.uint8)), label\n\n def __len__(self):\n return int(self.imgs.len())",
"import torchvision.transforms as transforms\nfrom PIL import Image, ImageDraw, ImageFont\nimport h5py\nfrom torch.utils.data import Dataset, DataLoader\n\nimport math\nimport h5py\nimport numpy as np\nfrom tqdm import tqdm\n\ndef load_data(root_path, batch_size=16, num_workers=2): \n transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n \n\n img_path = root_path+'/images.h5'\n img_h5 = h5py.File(img_path , 'r', swmr=True)\n img_key = list(img_h5.keys())[0]\n imgs = img_h5[img_key]\n\n label_type = ['binary', 'bboxes', 'masks']\n label_path = [root_path+'/'+label_type[i]+'.h5' for i in range(len(label_type))]\n label_h5 = [h5py.File(label_path[i] , 'r', swmr=True) for i in range(len(label_path))]\n label_key = [list(label_h5[i].keys())[0] for i in range(len(label_path))]\n labels = [label_h5[i][label_key[i]] for i in range(len(label_type))]\n\n dataset = MyDataset(imgs, labels, len(label_type), transform)\n dataloader = DataLoader(dataset, batch_size = 16, shuffle=True, num_workers=num_workers)\n return dataset, dataloader\n\nclass MyDataset(Dataset):\n def __init__(self, images, labels, num_label, transform):\n super(MyDataset, self).__init__()\n self.transform = transform\n self.imgs = images\n self.labels = labels\n self.num_label = num_label\n\n def __getitem__(self, index):\n image = self.imgs[index]\n label = [self.labels[i][index] for i in range(self.num_label)]\n return self.transform(np.array(image, dtype=np.uint8)), label\n\n def __len__(self):\n return int(self.imgs.len())"
]
| [
[
"numpy.array",
"torch.utils.data.DataLoader"
],
[
"numpy.array",
"torch.utils.data.DataLoader"
]
]
|
smearle/Griddly | [
"e621285b15fdc45689c08536ab8c3e0f7b52d5cb"
]
| [
"python/examples/vectorized.py"
]
| [
"from stable_baselines3.common.vec_env import SubprocVecEnv\nimport numpy as np\nimport gym\nimport griddly\n\ngame = \"GDY-Partially-Observable-Zelda-v0\"\n\ndef make_env():\n def _monad():\n env = gym.make(game)\n return env\n return _monad\n\nif __name__ == '__main__':\n raw_list = [make_env() for _ in range(10)]\n envs = SubprocVecEnv(raw_list)\n\n init_obs = envs.reset()\n\n for i in range(10000):\n\n envs.step(np.zeros((10,2)))\n envs.render()"
]
| [
[
"numpy.zeros"
]
]
|
neonkitchen/disent | [
"0f45fefea03473690dfdbf48ef83f6e17ca9b8b3"
]
| [
"disent/schedule/_schedule.py"
]
| [
"# ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~\n# MIT License\n#\n# Copyright (c) 2021 Nathan Juraj Michlo\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\n# all 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\nimport numpy as np\n\nfrom disent.schedule.lerp import cyclical_anneal\nfrom disent.schedule.lerp import lerp_step\nfrom disent.schedule.lerp import scale\n\n\n# ========================================================================= #\n# Schedules #\n# ========================================================================= #\n\n\nclass Schedule(object):\n\n def __call__(self, step: int, value):\n return self.compute_value(step=step, value=value)\n\n def compute_value(self, step: int, value):\n raise NotImplementedError\n\n\n# ========================================================================= #\n# Value Schedules #\n# ========================================================================= #\n\n\nclass NoopSchedule(Schedule):\n\n def compute_value(self, step: int, value):\n # does absolutely nothing!\n return value\n\n\n# ========================================================================= #\n# Value Schedules #\n# ========================================================================= #\n\n\ndef _common(value, ratio, a, b):\n # scale the ratio (which should be in the range [0, 1]) between [r_min, r_max]\n sratio = scale(ratio, a, b)\n # multiply the value\n result = value * sratio\n return result\n\n\nclass LinearSchedule(Schedule):\n \"\"\"\n A simple lerp schedule based on some start and end ratio.\n\n Multiples the value based on the step by some\n computed value that is in the range [0, 1]\n \"\"\"\n\n def __init__(self, min_step: int, max_step: int, r_start: float = 0.0, r_end: float = 1.0):\n assert max_step > 0\n assert min_step >= 0\n assert min_step < max_step\n self.min_step = min_step\n self.max_step = max_step\n self.r_start = r_start\n self.r_end = r_end\n\n def compute_value(self, step: int, value):\n ratio = lerp_step(\n step=(step - self.min_step),\n max_step=(self.max_step - self.min_step),\n a=0.0,\n b=1.0,\n )\n return _common(value, ratio, a=self.r_start, b=self.r_end)\n\n\nclass CyclicSchedule(Schedule):\n \"\"\"\n Cyclical schedule based on:\n https://arxiv.org/abs/1903.10145\n\n Multiples the value based on the step by some\n computed value that is in the range [0, 1]\n \"\"\"\n\n # TODO: maybe move this api into cyclical_anneal\n def __init__(self, period: int, repeats: int = None, r_start=0.0, r_end=1.0, end_value='end', mode='linear', p_low=0.0, p_high=0.0):\n self.period = period\n self.repeats = repeats\n self.end_value = {'start': 'low', 'end': 'high'}[end_value]\n self.mode = mode\n # scale values\n self.r_start = r_start\n self.r_end = r_end\n # portions of low and high -- low + high <= 1.0 -- low + slope + high == 1.0\n self.p_low = p_low\n self.p_high = p_high\n\n def compute_value(self, step: int, value):\n # outputs value in range [0, 1]\n ratio = cyclical_anneal(\n step=step,\n period=self.period,\n low_ratio=self.p_low,\n high_ratio=self.p_high,\n repeats=self.repeats,\n start_low=True,\n end_value=self.end_value,\n mode=self.mode\n )\n return _common(value, ratio, a=self.r_start, b=self.r_end)\n\n\nclass SingleSchedule(CyclicSchedule):\n \"\"\"\n A single repeat version of CyclicSchedule that automatically\n chooses if its going from high to low or low to high based on the start_value.\n\n Multiples the value based on the step by some\n computed value that is in the range [0, 1]\n \"\"\"\n\n def __init__(self, max_step, r_start=0.0, r_end=1.0, mode='linear'):\n super().__init__(\n period=max_step,\n repeats=1,\n r_start=r_start,\n r_end=r_end,\n end_value='end',\n mode=mode,\n )\n\n\nclass CosineWaveSchedule(Schedule):\n \"\"\"\n A simple cosine wave schedule based on some start and end ratio.\n -- note this starts at zero by default\n\n Multiples the value based on the step by some\n computed value that is in the range [0, 1]\n \"\"\"\n\n def __init__(self, period: int, r_start: float = 0.0, r_end: float = 1.0):\n assert period > 0\n self.period = period\n self.r_start = r_start\n self.r_end = r_end\n\n def compute_value(self, step: int, value):\n ratio = 0.5 * (1 + np.cos(step * (2 * np.pi / self.period) + np.pi))\n return _common(value, ratio, a=self.r_start, b=self.r_end)\n\n\n# ========================================================================= #\n# Clip Schedules #\n# ========================================================================= #\n\n\nclass ClipSchedule(Schedule):\n \"\"\"\n This schedule shifts the step, or clips the value\n \"\"\"\n\n def __init__(self, schedule: Schedule, min_step=None, max_step=None, shift_step=True, min_value=None, max_value=None):\n assert isinstance(schedule, Schedule)\n self.schedule = schedule\n # step settings\n self.min_step = min_step if (min_step is not None) else 0\n self.max_step = max_step\n if isinstance(shift_step, bool):\n shift_step = (-self.min_step) if shift_step else None\n self.shift_step = shift_step\n # value settings\n self.min_value = min_value\n self.max_value = max_value\n\n def compute_value(self, step: int, value):\n if self.max_step is not None: step = np.minimum(self.max_step, step)\n if self.min_step is not None: step = np.maximum(self.min_step, step)\n if self.shift_step is not None: step += self.shift_step\n result = self.schedule(step, value)\n if self.max_value is not None: result = np.minimum(self.max_value, result)\n if self.min_value is not None: result = np.maximum(self.min_value, result)\n return result\n\n\n# ========================================================================= #\n# END #\n# ========================================================================= #\n"
]
| [
[
"numpy.maximum",
"numpy.cos",
"numpy.minimum"
]
]
|
domoritz/streamlit | [
"5e8e0ec1b46ac0b322dc48d27494be674ad238fa"
]
| [
"lib/streamlit/__init__.py"
]
| [
"# -*- coding: utf-8 -*-\n# Copyright 2018-2020 Streamlit Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Streamlit.\n\nHow to use Streamlit in 3 seconds:\n\n 1. Write an app\n >>> import streamlit as st\n >>> st.write(anything_you_want)\n\n 2. Run your app\n $ streamlit run my_script.py\n\n 3. Use your app\n A new tab will open on your browser. That's your Streamlit app!\n\n 4. Modify your code, save it, and watch changes live on your browser.\n\nTake a look at the other commands in this module to find out what else\nStreamlit can do:\n\n >>> dir(streamlit)\n\nOr try running our \"Hello World\":\n\n $ streamlit hello\n\nFor more detailed info, see https://docs.streamlit.io.\n\"\"\"\n\n# IMPORTANT: Prefix with an underscore anything that the user shouldn't see.\n\n# NOTE: You'll see lots of \"noqa: F821\" in this file. That's because we\n# manually mess with the local namespace so the linter can't know that some\n# identifiers actually exist in the namespace.\n\n# Python 2/3 compatibility\nfrom __future__ import print_function, division, unicode_literals, absolute_import\nfrom streamlit.compatibility import (\n setup_2_3_shims as _setup_2_3_shims,\n is_running_py3 as _is_running_py3,\n)\n\n_setup_2_3_shims(globals())\n\n# Must be at the top, to avoid circular dependency.\nfrom streamlit import logger as _logger\nfrom streamlit import config as _config\n\n_LOGGER = _logger.get_logger(\"root\")\n\n# Give the package a version.\nimport pkg_resources as _pkg_resources\nimport uuid as _uuid\nimport subprocess\nimport platform\nimport os\n\n# This used to be pkg_resources.require('streamlit') but it would cause\n# pex files to fail. See #394 for more details.\n__version__ = _pkg_resources.get_distribution(\"streamlit\").version\n\n# Deterministic Unique Streamlit User ID\n# The try/except is needed for python 2/3 compatibility\ntry:\n\n if (\n platform.system() == \"Linux\"\n and os.path.isfile(\"/etc/machine-id\") == False\n and os.path.isfile(\"/var/lib/dbus/machine-id\") == False\n ):\n print(\"Generate machine-id\")\n subprocess.run([\"sudo\", \"dbus-uuidgen\", \"--ensure\"])\n\n machine_id = _uuid.getnode()\n if os.path.isfile(\"/etc/machine-id\"):\n with open(\"/etc/machine-id\", \"r\") as f:\n machine_id = f.read()\n elif os.path.isfile(\"/var/lib/dbus/machine-id\"):\n with open(\"/var/lib/dbus/machine-id\", \"r\") as f:\n machine_id = f.read()\n\n __installation_id__ = str(_uuid.uuid5(_uuid.NAMESPACE_DNS, str(machine_id)))\n\nexcept UnicodeDecodeError:\n __installation_id__ = str(\n _uuid.uuid5(_uuid.NAMESPACE_DNS, str(_uuid.getnode()).encode(\"utf-8\"))\n )\n\nimport contextlib as _contextlib\nimport re as _re\nimport sys as _sys\nimport textwrap as _textwrap\nimport threading as _threading\nimport traceback as _traceback\nimport types as _types\nimport json as _json\nimport numpy as _np\n\nfrom streamlit import code_util as _code_util\nfrom streamlit import env_util as _env_util\nfrom streamlit import source_util as _source_util\nfrom streamlit import string_util as _string_util\nfrom streamlit import type_util as _type_util\nfrom streamlit.DeltaGenerator import DeltaGenerator as _DeltaGenerator\nfrom streamlit.ReportThread import add_report_ctx as _add_report_ctx\nfrom streamlit.ReportThread import get_report_ctx as _get_report_ctx\nfrom streamlit.errors import StreamlitAPIException\nfrom streamlit.proto import BlockPath_pb2 as _BlockPath_pb2\nfrom streamlit.util import functools_wraps as _functools_wraps\n\n# Modules that the user should have access to.\nfrom streamlit.caching import cache # noqa: F401\n\n# This is set to True inside cli._main_run(), and is False otherwise.\n# If False, we should assume that DeltaGenerator functions are effectively\n# no-ops, and adapt gracefully.\n_is_running_with_streamlit = False\n\n\ndef _set_log_level():\n _logger.set_log_level(_config.get_option(\"global.logLevel\").upper())\n _logger.init_tornado_logs()\n\n\n# Make this file only depend on config option in an asynchronous manner. This\n# avoids a race condition when another file (such as a test file) tries to pass\n# in an alternative config.\n_config.on_config_parsed(_set_log_level)\n\n\ndef _reset():\n # TODO: Move this out of here. This isn't a particularly nice place to\n # reset this...\n _get_report_ctx().widget_ids_this_run.clear()\n\n\n_main = _DeltaGenerator(container=_BlockPath_pb2.BlockPath.MAIN)\nsidebar = _DeltaGenerator(container=_BlockPath_pb2.BlockPath.SIDEBAR)\n\n# DeltaGenerator methods:\n\naltair_chart = _main.altair_chart # noqa: E221\narea_chart = _main.area_chart # noqa: E221\naudio = _main.audio # noqa: E221\nballoons = _main.balloons # noqa: E221\nbar_chart = _main.bar_chart # noqa: E221\nbokeh_chart = _main.bokeh_chart # noqa: E221\nbutton = _main.button # noqa: E221\ncheckbox = _main.checkbox # noqa: E221\ncode = _main.code # noqa: E221\ndataframe = _main.dataframe # noqa: E221\ndate_input = _main.date_input # noqa: E221\ndeck_gl_chart = _main.deck_gl_chart # noqa: E221\npydeck_chart = _main.pydeck_chart # noqa: E221\nempty = _main.empty # noqa: E221\nerror = _main.error # noqa: E221\nexception = _main.exception # noqa: E221\nfile_uploader = _main.file_uploader # noqa: E221\ngraphviz_chart = _main.graphviz_chart # noqa: E221\nheader = _main.header # noqa: E221\nhelp = _main.help # noqa: E221\nimage = _main.image # noqa: E221\ninfo = _main.info # noqa: E221\njson = _main.json # noqa: E221\nlatex = _main.latex # noqa: E221\nline_chart = _main.line_chart # noqa: E221\nmap = _main.map # noqa: E221\nmarkdown = _main.markdown # noqa: E221\nmultiselect = _main.multiselect # noqa: E221\nnumber_input = _main.number_input # noqa: E221\nplotly_chart = _main.plotly_chart # noqa: E221\nprogress = _main.progress # noqa: E221\npyplot = _main.pyplot # noqa: E221\nradio = _main.radio # noqa: E221\nselectbox = _main.selectbox # noqa: E221\nslider = _main.slider # noqa: E221\nsubheader = _main.subheader # noqa: E221\nsuccess = _main.success # noqa: E221\ntable = _main.table # noqa: E221\ntext = _main.text # noqa: E221\ntext_area = _main.text_area # noqa: E221\ntext_input = _main.text_input # noqa: E221\ntime_input = _main.time_input # noqa: E221\ntitle = _main.title # noqa: E221\nvega_lite_chart = _main.vega_lite_chart # noqa: E221\nvideo = _main.video # noqa: E221\nwarning = _main.warning # noqa: E221\n\n# Config\n\nget_option = _config.get_option\n\n\ndef set_option(key, value):\n \"\"\"Set config option.\n\n Currently, only two config options can be set within the script itself:\n * client.caching\n * client.displayEnabled\n\n Calling with any other options will raise StreamlitAPIException.\n\n Run `streamlit config show` in the terminal to see all available options.\n\n Parameters\n ----------\n key : str\n The config option key of the form \"section.optionName\". To see all\n available options, run `streamlit config show` on a terminal.\n\n value\n The new value to assign to this config option.\n\n \"\"\"\n opt = _config._config_options[key]\n if opt.scriptable:\n _config.set_option(key, value)\n return\n\n raise StreamlitAPIException(\n \"{key} cannot be set on the fly. Set as command line option, e.g. streamlit run script.py --{key}, or in config.toml instead.\".format(\n key=key\n )\n )\n\n\n# Special methods:\n\n_HELP_TYPES = (\n _types.BuiltinFunctionType,\n _types.BuiltinMethodType,\n _types.FunctionType,\n _types.MethodType,\n _types.ModuleType,\n)\n\nif not _is_running_py3():\n _HELP_TYPES = list(_HELP_TYPES)\n _HELP_TYPES.append(_types.ClassType)\n _HELP_TYPES.append(_types.InstanceType)\n _HELP_TYPES = tuple(_HELP_TYPES)\n\n\ndef write(*args, **kwargs):\n \"\"\"Write arguments to the app.\n\n This is the swiss-army knife of Streamlit commands. It does different\n things depending on what you throw at it.\n\n Unlike other Streamlit commands, write() has some unique properties:\n\n 1. You can pass in multiple arguments, all of which will be written.\n 2. Its behavior depends on the input types as follows.\n 3. It returns None, so it's \"slot\" in the App cannot be reused.\n\n Parameters\n ----------\n *args : any\n One or many objects to print to the App.\n\n Arguments are handled as follows:\n\n - write(string) : Prints the formatted Markdown string, with\n support for LaTeX expression and emoji shortcodes.\n See docs for st.markdown for more.\n - write(data_frame) : Displays the DataFrame as a table.\n - write(error) : Prints an exception specially.\n - write(func) : Displays information about a function.\n - write(module) : Displays information about the module.\n - write(dict) : Displays dict in an interactive widget.\n - write(obj) : The default is to print str(obj).\n - write(mpl_fig) : Displays a Matplotlib figure.\n - write(altair) : Displays an Altair chart.\n - write(keras) : Displays a Keras model.\n - write(graphviz) : Displays a Graphviz graph.\n - write(plotly_fig) : Displays a Plotly figure.\n - write(bokeh_fig) : Displays a Bokeh figure.\n - write(sympy_expr) : Prints SymPy expression using LaTeX.\n\n unsafe_allow_html : bool\n This is a keyword-only argument that defaults to False.\n\n By default, any HTML tags found in strings will be escaped and\n therefore treated as pure text. This behavior may be turned off by\n setting this argument to True.\n\n That said, *we strongly advise* against it*. It is hard to write secure\n HTML, so by using this argument you may be compromising your users'\n security. For more information, see:\n\n https://github.com/streamlit/streamlit/issues/152\n\n *Also note that `unsafe_allow_html` is a temporary measure and may be\n removed from Streamlit at any time.*\n\n If you decide to turn on HTML anyway, we ask you to please tell us your\n exact use case here:\n\n https://discuss.streamlit.io/t/96\n\n This will help us come up with safe APIs that allow you to do what you\n want.\n\n Example\n -------\n\n Its simplest use case is to draw Markdown-formatted text, whenever the\n input is a string:\n\n >>> write('Hello, *World!* :sunglasses:')\n\n .. output::\n https://share.streamlit.io/0.50.2-ZWk9/index.html?id=Pn5sjhgNs4a8ZbiUoSTRxE\n height: 50px\n\n As mentioned earlier, `st.write()` also accepts other data formats, such as\n numbers, data frames, styled data frames, and assorted objects:\n\n >>> st.write(1234)\n >>> st.write(pd.DataFrame({\n ... 'first column': [1, 2, 3, 4],\n ... 'second column': [10, 20, 30, 40],\n ... }))\n\n .. output::\n https://share.streamlit.io/0.25.0-2JkNY/index.html?id=FCp9AMJHwHRsWSiqMgUZGD\n height: 250px\n\n Finally, you can pass in multiple arguments to do things like:\n\n >>> st.write('1 + 1 = ', 2)\n >>> st.write('Below is a DataFrame:', data_frame, 'Above is a dataframe.')\n\n .. output::\n https://share.streamlit.io/0.25.0-2JkNY/index.html?id=DHkcU72sxYcGarkFbf4kK1\n height: 300px\n\n Oh, one more thing: `st.write` accepts chart objects too! For example:\n\n >>> import pandas as pd\n >>> import numpy as np\n >>> import altair as alt\n >>>\n >>> df = pd.DataFrame(\n ... np.random.randn(200, 3),\n ... columns=['a', 'b', 'c'])\n ...\n >>> c = alt.Chart(df).mark_circle().encode(\n ... x='a', y='b', size='c', color='c')\n >>>\n >>> st.write(c)\n\n .. output::\n https://share.streamlit.io/0.25.0-2JkNY/index.html?id=8jmmXR8iKoZGV4kXaKGYV5\n height: 200px\n\n \"\"\"\n # Python2 doesn't support this syntax\n # def write(*args, unsafe_allow_html=False)\n # so we do this instead:\n unsafe_allow_html = kwargs.get(\"unsafe_allow_html\", False)\n\n try:\n string_buffer = []\n\n def flush_buffer():\n if string_buffer:\n markdown(\n \" \".join(string_buffer), unsafe_allow_html=unsafe_allow_html\n ) # noqa: F821\n string_buffer[:] = []\n\n for arg in args:\n # Order matters!\n if isinstance(arg, string_types): # noqa: F821\n string_buffer.append(arg)\n elif _type_util.is_dataframe_like(arg):\n flush_buffer()\n if len(_np.shape(arg)) > 2:\n text(arg)\n else:\n dataframe(arg) # noqa: F821\n elif isinstance(arg, Exception):\n flush_buffer()\n exception(arg) # noqa: F821\n elif isinstance(arg, _HELP_TYPES):\n flush_buffer()\n help(arg)\n elif _type_util.is_altair_chart(arg):\n flush_buffer()\n altair_chart(arg)\n elif _type_util.is_type(arg, \"matplotlib.figure.Figure\"):\n flush_buffer()\n pyplot(arg)\n elif _type_util.is_plotly_chart(arg):\n flush_buffer()\n plotly_chart(arg)\n elif _type_util.is_type(arg, \"bokeh.plotting.figure.Figure\"):\n flush_buffer()\n bokeh_chart(arg)\n elif _type_util.is_graphviz_chart(arg):\n flush_buffer()\n graphviz_chart(arg)\n elif _type_util.is_sympy_expession(arg):\n flush_buffer()\n latex(arg)\n elif _type_util.is_keras_model(arg):\n from tensorflow.python.keras.utils import vis_utils\n\n flush_buffer()\n dot = vis_utils.model_to_dot(arg)\n graphviz_chart(dot.to_string())\n elif (type(arg) in dict_types) or (isinstance(arg, list)): # noqa: F821\n flush_buffer()\n json(arg)\n elif _type_util.is_namedtuple(arg):\n flush_buffer()\n json(_json.dumps(arg._asdict()))\n elif _type_util.is_pydeck(arg):\n flush_buffer()\n pydeck_chart(arg)\n else:\n string_buffer.append(\"`%s`\" % str(arg).replace(\"`\", \"\\\\`\"))\n\n flush_buffer()\n\n except Exception:\n _, exc, exc_tb = _sys.exc_info()\n exception(exc, exc_tb) # noqa: F821\n\n\ndef show(*args):\n \"\"\"Write arguments to your app for debugging purposes.\n\n Show() has similar properties to write():\n\n 1. You can pass in multiple arguments, all of which will be debugged.\n 2. It returns None, so it's \"slot\" in the app cannot be reused.\n\n Parameters\n ----------\n *args : any\n One or many objects to debug in the App.\n\n Example\n -------\n\n >>> dataframe = pd.DataFrame({\n ... 'first column': [1, 2, 3, 4],\n ... 'second column': [10, 20, 30, 40],\n ... }))\n >>> st.show(dataframe)\n\n Notes\n -----\n This is an experimental feature with usage limitations.\n\n - The method must be called with the name `show`\n - Must be called in one line of code, and only once per line\n - When passing multiple arguments the inclusion of `,` or `)` in a string\n argument may cause an error.\n\n \"\"\"\n if not args:\n return\n\n try:\n import inspect\n\n # Get the calling line of code\n previous_frame = inspect.currentframe().f_back\n lines = inspect.getframeinfo(previous_frame)[3]\n\n if not lines:\n warning(\"`show` not enabled in the shell\")\n return\n\n # Parse arguments from the line\n line = lines[0].split(\"show\", 1)[1]\n inputs = _code_util.get_method_args_from_code(args, line)\n\n # Escape markdown and add deltas\n for idx, input in enumerate(inputs):\n escaped = _string_util.escape_markdown(input)\n\n markdown(\"**%s**\" % escaped)\n write(args[idx])\n\n except Exception:\n _, exc, exc_tb = _sys.exc_info()\n exception(exc, exc_tb) # noqa: F821\n\n\n@_contextlib.contextmanager\ndef spinner(text=\"In progress...\"):\n \"\"\"Temporarily displays a message while executing a block of code.\n\n Parameters\n ----------\n text : str\n A message to display while executing that block\n\n Example\n -------\n\n >>> with st.spinner('Wait for it...'):\n >>> time.sleep(5)\n >>> st.success('Done!')\n\n \"\"\"\n import streamlit.caching as caching\n\n display_message_lock = None\n\n # @st.cache optionally uses spinner for long-running computations.\n # Normally, streamlit warns the user when they call st functions\n # from within an @st.cache'd function. But we do *not* want to show\n # these warnings for spinner's message, so we create and mutate this\n # message delta within the \"suppress_cached_st_function_warning\"\n # context.\n with caching.suppress_cached_st_function_warning():\n message = empty()\n\n try:\n # Set the message 0.1 seconds in the future to avoid annoying\n # flickering if this spinner runs too quickly.\n DELAY_SECS = 0.1\n display_message = True\n display_message_lock = _threading.Lock()\n\n def set_message():\n with display_message_lock:\n if display_message:\n with caching.suppress_cached_st_function_warning():\n message.warning(str(text))\n\n _add_report_ctx(_threading.Timer(DELAY_SECS, set_message)).start()\n\n # Yield control back to the context.\n yield\n finally:\n if display_message_lock:\n with display_message_lock:\n display_message = False\n with caching.suppress_cached_st_function_warning():\n message.empty()\n\n\n_SPACES_RE = _re.compile(\"\\\\s*\")\n\n\n@_contextlib.contextmanager\ndef echo():\n \"\"\"Use in a `with` block to draw some code on the app, then execute it.\n\n Example\n -------\n\n >>> with st.echo():\n >>> st.write('This code will be printed')\n\n \"\"\"\n code = empty() # noqa: F821\n try:\n frame = _traceback.extract_stack()[-3]\n if _is_running_py3():\n filename, start_line = frame.filename, frame.lineno\n else:\n filename, start_line = frame[:2]\n yield\n frame = _traceback.extract_stack()[-3]\n if _is_running_py3():\n end_line = frame.lineno\n else:\n end_line = frame[1]\n lines_to_display = []\n with _source_util.open_python_file(filename) as source_file:\n source_lines = source_file.readlines()\n lines_to_display.extend(source_lines[start_line:end_line])\n initial_spaces = _SPACES_RE.match(lines_to_display[0]).end()\n for line in source_lines[end_line:]:\n indentation = _SPACES_RE.match(line).end()\n # The != 1 is because we want to allow '\\n' between sections.\n if indentation != 1 and indentation < initial_spaces:\n break\n lines_to_display.append(line)\n lines_to_display = _textwrap.dedent(\"\".join(lines_to_display))\n code.code(lines_to_display, \"python\")\n\n except FileNotFoundError as err: # noqa: F821\n code.warning(\"Unable to display code. %s\" % err)\n\n\ndef _transparent_write(*args):\n \"\"\"This is just st.write, but returns the arguments you passed to it.\"\"\"\n write(*args)\n if len(args) == 1:\n return args[0]\n return args\n\n\n# We want to show a warning when the user runs a Streamlit script without\n# 'streamlit run', but we need to make sure the warning appears only once no\n# matter how many times __init__ gets loaded.\n_repl_warning_has_been_displayed = False\n\n\ndef _maybe_print_repl_warning():\n global _repl_warning_has_been_displayed\n\n if not _repl_warning_has_been_displayed:\n _repl_warning_has_been_displayed = True\n\n if _env_util.is_repl():\n _LOGGER.warning(\n _textwrap.dedent(\n \"\"\"\n\n Will not generate Streamlit app\n\n To generate an app, use Streamlit in a file and run it with:\n $ streamlit run [FILE_NAME] [ARGUMENTS]\n\n \"\"\"\n )\n )\n\n elif _config.get_option(\"global.showWarningOnDirectExecution\"):\n script_name = _sys.argv[0]\n\n _LOGGER.warning(\n _textwrap.dedent(\n \"\"\"\n\n Will not generate Streamlit App\n\n To generate an App, run this file with:\n $ streamlit run %s [ARGUMENTS]\n\n \"\"\"\n ),\n script_name,\n )\n"
]
| [
[
"tensorflow.python.keras.utils.vis_utils.model_to_dot",
"numpy.shape"
]
]
|
NASA-LIS/neuralhydrology | [
"9626578d6013aa08864caf29d9520321cdcafc24"
]
| [
"neuralhydrology/nh_run_scheduler.py"
]
| [
"#!/usr/bin/env python\nimport argparse\nimport random\nimport subprocess\nimport sys\nimport time\nfrom pathlib import Path\nfrom typing import List\n\nimport numpy as np\n\n\ndef _get_args() -> dict:\n\n parser = argparse.ArgumentParser()\n parser.add_argument('mode', choices=[\"train\", \"evaluate\"])\n parser.add_argument('--directory', type=str, required=True)\n parser.add_argument('--gpu-ids', type=int, nargs='+', required=True)\n parser.add_argument('--runs-per-gpu', type=int, required=True)\n\n args = vars(parser.parse_args())\n\n args[\"directory\"] = Path(args[\"directory\"])\n if not args[\"directory\"].is_dir():\n raise ValueError(f\"No folder at {args['directory']}\")\n\n return args\n\n\ndef _main():\n args = _get_args()\n schedule_runs(**args)\n\n\ndef schedule_runs(mode: str, directory: Path, gpu_ids: List[int], runs_per_gpu: int):\n \"\"\"Schedule multiple runs across one or multiple GPUs.\n \n Parameters\n ----------\n mode : {'train', 'evaluate'}\n Use 'train' if you want to schedule training of multiple models and 'evaluate' if you want to schedule\n evaluation of multiple trained models.\n directory : Path\n If mode is 'train', this path should point to a folder containing the config files (.yml) to use for model\n training. For each config file, one run is started. If mode is 'evaluate', this path should point to the folder \n containing the different model run directories.\n gpu_ids : List[int]\n List of GPU ids to use for training/evaluating.\n runs_per_gpu : int\n Number of runs to start on a single GPU.\n\n \"\"\"\n\n if mode == \"train\":\n processes = list(directory.glob('**/*.yml'))\n elif mode == \"evaluate\":\n processes = list(directory.glob('*'))\n else:\n raise ValueError(\"'mode' must be either 'train' or 'evaluate'\")\n\n # if used as command line tool, we need full path's to the fils/directories\n processes = [str(p.absolute()) for p in processes]\n\n # for approximately equal memory usage during hyperparam tuning, randomly shuffle list of processes\n random.shuffle(processes)\n\n # array to keep track on how many runs are currently running per GPU\n n_parallel_runs = len(gpu_ids) * runs_per_gpu\n gpu_counter = np.zeros((len(gpu_ids)), dtype=np.int)\n\n # for command line tool, we need full path to the main.py script\n script_path = str(Path(__file__).absolute().parent / \"nh_run.py\")\n\n running_processes = {}\n counter = 0\n while True:\n\n # start new runs\n for _ in range(n_parallel_runs - len(running_processes)):\n\n if counter >= len(processes):\n break\n\n # determine which GPU to use\n node_id = np.argmin(gpu_counter)\n gpu_counter[node_id] += 1\n gpu_id = gpu_ids[node_id]\n process = processes[counter]\n\n # start run via subprocess call\n if mode == \"train\":\n run_command = f\"python {script_path} train --config-file {process} --gpu {gpu_id}\"\n else:\n run_command = f\"python {script_path} evaluate --run-dir {process} --gpu {gpu_id}\"\n print(f\"Starting run {counter+1}/{len(processes)}: {run_command}\")\n running_processes[(run_command, node_id)] = subprocess.Popen(run_command,\n stdout=subprocess.DEVNULL,\n shell=True)\n\n counter += 1\n time.sleep(2)\n\n # check for completed runs\n for key, process in running_processes.items():\n if process.poll() is not None:\n print(f\"Finished run {key[0]}\")\n gpu_counter[key[1]] -= 1\n print(\"Cleaning up...\\n\\n\")\n try:\n _ = process.communicate(timeout=5)\n except TimeoutError:\n print('')\n print(\"WARNING: PROCESS {} COULD NOT BE REAPED!\".format(key))\n print('')\n running_processes[key] = None\n\n # delete possibly finished runs\n running_processes = {key: val for key, val in running_processes.items() if val is not None}\n time.sleep(2)\n\n if (len(running_processes) == 0) and (counter >= len(processes)):\n break\n\n print(\"Done\")\n sys.stdout.flush()\n\n\nif __name__ == \"__main__\":\n _main()\n"
]
| [
[
"numpy.argmin"
]
]
|
YuZiHanorz/stacked_capsule_autoencoders | [
"b85fb1b8b4d4f385f137b865469a20271a234162"
]
| [
"capsules/models/scae.py"
]
| [
"# coding=utf-8\n# Copyright 2019 The Google Research 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\"\"\"Capsule autoencoder implementation.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport sonnet as snt\nimport tensorflow as tf\nimport tensorflow_probability as tfp\n\nfrom stacked_capsule_autoencoders.capsules import capsule as _capsule\nfrom stacked_capsule_autoencoders.capsules import math_ops\nfrom stacked_capsule_autoencoders.capsules import plot\nfrom stacked_capsule_autoencoders.capsules import probe\nfrom stacked_capsule_autoencoders.capsules import tensor_ops\nfrom stacked_capsule_autoencoders.capsules.data import preprocess\nfrom stacked_capsule_autoencoders.capsules.models import Model\nfrom stacked_capsule_autoencoders.capsules.tensor_ops import make_brodcastable\n\ntfd = tfp.distributions\n\n\nclass ImageCapsule(snt.AbstractModule):\n \"\"\"Capsule decoder for constellations.\"\"\"\n def __init__(self, n_caps, n_caps_dims, n_votes, **capsule_kwargs):\n \"\"\"Builds the module.\n\n Args:\n n_caps: int, number of capsules.\n n_caps_dims: int, number of capsule coordinates.\n n_votes: int, number of votes generated by each capsule.\n **capsule_kwargs: kwargs passed to capsule layer.\n \"\"\"\n super(ImageCapsule, self).__init__()\n self._n_caps = n_caps\n self._n_caps_dims = n_caps_dims\n self._n_votes = n_votes\n self._capsule_kwargs = capsule_kwargs\n\n def _build(self, h, x, presence=None):\n \"\"\"Builds the module.\n\n Args:\n h: Tensor of encodings of shape [B, n_enc_dims].\n x: Tensor of inputs of shape [B, n_points, n_input_dims]\n presence: Tensor of shape [B, n_points, 1] or None; if it exists, it\n indicates which input points exist.\n\n Returns:\n A bunch of stuff.\n \"\"\"\n batch_size = int(x.shape[0])\n\n capsule = _capsule.CapsuleLayer(self._n_caps, self._n_caps_dims,\n self._n_votes, **self._capsule_kwargs)\n\n res = capsule(h)\n vote_shape = [batch_size, self._n_caps, self._n_votes, 6]\n res.vote = tf.reshape(res.vote[Ellipsis, :-1, :], vote_shape)\n\n votes, scale, vote_presence_prob = res.vote, res.scale, res.vote_presence\n\n likelihood = _capsule.CapsuleLikelihood(votes, scale,\n vote_presence_prob)\n ll_res = likelihood(x, presence)\n res.update(ll_res._asdict())\n\n caps_presence_prob = tf.reduce_max(\n tf.reshape(vote_presence_prob,\n [batch_size, self._n_caps, self._n_votes]), 2)\n\n res.caps_presence_prob = caps_presence_prob\n return res\n\n\nclass ImageAutoencoder(Model):\n \"\"\"Capsule autoencoder.\"\"\"\n def __init__(\n self,\n primary_encoder,\n primary_decoder,\n encoder,\n decoder,\n input_key,\n label_key=None,\n n_classes=None,\n dynamic_l2_weight=0.,\n caps_ll_weight=0.,\n vote_type='soft',\n pres_type='enc',\n img_summaries=False,\n stop_grad_caps_inpt=False,\n stop_grad_caps_target=False,\n prior_sparsity_loss_type='kl',\n prior_within_example_sparsity_weight=0.,\n prior_between_example_sparsity_weight=0.,\n prior_within_example_constant=0.,\n posterior_sparsity_loss_type='kl',\n posterior_within_example_sparsity_weight=0.,\n posterior_between_example_sparsity_weight=0.,\n primary_caps_sparsity_weight=0.,\n weight_decay=0.,\n feed_templates=True,\n prep='none',\n ):\n\n super(ImageAutoencoder, self).__init__()\n self._primary_encoder = primary_encoder\n self._primary_decoder = primary_decoder\n self._encoder = encoder\n self._decoder = decoder\n self._input_key = input_key\n self._label_key = label_key\n self._n_classes = n_classes\n\n self._dynamic_l2_weight = dynamic_l2_weight\n self._caps_ll_weight = caps_ll_weight\n self._vote_type = vote_type\n self._pres_type = pres_type\n self._img_summaries = img_summaries\n\n self._stop_grad_caps_inpt = stop_grad_caps_inpt\n self._stop_grad_caps_target = stop_grad_caps_target\n self._prior_sparsity_loss_type = prior_sparsity_loss_type\n self._prior_within_example_sparsity_weight = prior_within_example_sparsity_weight\n self._prior_between_example_sparsity_weight = prior_between_example_sparsity_weight\n self._prior_within_example_constant = prior_within_example_constant\n self._posterior_sparsity_loss_type = posterior_sparsity_loss_type\n self._posterior_within_example_sparsity_weight = posterior_within_example_sparsity_weight\n self._posterior_between_example_sparsity_weight = posterior_between_example_sparsity_weight\n self._primary_caps_sparsity_weight = primary_caps_sparsity_weight\n self._weight_decay = weight_decay\n self._feed_templates = feed_templates\n\n self._prep = prep\n\n def _img(self, data, prep='none'):\n\n img = data[self._input_key]\n if prep == 'sobel':\n img = preprocess.normalized_sobel_edges(img)\n\n return img\n\n def _label(self, data):\n return data.get(self._label_key, None)\n\n def _build(self, data):\n\n input_x = self._img(data, False)\n target_x = self._img(data, prep=self._prep)\n batch_size = int(input_x.shape[0])\n\n primary_caps = self._primary_encoder(input_x)\n pres = primary_caps.presence\n\n expanded_pres = tf.expand_dims(pres, -1)\n pose = primary_caps.pose\n input_pose = tf.concat([pose, 1. - expanded_pres], -1)\n\n input_pres = pres\n if self._stop_grad_caps_inpt:\n input_pose = tf.stop_gradient(input_pose)\n input_pres = tf.stop_gradient(pres)\n\n target_pose, target_pres = pose, pres\n if self._stop_grad_caps_target:\n target_pose = tf.stop_gradient(target_pose)\n target_pres = tf.stop_gradient(target_pres)\n\n # skip connection from the img to the higher level capsule\n if primary_caps.feature is not None:\n input_pose = tf.concat([input_pose, primary_caps.feature], -1)\n\n # try to feed presence as a separate input\n # and if that works, concatenate templates to poses\n # this is necessary for set transformer\n n_templates = int(primary_caps.pose.shape[1])\n templates = self._primary_decoder.make_templates(\n n_templates, primary_caps.feature)\n\n try:\n if self._feed_templates:\n inpt_templates = templates\n if self._stop_grad_caps_inpt:\n inpt_templates = tf.stop_gradient(inpt_templates)\n\n if inpt_templates.shape[0] == 1:\n inpt_templates = snt.TileByDim(\n [0], [batch_size])(inpt_templates)\n inpt_templates = snt.BatchFlatten(2)(inpt_templates)\n pose_with_templates = tf.concat([input_pose, inpt_templates],\n -1)\n else:\n pose_with_templates = input_pose\n\n h = self._encoder(pose_with_templates, input_pres)\n\n except TypeError:\n h = self._encoder(input_pose)\n\n res = self._decoder(h, target_pose, target_pres)\n res.primary_presence = primary_caps.presence\n\n if self._vote_type == 'enc':\n primary_dec_vote = primary_caps.pose\n elif self._vote_type == 'soft':\n primary_dec_vote = res.soft_winner\n elif self._vote_type == 'hard':\n primary_dec_vote = res.winner\n else:\n raise ValueError('Invalid vote_type=\"{}\"\".'.format(\n self._vote_type))\n\n if self._pres_type == 'enc':\n primary_dec_pres = pres\n elif self._pres_type == 'soft':\n primary_dec_pres = res.soft_winner_pres\n elif self._pres_type == 'hard':\n primary_dec_pres = res.winner_pres\n else:\n raise ValueError('Invalid pres_type=\"{}\"\".'.format(\n self._pres_type))\n\n res.bottom_up_rec = self._primary_decoder(\n primary_caps.pose,\n primary_caps.presence,\n template_feature=primary_caps.feature,\n img_embedding=primary_caps.img_embedding)\n\n res.top_down_rec = self._primary_decoder(\n res.winner,\n primary_caps.presence,\n template_feature=primary_caps.feature,\n img_embedding=primary_caps.img_embedding)\n\n rec = self._primary_decoder(primary_dec_vote,\n primary_dec_pres,\n template_feature=primary_caps.feature,\n img_embedding=primary_caps.img_embedding)\n\n tile = snt.TileByDim([0], [res.vote.shape[1]])\n tiled_presence = tile(primary_caps.presence)\n\n tiled_feature = primary_caps.feature\n if tiled_feature is not None:\n tiled_feature = tile(tiled_feature)\n\n tiled_img_embedding = tile(primary_caps.img_embedding)\n\n res.top_down_per_caps_rec = self._primary_decoder(\n snt.MergeDims(0, 2)(res.vote),\n snt.MergeDims(0, 2)(res.vote_presence) * tiled_presence,\n template_feature=tiled_feature,\n img_embedding=tiled_img_embedding)\n\n res.templates = templates\n res.template_pres = pres\n res.used_templates = rec.transformed_templates\n\n res.rec_mode = rec.pdf.mode()\n res.rec_mean = rec.pdf.mean()\n\n res.mse_per_pixel = tf.square(target_x - res.rec_mode)\n res.mse = math_ops.flat_reduce(res.mse_per_pixel)\n\n res.rec_ll_per_pixel = rec.pdf.log_prob(target_x)\n res.rec_ll = math_ops.flat_reduce(res.rec_ll_per_pixel)\n\n n_points = int(res.posterior_mixing_probs.shape[1])\n mass_explained_by_capsule = tf.reduce_sum(res.posterior_mixing_probs,\n 1)\n\n (res.posterior_within_sparsity_loss,\n res.posterior_between_sparsity_loss) = _capsule.sparsity_loss(\n self._posterior_sparsity_loss_type,\n mass_explained_by_capsule / n_points,\n num_classes=self._n_classes)\n\n (res.prior_within_sparsity_loss,\n res.prior_between_sparsity_loss) = _capsule.sparsity_loss(\n self._prior_sparsity_loss_type,\n res.caps_presence_prob,\n num_classes=self._n_classes,\n within_example_constant=self._prior_within_example_constant)\n\n label = self._label(data)\n if label is not None:\n res.posterior_cls_xe, res.posterior_cls_acc = probe.classification_probe(\n mass_explained_by_capsule,\n label,\n self._n_classes,\n labeled=data.get('labeled', None))\n res.prior_cls_xe, res.prior_cls_acc = probe.classification_probe(\n res.caps_presence_prob,\n label,\n self._n_classes,\n labeled=data.get('labeled', None))\n\n res.best_cls_acc = tf.maximum(res.prior_cls_acc, res.posterior_cls_acc)\n\n res.primary_caps_l1 = math_ops.flat_reduce(res.primary_presence)\n\n if self._weight_decay > 0.0:\n decay_losses_list = []\n for var in tf.trainable_variables():\n if 'w:' in var.name or 'weights:' in var.name:\n decay_losses_list.append(tf.nn.l2_loss(var))\n res.weight_decay_loss = tf.reduce_sum(decay_losses_list)\n else:\n res.weight_decay_loss = 0.0\n\n return res\n\n def _loss(self, data, res):\n\n loss = (-res.rec_ll - self._caps_ll_weight * res.log_prob +\n self._dynamic_l2_weight * res.dynamic_weights_l2 +\n self._primary_caps_sparsity_weight * res.primary_caps_l1 +\n self._posterior_within_example_sparsity_weight *\n res.posterior_within_sparsity_loss -\n self._posterior_between_example_sparsity_weight *\n res.posterior_between_sparsity_loss +\n self._prior_within_example_sparsity_weight *\n res.prior_within_sparsity_loss -\n self._prior_between_example_sparsity_weight *\n res.prior_between_sparsity_loss +\n self._weight_decay * res.weight_decay_loss)\n\n try:\n loss += res.posterior_cls_xe + res.prior_cls_xe\n except AttributeError:\n pass\n\n return loss\n\n def _report(self, data, res):\n reports = super(ImageAutoencoder, self)._report(data, res)\n\n n_caps = self._decoder._n_caps # pylint:disable=protected-access\n\n is_from_capsule = res.is_from_capsule\n ones = tf.ones_like(is_from_capsule)\n capsule_one_hot = tf.one_hot((is_from_capsule + ones),\n depth=n_caps + 1)[Ellipsis, 1:]\n\n num_per_group = tf.reduce_sum(capsule_one_hot, 1)\n num_per_group_per_batch = tf.reduce_mean(tf.to_float(num_per_group), 0)\n\n reports.update({\n 'votes_per_capsule_{}'.format(k): v\n for k, v in enumerate(tf.unstack(num_per_group_per_batch))\n })\n\n label = self._label(data)\n\n return reports\n\n def _plot(self, data, res, name=None):\n\n img = self._img(data)\n label = self._label(data)\n if label is not None:\n label_one_hot = tf.one_hot(label, depth=self._n_classes)\n\n _render_activations = functools.partial( # pylint:disable=invalid-name\n plot.render_activations,\n height=int(img.shape[1]),\n pixels_per_caps=3,\n cmap='viridis')\n\n mass_explained_by_capsule = tf.reduce_sum(res.posterior_mixing_probs,\n 1)\n normalized_mass_expplained_by_capsule = mass_explained_by_capsule / tf.reduce_max(\n mass_explained_by_capsule, -1, keepdims=True) # pylint:disable=line-too-long\n\n posterior_caps_activation = _render_activations(\n normalized_mass_expplained_by_capsule) # pylint:disable=line-too-long\n prior_caps_activation = _render_activations(res.caps_presence_prob)\n\n is_from_capsule = snt.BatchApply(_render_activations)(\n res.posterior_mixing_probs)\n\n green = res.top_down_rec\n rec_red = res.rec_mode\n rec_green = green.pdf.mode()\n\n flat_per_caps_rec = res.top_down_per_caps_rec.pdf.mode()\n shape = res.vote.shape[:2].concatenate(flat_per_caps_rec.shape[1:])\n per_caps_rec = tf.reshape(flat_per_caps_rec, shape)\n per_caps_rec = plot.concat_images(tf.unstack(per_caps_rec, axis=1),\n 1,\n vertical=False)\n one_image = tf.reduce_mean(self._img(data, self._prep),\n axis=-1,\n keepdims=True)\n one_rec = tf.reduce_mean(rec_red, axis=-1, keepdims=True)\n diff = tf.concat([one_image, one_rec, tf.zeros_like(one_image)], -1)\n\n used_templates = tf.reduce_mean(res.used_templates,\n axis=-1,\n keepdims=True)\n green_templates = tf.reduce_mean(green.transformed_templates,\n axis=-1,\n keepdims=True)\n templates = tf.concat(\n [used_templates, green_templates,\n tf.zeros_like(used_templates)], -1)\n\n templates = tf.concat(\n [templates,\n tf.ones_like(templates[:, :, :, :1]), is_from_capsule], 3)\n\n all_imgs = [\n img, rec_red, rec_green, diff, prior_caps_activation,\n tf.zeros_like(rec_red[:, :, :1]), posterior_caps_activation,\n per_caps_rec\n ] + list(tf.unstack(templates, axis=1))\n\n for i, img in enumerate(all_imgs):\n if img.shape[-1] == 1:\n all_imgs[i] = tf.image.grayscale_to_rgb(img)\n\n img_with_templates = plot.concat_images(all_imgs, 1, vertical=False)\n\n def render_corr(x, y):\n corr = abs(plot.correlation(x, y))\n rendered_corr = tf.expand_dims(_render_activations(corr), 0)\n return plot.concat_images(tf.unstack(rendered_corr, axis=1),\n 3,\n vertical=False)\n\n if label is not None:\n\n posterior_label_corr = render_corr(\n normalized_mass_expplained_by_capsule, label_one_hot)\n prior_label_corr = render_corr(res.caps_presence_prob,\n label_one_hot)\n label_corr = plot.concat_images(\n [prior_label_corr, posterior_label_corr], 3, vertical=True)\n else:\n label_corr = tf.zeros_like(img)\n\n n_examples = min(int(shape[0]), 16)\n plot_params = dict(img_with_templates=dict(\n grid_height=n_examples,\n zoom=3.,\n ))\n\n templates = res.templates\n if len(templates.shape) == 5:\n if templates.shape[0] == 1:\n templates = tf.squeeze(templates, 0)\n\n else:\n templates = templates[:n_examples]\n templates = plot.concat_images(tf.unstack(templates, axis=1),\n 1,\n vertical=False)\n plot_params['templates'] = dict(grid_height=n_examples)\n\n plot_dict = dict(\n templates=templates,\n img_with_templates=img_with_templates[:n_examples],\n label_corr=label_corr,\n )\n\n return plot_dict, plot_params\n"
]
| [
[
"tensorflow.trainable_variables",
"tensorflow.concat",
"tensorflow.expand_dims",
"tensorflow.ones_like",
"tensorflow.reshape",
"tensorflow.nn.l2_loss",
"tensorflow.reduce_max",
"tensorflow.zeros_like",
"tensorflow.squeeze",
"tensorflow.reduce_sum",
"tensorflow.to_float",
"tensorflow.stop_gradient",
"tensorflow.maximum",
"tensorflow.one_hot",
"tensorflow.reduce_mean",
"tensorflow.square",
"tensorflow.unstack",
"tensorflow.image.grayscale_to_rgb"
]
]
|
SSG-DRD-IOT/commercial-iot-security-system | [
"0c3d89b35d0468d4d3cc5ce2653b3f0ac82652a9",
"0c3d89b35d0468d4d3cc5ce2653b3f0ac82652a9"
]
| [
"opencv/experiments_raw/contour_Backproject/backProjection_masked.py",
"opencv/tutorials/videoAnalysis/meanshift_camshift/camshift.py"
]
| [
"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n\nxi, yi, xf, yf = 0, 0, 0, 0\nselecting = False\nfoo = False\n# bar = False\ndef regionSelect(event, x, y, flags, param):\n # print(selecting)\n global xi, yi, xf, yf, selecting, foo, roiHist #, bar\n if event == cv2.EVENT_LBUTTONDOWN:\n plt.close('all')\n selecting = True\n xi, yi = x, y\n elif event == cv2.EVENT_LBUTTONUP:\n selecting = False\n foo = True\n xf, yf = x, y\n # mask[min(yi, yf):max(yi, yf), min(xi, xf):max(xi, xf)] = 255\n roiHist = cv2.calcHist([hsv], [0, 1], mask, [180, 256], [0, 180, 0, 256])\n # roiHist = cv2.normalize(roiHist, roiHist, 0, 255, cv2.NORM_MINMAX)\n\ncap = cv2.VideoCapture(1)\ncv2.namedWindow('frame')\ncv2.setMouseCallback('frame', regionSelect)\n\nroiHist = np.zeros((180, 256), np.uint8)\n\nwhile(True):\n _, frame = cap.read()\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n mask = np.zeros(frame.shape[:2], np.uint8)\n\n mask[min(yi, yf):max(yi, yf), min(xi, xf):max(xi, xf)] = 255\n # cv2.rectangle(frame, (xi, yi), (xf, yf), (255, 0, 0), 3)\n # roiHist = cv2.calcHist([hsv], [0, 1], mask, [180, 256], [0, 180, 0, 256])\n roiHist = cv2.normalize(roiHist, roiHist, 0, 255, cv2.NORM_MINMAX)\n\n targetHist = cv2.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])\n\n dst = cv2.calcBackProject([hsv], [0, 1], roiHist, [0, 180, 0, 256], 1)\n disk = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))\n cv2.filter2D(dst, -1, disk, dst)\n gray = np.copy(dst)\n # threshold and binary AND\n ret, thresh = cv2.threshold(dst, 50, 255, 0)\n # ret, thresh = cv2.threshold(dst, 230, 255, 0)\n # kernel = np.ones((5,5), np.uint8)\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))\n # kernel = disk\n # threshold = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)\n\n thresh = cv2.erode(thresh, kernel, iterations = 3) # iter = 2\n thresh = cv2.dilate(thresh, kernel, iterations= 4) # iter = 3\n\n masked_dots = cv2.bitwise_and(gray, gray, mask = thresh)\n\n\n # apply color maps - applyColorMap(src, dst, colormap)\n gray = cv2.applyColorMap(gray, cv2.COLORMAP_JET)\n\n # thresh = cv2.merge((thresh, thresh, thresh))\n # res = cv2.bitwise_and(frame, thresh)\n cv2.imshow('mask', mask)\n # display the resulting frame\n cv2.imshow('frame', frame)\n cv2.imshow('roiHist', roiHist)\n cv2.imshow('tHist', targetHist)\n cv2.imshow('threshold map', thresh)\n cv2.imshow('distance', gray)\n cv2.imshow('maskedDots', masked_dots)\n # cv2.imshow('dst', dst)\n\n if cv2.waitKey(1) & 0xFF == 27:\n break\n# when everything is done, release the capture\nplt.close('all')\ncap.release()\ncv2.destroyAllWindows()\n",
"\"\"\"\nCamshift\n\nproblem with meanshift: window always has same size when car (in example) is farther away and is very close to camera\n not good\nneed to adapt window size with size and rotation of target\n solution from OpenCV Labs\nCAMshift - continously adaptive meanshift by Gary Bradsky\n\napplies meanshift first\n once converges, updates size of the window as\n s = 2 * sqrt(M_00 / 256)\n also calculates orientation of best fitting ellipse to it\n again applies meanshift with new scaled search window and previous window location\n process continues until required accuracy is met\n\"\"\"\n\n# Camshift in OpenCV\n# almost same as meanshift\n # but returns rotated rectangle (our result)\n # and box parameters (pased as search window in next iteration)\n\nimport numpy as np\nimport cv2\n\ncap = cv2.VideoCapture('slow.flv')\n\n# take first frame of the video\nret, frame = cap.read()\n\n# setup initial location of window\nr, h, c, w = 250, 90, 400, 125 # simply hardcoded values\ntrack_window = (c, r, w, h)\n\n# set up the ROI for tracking\nroi = frame[r:r+h, c:c+w]\nhsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)\nmask = cv2.inRange(hsv_roi, np.array((0., 60., 32.)), np.array((180., 255., 255.)))\nroi_hist = cv2.calcHist([hsv_roi],[0],mask,[180],[0,180])\ncv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)\n\n# setup the termination criteria; either 10 iterations or move by at least 1 pt\nterm_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )\n\nwhile(1):\n ret, frame = cap.read()\n\n if ret == True:\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n dst = cv2.calcBackProject([hsv], [0], roi_hist, [0, 180], 1)\n\n # apply meanshift to get the new location\n ret, track_window = cv2.CamShift(dst, track_window, term_crit)\n\n # draw it on the image\n pts = cv2.boxPoints(ret)\n pts = np.int0(pts)\n img2 = cv2.polylines(frame, [pts], True, 255, 2)\n\n if k == 27:\n break\n else:\n cv2.imwrite(chr(k)+\".jpg\", img2)\n else:\n break\ncv2.destroyAllWindows()\ncap.release()\n"
]
| [
[
"numpy.copy",
"matplotlib.pyplot.close",
"numpy.zeros"
],
[
"numpy.array",
"numpy.int0"
]
]
|
strawpants/cate | [
"eeef7da204b2f5c6dab1a90cb240aa5158c44513"
]
| [
"cate/webapi/start.py"
]
| [
"# The MIT License (MIT)\n# Copyright (c) 2016, 2017 by the ESA CCI Toolbox development team and contributors\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n# of the Software, and to permit persons to whom the Software is furnished to do\n# 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\"\"\"\nDescription\n===========\n\nThis module provides Cate's WebAPI Start executable.\n\nTo use the WebAPI executable, invoke the module file as a script,\ntype ``python3 cate/webapi/start.py [ARGS] [OPTIONS]``.\nType `python3 cate/webapi/start.py --help`` for usage help.\n\nVerification\n============\n\nThe module's unit-tests are located in\n`test/webapi <https://github.com/CCI-Tools/cate/blob/master/test/webapi>`_\nand may be executed using ``$ py.test test/webapi --cov=cate/webapi``\nfor extra code coverage information.\n\nComponents\n==========\n\"\"\"\nimport warnings\n\nwarnings.filterwarnings(\"ignore\") # never print any warnings to users\n\nimport os\nimport sys\nimport platform\nfrom datetime import date\n\nfrom tornado.web import Application, StaticFileHandler\nfrom matplotlib.backends.backend_webagg_core import FigureManagerWebAgg\n\nfrom cate.conf.defaults import WEBAPI_LOG_FILE_PREFIX, WEBAPI_PROGRESS_DEFER_PERIOD\nfrom cate.core.types import ValidationError\nfrom cate.core.wsmanag import FSWorkspaceManager\nfrom cate.util.web import JsonRpcWebSocketHandler\nfrom cate.util.web.webapi import run_start, url_pattern, WebAPIRequestHandler, WebAPIExitHandler\nfrom cate.version import __version__\nfrom cate.webapi.rest import ResourcePlotHandler, CountriesGeoJSONHandler, ResVarTileHandler, \\\n ResFeatureCollectionHandler, ResFeatureHandler, ResVarCsvHandler, ResVarHtmlHandler, NE2Handler, \\\n FilesUploadHandler, FilesDownloadHandler\nfrom cate.webapi.mpl import MplJavaScriptHandler, MplDownloadHandler, MplWebSocketHandler\nfrom cate.webapi.websocket import WebSocketService\nfrom cate.webapi.service import SERVICE_NAME, SERVICE_TITLE\n\n# Explicitly load Cate-internal plugins.\n__import__('cate.ds')\n__import__('cate.ops')\n\n__author__ = \"Norman Fomferra (Brockmann Consult GmbH), \" \\\n \"Marco Zühlke (Brockmann Consult GmbH)\"\n\n\n# noinspection PyAbstractClass\nclass WebAPIInfoHandler(WebAPIRequestHandler):\n def get(self):\n # noinspection PyUnresolvedReferences\n user_root_mode = isinstance(self.application.workspace_manager, FSWorkspaceManager) \\\n and self.application.workspace_manager.root_path is not None\n\n self.write_status_ok(content={'name': SERVICE_NAME,\n 'version': __version__,\n 'timestamp': date.today().isoformat(),\n 'user_root_mode': user_root_mode,\n 'host_os': platform.system()})\n\n self.finish()\n\n\ndef service_factory(application):\n return WebSocketService(application.workspace_manager)\n\n\n# All JSON REST responses should have same structure, namely a dictionary as follows:\n#\n# {\n# \"status\": \"ok\" | \"error\",\n# \"error\": optional error-details,\n# \"content\": optional content, if status \"ok\"\n# }\n\ndef create_application(user_root_path: str = None):\n default_url_root = \"/\"\n # replace default url_root with /user/username/ if running in Cate Hub context.\n url_root = os.environ.get(\"JUPYTERHUB_SERVICE_PREFIX\", default_url_root)\n if url_root is not default_url_root:\n print(f\"warning: detected jupyterhub environment variable JUPYTERHUB_SERVICE_PREFIX \"\n f\"using {url_root} as default root url for the api.\")\n\n application = Application([\n (url_root + '_static/(.*)', StaticFileHandler, {'path': FigureManagerWebAgg.get_static_file_path()}),\n (url_root + 'mpl.js', MplJavaScriptHandler),\n (url_pattern(url_root + 'mpl/download/{{base_dir}}/{{figure_id}}/{{format_name}}'), MplDownloadHandler),\n (url_pattern(url_root + 'mpl/figures/{{base_dir}}/{{figure_id}}'), MplWebSocketHandler),\n (url_pattern(url_root + 'files/upload'), FilesUploadHandler),\n (url_pattern(url_root + 'files/download'), FilesDownloadHandler),\n (url_pattern(url_root), WebAPIInfoHandler),\n (url_pattern(url_root + 'exit'), WebAPIExitHandler),\n (url_pattern(url_root + 'api'), JsonRpcWebSocketHandler, dict(\n service_factory=service_factory,\n validation_exception_class=ValidationError,\n report_defer_period=WEBAPI_PROGRESS_DEFER_PERIOD)\n ),\n (url_pattern(url_root + 'ws/res/plot/{{base_dir}}/{{res_name}}'), ResourcePlotHandler),\n (url_pattern(url_root + 'ws/res/geojson/{{base_dir}}/{{res_id}}'), ResFeatureCollectionHandler),\n (url_pattern(url_root + 'ws/res/geojson/{{base_dir}}/{{res_id}}/{{feature_index}}'), ResFeatureHandler),\n (url_pattern(url_root + 'ws/res/csv/{{base_dir}}/{{res_id}}'), ResVarCsvHandler),\n (url_pattern(url_root + 'ws/res/html/{{base_dir}}/{{res_id}}'), ResVarHtmlHandler),\n (url_pattern(url_root + 'ws/res/tile/{{base_dir}}/{{res_id}}/{{z}}/{{y}}/{{x}}.png'), ResVarTileHandler),\n (url_pattern(url_root + 'ws/ne2/tile/{{z}}/{{y}}/{{x}}.jpg'), NE2Handler),\n (url_pattern(url_root + 'ws/countries'), CountriesGeoJSONHandler),\n ])\n\n default_user_root_path = os.environ.get('CATE_USER_ROOT')\n if user_root_path is None:\n user_root_path = default_user_root_path\n elif default_user_root_path:\n print(f\"warning: user root path given by environment variable CATE_USER_ROOT superseded by {user_root_path}\")\n\n application.workspace_manager = FSWorkspaceManager(user_root_path)\n\n return application\n\n\ndef main(args=None) -> int:\n return run_start(SERVICE_NAME,\n 'Starts a new {}'.format(SERVICE_TITLE),\n __version__,\n application_factory=create_application,\n log_file_prefix=WEBAPI_LOG_FILE_PREFIX,\n args=args)\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n"
]
| [
[
"matplotlib.backends.backend_webagg_core.FigureManagerWebAgg.get_static_file_path"
]
]
|
Ruil/fairseq | [
"5cd5c334631a2aca1d3cfaaaddeec1b56df9e0e4"
]
| [
"fairseq/data/data_utils.py"
]
| [
"# Copyright (c) 2017-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the LICENSE file in\n# the root directory of this source tree. An additional grant of patent rights\n# can be found in the PATENTS file in the same directory.\n\nimport contextlib\nimport os\nimport numpy as np\n\n\ndef infer_language_pair(path):\n \"\"\"Infer language pair from filename: <split>.<lang1>-<lang2>.(...).idx\"\"\"\n src, dst = None, None\n for filename in os.listdir(path):\n parts = filename.split('.')\n if len(parts) >= 3 and len(parts[1].split('-')) == 2:\n return parts[1].split('-')\n return src, dst\n\n\ndef collate_tokens(values, pad_idx, eos_idx, sos_idx, left_pad, move_eos_to_beginning=False):\n \"\"\"Convert a list of 1d tensors into a padded 2d tensor.\"\"\"\n size = max(v.size(0) for v in values)\n res = values[0].new(len(values), size).fill_(pad_idx)\n\n def copy_tensor(src, dst):\n #print('src: ', src)\n #print(sos_idx)\n #sys.exit()\n assert dst.numel() == src.numel()\n if move_eos_to_beginning:\n assert src[-1] == eos_idx\n assert src[0] == sos_idx\n dst[0] = eos_idx \n dst[1:] = src[:-1]\n #dst[-1] = sos_idx\n #dst[1:-1] = src[1:-1]\n else:\n dst.copy_(src)\n\n for i, v in enumerate(values):\n copy_tensor(v, res[i][size - len(v):] if left_pad else res[i][:len(v)])\n return res\n\n\[email protected]\ndef numpy_seed(seed):\n \"\"\"Context manager which seeds the NumPy PRNG with the specified seed and\n restores the state afterward\"\"\"\n if seed is None:\n yield\n return\n state = np.random.get_state()\n np.random.seed(seed)\n try:\n yield\n finally:\n np.random.set_state(state)\n\n\ndef collect_filtered(function, iterable, filtered):\n \"\"\"\n Similar to :func:`filter` but collects filtered elements in ``filtered``.\n\n Args:\n function (callable): function that returns ``False`` for elements that\n should be filtered\n iterable (iterable): iterable to filter\n filtered (list): list to store filtered elements\n \"\"\"\n for el in iterable:\n if function(el):\n yield el\n else:\n filtered.append(el)\n\n\ndef filter_by_size(indices, size_fn, max_positions, raise_exception=False):\n \"\"\"\n Filter indices based on their size.\n\n Args:\n indices (List[int]): ordered list of dataset indices\n size_fn (callable): function that returns the size of a given index\n max_positions (tuple): filter elements larger than this size.\n Comparisons are done component-wise.\n raise_exception (bool, optional): if ``True``, raise an exception if\n any elements are filtered (default: False).\n \"\"\"\n def check_size(idx):\n if isinstance(max_positions, float) or isinstance(max_positions, int):\n return size_fn(idx) <= max_positions\n elif isinstance(max_positions, dict):\n idx_size = size_fn(idx)\n assert isinstance(idx_size, dict)\n intersect_keys = set(max_positions.keys()) & set(idx_size.keys())\n return all(\n all(a is None or b is None or a <= b\n for a, b in zip(idx_size[key], max_positions[key]))\n for key in intersect_keys\n )\n else:\n #print('size: ', size_fn(idx))\n return all(a is None or b is None or a <= b\n for a, b in zip(size_fn(idx), max_positions))\n\n ignored = []\n itr = collect_filtered(check_size, indices, ignored)\n\n for idx in itr:\n if len(ignored) > 0 and raise_exception:\n raise Exception((\n 'Size of sample #{} is invalid (={}) since max_positions={}, '\n 'skip this example with --skip-invalid-size-inputs-valid-test'\n ).format(ignored[0], size_fn(ignored[0]), max_positions))\n yield idx\n\n if len(ignored) > 0:\n print((\n '| WARNING: {} samples have invalid sizes and will be skipped, '\n 'max_positions={}, first few sample ids={}'\n ).format(len(ignored), max_positions, ignored[:10]))\n\n\ndef batch_by_size(\n indices, num_tokens_fn, max_tokens=None, max_sentences=None,\n required_batch_size_multiple=1,\n):\n \"\"\"\n Yield mini-batches of indices bucketed by size. Batches may contain\n sequences of different lengths.\n\n Args:\n indices (List[int]): ordered list of dataset indices\n num_tokens_fn (callable): function that returns the number of tokens at\n a given index\n max_tokens (int, optional): max number of tokens in each batch\n (default: None).\n max_sentences (int, optional): max number of sentences in each\n batch (default: None).\n required_batch_size_multiple (int, optional): require batch size to\n be a multiple of N (default: 1).\n \"\"\"\n max_tokens = max_tokens if max_tokens is not None else float('Inf')\n max_sentences = max_sentences if max_sentences is not None else float('Inf')\n bsz_mult = required_batch_size_multiple\n\n batch = []\n\n def is_batch_full(num_tokens):\n if len(batch) == 0:\n return False\n if len(batch) == max_sentences:\n return True\n if num_tokens > max_tokens:\n return True\n return False\n\n sample_len = 0\n sample_lens = []\n for idx in indices:\n sample_lens.append(num_tokens_fn(idx))\n sample_len = max(sample_len, sample_lens[-1])\n assert sample_len <= max_tokens, \"sentence at index {idx} exceeds max_tokens limit!\".format(idx=idx)\n num_tokens = (len(batch) + 1) * sample_len\n if is_batch_full(num_tokens):\n mod_len = max(\n bsz_mult * (len(batch) // bsz_mult),\n len(batch) % bsz_mult,\n )\n yield batch[:mod_len]\n batch = batch[mod_len:]\n sample_lens = sample_lens[mod_len:]\n sample_len = max(sample_lens) if len(sample_lens) > 0 else 0\n\n batch.append(idx)\n\n if len(batch) > 0:\n yield batch\n\n\ndef process_bpe_symbol(sentence: str, bpe_symbol: str):\n if bpe_symbol == 'sentencepiece':\n sentence = sentence.replace(' ','').replace('\\u2581', ' ').strip()\n elif bpe_symbol is not None:\n sentence = (sentence + ' ').replace(bpe_symbol, '').rstrip()\n return sentence\n"
]
| [
[
"numpy.random.seed",
"numpy.random.get_state",
"numpy.random.set_state"
]
]
|
wsmorgan/phonon-enumeration | [
"5d7a8d8e3403cc387bdd58cf98a23e4751ea34dd"
]
| [
"phenum/grouptheory.py"
]
| [
"\"\"\"Methods for taking an HNF and finding the site permutations and the\narrow permutations. All of these have been modified for python from\ntheir original fortran implementations which can be found at:\nhttps://github.com/msg-byu/enumlib/. Of these only get_rotation\nget_rotation_perms_lists() has been modified in order to produce the\narrow group. The class ArrowPerm has also been added and implemented\ninside the RotPermList class.\n\"\"\"\n\nimport itertools\nimport numpy as np\nimport operator\n\nclass ArrowPerm(object):\n \"\"\"ArrowPerm pairs a site permutation with an arrow permutation.\n\n Attributes:\n site_perm (list): A 1D array containing a site permutation.\n arrow_perm (list): A 1D array containing an arrow permutation.\n \"\"\"\n def __init__(self,site_perm = None,arrow_perm = None):\n \"\"\"Initializes the ArrowPerm.\n \n Args:\n site_perm (list): A 1D array containing a site permutation.\n arrow_perm (list): A 1D array containing an arrow permutation.\n \"\"\"\n self.site_perm = site_perm\n self.arrow_perm = arrow_perm\n\nclass RotPermList(object):\n \"\"\"RotPermList maintains the data structure for the rotations and\n permutations from the fortran code.\n\n Attributes:\n nL (int): An integer indicating the number of operations.\n v (array-like): A 2D array containing the lattice vectors.\n perm (ArrowPerm): An ArrowPerm object.\n RotIndx (list): List of the rotation indices.\n \"\"\"\n def __init__(self,nL = None,v =None,perm = None,RotIndx = None,arrows=None):\n \"\"\"Initializes the RotPermList.\n\n Args:\n nL (int): An integer indicating the number of operations.\n v (array-like): A 2D array containing the lattice vectors.\n perm (ArrowPerm): An ArrowPerm object.\n RotIndx (list): List of the rotation indices.\n \"\"\"\n self.nL = nL\n self.v = v\n self.perm = ArrowPerm(site_perm = perm, arrow_perm=arrows)\n self.RotIndx = RotIndx\n\nclass OpList(object):\n \"\"\"OpList maintains the data structure of the fixing operations form\n the fortran code.\n\n Attributes:\n rot (array-like): A 3D array containing the rotations.\n shift (array-like): A 2D array containing the translations of the lattice.\n \"\"\"\n def __init__(self,rot = None, shift = None):\n \"\"\"Initializes the OpList.\n \n Args:\n rot (array-like): A 3D array containing the rotations.\n shift (array-like): An 2D array containing the translations of th lattice.\n \"\"\"\n self.rot = rot\n self.shift = shift\n\ndef _make_member_list(n):\n \"\"\"Takes the length of three cyclic group and constructs the member\n list so that the permutations can be determined. Each member has\n three components, corresponding to the entries for each of the\n three cyclic groups.\n \n Args:\n n (int): array containing the diagonal elements of the SNF.\n\n Returns:\n p (list): The member list for the symmetry group.\n \"\"\"\n from operator import mul\n from functools import reduce\n \n depth = int(round(reduce(mul,n,1)))\n p = np.zeros([depth,3])\n for im in range(1,depth): # Loop over the members of the translation group\n p[im] = list(p[im-1]) # Start with the same digits as in the previous increment \n p[im][2] = (p[im-1][2]+1)%n[2] # Increment the first cyclic group\n if (p[im][2]==0): # If it rolled over then\n p[im][1] = (p[im-1][1] +1) % n[1] # increment the next cyclic group\n if (p[im][1]==0): # If this one rolled over too\n p[im][0] = (p[im-1][0]+1)%n[0] # Then increment the third one\n return p\n\ndef _find_permutation_of_group(g,gp):\n \"\"\"Constructs the permutation group from the point group.\n \n Args:\n g (list): The unpermuted symmetry group.\n gp (list): The permuted symmetry group.\n\n Returns:\n perm (list): Permutation of g to get gp.\n \"\"\"\n n = len(g)\n perm = []\n skip = [False]*n\n for im in range(n):\n for jm in range(n):\n if skip[jm]:\n continue # This is just for efficiency\n if np.allclose(gp[jm],g[im]):\n perm.append(jm)\n skip[jm] = True\n break # don't keep looking if you already found the match\n \n return perm\n\ndef _is_equiv_lattice(lat1,lat2,eps):\n \"\"\"This function determines whether two lattices are equivalent. That\n is, if one is an equal-volume derivative lattice of the other. It\n uses the idea of Santoro and Mighell (Acta. Cryst. 1972) that, for\n equivalent lattices, the transformation matrix that takes the\n vectors of str2 to str1 has determinant of 1 and all integer\n elements. [LV2]=[LV1][S]=>S=LV1^-1*LV2. But I had to use abs on\n the determinant. This is not mentioned by Santoro and Mighell\n (issue of opposite handedness---which doesn't matter to me).\n\n Args:\n lat1 (array-like): 2D array containing the first lattice.\n lat2 (array-like): 2D array containing the second lattice.\n eps (float): The finite precision tolerance.\n\n Returns:\n is_equiv_lattice (bool): True if lattice are equivalent.\n \"\"\"\n from numpy import linalg, allclose, matmul\n is_equiv_lattice = False\n lat1inv = linalg.inv(lat1)\n S = matmul(lat1inv,lat2).tolist()\n if (allclose(abs(linalg.det(S)),1.0,rtol=0,atol=eps) and\n allclose(S,[[int(round(S[i][j])) for j in range(3)] for i in range(3)],rtol=0,atol=eps)):\n is_equiv_lattice = True\n return is_equiv_lattice\n \ndef _get_sLV_fixing_operations(HNF,pLV,rot,shift,dPerm,eps):\n \"\"\"This subroutine deteremines which operations of the parent cell\n don't change the supercell. These operations are the symmetry\n operations of the supercell.\n\n Args:\n HNF (list): A 2D integer list containing the hermite normal form matrix.\n pLV (array-like): A 2D array containing the parent lattice vectors.\n rot (array-like): A 3D array containing all the rotation matrices.\n shift (array-like): A 2D array containing the translations. \n dPerm (list): List of basis vector permutations.\n eps (float): Finite precision tolerance.\n\n Returns:\n fix_op (OpList): A list of the lattice fixing symmetry operations.\n rot_perm (list): The rotation permutations.\n degeneracy (int): Degeneracy of the supercell.\n \"\"\"\n\n n_rot = len(rot)\n degen_lattices = np.zeros([n_rot,3,3])\n \n c_degen = 0\n ic = 0 # Counter for the fixing operations\n tv = 0\n tmp_op_rot = []\n tmp_op_shift = []\n tv = []\n t_index = [] # temp variables\n for iRot in range(n_rot): # Loop over each rotation\n this_rot = rot[iRot] # Store the rotation\n orig_lat = np.matmul(np.transpose(pLV),HNF) # Compute the superlattice\n rot_lat = np.matmul(this_rot,orig_lat) # Compute the rotated superlattice\n if _is_equiv_lattice(rot_lat,orig_lat,eps):\n # this operation fixes the lattice and should be recorded\n ic += 1\n tmp_op_rot.append(this_rot)\n tmp_op_shift.append(shift[iRot])\n tv.append(dPerm.v[iRot])\n t_index.append(iRot)\n # Added by LN from here\n else:\n in_list = False\n for iDegen in range(c_degen):\n if _is_equiv_lattice(degen_lattices[iDegen],rot_lat,eps):\n in_list = True\n break\n \n if not in_list:\n degen_lattices[c_degen] = rot_lat\n c_degen += 1\n # End of LN additions for degeneracy\n # Now we know which rotations fix the lattice and how many\n # there are so store them\n degeneracy = c_degen\n # Allocate the storage for them\n fix_op = OpList(tmp_op_rot,tmp_op_shift) # Stuff the rotations into the permanent array\n\n rot_perm = RotPermList(v=tv,RotIndx=t_index)\n \n return(fix_op,rot_perm,degeneracy)\n\ndef _map_dvector_permutation(rd,d,eps):\n \"\"\"Maps the basis vectors to a permutation.\n \n Args:\n rd (array-like): 2D array of the rotated basis vectors.\n d (array-like): 2D array of the original basis vectors.\n eps (float): Finite precision tolerance.\n\n Returns:\n RP (list): The permutation of the basis vectors.\n \"\"\"\n n_d = len(rd) # of d-vectors\n found = [False]*n_d\n RP = []\n for iD in range(n_d):\n for jD in range(n_d):\n if found[jD]:\n continue\n if np.allclose(rd[iD],d[jD],atol=eps,rtol=0):\n RP.append(jD)\n found[jD] = True\n break\n\n if len(RP) != len(d): #pragma: no cover\n print(\"d-vector didn't permute in map_dvector_permutation \"\n \"This usually means that the d-set from the input structure and the d-set\"\n \" from the struct_enum.out have a different origin or don't live in the same\"\n \" unit cell. This probably isn't your fault---the code should overcome this.\"\n ,RP)\n exit()\n return(RP)\n\n \ndef _find_minmax_indices(invec):\n \"\"\"Finds the indices corresponding to the minimum and maximum values\n in an integer vector.\n\n Args:\n invec (list): The input array.\n\n Returns:\n this_min (int): The minimum index.\n this_max (int): The maximum index.\n \"\"\"\n\n vec = [abs(i) for i in invec]\n \n this_min = vec.index(min([i for i in vec if i > 0]))\n\n rvec = [i for i in reversed(vec)]\n \n this_max = 2 - rvec.index(max(rvec))\n\n return (this_min,this_max)\n\ndef SmithNormalForm(HNF):\n \"\"\"Finds the Smith Normal Form (SNF) of an HNF as well as the left and\n right transforms.\n \n Args:\n HNF (list of list): An integer matrix for which the SNF is to be found.\n\n Returns:\n\n (M, A, B) (matrix, matrix, matrix): The M is the Smith Normal Form\n matrix of the input matrix, A is the left transform matrix,\n and B is the right transform matrix. The matrices are such\n that np.dot(np.dot(A,HNF),B) = M.\n\n \"\"\"\n from numpy import dot\n from copy import deepcopy\n \n if np.linalg.det(HNF) < 1:\n raise ValueError(\"SmithNormalForm routine failed because the input matrix had a \"\n \"determinant less than 1.\")\n\n A = [[0,0,0],[0,0,0],[0,0,0]]\n Mpre = deepcopy(list(HNF))\n M = [[int(x) for x in i] for i in Mpre]\n B = [[0,0,0],[0,0,0],[0,0,0]]\n\n if not np.allclose(M,Mpre):\n raise ValueError(\"The input matrix to SmithNormalForm was not integer.\")\n \n for i in range(3):\n A[i][i] = 1\n B[i][i] = 1\n\n j = 0\n it_cnt = 0\n\n stop_loop = False\n while not stop_loop:\n it_cnt += 1\n if (it_cnt >=100): #pragma: no cover\n raise RuntimeError(\"Bad programming in SmithNormalForm\")\n \n while (3-[M[0][j],M[1][j],M[2][j]].count(0)) > 1:\n (minidx,maxidx) = _find_minmax_indices([M[0][j],M[1][j],M[2][j]])\n minm = M[minidx][j]\n mult = M[maxidx][j]//minm\n\n M[maxidx] = list(map(operator.sub,M[maxidx],[mult*i for i in M[minidx]]))\n A[maxidx] = list(map(operator.sub,A[maxidx],[mult*i for i in A[minidx]]))\n if dot(dot(A,HNF),B).any() != np.array(M).any(): #pragma: no cover\n print(\"ROW: Transformation matrices didn't work\")\n exit()\n if M[j][j] == 0:\n maxidx = [abs(M[0][j]),abs(M[1][j]),abs(M[2][j])].index(max([abs(M[0][j]),abs(M[1][j]),abs(M[2][j])]))\n tmprow = list(A[j])\n A[j] = list(A[maxidx])\n A[maxidx] = tmprow\n\n tmprow = list(M[j])\n M[j] = list(M[maxidx])\n M[maxidx] = tmprow \n if np.dot(np.dot(A,HNF),B).any() != np.array(M).any(): #pragma: no cover\n print(\"ROWSWAP: Transformation matrices didn't work\")\n exit()\n\n while (3-M[j].count(0)) >1:\n (minidx,maxidx) = _find_minmax_indices(M[j])\n\n minm = M[j][minidx]\n mult = M[j][maxidx]//M[j][minidx]\n for i in range(3):\n M[i][maxidx] = M[i][maxidx]-mult * M[i][minidx]\n B[i][maxidx] = B[i][maxidx]-mult * B[i][minidx]\n\n if np.dot(np.dot(A,HNF),B).any() != np.array(M).any(): #pragma: no cover\n print(\"COLS: Transformation matrices didn't work\")\n exit()\n\n if M[j][j] < 0:\n for i in range(3):\n M[i][j] = -M[i][j]\n B[i][j] = -B[i][j]\n elif M[j][j] == 0:\n maxidx = [abs(i) for i in M[j]].index(max([abs(i) for i in M[j]]))\n for i in range(3):\n tmp = B[i][j]\n B[i][j] = B[i][maxidx]\n B[i][maxidx] = tmp \n tmp = M[i][j]\n M[i][j] = M[i][maxidx]\n M[i][maxidx] = tmp\n\n if ((3-M[j].count(0)) >1) or ((3-[M[0][j],M[1][j],M[2][j]].count(0)) >1):\n continue\n if np.dot(np.dot(A,HNF),B).any() != np.array(M).any(): #pragma: no cover\n print(\"COLSWAP: Transformation matrices didn't work\")\n exit()\n\n l_div = []\n for i in range(1,3):\n for k in range(1,3):\n l_div.append((M[i][k]%M[0][0] == 0))\n\n if j == 0 and False in l_div:\n local = [[0,0],[0,0]] \n for i in range(1,3):\n for k in range(1,3):\n local[i-1][k-1] = abs(M[i][k]%M[0][0])\n nondividx = local.index(max(local))\n M[0] = list(map(operator.add,M[0],M[nondividx+1]))\n A[0] = list(map(operator.add,A[0],A[nondividx+1]))\n continue\n\n if j == 1 and M[2][2]%M[1][1] != 0:\n M[1] = list(map(operator.add,M[1],M[2]))\n A[1] = list(map(operator.add,A[1],A[2]))\n continue\n elif j != 1:\n j = 1\n continue\n if j == 1 and (M[2][1] != 0 or M[1][2] != 0): #pragma: no cover\n # I literally could not trigger this section of code in my testse.\n continue\n stop_loop = True\n\n if M[2][2] < 0:\n for i in range(3):\n M[i][2]=-M[i][2]\n B[i][2]=-B[i][2]\n\n if np.dot(np.dot(A,HNF),B).any() != np.array(M).any(): #pragma: no cover\n print(\"END: Transformation matrices didn't work.\")\n exit()\n check = [M[0][1],M[0][2],M[1][0],M[1][2],M[2][0],M[2][1]]\n if any(check) != 0: #pragma: no cover\n print(\"Not diagonal\")\n exit()\n if M[1][1] % M[0][0] != 0 or M[2][2] % M[1][1] != 0: #pragma: no cover\n print(\"SNF conditions not met\")\n exit()\n \n return(M,A,B)\n\ndef _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps):\n \"\"\"This routine applies the symmetry operations of the parent lattice\n to the interior points (i.e., the d-set) to see which ones are\n equivalent. Labelings of the lattice points that are contain\n permutations only of labels on equivalant sites are physically\n equivalent and therefore redundant. We use these permutations to\n eliminate those duplicate labelings\n\n Args:\n par_lat (list): A 2D array containing the parent lattice vectors.\n bas_vacs (list): A 2D array containing the basis vectors for the cell.\n LatDim (int): 2 if a 2D case 3 if 3D.\n eps (float): Finite precesion tolerance.\n\n Returns:\n drp_list (list): The basis vector permutations.\n \"\"\"\n\n from phenum.symmetry import get_spaceGroup, bring_into_cell\n from copy import deepcopy\n \n n_d = len(bas_vecs)\n a_type = [1]*n_d\n\n bv_copy = deepcopy(bas_vecs)\n (rot,shift) = get_spaceGroup(par_lat,a_type,bv_copy,eps = eps)\n\n if LatDim==2:\n (rot,shift) = _rm_3D_operations(par_lat,rot,shift,eps)\n\n n_op = len(rot)\n inv_par_lat = np.linalg.inv(np.transpose(par_lat))\n nl_temp= n_op # Number of operations that fix the parent\n\n # lattice (but may permute the d-vectors)\n v_temp = []\n perm_temp = []\n for iOp in range(n_op): # Try each operation in turn and see how the\n # d-vectors are permuted for each\n # Rotate each d and add the shift\n if len(bas_vecs) == 1:\n temp_b = bas_vecs[0]\n else:\n temp_b = bas_vecs\n rd_rot = np.matmul(temp_b,rot[iOp]).tolist()\n\n if n_d > 1:\n rd_shift = [shift[iOp]]*n_d\n rd = [[rd_rot[i][j] + rd_shift[i][j] for j in range(len(rd_rot[i]))] for i in range(len(rd_rot))]\n \n else:\n rd = [rd_rot[i] + shift[iOp][i] for i in range(len(rd_rot))]\n \n trd = list(rd)\n if n_d > 1:\n for iD in range(n_d):\n rd[iD] = bring_into_cell(rd[iD],inv_par_lat,np.transpose(par_lat),eps)\n else:\n rd = bring_into_cell(rd,inv_par_lat,np.transpose(par_lat),eps)\n \n # The v vector is the vector that must be added (it's a lattice\n # vector) to move a rotated d-vector back into the parent cell.\n\n if n_d > 1:\n v_temp.append([[rd[i][j] - trd[i][j] for j in range(len(rd[i]))] for i in range(len(rd))])\n else:\n v_temp.append([[rd[i] - trd[i] for i in range(len(rd))]])\n if n_d > 1:\n perm_temp.append(_map_dvector_permutation(rd,bas_vecs,eps))\n else:\n perm_temp.append(_map_dvector_permutation([rd],[bas_vecs],eps))\n\n drp_list = RotPermList(nL=nl_temp,v=v_temp,perm=perm_temp)\n\n # I don't think we should reduce this list to a unique one. Some\n # rotations that don't permute the d's could still permute the\n # g's. So we have to keep all the d permutations, even if they\n # look redundant here.\n return(drp_list)\n \ndef _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps, arrows=False):\n \"\"\"For each HNF, we have a list of the operations (rotations + shifts,\n if present) that leave the superlattice fixed. Given this set of\n fixing operations, make a list of the permutations on the\n d-vectors (interior points of the multilattice) effected by the\n rotations. Then sort the HNFs into blocks that have the same\n rotation permutations.\n\n Args:\n A (numpy ndarray): Lattice vectors of the parent lattice as rows of a matrix.\n HNF (numpy ndarray): The HNF matrix.\n L (numpy ndarray): Left transforms matrix.\n SNF (numpy ndarray): The SNF matrix.\n Op (OpList): A list of symmetry ops (rots and shifts) for the parent multilattice.\n RPlist (list of RotPermList): A list of permutations effected by the Ops.\n dperms (list): The permutation of the basis vectors.\n eps (float): Finite precision tolerance.\n arrows (bool, optional): True if arrow group is to be found as well.\n\n Returns:\n RPlist (list of RotPermList): The symmetry operations represented as permutations\n of a list.\n \"\"\"\n\n # Index of the superlattices; Number of d-vectors in d set \n n = int(round(np.linalg.det(HNF[0])))\n n_h = len(HNF) \n n_d = np.array(dperms.perm.site_perm).shape[-1]\n\n skip = []\n gp = []\n\n arrowg = [[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]]\n \n tg = []\n perm = []\n ident = []\n tperms_perm = []\n temp_rperms_perm = []\n ident = np.reshape([range(n*n_d)],(n_d,n))\n\n len_rp = len(RPlist)\n for i in range(len_rp):\n RPlist[i].nL=0 # initialize the number\n # Make the group member list for the first SNF\n diag = [SNF[0][0][0],SNF[0][1][1],SNF[0][2][2]]\n g = np.transpose(_make_member_list(diag))\n\n a_t = np.transpose(A)\n a_tinv = np.linalg.inv(a_t)\n\n for iH in range(n_h):\n if iH > 0 and not (SNF[iH][0][0] == SNF[iH-1][0][0] and SNF[iH][1][1] == SNF[iH-1][1][1] and SNF[iH][2][2] == SNF[iH-1][2][2]):\n # Make the transform matrices for taking the g's and rotating them\n diag = [SNF[iH][0][0],SNF[iH][1][1],SNF[iH][2][2]]\n g = np.transpose(_make_member_list(diag))\n \n t_inv = np.matmul(L[iH],a_tinv)\n T = np.linalg.inv(t_inv)\n n_op = len(Op[iH].rot)\n na_op = len(arrowg)\n \n temp_rperms_perm = []\n temp_arrow_perm = []\n for iOp in range(n_op): # For each rotation, find the permutation\n dap = np.zeros(na_op)\n dgp = []\n for i in range(n):\n tt = []\n tt = np.zeros(n_d).tolist()\n dgp.append(tt)\n\n for iD in range(n_d): # Loop over each row in the (d,g) table\n temp1 = np.transpose([RPlist[iH].v[iOp][iD]]*n)\n temp2 = np.matmul(np.matmul(Op[iH].rot[iOp],T),g)\n rag = np.transpose(np.matmul(arrowg,Op[iH].rot[iOp]))\n rgp = np.matmul(t_inv,(-temp1+temp2))\n temp_gp = np.round(rgp).astype(int)\n temp_ag = np.round(rag).astype(int)\n if not np.allclose(rgp,temp_gp,rtol=0,atol=eps): #pragma: no cover\n print(\"Transform left big fractional parts\")\n exit()\n\n gp = temp_gp\n ag = temp_ag\n temp_diag = np.transpose([diag]*n)\n gp = gp%temp_diag # Mod by each entry of\n # the SNF to bring into group Now that the rotated group\n # is known, find the mapping of the elements between the\n # original group and the permuted group. This is the\n # permutation.\n \n skip = [False]*n\n for im in range(n):\n for jm in range(n):\n if skip[jm]:\n continue # Skip elements whose mapping is already known\n if np.allclose(gp[:,jm],g[:,im]): # these elements\n # map to each other The list of operations that fix\n # the superlattice are a subset of those that fix\n # the parent lattice. RotIndx stores the indicies\n # of the parent lattice operations in a list with\n # as many entries as supercell fixing operations.\n\n # dperms%perm stores a list of d-vector\n # permutations, one permutation (an n_d list) for\n # each operation in the parent lattice symmetries\n op_indx_in_supercell_list = RPlist[iH].RotIndx[iOp]\n row_indx_gtable = dperms.perm.site_perm[op_indx_in_supercell_list][iD]\n dgp[im][row_indx_gtable] = jm+iD*n\n skip[jm] = True\n break\n \n # do the same thing for the arrows\n skip = [False]*na_op\n for im in range(na_op):\n for jm in range(na_op):\n if skip[jm]:\n continue\n if (ag[:,jm] == arrowg[im]).all():\n dap[im] = jm\n skip[jm] = True\n break\n\n if np.count_nonzero(dgp == 0) > 1 or np.count_nonzero(dap == 0) > 1: #pragma: no cover\n print(\"(d,g)-->(d',g') mapping failed in get_rotation_perm_lists\")\n exit()\n\n # Now we have the (d',g') table for this rotation. Now\n # record the permutation\n # permutation in the \"long form\"\n temp_rperms_perm.append(np.transpose(dgp).reshape(n_d*n).tolist()) # store\n temp_arrow_perm.append(dap)\n\n # nomenclature:\n # N+t = rotation (N) + fractional translation (t) (me bethinks....)\n # r = lattice translation\n\n # Now that we have the permutations that are effected by N+t\n # type of rotations (for each N in the point group), we need to\n # compose them with the permutations effected by lattice\n # translations, (parent) lattice translations contained inside the\n # supercell (N+t+r, in Rod's nomenclature). Only when we have these\n # two lists, and compose them, do we have a guarantee that the\n # resulting list is actually a group. For efficiency, we reduce the\n # N+t list (remove duplicates). Rod claims that the compositions\n # (with the translations) will not have duplicates.\n if len(temp_rperms_perm) > 1 and arrows == False:\n temp_rperms_perm.sort()\n temp_rperms_perm = list(temp_rperms_perm for temp_rperms_perm, _ in itertools.groupby(temp_rperms_perm))\n elif len(temp_rperms_perm) > 1 and arrows == True:\n nr = len(temp_rperms_perm[0])\n na = len(temp_arrow_perm[0])\n len_temp_rp = len(temp_rperms_perm)\n perms = []\n for i in range(len_temp_rp):\n perms.append(list(temp_rperms_perm[i])+list(temp_arrow_perm[i]))\n\n perms = list(perms for perms, _ in itertools.groupby(perms))\n perms.sort()\n temp_rperms_perm = []\n temp_arrow_perm = []\n len_perms = len(perms)\n for i in range(len_perms):\n temp_rperms_perm =[p[:nr] for p in perms]\n temp_arrow_perm = [p[-na:] for p in perms]\n # The rotations permutations list is now in \"alphabetical\"\n # order and contains no duplicates\n \n # To get the permutations effected by the r's, we don't need\n # the r's. We can merely take the member list, the group, and\n # add each element of the group to the group itself and see\n # what permutation happens. (This part is somewhat redundant\n # with make_translation_group in labeling_related module.)\n tperms_perm = []\n for ig in range(n): # The number of r's inside the superlattice (the\n # translation perms) is the same as the index n\n temp_g = np.transpose([g[:,ig]]*n)\n tg = g+temp_g#[[g[i][j]+temp_g[i][j] for j in range(len(g[i]))] for i in range(len(g))] # Add the element to the group\n temp_diag = np.transpose([diag]*n)\n tg = tg%temp_diag#[[tg[i][j]%temp_diag[i][j] for j in range(len(tg[i]))] for i in range(len(tg))] # mod by the SNF entries to\n # bring it back to the \"primitive\" representation\n perm = _find_permutation_of_group(np.transpose(g),np.transpose(tg))\n temp_ident = []\n\n len_ident = len(ident)\n for il in range(len_ident):\n temp_ident.append([ident[il][i] for i in perm])\n tperms_perm.append(np.reshape(temp_ident,(n*n_d)).tolist())\n \n rp_list_nl = len(temp_rperms_perm)*n\n rp_list_perm_sites = [0]*rp_list_nl\n rp_list_perm_arrows = [0]*rp_list_nl\n len_t_perm = len(temp_rperms_perm)\n for it in range(n): # Loop over unique rotation\n for iOp in range(len_t_perm): # Loop over translation perms (r type)\n # perms (N+t type) Form the permutation effected by\n # composing the iOp-th one with the it-th one\n rp_list_temp = [tperms_perm[it][i] for i in temp_rperms_perm[iOp]]\n rp_list_perm_sites[iOp*n + it] = rp_list_temp\n rp_list_perm_arrows[iOp*n+it] = temp_arrow_perm[iOp]\n # ^--- Having gotten both the rotations and the\n # translation in the sections above (sort_permutations_list\n # etc...), the \"operators\" of the rotation (one of them is\n # R_i) and the translations (one of them is T_j) are now\n # \"scrambled\", i.e., (T_j) o (R_i). Since the *first*\n # Rotation R_1 = Id, the *first* entries in the\n # RPlist(iH)%perm are equivalent to pure translations only.\n # The following entries are a combination of both.\n\n RPlist[iH].perm.site_perm = rp_list_perm_sites\n if arrows: \n RPlist[iH].perm.arrow_perm = rp_list_perm_arrows\n else:\n RPlist[iH].perm.arrow_perm = [range(na_op)]*len(rp_list_perm_arrows)\n RPlist[iH].n = rp_list_nl\n \n return (RPlist)\n \ndef get_sym_group(par_lat,bas_vecs,HNF,LatDim,arrows=True):\n \"\"\"Generates the symmetry group for a given lattice and HNF\n\n Args:\n\n par_lat (numpy ndarray): a 2D array that contains the parrent\n lattice vectors\n\n bas_vecs (list): A list of the atomic basis vectors for the lattice.\n HNF (numpy ndarray): The HNF matrix that defines the supercell.\n LatDim (int): 2 if a surface case case 3 if bulk.\n arrows (bool, optional): True if the arrow group is to be found as well.\n\n Returns:\n sym_group (RotPermList): The symmetry operations represented as permutations\n of a list.\n \"\"\"\n\n from numpy import linalg, allclose\n from phenum.symmetry import bring_into_cell, get_spaceGroup\n from copy import deepcopy\n\n eps = 1E-10\n # map any atoms in the basis that aren't within the cell to be in\n # the cell\n par_lat_inv = np.transpose(linalg.inv(par_lat))\n temp_basis = deepcopy(bas_vecs)\n for i, b_vecs in enumerate(bas_vecs):\n # par_lat_inv = linalg.inv(np.transpose(par_lat))\n bas_vecs[i] = bring_into_cell(b_vecs,par_lat_inv,np.transpose(par_lat),eps)\n if not allclose(b_vecs, temp_basis[i], rtol=0, atol=eps): # pragma: no cover\n from phenum.msg import warn\n warn(\"An atomic basis vector was not inside the unit cell. It has been \"\n \"remapped.\\n Original vector: {} \\n Remapped vector: {}\"\n .format(\" \".join([str(p) for p in temp_basis[i]]),\n \" \".join([str(p) for p in b_vecs])))\n\n par_rp_list = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps)\n\n a_type = [1]*len(bas_vecs)\n \n (sgrots,sgshifts) = get_spaceGroup(par_lat,a_type,bas_vecs,eps)\n (fixing_ops,RPList,degeneracy) = _get_sLV_fixing_operations(HNF,par_lat,sgrots,sgshifts,\n par_rp_list,eps)\n\n (SNF,L,R) = SmithNormalForm(deepcopy(HNF))\n sym_group = _get_rotation_perms_lists(par_lat,[HNF],[L],[SNF],[fixing_ops],[RPList],\n par_rp_list,eps,arrows=arrows)\n\n return(sym_group[0])\n\n#a_group take the set of translations of the lattice and the set of\n#rotations of the lattice paired with their effect on the arrows of\n#the lattice. It makes a direct product of the transformations and the\n#rotations and pairs them with the combination of th arraws. If the\n#resultant operation is not in the group it then adds it to the group.\ndef a_group(trans,rots):\n \"\"\"This subroutine combines that translations of the lattice with the\n rotatians of the lattice.\n\n Args:\n trans (list): A 2D array where each row is an translation\n of the lattice.\n\n rots (list): A 3D array. Each row's first entry is the\n site permutations and the second entry is the arrow\n permutations.\n\n Returns:\n groupi (list): The full symmetry group.\n \"\"\"\n groupi = []\n for i in trans:\n for j in rots:\n c = [] \n c.append([j[0][i[l]] for l in range(0,len(i))])\n c.append(j[1])\n if c not in groupi:\n groupi.append(c)\n\n return(groupi)\n\ndef a_group_gen(trans,rots):\n \"\"\"This subroutine combines that translations of the lattice with the\n rotatians of the lattice for the generators of the system.\n \n Args:\n trans (list): A 2D array where each row is an translation\n of the lattice.\n\n rots (list): A 3D array. Each row's first entry is the\n site permutations and the second entry is the arrow\n permutations.\n\n Returns:\n groupi (list): The full symmetry group.\n \"\"\"\n groupi = []\n for i in trans:\n for j in rots:\n c = [] \n c.append([j[0][i[l]] for l in range(0,len(i))])\n c.append(j[1])\n if c not in groupi:\n groupi.append(c)\n\n groupi = _group(groupi)\n \n return(groupi)\n\ndef _group(gen): # pragma: no cover\n \"\"\"This subroutine takes the generators of the group then uses them\n to form the entire group.\n\n Args:\n gen (list): A 2D array of the generators of the group\n where each row is a seperate generator.\n\n Returns:\n groupi (list): The full symmetry group.\n \"\"\"\n # q is a counter to track how many group elements we've found\n q = 1\n # the final output group\n groupi = []\n # loop over the generators\n for i in gen:\n # a second set of generators used to ensure that a group\n # action doesn't act an its self\n gen2 = [] \n # if k is not the ith element of the generators add it to the\n # set gen2\n for k in gen:\n if k != i:\n gen2.append(k)\n # loop over all except the ith generator\n for j in gen2:\n # handle the site group and arrow group independently\n trans = [j[0][i[0][l]] for l in range(0,len(i[0]))]\n rots = [j[1][i[1][l]] for l in range(0,len(i[1]))]\n # c is the combination of the trans and rots, if it's not\n # in groupi then it should be added.\n c = [trans,rots]\n if c not in groupi:\n groupi.append(c)\n\n # for each new group element, c, we should also see if\n # the ith group element acting on it will make another\n # new group element.\n trans = [c[0][i[0][l]] for l in range(0,len(i[0]))]\n rots = [c[1][i[1][l]] for l in range(0,len(i[1]))]\n # d is the group action after the ith element has acted on\n # c, if it's not in groupi then add it.\n d = [trans, rots]\n if d not in groupi:\n groupi.append(d)\n # until d and c are the same again we want to apply the\n # ith group element to d so that we've found all possible\n # group elements for the combination\n while d != c:\n trans = [d[0][i[0][l]] for l in range(0,len(i[0]))]\n rots = [d[1][i[1][l]] for l in range(0,len(i[1]))]\n d = [trans,rots]\n # increment q because we found a new group element\n q += 1\n # every time d is not in group i add it\n if d not in groupi:\n groupi.append(d)\n # new is a tracker that is 0 while we are still finding new group\n # elements and 1 when no new ones are found\n new = 0\n\n #Here each generator is applied to the group over and over until no new group\n #elements are found\n while new == 0:\n # a second set to store any additional group elements\n group2 = []\n for i in gen:\n for h in groupi:\n # apply the ith generator to the hth element of groupi\n # from above to search for new group elements\n trans = [h[0][i[0][l]] for l in range(0,len(i[0]))]\n rots = [h[1][i[1][l]] for l in range(0,len(i[1]))]\n \n d = [trans,rots]\n # if do isn't in groupi or in group2 then add it to\n # group2\n if d not in groupi and d not in group2:\n group2.append(d)\n # add anything that is in group2 to groupi\n if len(group2) > 0:\n groupi.extend(group2)\n else:\n # if no new group elements were found then we'v found the\n # whole group and new is set to 1\n new = 1\n \n return(groupi)\n\ndef get_full_HNF(HNF):\n \"\"\"Turns the reduced HNF to a full HNF matrix.\n\n Args:\n HNF (list): The 1D array that contains all the lower\n diagonal entries of the HNF matrix.\n\n Returns:\n full_hnf (list of list): A 2D list containing the HNF matrix.\n \"\"\"\n\n if type(HNF).__module__ == np.__name__:\n temp_hnf = HNF.tolist()\n else:\n temp_hnf = HNF\n full_hnf = [[temp_hnf[0],0,0],[temp_hnf[1],temp_hnf[2],0],temp_hnf[3:]]\n\n return full_hnf\n\ndef _rm_3D_operations(aVecs,sgrots,sgshifts,eps):\n \"\"\"This subroutine removes operations that are 3 dimmensional.\n\n Args:\n aVecs (list): The 2D array of the primitive real space lattice vectors.\n sgrots (list): The 3D array containing the space group rotations.\n sgshifts (list): The 2D array containing the space group shifts.\n eps (float): Finite precisions tolerance.\n\n Returns:\n t_sg_rots (list): The 3D array of the surface rotations.\n t_sg_shifts (list): The 2D array of the surface translations.\n \n Raises:\n ValueError: if the input vectors aren't primitive.\n \"\"\"\n \n if not np.allclose(\n aVecs[0][1:3],0.0,rtol=0, atol=eps) or not np.allclose(aVecs[2][0:2]\n ,0.0,rtol=0,atol=eps):\n raise ValueError(\"Error in rm_3d_operations: only allowed for primitive vectors x00,0xx,0xx\")\n \n n_rot = len(sgrots)\n irot = 0\n t_sg_rots = []\n t_sg_shifts = []\n for i in range(n_rot):\n if (np.allclose(sgrots[i][0][1:3],0.0,rtol=0,atol=eps) and\n np.allclose([sgrots[i][1][0],sgrots[i][2][0]],0.0,rtol=0,atol=eps)\n and np.allclose(abs(sgrots[i][0][0]),1.0,rtol=0,atol=eps)):\n # this operation is \"2D\" \n irot += 1\n t_sg_rots.append(sgrots[i])\n t_sg_shifts.append(sgshifts[i])\n\n return(t_sg_rots,t_sg_shifts)\n"
]
| [
[
"numpy.array",
"numpy.dot",
"numpy.count_nonzero",
"numpy.matmul",
"numpy.zeros",
"numpy.reshape",
"numpy.round",
"numpy.linalg.det",
"numpy.allclose",
"numpy.transpose",
"numpy.linalg.inv"
]
]
|
LuanAGoncalves/pytorch-ssd | [
"37804052d04ff588c76818e862123d1d8cca1bde"
]
| [
"vision/ssd/ssd.py"
]
| [
"import torch.nn as nn\nimport torch\nimport numpy as np\nfrom typing import List, Tuple\nimport torch.nn.functional as F\n\nfrom ..utils import box_utils\nfrom collections import namedtuple\n\nGraphPath = namedtuple(\"GraphPath\", [\"s0\", \"name\", \"s1\"]) #\n\n\nclass SSD(nn.Module):\n def __init__(\n self,\n num_classes: int,\n base_net: nn.ModuleList,\n source_layer_indexes: List[int],\n extras: nn.ModuleList,\n classification_headers: nn.ModuleList,\n regression_headers: nn.ModuleList,\n is_test=False,\n config=None,\n device=None,\n ):\n \"\"\"Compose a SSD model using the given components.\n \"\"\"\n super(SSD, self).__init__()\n\n self.num_classes = num_classes\n self.base_net = base_net\n self.source_layer_indexes = source_layer_indexes\n self.extras = extras\n self.classification_headers = classification_headers\n self.regression_headers = regression_headers\n self.is_test = is_test\n self.config = config\n\n # register layers in source_layer_indexes by adding them to a module list\n self.source_layer_add_ons = nn.ModuleList(\n [\n t[1]\n for t in source_layer_indexes\n if isinstance(t, tuple) and not isinstance(t, GraphPath)\n ]\n )\n if device:\n self.device = device\n else:\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n if is_test:\n self.config = config\n self.priors = config.priors.to(self.device)\n\n def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n confidences = []\n locations = []\n start_layer_index = 0\n header_index = 0\n for end_layer_index in self.source_layer_indexes:\n if isinstance(end_layer_index, GraphPath):\n path = end_layer_index\n end_layer_index = end_layer_index.s0\n added_layer = None\n elif isinstance(end_layer_index, tuple):\n added_layer = end_layer_index[1]\n end_layer_index = end_layer_index[0]\n path = None\n else:\n added_layer = None\n path = None\n for layer in self.base_net[start_layer_index:end_layer_index]:\n x = layer(x)\n if added_layer:\n y = added_layer(x)\n else:\n y = x\n if path:\n sub = getattr(self.base_net[end_layer_index], path.name)\n for layer in sub[: path.s1]:\n x = layer(x)\n y = x\n for layer in sub[path.s1 :]:\n x = layer(x)\n end_layer_index += 1\n start_layer_index = end_layer_index\n confidence, location = self.compute_header(header_index, y)\n header_index += 1\n confidences.append(confidence)\n locations.append(location)\n\n for layer in self.base_net[end_layer_index:]:\n x = layer(x)\n\n for layer in self.extras:\n x = layer(x)\n confidence, location = self.compute_header(header_index, x)\n header_index += 1\n confidences.append(confidence)\n locations.append(location)\n\n confidences = torch.cat(confidences, 1)\n locations = torch.cat(locations, 1)\n\n if self.is_test:\n confidences = F.softmax(confidences, dim=2)\n boxes = box_utils.convert_locations_to_boxes(\n locations,\n self.priors,\n self.config.center_variance,\n self.config.size_variance,\n )\n boxes = box_utils.center_form_to_corner_form(boxes)\n return confidences, boxes\n else:\n return confidences, locations\n\n def compute_header(self, i, x):\n confidence = self.classification_headers[i](x)\n confidence = confidence.permute(0, 2, 3, 1).contiguous()\n confidence = confidence.view(confidence.size(0), -1, self.num_classes)\n\n location = self.regression_headers[i](x)\n location = location.permute(0, 2, 3, 1).contiguous()\n location = location.view(location.size(0), -1, 4)\n\n return confidence, location\n\n def init_from_base_net(self, model):\n self.base_net.load_state_dict(\n torch.load(model, map_location=lambda storage, loc: storage), strict=True\n )\n self.source_layer_add_ons.apply(_xavier_init_)\n self.extras.apply(_xavier_init_)\n self.classification_headers.apply(_xavier_init_)\n self.regression_headers.apply(_xavier_init_)\n\n def init_from_pretrained_ssd(self, model):\n state_dict = torch.load(model, map_location=lambda storage, loc: storage)\n state_dict = {\n k: v\n for k, v in state_dict.items()\n if not (\n k.startswith(\"classification_headers\")\n or k.startswith(\"regression_headers\")\n )\n }\n model_dict = self.state_dict()\n model_dict.update(state_dict)\n self.load_state_dict(model_dict)\n self.classification_headers.apply(_xavier_init_)\n self.regression_headers.apply(_xavier_init_)\n\n def init(self):\n self.base_net.apply(_xavier_init_)\n self.source_layer_add_ons.apply(_xavier_init_)\n self.extras.apply(_xavier_init_)\n self.classification_headers.apply(_xavier_init_)\n self.regression_headers.apply(_xavier_init_)\n\n def load(self, model):\n self.load_state_dict(\n torch.load(model, map_location=lambda storage, loc: storage)\n )\n\n def save(self, model_path):\n torch.save(self.state_dict(), model_path)\n\n\nclass MatchPrior(object):\n def __init__(\n self, center_form_priors, center_variance, size_variance, iou_threshold\n ):\n self.center_form_priors = center_form_priors\n self.corner_form_priors = box_utils.center_form_to_corner_form(\n center_form_priors\n )\n self.center_variance = center_variance\n self.size_variance = size_variance\n self.iou_threshold = iou_threshold\n\n def __call__(self, gt_boxes, gt_labels):\n if type(gt_boxes) is np.ndarray:\n gt_boxes = torch.from_numpy(gt_boxes)\n if type(gt_labels) is np.ndarray:\n gt_labels = torch.from_numpy(gt_labels)\n boxes, labels = box_utils.assign_priors(\n gt_boxes, gt_labels, self.corner_form_priors, self.iou_threshold\n )\n boxes = box_utils.corner_form_to_center_form(boxes)\n locations = box_utils.convert_boxes_to_locations(\n boxes, self.center_form_priors, self.center_variance, self.size_variance\n )\n return locations, labels\n\n\ndef _xavier_init_(m: nn.Module):\n if isinstance(m, nn.Conv2d):\n nn.init.xavier_uniform_(m.weight)\n"
]
| [
[
"torch.cat",
"torch.nn.init.xavier_uniform_",
"torch.from_numpy",
"torch.cuda.is_available",
"torch.load",
"torch.nn.functional.softmax"
]
]
|
idc9/mvmm | [
"64fce755a7cd53be9b08278484c7a4c77daf38d1"
]
| [
"mvmm/multi_view/LogPenMVMM.py"
]
| [
"import numpy as np\nfrom warnings import warn\nfrom copy import deepcopy\nfrom textwrap import dedent\n\nfrom mvmm.base import _em_docs\nfrom mvmm.multi_view.MaskedMVMM import MaskedMVMM\n\n\nclass LogPenMVMM(MaskedMVMM):\n\n def __init__(self,\n pen=None,\n delta=1e-6,\n base_view_models=None,\n max_n_steps=200,\n abs_tol=1e-9,\n rel_tol=None,\n n_init=1,\n init_params_method='init',\n init_params_value=None,\n init_weights_method='uniform',\n init_weights_value=None,\n random_state=None,\n verbosity=0,\n history_tracking=0):\n\n super().__init__(base_view_models=base_view_models,\n max_n_steps=max_n_steps,\n abs_tol=abs_tol,\n rel_tol=rel_tol,\n n_init=n_init,\n init_params_method=init_params_method,\n init_params_value=init_params_value,\n init_weights_method=init_weights_method,\n init_weights_value=init_weights_value,\n random_state=random_state,\n verbosity=verbosity,\n history_tracking=history_tracking)\n\n self.pen = pen\n self.delta = delta\n\n def _m_step_weights(self, X, log_resp):\n \"\"\"\n M step for the cluster membership weights.\n\n log_resp : array-like, shape (n_samples, n_components)\n Logarithm of the posterior probabilities (or responsibilities) of\n the point of each sample in X.\n \"\"\"\n\n n_samples = log_resp.shape[0]\n resp = np.exp(log_resp)\n nk = resp.sum(axis=0) + 10 * np.finfo(resp.dtype).eps\n a = nk / n_samples # normalize so sum(a) == 1\n\n if self.pen is None:\n return a\n\n # compute soft thresholding operation\n a_thresh, idxs_dropped = soft_thresh(a, pen=self.pen)\n\n # if all entries are dropped then set largest entry to 0\n if len(idxs_dropped) == len(a):\n idx_max = np.argmax(a)\n a_thresh[idx_max] = 1.0\n idxs_dropped = np.delete(idxs_dropped, idx_max)\n\n warn('Soft-thresholding attempting to drop every component.'\n 'Retaining component with largest weight.')\n\n # TODO: this violates setting the parameters using\n # _set_parameters() -- need to figure out what to do with\n # drop_component e.g. make drop_component return the new zero mask\n\n # set weights to soft-thresholded values\n # self.weights_ = a_thresh\n\n # drop any components which got zeroed out\n # if len(idxs_dropped) > 0:\n # self.drop_component(idxs_dropped)\n\n return a_thresh\n\n def compute_tracking_data(self, X, E_out):\n\n out = {}\n\n if 'obs_nll' in E_out.keys():\n out['obs_nll'] = E_out['obs_nll']\n else:\n out['obs_nll'] = - self.score(X)\n\n out['n_zeroed_comps'] = deepcopy(self.n_zeroed_comps_)\n\n if self.pen is not None:\n out['log_pen'] = self.pen * \\\n (np.log(self.delta + self.weights_).sum() +\n np.log(self.delta) * self.n_zeroed_comps_)\n else:\n out['log_pen'] = 0\n\n out['loss_val'] = out['obs_nll'] + out['log_pen']\n\n # maybe track model history\n if self.history_tracking >= 2:\n out['model'] = deepcopy(self._get_parameters())\n\n return out\n\n\nLogPenMVMM.__doc__ = dedent(\"\"\"\\\nLog penalized multi-view mixture model fit using an EM algorithm.\n\nParameters\n----------\npen: float\n Penalty value.\n\ndelta: float\n Delta value for penalty -- only used for stopping criterion.\n\nbase_view_models: list of mixture models\n Mixture models for each view. These should specify the number of view components.\n\n{em_param_docs}\n\nAttributes\n----------\nweights_\n\nweights_mat_\n\nzero_mask_\n\nmetadata_\n\n\"\"\".format(**_em_docs))\n\n\ndef soft_thresh(a, pen):\n \"\"\"\n Computes soft-thresholding operation approximation of log(pi_k + epsilon) penalty.\n\n a_thresh = max(0, a - pen)\n\n if epsilon is not None:\n a_thresh[zeroed_entries] = epsilon\n\n a_thresh = noralize(a_thresh)\n\n\n Parameters\n ----------\n a: array-like, (n_components, )\n The coefficient values.\n\n pen: float\n The soft-thresholding parameter.\n\n\n Output\n ------\n a_thresh, idxs_dropped\n\n a_thresh: array-like, (n_components, )\n The thresholded coefficient values\n\n idxs_dropped: array-like\n List of indices set to zero.\n \"\"\"\n a = np.array(a)\n\n # which components will be dropped\n drop_mask = a <= pen\n\n if np.mean(drop_mask) == 1:\n raise warn('Soft-thresholding dropping all components')\n\n # soft threshold entries of a\n a_soft_thresh = np.clip(a - pen, a_min=0, a_max=None)\n\n # normalize\n tot = a_soft_thresh.sum()\n a_soft_thresh = a_soft_thresh / tot\n\n drop_idxs = np.where(drop_mask)[0]\n return a_soft_thresh, drop_idxs\n"
]
| [
[
"numpy.array",
"numpy.delete",
"numpy.log",
"numpy.exp",
"numpy.mean",
"numpy.where",
"numpy.finfo",
"numpy.argmax",
"numpy.clip"
]
]
|
WalterZWang/AlphaBuilding-MedOffice | [
"744a68c4f3591f38b83fc08d81929d8ff6b1274d"
]
| [
"gym_AlphaBuilding/fmuModel/test_fmu.py"
]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nTest the FMU using the rule based control.\n\nThe results are stored in pandas dataframe\n\n@author: walter\n\"\"\"\n\nfrom pyfmi import load_fmu\nimport numpy as np\nimport pylab as plt\nimport pandas as pd\n\n\ndef terminal_sat(T_room, T_set=22):\n '''\n A simple controller for hvac input heat\n\n '''\n if T_room - T_set > 1.5:\n T_sa = T_set-10\n elif T_room - T_set > 1.2:\n T_sa = T_set-6\n elif T_room - T_set > 0.8:\n T_sa = T_set-3\n elif T_room - T_set < -1.8:\n T_sa = T_set+10\n elif T_room - T_set < -1.3:\n T_sa = T_set+6\n elif T_room - T_set < -0.8:\n T_sa = T_set+3\n else:\n T_sa = T_set-1\n\n return T_sa\n\n\ndef ahu_sat(T_mean, T_set=22):\n # lower supply air to avoid overheating as no cooling in terminal\n return terminal_sat(T_mean)-2\n\n\ndef reheat(ahuSAT, T_sa, FR=0.1):\n reheat = 1004*max(0, T_sa-ahuSAT)*FR\n return reheat\n\n\ndef define_IO():\n # define model inputs and outputs\n '''\n actions:\n ahuSAT: AHU supply air (to room) temperature, [degC]\n *FR: terminal flow rate, [kg/s]\n *Reheat: terminal reheat, [W]\n '''\n actions = ['ahuSAT',\n 'conf1FR', 'conf1Reheat', 'conf2FR', 'conf2Reheat',\n 'enOff1FR', 'enOff1Reheat', 'enOff2FR', 'enOff2Reheat', 'enOff3FR', 'enOff3Reheat',\n 'opOff1FR', 'opOff1Reheat', 'opOff2FR', 'opOff2Reheat', 'opOff3FR', 'opOff3Reheat', 'opOff4FR', 'opOff4Reheat']\n\n '''\n\tstates:\n\t\tstates_amb: ambient temperature\n\t\tstates_temp: temperature of controlled rooms\n\t\tstates_energy: fan, cooling and heating energy consumption\n '''\n states_amb = ['outTemp', 'outSolar', 'outRH']\n states_temp = ['conf1Temp', 'conf2Temp', 'enOff1Temp', 'enOff2Temp', 'enOff3Temp',\n 'opOff1Temp', 'opOff2Temp', 'opOff3Temp', 'opOff4Temp']\n states_energy = ['fanEnergy', 'coolEnergy', 'heatEnergy']\n\n # create pandas dataframe to save the result\n res = pd.DataFrame(columns=actions+states_amb+states_temp +\n states_energy+['aveTemp', 'totalEnergy'])\n return actions, states_amb, states_temp, states_energy, res\n\n\ndef FMU_simulate(eplus_path, sim_days=365, with_plots=True, save_res=True):\n '''\n\n '''\n # Create a simulation time grid\n tStart = 0\n tStop = 900*4*24*sim_days\n hStep = 900 # 15 min\n t = np.arange(tStart, tStop, hStep)\n n_steps = len(t)\n\n # Load FMUs\n envelope = load_fmu(eplus_path, kind='cs', log_level=7)\n\n # initialize models\n envelope.initialize(tStart, tStop)\n actions, states_amb, states_temp, states_energy, res = define_IO()\n states = states_amb+states_temp+states_energy\n\n # initial the counter and heat input\n i = 0\n action_ini = [20,\n 0.1, 0, 0.1, 0,\n 0.1, 0, 0.1, 0, 0.1, 0,\n 0.1, 0, 0.1, 0, 0.1, 0, 0.1, 0]\n res.loc[i, actions] = action_ini\n\n # Main simulation loop\n while i < n_steps:\n # model the envelope\n envelope.set(actions, res.loc[i, actions].values)\n # Do one step of simulation\n envelope.do_step(current_t=t[i], step_size=hStep, new_step=True)\n # Get the outputs of the simulation\n res.loc[i, states] = envelope.get(states)\n\n # net power consumption\n res.loc[i, 'aveTemp'] = res.loc[i, states_temp].mean()\n res.loc[i, 'totalEnergy'] = res.loc[i, states_energy].sum()\n\n # Calculate the input for the next step\n # Interface for RL controller\n control = []\n control_ahuSAT = ahu_sat(res.loc[i, 'aveTemp'])\n control.append(control_ahuSAT)\n\n for Temp in res.loc[i, states_temp]:\n temp = Temp[0] # get the value from the list\n terminal_fr = 0.1\n terminal_t = terminal_sat(temp, T_set=22)\n terminal_reheat = reheat(control_ahuSAT, terminal_t, terminal_fr)\n control.append(terminal_fr)\n control.append(terminal_reheat)\n\n res.loc[i+1, actions] = control\n # print the result\n print('Time {0}: mean zone temp is {1}, AHU SAT is {2}, total energy consumption is {3}'.format(\n t[i], res.loc[i, 'aveTemp'], res.loc[i, 'ahuSAT'], res.loc[i, 'totalEnergy']))\n i += 1\n # delete last timestamp which only has inputs, outputs are na\n res.dropna(inplace=True)\n\n if save_res:\n time = pd.date_range(\n start='1/1/2015', periods=n_steps, freq='15min').values\n res.reindex(time)\n res.to_csv('result.csv')\n\n if with_plots:\n f, axarr = plt.subplots(3)\n axarr[0].plot(time, res.aveTemp)\n axarr[0].set_ylabel('Mean zone temp')\n axarr[1].plot(time, res.ahuSAT)\n axarr[1].set_ylabel('AHU SAT')\n axarr[2].plot(time, res.totalEnergy)\n axarr[2].set_ylabel('Total Energy')\n plt.show()\n\n\nif __name__ == '__main__':\n envelope_path = 'fmuModel/v1_fmu.fmu'\n sim_days = 2 # number of simulation days\n FMU_simulate(envelope_path, sim_days, with_plots=False, save_res=True)\n"
]
| [
[
"pandas.DataFrame",
"pandas.date_range",
"numpy.arange"
]
]
|
chongzhou96/maskrcnn-benchmark | [
"f88e33e930390c9b961ebadf510e5ca80620af6f"
]
| [
"maskrcnn_benchmark/utils/visualize.py"
]
| [
"from visdom import Visdom\nimport numpy as np\nimport logging\n\nclass Visualizer(object):\n\n def __init__(self, loss_keys, env, port, hostname, loss_log_dict=None):\n logger = logging.getLogger(\"maskrcnn_benchmark.visualize\")\n logger.info('Launching visdom server ...')\n\n self.viz = Visdom(env=env, port=port, server=hostname)\n assert self.viz.check_connection(timeout_seconds=3), \\\n 'No connection could be formed quickly'\n\n self.title = env\n self.loss_keys = loss_keys\n self.colors, self.lines = self._get_loss_line_attribute(len(loss_keys))\n if loss_log_dict is None:\n self.loss_log_dict = {}\n else:\n self.loss_log_dict = loss_log_dict\n\n def _get_loss_line_attribute(self, cnt):\n COLORS = [[244, 67, 54],\n [233, 30, 99],\n [156, 39, 17],\n [103, 58, 183],\n [ 63, 81, 181],\n [ 33, 150, 243],\n [ 3, 169, 244],\n [ 0, 188, 212],\n [ 0, 150, 136],\n [ 76, 175, 80],\n [139, 195, 74],\n [205, 220, 57],\n [255, 235, 59],\n [255, 193, 7],\n [255, 152, 0],\n [255, 87, 34]]\n LINES = ['solid', 'dash', 'dashdot']\n\n assert cnt < len(COLORS)\n\n colors = [COLORS[i] for i in range(0, cnt)]\n lines = [LINES[i%3] for i in range(0, cnt)]\n\n return np.array(colors), np.array(lines)\n\n def _moving_average(self, data, window=40):\n if len(data) < 2*window:\n return data\n ret = np.cumsum(data, dtype=float)\n ret[window:] = ret[window:] - ret[:-window]\n return ret[window-1:] / window\n\n def add_data_point(self, loss_dict_reduced):\n X = []\n Y = []\n for key in self.loss_keys:\n if key not in self.loss_log_dict:\n self.loss_log_dict[key] = []\n self.loss_log_dict[key].append(loss_dict_reduced[key].item())\n y = self._moving_average(self.loss_log_dict[key])\n x = np.arange(0, len(y))\n X.append(x)\n Y.append(y)\n\n self.viz.line(\n X=np.array(X).transpose(1,0),\n Y=np.array(Y).transpose(1,0),\n opts={\n 'dash': self.lines,\n 'linecolor': self.colors,\n 'legend': self.loss_keys,\n 'title': self.title + ' training losses'\n },\n win = 1,\n )\n \n def get_loss_log_dict(self):\n return self.loss_log_dict\n"
]
| [
[
"numpy.array",
"numpy.cumsum"
]
]
|
Sam-Armstrong/PyTorch-Practice | [
"f5bca54579d3e023519ce505054b88fc118818ea"
]
| [
"Circular/CifarFFCircular.py"
]
| [
"\"\"\"\nUses the pre-training circular model to train a single-layer perceptron for classifying MNIST digits.\n\"\"\"\n\nimport torch.nn as nn\nimport torch\nimport torch.optim as optim\nfrom torchvision import datasets\nfrom torchvision.transforms import ToTensor\nfrom torch.utils.data import DataLoader, random_split\nimport time\nimport torch.optim.lr_scheduler as lr_s\nfrom CifarCircular import CifarCircular\n\nclass CifarFFCircular(nn.Module):\n def __init__(self):\n super(CifarFFCircular, self).__init__()\n\n self.dropout = nn.Dropout(p = 0.5)\n\n self.fc = nn.Linear(10000, 10)\n #self.fc2 = nn.Linear(1200, 400)\n #self.fc3 = nn.Linear(400, 10)\n\n self.bn7 = nn.BatchNorm1d(1200)\n self.bn8 = nn.BatchNorm1d(400)\n\n self.softmax = nn.Softmax(dim = -1)\n self.gelu = nn.GELU()\n\n model = CifarCircular()\n model.load_state_dict(torch.load('cifar-circular.pickle'))\n model.eval()\n\n self.bn1 = model.bn1\n self.bn2 = model.bn2\n self.bn3 = model.bn3\n self.bn4 = model.bn4\n\n self.conv1 = model.conv1\n self.conv2 = model.conv2\n self.conv3 = model.conv3\n self.conv4 = model.conv4\n self.conv10 = model.conv10\n self.conv11 = model.conv11\n\n self.fc1 = model.fc1\n self.fc2 = model.fc2\n self.fc3 = model.fc3\n\n self.pooling = model.pooling\n \n\n def forward(self, x):\n x = self.conv1(x)\n x = self.gelu(x)\n\n x = self.conv2(x)\n x = self.gelu(x)\n\n x = self.pooling(x)\n\n x = self.conv3(x)\n x = self.gelu(x)\n\n x = self.conv4(x)\n x = self.gelu(x)\n\n x = x.reshape(x.shape[0], -1)\n\n x = self.fc1(x)\n x = self.gelu(x)\n x = self.bn1(x)\n\n x = self.fc2(x)\n x = self.gelu(x)\n x = self.bn2(x)\n\n x = self.fc3(x)\n x = self.gelu(x)\n x = self.bn3(x)\n\n x = x.reshape(x.shape[0], -1)\n\n x = self.fc(x)\n x = self.softmax(x)\n\n return x\n\nstart_time = time.time()\n\nnum_epochs = 20\ndevice = torch.device('cuda')\n\n# Loads the train and test data into PyTorch tensors\ntraining_data = datasets.CIFAR10(root = \"data\", train = True, download = True, transform = ToTensor())\ntest_data = datasets.CIFAR10(root = \"data\", train = False, download = True, transform = ToTensor())\n\ntraining_data, validation_set = random_split(training_data, [45000, 5000])\n\n# Loads the data into batches\ntrain_dataloader = DataLoader(training_data, batch_size = 500, shuffle = True)\nvalid_dataloader = DataLoader(validation_set, batch_size = 500, shuffle = True)\ntest_dataloader = DataLoader(test_data, batch_size = 500, shuffle = True)\n\n\nmodel = CifarFFCircular().to(device)\n\ntrainable_shapes = [torch.Size([10, 10000]), torch.Size([10])]\n\n# Prevents additional training or pre-trained layers\nfor param in model.parameters():\n if param.shape in trainable_shapes:\n pass\n else:\n param.requires_grad = False\n\nloss_f = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr = 0.000003, weight_decay = 0)\nscheduler = lr_s.ReduceLROnPlateau(optimizer, 'min', patience = 3)\n\nold_loss = 10000\ntimes_worse = 0\n\nfor epoch in range(num_epochs):\n print('Epoch: ', epoch)\n train_loss = 0.0\n\n for batch_idx, (data, labels) in enumerate(train_dataloader):\n #print(batch_idx)\n #print(model.fc4.weight)\n\n data = data.to(device = device)\n labels = labels.to(device = device)\n\n scores = model(data) # Runs a forward pass of the model for all the data\n loss = loss_f(scores, labels) # Calculates the loss of the forward pass using the loss function\n train_loss += loss\n\n optimizer.zero_grad() # Resets the optimizer gradients to zero for each batch\n loss.backward() # Backpropagates the network using the loss to calculate the local gradients\n\n optimizer.step() # Updates the network weights and biases\n\n\n valid_loss = 0.0\n model.eval()\n for data, labels in valid_dataloader:\n if torch.cuda.is_available():\n data, labels = data.cuda(), labels.cuda()\n \n target = model(data)\n loss = loss_f(target,labels)\n valid_loss = loss.item() * data.size(0)\n\n scheduler.step(valid_loss)\n print('Validation Loss: ', valid_loss)\n\n if valid_loss >= old_loss:\n times_worse += 1\n else:\n times_worse = 0\n\n\n if times_worse >= 3:\n print('Reducing learning rate.')\n\n if times_worse >= 6:\n print('Stopping early.')\n start_time = time.time()\n break\n\n old_loss = valid_loss\n\n\n# Checks the performance of the model on the test set\ndef check_accuracy(loader, model):\n num_correct = 0\n num_samples = 0\n model.eval()\n\n with torch.no_grad():\n for x, y in loader:\n x = x.to(device = device)\n y = y.to(device = device)\n #x = x.reshape(x.shape[0], -1)\n\n scores = model(x)\n _, predictions = scores.max(1)\n num_correct += (predictions == y).sum()\n num_samples += predictions.size(0)\n\n print((num_correct * 100 / num_samples).item(), '% Correct')\n\nprint('\\n')\ncheck_accuracy(test_dataloader, model)\n\nprint('Finished in %s seconds' % round(time.time() - start_time, 1))"
]
| [
[
"torch.Size",
"torch.device",
"torch.nn.Dropout",
"torch.nn.Linear",
"torch.nn.Softmax",
"torch.utils.data.random_split",
"torch.no_grad",
"torch.nn.BatchNorm1d",
"torch.cuda.is_available",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.utils.data.DataLoader",
"torch.load",
"torch.nn.GELU",
"torch.nn.CrossEntropyLoss"
]
]
|
r4tn3sh/MIMO_detection | [
"3bfe80c4c3d7e6cfef4510b6e81683d987dc14ac"
]
| [
"src/channels.py"
]
| [
"import os\nimport math\nimport numpy as np\nfrom scipy import linalg\nfrom mimoclasses import Channel\n\n# ---------- CHANNEL ------------\ndef awgnChannel(x,N0):\n \"\"\"\n Generates the AWGN channel\n Input parameters\n - Signal x (should be avg unit power)\n - Noise variance N0\n Other parameters\n - Thermal noise = -174dBm/Hz\n - Variance N0/2 per real symbol\n \"\"\"\n N0_r = np.random.normal(0, N0/2, x.shape)\n N0_i = np.random.normal(0, N0/2, x.shape)\n return (x+N0_r+1j*N0_i)\n\n\ndef generateChMatrix(Nr,Nt,chtype):\n # Current threshold for good/bad condition number\n cond_num_thr = 5\n\n # Condition number based channel will not make sense for Nr=Nt=1\n # since the condition number is always 1\n if Nr==1 and Nt==1:\n if chtype > Channel.RAND_UNIT:\n chtype = Channel.RAND_UNIT\n\n # TODO: support different channel models in future.\n if chtype == Channel.NONE:\n if Nr==Nt:\n H_r = np.identity(Nr)\n H_i = np.zeros((Nr,Nt))\n else:\n raise ValueError('For channel type-'+str(chtype)+', Nr=Nt is needed.')\n return -1\n elif chtype == Channel.RAND_UNIT:\n # Using complex gaussian random variable\n # Real and Img part: mean = 0, variance = 1\n H_r = np.random.normal(0, 1, size=(Nr,Nt))\n H_i = np.random.normal(0, 1, size=(Nr,Nt))\n elif chtype == Channel.RAND_UNIT_GOOD:\n cond_num = cond_num_thr + 1\n while cond_num > cond_num_thr:\n # Using complex gaussian random variable\n # Real and Img part: mean = 0, variance = 1\n H_r = np.random.normal(0, 1, size=(Nr,Nt))\n H_i = np.random.normal(0, 1, size=(Nr,Nt))\n cond_num = np.linalg.cond(np.asmatrix((H_r + 1j*H_i)))\n elif chtype == Channel.RAND_UNIT_BAD:\n cond_num = 0\n while cond_num < cond_num_thr:\n # Using complex gaussian random variable\n # Real and Img part: mean = 0, variance = 1\n H_r = np.random.normal(0, 1, size=(Nr,Nt))\n H_i = np.random.normal(0, 1, size=(Nr,Nt))\n cond_num = np.linalg.cond(np.asmatrix((H_r + 1j*H_i)))\n else:\n raise ValueError('Channel type-'+str(chtype)+' is not supported.')\n return -1\n\n cond_num = np.linalg.cond(np.asmatrix((H_r + 1j*H_i)))\n print('Condition number of the generated channel: '+str(cond_num))\n return np.asmatrix((H_r + 1j*H_i))\n"
]
| [
[
"numpy.identity",
"numpy.random.normal",
"numpy.zeros",
"numpy.asmatrix"
]
]
|
jjjjamess/GFPGAN-1 | [
"2226e7297f2492270be59e2bc29bcecddad9633c"
]
| [
"myapp.py"
]
| [
"import io\nimport json\nimport argparse\nimport cv2\nimport glob\nimport numpy as np\nimport os\nfrom basicsr.utils import imwrite\n\nfrom gfpgan import GFPGANer\n\nimport torch\nimport torchvision.transforms as transforms\nfrom PIL import Image\nfrom flask import Flask, jsonify, request\n\nUPLOAD_FOLDER = 'upload'\n\napp = Flask(__name__)\n\nmodel = torch.load('GFPGANCleanv1-NoCE-C2.pth')\n\[email protected]('/main', methods=['POST'])\ndef main(args):\n \"\"\"Inference demo for GFPGAN.\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--upscale', type=int, default=2, help='The final upsampling scale of the image')\n parser.add_argument('--arch', type=str, default='clean', help='The GFPGAN architecture. Option: clean | original')\n parser.add_argument('--channel', type=int, default=2, help='Channel multiplier for large networks of StyleGAN2')\n parser.add_argument('--model_path', type=str, default='experiments/pretrained_models/GFPGANCleanv1-NoCE-C2.pth')\n parser.add_argument('--bg_upsampler', type=str, default='realesrgan', help='background upsampler')\n parser.add_argument(\n '--bg_tile', type=int, default=400, help='Tile size for background sampler, 0 for no tile during testing')\n parser.add_argument('--test_path', type=str, default='upload/', help='Input folder')\n parser.add_argument('--suffix', type=str, default=None, help='Suffix of the restored faces')\n parser.add_argument('--only_center_face', action='store_true', help='Only restore the center face')\n parser.add_argument('--aligned', action='store_true', help='Input are aligned faces')\n parser.add_argument('--paste_back', action='store_false', help='Paste the restored faces back to images')\n parser.add_argument('--save_root', type=str, default='results', help='Path to save root')\n parser.add_argument(\n '--ext',\n type=str,\n default='auto',\n help='Image extension. Options: auto | jpg | png, auto means using the same extension as inputs')\n args = parser.parse_args()\n\n args = parser.parse_args()\n if args.test_path.endswith('/'):\n args.test_path = args.test_path[:-1]\n os.makedirs(args.save_root, exist_ok=True)\n\n # background upsampler\n if args.bg_upsampler == 'realesrgan':\n if not torch.cuda.is_available(): # CPU\n import warnings\n warnings.warn('The unoptimized RealESRGAN is very slow on CPU. We do not use it. '\n 'If you really want to use it, please modify the corresponding codes.')\n bg_upsampler = None\n else:\n from realesrgan import RealESRGANer\n bg_upsampler = RealESRGANer(\n scale=2,\n model_path='https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth',\n tile=args.bg_tile,\n tile_pad=10,\n pre_pad=0,\n half=True) # need to set False in CPU mode\n else:\n bg_upsampler = None\n # set up GFPGAN restorer\n restorer = GFPGANer(\n model_path=args.model_path,\n upscale=args.upscale,\n arch=args.arch,\n channel_multiplier=args.channel,\n bg_upsampler=bg_upsampler)\n\n img_list = sorted(glob.glob(os.path.join(args.test_path, '*')))\n for img_path in img_list:\n # read image\n img_name = os.path.basename(img_path)\n print(f'Processing {img_name} ...')\n basename, ext = os.path.splitext(img_name)\n input_img = cv2.imread(img_path, cv2.IMREAD_COLOR)\n\n # restore faces and background if necessary\n cropped_faces, restored_faces, restored_img = restorer.enhance(\n input_img, has_aligned=args.aligned, only_center_face=args.only_center_face, paste_back=args.paste_back)\n\n # save faces\n for idx, (cropped_face, restored_face) in enumerate(zip(cropped_faces, restored_faces)):\n # save cropped face\n save_crop_path = os.path.join(args.save_root, 'cropped_faces', f'{basename}_{idx:02d}.png')\n imwrite(cropped_face, save_crop_path)\n # save restored face\n if args.suffix is not None:\n save_face_name = f'{basename}_{idx:02d}_{args.suffix}.png'\n else:\n save_face_name = f'{basename}_{idx:02d}.png'\n save_restore_path = os.path.join(args.save_root, 'restored_faces', save_face_name)\n imwrite(restored_face, save_restore_path)\n # save comparison image\n cmp_img = np.concatenate((cropped_face, restored_face), axis=1)\n imwrite(cmp_img, os.path.join(args.save_root, 'cmp', f'{basename}_{idx:02d}.png'))\n\n # save restored img\n if restored_img is not None:\n if args.ext == 'auto':\n extension = ext[1:]\n else:\n extension = args.ext\n\n if args.suffix is not None:\n save_restore_path = os.path.join(args.save_root, 'restored_imgs',\n f'{basename}_{args.suffix}.{extension}')\n else:\n save_restore_path = os.path.join(args.save_root, 'restored_imgs', f'{basename}.{extension}')\n imwrite(restored_img, save_restore_path)\n\n\[email protected]('/')\[email protected]('/index')\ndef show_index():\n full_filename = os.path.join(app.config['UPLOAD_FOLDER'], os.path.join(app.config['UPLOAD_FOLDER'], request.files['file1']))\n return render_template(\"index.html\", user_image = full_filename)\n\n\nif __name__ == '__main__':\n app.run()"
]
| [
[
"numpy.concatenate",
"torch.cuda.is_available",
"torch.load"
]
]
|
pnijhara/h2o4gpu | [
"9885416deb3285f5d0f33023d6c07373ac4fc0b7"
]
| [
"tests/python/open_data/daal/test_daal_regression.py"
]
| [
"# -*- encoding: utf-8 -*-\n\"\"\"\n:copyright: 2017-2018 H2O.ai, Inc.\n:license: Apache License Version 2.0 (see LICENSE for details)\n\"\"\"\ntry:\n __import__('daal')\nexcept ImportError:\n import platform\n print(\"Daal is not supported. Architecture detected {}\".format(platform.architecture()))\nelse:\n from numpy.random import RandomState\n import time\n import os\n import numpy as np\n import logging\n from daal.data_management import HomogenNumericTable\n from daal.algorithms.linear_regression import training as linear_training\n from daal.algorithms.linear_regression import prediction as linear_prediction\n from h2o4gpu.solvers.daal_solver.daal_data import getNumpyArray\n from h2o4gpu import LinearMethod\n from numpy.linalg.tests.test_linalg import assert_almost_equal\n from numpy.ma.testutils import assert_array_almost_equal\n import h2o4gpu\n\n logging.basicConfig(level=logging.DEBUG)\n\n seeded = RandomState(42)\n\n from h2o4gpu.solvers.linear_regression import LinearRegression\n\n def test_fit_linear_regression_daal_vs_sklearn():\n\n trainData = seeded.rand(200,10)\n trainDependentVariables = seeded.rand(200,2)\n\n solver_daal = LinearRegression(\n fit_intercept=True,\n normalize=False,\n verbose=True,\n backend='daal')\n\n start_daal = time.time()\n solver_daal.fit(trainData, trainDependentVariables)\n end_daal = time.time()\n\n solver_sk = LinearRegression(normalize=True)\n start_sklearn = time.time()\n solver_sk.fit(trainData, trainDependentVariables)\n end_sklearn = time.time()\n\n print(\"TEST FIT Sklearn vs Daal\")\n print(\"Time taken in daal: {}\".format(end_daal-start_daal))\n print(\"Time taken in sklearn: {}\".format(end_sklearn-start_sklearn))\n print(\"DONE.\")\n\n if os.getenv(\"CHECKPERFORMANCE\") is not None:\n assert end_daal - start_daal <= end_sklearn - start_sklearn\n\n def test_linear_regression_simple():\n\n # calculate beta coefficients\n x = np.array([0.,2.,3.]).reshape(3,1)\n\n nt_x = nt_y = HomogenNumericTable(x)\n\n lr_alg = linear_training.Batch(method=linear_training.qrDense)\n lr_alg.input.set(linear_training.data, nt_x)\n lr_alg.input.set(linear_training.dependentVariables, nt_y)\n result = lr_alg.compute()\n model = result.get(linear_training.model)\n beta_coeff = model.getBeta()\n np_beta_coeff = getNumpyArray(beta_coeff)\n\n res_beta_coeff = np.array([0,1]).reshape(1,2)\n\n assert_almost_equal(res_beta_coeff, np_beta_coeff)\n\n # predict\n lr_alg_predict = linear_prediction.Batch()\n lr_alg_predict.input.setModel(linear_prediction.model, model)\n lr_alg_predict.input.setTable(linear_prediction.data, nt_x)\n result = lr_alg_predict.compute()\n np_predict = getNumpyArray(result.get(linear_prediction.prediction))\n assert_array_almost_equal(x, np_predict)\n\n def get_random_array(rows=10, columns=9):\n x = np.random.rand(rows, columns)\n y = np.random.rand(rows, 1)\n\n return (x,y)\n\n def test_overfitting(rows=10, columns=9):\n '''\n overfitting - more features than data points\n for n(number of observation) > p (number of variables)\n in this case, the least squares estimates tend to have low variance,\n and hence performs well on test observations\n for n <= p, in this case a lot of variability in the least squares fit\n for n << p, no longer a unique least squares coefficient estimate, the variance\n is infinite so the method cannot be used at all.\n for the last second cases, one has to use ridgit regression, lasso, or \n reduct dimension (subset selection, e.g. scikit does this approach)\n '''\n assert rows > columns, \"More features than data points in linear regression!\"\n\n def get_daal_prediction(x=np.array([1,2,3]), y=np.array([1,2,3])):\n ntX = HomogenNumericTable(x)\n ntY = HomogenNumericTable(y)\n\n lr_train = linear_training.Batch()\n lr_train.input.set(linear_training.data, ntX)\n lr_train.input.set(linear_training.dependentVariables, ntY)\n result = lr_train.compute()\n model = result.get(linear_training.model)\n\n lr_predict = linear_prediction.Batch()\n lr_predict.input.setModel(linear_prediction.model, model)\n lr_predict.input.setTable(linear_prediction.data, ntX)\n result = lr_predict.compute()\n\n np_predicted = getNumpyArray(result.get(linear_prediction.prediction))\n # assert the same as the initial dependent variable\n assert_array_almost_equal(y, np_predicted)\n return np_predicted\n\n def get_scikit_prediction(x=np.array([1,2,3]), y=np.array([1,2,3])):\n\n from sklearn.linear_model.base import LinearRegression as ScikitLinearRegression\n\n regression = ScikitLinearRegression()\n regression.fit(x, y)\n\n return regression.predict(x)\n\n def test_linear_regression_against_scikit(rows=10, columns=9):\n '''\n Test prediction daal against scikit\n Test for overfitting\n :param rows:\n :param columns:\n '''\n inout = get_random_array(rows, columns)\n test_overfitting(rows, columns)\n x = inout[0]\n y = inout[1]\n daal_predicted = get_daal_prediction(x, y)\n scik_predicted = get_scikit_prediction(x, y)\n\n assert_array_almost_equal(daal_predicted, scik_predicted)\n\n def test_coeff_size(rows=10, columns=9):\n '''\n number of beta coefficients (with intercept flag on)\n is the same number as size of data sample\n '''\n inout = get_random_array(rows, columns)\n test_overfitting(rows, columns)\n x = inout[0]\n y = inout[1]\n\n ntX = HomogenNumericTable(x)\n ntY = HomogenNumericTable(y)\n\n lr_train = linear_training.Batch()\n lr_train.input.set(linear_training.data, ntX)\n lr_train.input.set(linear_training.dependentVariables, ntY)\n result = lr_train.compute()\n model = result.get(linear_training.model)\n beta_coeff = model.getBeta()\n np_beta = getNumpyArray(beta_coeff)\n\n assert y.transpose().shape == np_beta.shape, \"Dependent variable size must have\\\n the same size as Beta coefficient\"\n\n def test_intercept_flag(rows=10, columns=9):\n inout = get_random_array(rows, columns)\n test_overfitting(rows, columns)\n x = inout[0]\n y = inout[1]\n\n ntX = HomogenNumericTable(x)\n ntY = HomogenNumericTable(y)\n\n lr_train = linear_training.Batch()\n lr_train.input.set(linear_training.data, ntX)\n lr_train.input.set(linear_training.dependentVariables, ntY)\n result = lr_train.compute()\n model = result.get(linear_training.model)\n beta_coeff = model.getBeta()\n np_beta = getNumpyArray(beta_coeff)\n daal_intercept = np_beta[0,0]\n\n from sklearn.linear_model.base import LinearRegression as ScikitLinearRegression\n regression = ScikitLinearRegression()\n regression.fit(x, y)\n\n scikit_intercept = regression.intercept_\n assert_array_almost_equal(scikit_intercept, [daal_intercept])\n\n def test_linear_regression_daal_vs_sklearn(rows=10, columns=9,verbose=False):\n inout = get_random_array(rows, columns)\n x = inout[0]\n y = inout[1]\n\n start_sklearn = time.time()\n lin_solver_sklearn = h2o4gpu.LinearRegression(verbose=True,\n backend='sklearn')\n lin_solver_sklearn.fit(x, y)\n sklearn_predicted = lin_solver_sklearn.predict(x)\n end_sklearn = time.time()\n\n print((\"Sklearn prediction: \", sklearn_predicted) if verbose else \"\",\n end=\"\")\n\n start_daal = time.time()\n lin_solver_daal = h2o4gpu.LinearRegression(fit_intercept=True,\n verbose=True,\n backend='daal',\n method=LinearMethod.normal_equation)\n\n lin_solver_daal.fit(x, y)\n daal_predicted = lin_solver_daal.predict(x)\n end_daal = time.time()\n\n print((\"Daal prediction: \", daal_predicted) if verbose else \"\",\n end=\"\")\n\n print(\"Prediction calculated:\")\n print(\"+ Sklearn: {}\".format(end_sklearn-start_sklearn))\n print(\"+ Daal: {}\".format(end_daal-start_daal))\n\n assert_array_almost_equal(daal_predicted, sklearn_predicted, decimal=4)\n assert_array_almost_equal(daal_predicted, y, decimal=4)\n\n if os.getenv(\"CHECKPERFORMANCE\") is not None:\n assert end_daal - start_daal <= end_sklearn - start_sklearn\n\n sklearn_score = lin_solver_sklearn.score(x, y)\n daal_score = lin_solver_daal.score(x, y)\n print(\"Score calculated: \")\n print(\"+ Sklearn: {}\".format(sklearn_score))\n print(\"+ Daal: {}\".format(daal_score))\n\n assert daal_score == sklearn_score\n\n def test_linear_regression_normalized(): test_fit_linear_regression_daal_vs_sklearn()\n def test_linear_regression(): test_linear_regression_simple()\n def test_linear_regression_param_3_2(): test_linear_regression_against_scikit(rows=3, columns=2)\n def test_linear_regression_with_sc(): test_linear_regression_against_scikit()\n def test_beta(): \n test_coeff_size(rows=10, columns=9)\n test_intercept_flag(rows=10, columns=9)\n def test_daal_linear_regression_wrapper():\n test_linear_regression_daal_vs_sklearn(rows=10, columns=9,verbose=True)\n #test_linear_regression_daal_vs_sklearn(rows=100, columns=99,verbose=False)\n #test_linear_regression_daal_vs_sklearn(rows=1000, columns=999,verbose=False)\n\n if __name__ == '__main__':\n test_linear_regression_simple()\n test_daal_linear_regression_wrapper()\n"
]
| [
[
"sklearn.linear_model.base.LinearRegression",
"numpy.array",
"numpy.random.rand",
"numpy.random.RandomState",
"numpy.linalg.tests.test_linalg.assert_almost_equal",
"numpy.ma.testutils.assert_array_almost_equal"
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.