repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
possible_versions
list
Iuiu1234/pipelines
[ "1e032f550ce23cd40bfb6827b995248537b07d08", "1e032f550ce23cd40bfb6827b995248537b07d08" ]
[ "components/contrib/_converters/KerasModelHdf5/to_TensorflowSavedModel/component.py", "samples/contrib/pytorch-samples/cifar10/cifar10_pre_process.py" ]
[ "from kfp.components import create_component_from_func, InputPath, OutputPath\n\ndef keras_convert_hdf5_model_to_tf_saved_model(\n model_path: InputPath('KerasModelHdf5'),\n converted_model_path: OutputPath('TensorflowSavedModel'),\n):\n '''Converts Keras HDF5 model to Tensorflow SavedModel format.\n\n Args:\n model_path: Keras model in HDF5 format.\n converted_model_path: Keras model in Tensorflow SavedModel format.\n\n Annotations:\n author: Alexey Volkov <[email protected]>\n '''\n from pathlib import Path\n from tensorflow import keras\n \n model = keras.models.load_model(filepath=model_path)\n keras.models.save_model(model=model, filepath=converted_model_path, save_format='tf')\n\n\nif __name__ == '__main__':\n keras_convert_hdf5_model_to_tf_saved_model_op = create_component_from_func(\n keras_convert_hdf5_model_to_tf_saved_model,\n base_image='tensorflow/tensorflow:2.3.0',\n packages_to_install=['h5py==2.10.0'],\n output_component_file='component.yaml',\n annotations={\n \"author\": \"Alexey Volkov <[email protected]>\",\n \"canonical_location\": \"https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/_converters/KerasModelHdf5/to_TensorflowSavedModel/component.yaml\",\n },\n )\n", "# !/usr/bin/env/python3\n# Copyright (c) Facebook, Inc. and its affiliates.\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\"\"\"Cifar10 pre-process module.\"\"\"\nimport subprocess\nfrom pathlib import Path\nfrom argparse import ArgumentParser\nimport torchvision\nimport webdataset as wds\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nfrom pytorch_kfp_components.components.visualization.component import Visualization\n\nif __name__ == \"__main__\":\n parser = ArgumentParser()\n parser.add_argument(\"--output_path\", type=str)\n\n parser.add_argument(\n \"--mlpipeline_ui_metadata\",\n type=str,\n help=\"Path to write mlpipeline-ui-metadata.json\",\n )\n\n args = vars(parser.parse_args())\n output_path = args[\"output_path\"]\n\n Path(output_path).mkdir(parents=True, exist_ok=True)\n\n trainset = torchvision.datasets.CIFAR10(\n root=\"./\", train=True, download=True\n )\n testset = torchvision.datasets.CIFAR10(\n root=\"./\", train=False, download=True\n )\n\n Path(output_path + \"/train\").mkdir(parents=True, exist_ok=True)\n Path(output_path + \"/val\").mkdir(parents=True, exist_ok=True)\n Path(output_path + \"/test\").mkdir(parents=True, exist_ok=True)\n\n RANDOM_SEED = 25\n y = trainset.targets\n trainset, valset, y_train, y_val = train_test_split(\n trainset,\n y,\n stratify=y,\n shuffle=True,\n test_size=0.2,\n random_state=RANDOM_SEED\n )\n\n for name in [(trainset, \"train\"), (valset, \"val\"), (testset, \"test\")]:\n with wds.ShardWriter(output_path + \"/\" + str(name[1]) + \"/\" +\n str(name[1]) + \"-%d.tar\", maxcount=1000) as sink:\n for index, (image, cls) in enumerate(name[0]):\n sink.write({\n \"__key__\": \"%06d\" % index,\n \"ppm\": image,\n \"cls\": cls\n })\n\n entry_point = [\"ls\", \"-R\", output_path]\n run_code = subprocess.run(entry_point, stdout=subprocess.PIPE) #pylint: disable=subprocess-run-check\n print(run_code.stdout)\n\n visualization_arguments = {\n \"output\": {\n \"mlpipeline_ui_metadata\": args[\"mlpipeline_ui_metadata\"],\n \"dataset_download_path\": args[\"output_path\"],\n },\n }\n\n markdown_dict = {\"storage\": \"inline\", \"source\": visualization_arguments}\n\n print(\"Visualization arguments: \", markdown_dict)\n\n visualization = Visualization(\n mlpipeline_ui_metadata=args[\"mlpipeline_ui_metadata\"],\n markdown=markdown_dict,\n )\n\n y_array = np.array(y)\n\n label_names = [\n \"airplane\",\n \"automobile\",\n \"bird\",\n \"cat\",\n \"deer\",\n \"dog\",\n \"frog\",\n \"horse\",\n \"ship\",\n \"truck\",\n ]\n label_counts = dict(zip(*np.unique(y_array, return_counts=True)))\n label_dict = {}\n TOTAL_COUNT = len(y)\n for key, value in label_counts.items():\n print(\n \"Label Counts of [{}]({}) : {}\".format(\n key, label_names[key].upper(), value\n )\n )\n label_dict[label_names[key].upper()] = int(value)\n\n label_dict[\"TOTAL_COUNT\"] = int(TOTAL_COUNT)\n\n markdown_dict = {\"storage\": \"inline\", \"source\": label_dict}\n\n visualization = Visualization(\n mlpipeline_ui_metadata=args[\"mlpipeline_ui_metadata\"],\n markdown=markdown_dict,\n )\n" ]
[ [ "tensorflow.keras.models.load_model", "tensorflow.keras.models.save_model" ], [ "numpy.array", "sklearn.model_selection.train_test_split", "numpy.unique" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
PayneLab/cptac
[ "531ec27a618270a2405bf876443fa58d0362b3c2" ]
[ "cptac/pancan/file_download.py" ]
[ "# Copyright 2018 Samuel Payne [email protected]\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# http://www.apache.org/licenses/LICENSE-2.0\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 os\nimport pandas as pd\nimport requests\nimport shutil\nimport warnings\n\nimport cptac\nfrom cptac.file_download import get_box_token\nfrom cptac.exceptions import DatasetAlreadyInstalledWarning, InvalidParameterError, NoInternetError, PdcDownloadError\n\nfrom .pancanbrca import SOURCES as BRCA_SOURCES\nfrom .pancanccrcc import SOURCES as CCRCC_SOURCES\nfrom .pancancoad import SOURCES as COAD_SOURCES\nfrom .pancangbm import SOURCES as GBM_SOURCES\nfrom .pancanhnscc import SOURCES as HNSCC_SOURCES\nfrom .pancanlscc import SOURCES as LSCC_SOURCES\nfrom .pancanluad import SOURCES as LUAD_SOURCES\nfrom .pancanov import SOURCES as OV_SOURCES\nfrom .pancanucec import SOURCES as UCEC_SOURCES\nfrom .pancanpdac import SOURCES as PDAC_SOURCES\n\nSTUDY_IDS_MAP = {\n \"pdcbrca\": {\n \"acetylome\": \"PDC000239\", # Prospective Breast BI Acetylome\n \"phosphoproteome\": \"PDC000121\", # Prospective BRCA Phosphoproteome S039-2\n \"proteome\": \"PDC000120\", # Prospective BRCA Proteome S039-1\n },\n \"pdcccrcc\": {\n \"phosphoproteome\": \"PDC000128\", # CPTAC CCRCC Discovery Study - Phosphoproteme S044-2\n \"proteome\": \"PDC000127\", # CPTAC CCRCC Discovery Study - Proteome S044-1\n },\n \"pdccoad\": {\n \"phosphoproteome\": \"PDC000117\", # Prospective COAD Phosphoproteome S037-3\n \"proteome\": \"PDC000116\", # Prospective COAD Proteome S037-2\n },\n \"pdcgbm\": {\n \"acetylome\": \"PDC000245\", # CPTAC GBM Discovery Study - Acetylome\n \"phosphoproteome\": \"PDC000205\", # CPTAC GBM Discovery Study - Phosphoproteome\n \"proteome\": \"PDC000204\", # CPTAC GBM Discovery Study - Proteome\n },\n \"pdchnscc\": {\n \"phosphoproteome\": \"PDC000222\", # CPTAC HNSCC Discovery Study - Phosphoproteome\n \"proteome\": \"PDC000221\", # CPTAC HNSCC Discovery Study - Proteome\n },\n \"pdclscc\": {\n \"acetylome\": \"PDC000233\", # CPTAC LSCC Discovery Study - Acetylome\n \"phosphoproteome\": \"PDC000232\", # CPTAC LSCC Discovery Study - Phosphoproteome\n \"proteome\": \"PDC000234\", # CPTAC LSCC Discovery Study - Proteome\n \"ubiquitylome\": \"PDC000237\", # CPTAC LSCC Discovery Study - Ubiquitylome\n },\n \"pdcluad\": {\n \"acetylome\": \"PDC000224\", # CPTAC LUAD Discovery Study - Acetylome\n \"phosphoproteome\": \"PDC000149\", # CPTAC LUAD Discovery Study - Phosphoproteome\n \"proteome\": \"PDC000153\", # CPTAC LUAD Discovery Study - Proteome\n },\n \"pdcov\": {\n \"phosphoproteome\": \"PDC000119\", # Prospective OV Phosphoproteome S038-3\n \"proteome\": \"PDC000118\", # Prospective OV Proteome S038-2\n },\n \"pdcpdac\": {\n \"proteome\": \"PDC000270\", # CPTAC PDAC Discovery Study - Proteome\n \"phosphoproteome\": \"PDC000271\", # CPTAC PDAC Discovery Study - Phosphoproteome\n },\n \"pdcucec\": {\n \"acetylome\": \"PDC000226\", # CPTAC UCEC Discovery Study - Acetylome\n \"phosphoproteome\": \"PDC000126\", # UCEC Discovery - Phosphoproteome S043-2\n \"proteome\": \"PDC000125\", # UCEC Discovery - Proteome S043-1\n },\n}\n\n\ndef download(dataset, version=\"latest\", redownload=False):\n\n dataset = dataset.lower()\n\n if dataset.startswith(\"pdc\"):\n box_token = get_box_token()\n if dataset != 'pdcbrca': # pdcbrca is the only dataset that doesn't need a mapping file for PDC\n mapping = cptac.download(dataset, version=version, redownload=redownload, _box_auth=True, _box_token=box_token) # download helper file for mapping aliquots to patient IDs \n omics = _pdc_download(dataset, version=version, redownload=redownload) \n if omics and mapping:\n return True\n else:\n return False\n else: # pdcbrca only needs omics\n omics = _pdc_download(dataset, version=version, redownload=redownload)\n if omics:\n return True\n else:\n return False\n\n elif dataset.startswith(\"pancan\") or dataset == \"all\":\n box_token = get_box_token()\n\n if dataset == \"pancanbrca\":\n sources = BRCA_SOURCES\n elif dataset == \"pancanccrcc\":\n sources = CCRCC_SOURCES\n elif dataset == \"pancancoad\":\n sources = COAD_SOURCES\n elif dataset == \"pancangbm\":\n sources = GBM_SOURCES\n elif dataset == \"pancanhnscc\":\n sources = HNSCC_SOURCES\n elif dataset == \"pancanlscc\":\n sources = LSCC_SOURCES\n elif dataset == \"pancanluad\":\n sources = LUAD_SOURCES\n elif dataset == \"pancanov\":\n sources = OV_SOURCES\n elif dataset == \"pancanucec\":\n sources = UCEC_SOURCES\n elif dataset == \"pancanpdac\":\n sources = PDAC_SOURCES\n elif dataset == \"all\":\n sources = sorted(set(BRCA_SOURCES + CCRCC_SOURCES + COAD_SOURCES + GBM_SOURCES + HNSCC_SOURCES + LSCC_SOURCES + LUAD_SOURCES + OV_SOURCES + UCEC_SOURCES + PDAC_SOURCES))\n else:\n raise InvalidParameterError(f\"{dataset} is not a valid dataset.\")\n\n overall_success = True\n for source in sources:\n\n if source.startswith(\"pdc\"):\n single_success = download(source, version=version, redownload=redownload)\n else:\n single_success = cptac.download(source, version=version, redownload=redownload, _box_auth=True, _box_token=box_token)\n\n if not single_success:\n overall_success = False\n\n return overall_success\n\n else:\n return cptac.download(dataset, version=version, redownload=redownload, _box_auth=True)\n\ndef download_pdc_id(pdc_id, _download_msg=True):\n \"\"\"Download a PDC dataset by its PDC study id.\n \n Returns:\n pandas.DataFrame: The clinical table for the study id.\n pandas.DataFrame: The quantitative table for the study id.\n \"\"\"\n\n if _download_msg:\n clin_msg = f\"Downloading clinical table for {pdc_id}...\"\n print(clin_msg, end=\"\\r\")\n\n # Download the clinical table\n clin = _download_study_clin(pdc_id).\\\n set_index(\"case_submitter_id\").\\\n sort_index()\n\n if _download_msg:\n print(\" \" * len(clin_msg), end=\"\\r\")\n bio_msg = f\"Downloading biospecimenPerStudy table for {pdc_id}...\"\n print(bio_msg, end=\"\\r\")\n\n # The the biospecimenPerStudy table, which has both patient IDs and aliquot IDs\n bio = _download_study_biospecimen(pdc_id).\\\n set_index(\"aliquot_submitter_id\").\\\n sort_index()\n\n if _download_msg:\n print(\" \" * len(bio_msg), end=\"\\r\")\n quant_msg = f\"Downloading quantitative table for {pdc_id}...\"\n print(quant_msg, end=\"\\r\")\n\n # Get the quantitative data table\n quant = _download_study_quant(pdc_id)\n\n if _download_msg:\n print(\" \" * len(quant_msg), end=\"\\r\")\n format_msg = f\"Formatting tables for {pdc_id}...\"\n print(format_msg, end=\"\\r\")\n\n # Join the patient IDs from the biospecimenPerStudy table into the quant table\n quant = quant.\\\n assign(aliquot_submitter_id=quant.iloc[:, 0].str.split(\":\", n=1, expand=True)[1]).\\\n drop(columns=quant.columns[0]).\\\n set_index(\"aliquot_submitter_id\").\\\n sort_index()\n\n quant = bio.\\\n join(quant, how=\"inner\").\\\n reset_index().\\\n set_index([\"case_submitter_id\", \"aliquot_submitter_id\"]).\\\n sort_index()\n\n # Clear message\n if _download_msg:\n print(\" \" * len(format_msg), end=\"\\r\")\n\n return clin, quant\n\ndef list_pdc_datasets():\n for dataset in STUDY_IDS_MAP.keys():\n print(f\"Pdc{dataset[3:].title()}:\")\n for data_type in STUDY_IDS_MAP[dataset].keys():\n print(f\"\\t{data_type}: {STUDY_IDS_MAP[dataset][data_type]}\")\n\n# Helper functions\n \ndef _pdc_download(dataset, version, redownload):\n \"\"\"Download data for the specified cancer type from the PDC.\"\"\"\n\n dataset = str.lower(dataset)\n\n if dataset == \"pdcall\":\n overall_result = True\n for dataset in STUDY_IDS_MAP.keys():\n if not pdc_download(dataset, version, redownload):\n overall_result = False\n\n return overall_result\n\n if not dataset.startswith(\"pdc\"):\n raise InvalidParameterError(f\"pdc_download function can only be used for PDC datasets, which start with the prefix 'pdc'. You tried to download '{dataset}'.\")\n\n if dataset not in STUDY_IDS_MAP.keys():\n raise InvalidParameterError(f\"PDC dataset must be one of the following:\\n{list(STUDY_IDS_MAP.keys())}\\nYou passed '{dataset}'.\")\n\n dataset_ids = STUDY_IDS_MAP[dataset]\n\n # Get the directory to where to store the data, and see if it exists\n path_here = os.path.abspath(os.path.dirname(__file__))\n cancer_dir = os.path.join(path_here, f\"data_{dataset}\")\n\n if os.path.isdir(cancer_dir):\n\n index_path = os.path.join(cancer_dir, \"index.txt\")\n\n # Check that they also have the index\n if not os.path.isfile(index_path):\n redownload = True\n else:\n # The PDC doesn't have a versioning scheme for the tables they serve, so originally we just called it version 0.0 but later decided it would be better to call it 1.0. So, check if theirs is called 0.0; if so, replace it with 1.0.\n\n with open(index_path, \"r\") as index_file:\n first_line = index_file.readline()\n\n if first_line.startswith(\"#0.0\"):\n redownload=True\n\n if redownload:\n shutil.rmtree(cancer_dir)\n else:\n\n return True\n\n os.mkdir(cancer_dir)\n data_dir = os.path.join(cancer_dir, f\"{dataset}_v1.0\")\n os.mkdir(data_dir)\n\n # We'll combine all the clinical tables in case there are differences\n master_clin = pd.DataFrame()\n\n for data_type in dataset_ids.keys():\n\n # Print an update\n download_msg = f\"Downloading {dataset} {data_type} files...\"\n print(download_msg, end=\"\\r\")\n\n # Get the clinical and quantitative tables for the study ID\n clin, quant = download_pdc_id(dataset_ids[data_type], _download_msg=False)\n\n # Print a new update\n print(\" \" * len(download_msg), end=\"\\r\")\n save_msg = f\"Saving {dataset} {data_type} files...\"\n print(save_msg, end=\"\\r\")\n\n # Append the clinical dataframe\n master_clin = master_clin.append(clin)\n\n # Save the quantitative table\n quant.to_csv(os.path.join(data_dir, f\"{data_type}.tsv.gz\"), sep=\"\\t\")\n\n # Erase update\n print(\" \" * len(save_msg), end=\"\\r\")\n\n # Print an update\n save_msg = f\"Saving {dataset} clinical file...\"\n print(save_msg, end=\"\\r\")\n\n # Drop any duplicated rows in combined clinical table, then save it too\n master_clin = master_clin.drop_duplicates(keep=\"first\")\n\n master_clin.to_csv(os.path.join(data_dir, \"clinical.tsv.gz\"), sep=\"\\t\")\n\n # Write a dummy index with just version numbers\n index_path = os.path.join(cancer_dir, \"index.txt\")\n\n with open(index_path, \"w\") as index_file:\n index_file.write(\"#1.0\\n\")\n \n # Erase update\n print(\" \" * len(save_msg), end=\"\\r\")\n\n return True\n\ndef _download_study_clin(pdc_study_id):\n \"\"\"Download PDC clinical data for a particular study.\"\"\"\n\n clinical_query = '''\n query {\n clinicalPerStudy(pdc_study_id: \"''' + pdc_study_id + '''\", acceptDUA: true) {\n age_at_diagnosis, ajcc_clinical_m, ajcc_clinical_n, ajcc_clinical_stage, ajcc_clinical_t, ajcc_pathologic_m,\n ajcc_pathologic_n, ajcc_pathologic_stage, ajcc_pathologic_t, ann_arbor_b_symptoms, ann_arbor_clinical_stage,\n ann_arbor_extranodal_involvement, ann_arbor_pathologic_stage, best_overall_response, burkitt_lymphoma_clinical_variant,\n case_id, case_submitter_id, cause_of_death, circumferential_resection_margin, classification_of_tumor, colon_polyps_history,\n days_to_best_overall_response, days_to_birth, days_to_death, days_to_diagnosis, days_to_hiv_diagnosis, days_to_last_follow_up,\n days_to_last_known_disease_status, days_to_new_event, days_to_recurrence, demographic_id, demographic_submitter_id,\n diagnosis_id, diagnosis_submitter_id, disease_type, ethnicity, figo_stage, gender, hiv_positive, hpv_positive_type, hpv_status,\n icd_10_code, iss_stage, last_known_disease_status, laterality, ldh_level_at_diagnosis, ldh_normal_range_upper,\n lymphatic_invasion_present, lymph_nodes_positive, method_of_diagnosis, morphology, new_event_anatomic_site, new_event_type,\n overall_survival, perineural_invasion_present, primary_diagnosis, primary_site, prior_malignancy, prior_treatment,\n progression_free_survival, progression_free_survival_event, progression_or_recurrence, race, residual_disease,\n site_of_resection_or_biopsy, status, synchronous_malignancy, tissue_or_organ_of_origin, tumor_cell_content, tumor_grade,\n tumor_stage, vascular_invasion_present, vital_status, year_of_birth, year_of_death, year_of_diagnosis\n }\n }\n '''\n\n result_json = _query_pdc(clinical_query)\n result_df = pd.\\\n DataFrame(result_json[\"data\"][\"clinicalPerStudy\"])\n\n return result_df\n\ndef _download_study_biospecimen(pdc_study_id):\n \"\"\"Download PDC biospecimen data for a particular study.\"\"\"\n\n biospecimen_query = '''\n query {\n biospecimenPerStudy(pdc_study_id: \"''' + pdc_study_id + '''\", acceptDUA: true) {\n aliquot_submitter_id\n case_submitter_id\n }\n }\n '''\n\n result_json = _query_pdc(biospecimen_query)\n result_df = pd.\\\n DataFrame(result_json[\"data\"][\"biospecimenPerStudy\"])\n\n return result_df\n\ndef _download_study_quant(pdc_study_id):\n \"\"\"Download PDC quantitative data for a particular study.\"\"\"\n\n proteome_query = '''\n query {\n quantDataMatrix(pdc_study_id: \"''' + pdc_study_id + '''\", data_type: \"log2_ratio\", acceptDUA: true)\n }\n '''\n\n result_json = _query_pdc(proteome_query)\n result_df = pd.DataFrame(result_json[\"data\"][\"quantDataMatrix\"])\n\n if result_df.shape[1] != 0:\n result_df = result_df.set_index(result_df.columns[0]).transpose()\n else:\n raise PdcDownloadError(f\"quantDataMatrix table returned for PDC study ID {pdc_study_id} was empty.\")\n\n return result_df\n\ndef _query_pdc(query):\n \"\"\"Send a GraphQL query to the PDC and return the results.\"\"\"\n\n url = 'https://pdc.cancer.gov/graphql'\n\n try:\n response = requests.post(url, json={'query': query})\n response.raise_for_status() # Raises a requests.HTTPError if the response code was unsuccessful\n\n except requests.RequestException: # Parent class for all exceptions in the requests module\n raise NoInternetError(\"Insufficient internet. Check your internet connection.\") from None\n\n return response.json()\n\ndef _check_ids_match(ids_map):\n \"\"\"Check that the ids in the download function's STUDY_IDS_MAP match up.\"\"\"\n \n for cancer in ids_map.values():\n for data in cancer.values():\n pdc_study_id = data[\"pdc_study_id\"]\n study_submitter_id = data[\"study_submitter_id\"]\n\n query = '''\n query {\n study (pdc_study_id: \"''' + pdc_study_id + '''\" acceptDUA: true) {\n pdc_study_id,\n study_submitter_id\n }\n }\n '''\n\n idres = _query_pdc(query)\n\n server_psi = idres[\"data\"][\"study\"][0][\"pdc_study_id\"]\n server_ssi = idres[\"data\"][\"study\"][0][\"study_submitter_id\"]\n\n assert server_psi == pdc_study_id\n assert server_ssi == study_submitter_id\n\n print(f\"{server_psi} == {pdc_study_id}\")\n print(f\"{server_ssi} == {study_submitter_id}\")\n print()\n" ]
[ [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
DhenryD/CrowdCount-mcnn
[ "a44bcbfd25ca681f7b57e2f92f10b06f602dd93f" ]
[ "src/models.py" ]
[ "import torch\nimport torch.nn as nn\nfrom src.network import Conv2d\n\n\nclass MCNN(nn.Module):\n\n def __init__(self, bn=False):\n super(MCNN, self).__init__()\n\n self.branch1 = nn.Sequential(Conv2d(1, 16, 9, same_padding=True, bn=bn),\n nn.MaxPool2d(2),\n Conv2d(16, 32, 7, same_padding=True, bn=bn),\n nn.MaxPool2d(2),\n Conv2d(32, 16, 7, same_padding=True, bn=bn),\n Conv2d(16, 8, 7, same_padding=True, bn=bn))\n\n self.branch2 = nn.Sequential(Conv2d(1, 20, 7, same_padding=True, bn=bn),\n nn.MaxPool2d(2),\n Conv2d(20, 40, 5, same_padding=True, bn=bn),\n nn.MaxPool2d(2),\n Conv2d(40, 20, 5, same_padding=True, bn=bn),\n Conv2d(20, 10, 5, same_padding=True, bn=bn))\n\n self.branch3 = nn.Sequential(Conv2d(1, 24, 5, same_padding=True, bn=bn),\n nn.MaxPool2d(2),\n Conv2d(24, 48, 3, same_padding=True, bn=bn),\n nn.MaxPool2d(2),\n Conv2d(48, 24, 3, same_padding=True, bn=bn),\n Conv2d(24, 12, 3, same_padding=True, bn=bn))\n\n self.branch4 = nn.Sequential(Conv2d(1, 28, 3, same_padding=True, bn=bn),\n nn.MaxPool2d(2),\n Conv2d(28, 56, 1, same_padding=True, bn=bn),\n nn.MaxPool2d(2),\n Conv2d(56, 28, 1, same_padding=True, bn=bn),\n Conv2d(28, 14, 1, same_padding=True, bn=bn))\n self.fuse = nn.Sequential(Conv2d(44, 1, 1, same_padding=True, bn=bn))\n\n def forward(self, im_data):\n x1 = self.branch1(im_data)\n x2 = self.branch2(im_data)\n x3 = self.branch3(im_data)\n x4 = self.branch4(im_data)\n x = torch.cat((x1, x2, x3, x4), 1)\n x = self.fuse(x)\n\n return x\n" ]
[ [ "torch.nn.MaxPool2d", "torch.cat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kymotsujason/crossybot
[ "68f585ee21b68394e1b09a63f39f8d2b54ac5f0c" ]
[ "main.py" ]
[ "import cv2\nfrom PIL import ImageGrab\nimport numpy as np\n\n\ndef main():\n while True:\n # bbox specifies specific region (bbox= x,y,width,height)\n img = ImageGrab.grab(bbox=(0, 40, 1075, 640))\n vanilla = img_np = np.array(img)\n img_np = np.array(img)\n gray = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)\n _, binary = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV)\n contours, hierarchy = cv2.findContours(\n binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n image = cv2.drawContours(img_np, contours, -1, (0, 255, 0), 2)\n cv2.imshow(\"test\", image)\n if cv2.waitKey(25) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n print(\"test\")\n break\n else:\n cv2.waitKey(1)\n # cv2.waitKey(0)\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kimhyuns91/bird_call
[ "eea20c6e305a2ac322a94f90075d489742e7295c" ]
[ "import_and_model.py" ]
[ "import pandas as pd\nimport numpy as np\nimport wave\nfrom scipy.io import wavfile\nimport os\nimport librosa\nimport pydub\nimport ffmpeg\nfrom librosa.feature import melspectrogram\nimport warnings\nfrom sklearn.utils import shuffle\nfrom sklearn.utils import class_weight\nfrom PIL import Image\nimport sklearn\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import Input\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, Flatten, Dropout, Activation\nfrom tensorflow.keras.layers import BatchNormalization, GlobalAveragePooling2D\nfrom tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.layers import Dense, Flatten, Dropout, Activation, LSTM, SimpleRNN, Conv1D, Input, BatchNormalization, GlobalAveragePooling2D\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import EfficientNetB0\nfrom keras.models import load_model\n\nimport boto3\nimport botocore\n\ndef model_input():\n # Load the trained model\n model = load_model(\"best_model.h5\")\n\n #Access S3 Bucket and Download the audio file\n BUCKET_NAME = 'thunderstruck-duck' # replace with your bucket name\n KEY = \"sample_mp3.mp3\" # replace with your object key\n\n s3 = boto3.client('s3',\n aws_access_key_id='AKIAISITTOGCJRNF46HQ',\n aws_secret_access_key= 'bq/VRAme7BxDMqf3hgEMLZdrJNVvrtdQ4VmoGAdB',\n )\n BUCKET_NAME = \"thunderstruck-duck\"\n\n\n try:\n s3.download_file(BUCKET_NAME, KEY, \"sample_mp3.mp3\")\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == \"404\":\n print(\"The object does not exist.\")\n # else:\n # raise\n \n #Load the audio data using librosa\n\n\n wave_data, wave_rate = librosa.load(\"sample_mp3.mp3\")\n wave_data, _ = librosa.effects.trim(wave_data)\n #only take 5s samples and add them to the dataframe\n song_sample = []\n sample_length = 5*wave_rate\n #The variable below is chosen mainly to create a 216x216 image\n N_mels=216\n for idx in range(0,len(wave_data),sample_length): \n song_sample = wave_data[idx:idx+sample_length]\n if len(song_sample)>=sample_length:\n mel = melspectrogram(song_sample, n_mels=N_mels)\n db = librosa.power_to_db(mel)\n normalised_db = sklearn.preprocessing.minmax_scale(db)\n filename = \"sample_mel.tif\"\n db_array = (np.asarray(normalised_db)*255).astype(np.uint8)\n db_image = Image.fromarray(np.array([db_array, db_array, db_array]).T)\n db_image.save(\"{}{}\".format(\"upload_mel/\",filename))\n \n #Create a DF that will take the created Melspectogram directory\n data_df = pd.DataFrame([{'bird': \"sample bird\", 'song_sample': f\"/app/upload_mel/{filename}\"}])\n \n # Users/HyunsooKim/Desktop/Boot_Camp/Homework/BIRD_CALL/upload_mel/{filename}\"}])\n \n #Compile the model\n callbacks = [ReduceLROnPlateau(monitor='val_loss', patience=2, verbose=1, factor=0.7),\n EarlyStopping(monitor='val_loss', patience=5),\n ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True)]\n model.compile(loss=\"categorical_crossentropy\", optimizer='adam')\n\n #Since we only have 1 melspectogram passing into the model, set batch size to 1 and the size of that image so the model can take the image file.\n validation_batch_size_full = 1\n target_size = (216,216)\n\n train_datagen_full = ImageDataGenerator(\n rescale=1. / 255\n )\n #Pass the columns into the model\n validation_datagen_full = ImageDataGenerator(rescale=1. / 255)\n validation_generator_full = validation_datagen_full.flow_from_dataframe(\n dataframe = data_df,\n x_col='song_sample',\n y_col='bird',\n directory='/',\n target_size=target_size,\n shuffle=False,\n batch_size=validation_batch_size_full,\n class_mode='categorical')\n \n #Run the model\n preds = model.predict_generator(validation_generator_full)\n\n #We want to find the \"INDEX\" of maximum value within the pred, a numpy array. Use np.argmax and index into 0th element.\n result = np.argmax(preds[0])\n\n #load in the index dataframe, so we can find the name of the bird that matches the index of our result\n index_df = pd.read_csv('xeno-canto_ca-nv_index.csv')\n #rename the english_cname to birds for better access and clearity\n bird_list = pd.DataFrame(index_df.english_cname.unique())\n bird_list.columns = [\"birds\"]\n\n #We are almost done. Save the percentage and the name of the bird into a variable and print it out!\n percentage = preds[0][result]\n Name_of_bird = bird_list['birds'][result]\n\n print(f\"This bird is {percentage} likely {Name_of_bird}\")\n\n\n final_data = {\"likelihood\": percentage, \"name_of_bird\": Name_of_bird}\n\n return final_data\n\n if __name__ == \"__main__\":\n print(model_input())" ]
[ [ "tensorflow.keras.callbacks.ModelCheckpoint", "pandas.read_csv", "tensorflow.keras.preprocessing.image.ImageDataGenerator", "numpy.asarray", "tensorflow.keras.callbacks.ReduceLROnPlateau", "pandas.DataFrame", "numpy.argmax", "numpy.array", "tensorflow.keras.callbacks.EarlyStopping", "sklearn.preprocessing.minmax_scale" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] } ]
maximumSHOT-HSE/CurriculumLearning
[ "bf5291812a9ec3feb083d3d84b579329781c8a6a" ]
[ "src/cluster/sort_dataset_by_column/test.py" ]
[ "import argparse\r\nimport datasets\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n\r\ndef parse_args():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--input', type=str, required=True, help='Path to the directory with input dataset')\r\n return parser.parse_args()\r\n\r\n\r\nif __name__ == '__main__':\r\n args = parse_args()\r\n dataset = datasets.load_from_disk(args.input).shuffle()\r\n\r\n for part in dataset:\r\n print()\r\n print('part', part)\r\n xs = []\r\n ys = []\r\n for i, x in enumerate(dataset[part]):\r\n print(x['tse'], len(x['input_ids']))\r\n xs.append(len(x['input_ids']))\r\n ys.append(x['tse'])\r\n if i >= 10000:\r\n break\r\n plt.clf()\r\n plt.cla()\r\n plt.title(f'{part} CDF')\r\n # plt.xlabel('len')\r\n # plt.ylabel('tse / len')\r\n # plt.scatter(xs, ys)\r\n # plt.hist(ys, bins=5000)\r\n ys.sort()\r\n ys = np.array(ys)\r\n plt.plot(ys, np.arange(len(ys)))\r\n plt.savefig(f'{part}.png')\r\n" ]
[ [ "matplotlib.pyplot.title", "matplotlib.pyplot.cla", "matplotlib.pyplot.savefig", "matplotlib.pyplot.clf", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
xiaolao/PaddleOCR
[ "21b9bd63646fdca95f63062d94fd62f35cfa61cc" ]
[ "tools/infer/utility.py" ]
[ "# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport argparse\nimport os\nimport sys\nimport cv2\nimport numpy as np\nimport json\nfrom PIL import Image, ImageDraw, ImageFont\nimport math\nfrom paddle import inference\n\n\ndef parse_args():\n def str2bool(v):\n return v.lower() in (\"true\", \"t\", \"1\")\n\n parser = argparse.ArgumentParser()\n # params for prediction engine\n parser.add_argument(\"--use_gpu\", type=str2bool, default=True)\n parser.add_argument(\"--ir_optim\", type=str2bool, default=True)\n parser.add_argument(\"--use_tensorrt\", type=str2bool, default=False)\n parser.add_argument(\"--use_fp16\", type=str2bool, default=False)\n parser.add_argument(\"--gpu_mem\", type=int, default=500)\n\n # params for text detector\n parser.add_argument(\"--image_dir\", type=str)\n parser.add_argument(\"--det_algorithm\", type=str, default='DB')\n parser.add_argument(\"--det_model_dir\", type=str)\n parser.add_argument(\"--det_limit_side_len\", type=float, default=960)\n parser.add_argument(\"--det_limit_type\", type=str, default='max')\n\n # DB parmas\n parser.add_argument(\"--det_db_thresh\", type=float, default=0.3)\n parser.add_argument(\"--det_db_box_thresh\", type=float, default=0.6)\n parser.add_argument(\"--det_db_unclip_ratio\", type=float, default=1.5)\n parser.add_argument(\"--max_batch_size\", type=int, default=10)\n parser.add_argument(\"--use_dilation\", type=bool, default=False)\n parser.add_argument(\"--det_db_score_mode\", type=str, default=\"fast\")\n # EAST parmas\n parser.add_argument(\"--det_east_score_thresh\", type=float, default=0.8)\n parser.add_argument(\"--det_east_cover_thresh\", type=float, default=0.1)\n parser.add_argument(\"--det_east_nms_thresh\", type=float, default=0.2)\n\n # SAST parmas\n parser.add_argument(\"--det_sast_score_thresh\", type=float, default=0.5)\n parser.add_argument(\"--det_sast_nms_thresh\", type=float, default=0.2)\n parser.add_argument(\"--det_sast_polygon\", type=bool, default=False)\n\n # params for text recognizer\n parser.add_argument(\"--rec_algorithm\", type=str, default='CRNN')\n parser.add_argument(\"--rec_model_dir\", type=str)\n parser.add_argument(\"--rec_image_shape\", type=str, default=\"3, 32, 320\")\n parser.add_argument(\"--rec_char_type\", type=str, default='ch')\n parser.add_argument(\"--rec_batch_num\", type=int, default=6)\n parser.add_argument(\"--max_text_length\", type=int, default=25)\n parser.add_argument(\n \"--rec_char_dict_path\",\n type=str,\n default=\"./ppocr/utils/ppocr_keys_v1.txt\")\n parser.add_argument(\"--use_space_char\", type=str2bool, default=True)\n parser.add_argument(\n \"--vis_font_path\", type=str, default=\"./doc/fonts/simfang.ttf\")\n parser.add_argument(\"--drop_score\", type=float, default=0.5)\n\n # params for e2e\n parser.add_argument(\"--e2e_algorithm\", type=str, default='PGNet')\n parser.add_argument(\"--e2e_model_dir\", type=str)\n parser.add_argument(\"--e2e_limit_side_len\", type=float, default=768)\n parser.add_argument(\"--e2e_limit_type\", type=str, default='max')\n\n # PGNet parmas\n parser.add_argument(\"--e2e_pgnet_score_thresh\", type=float, default=0.5)\n parser.add_argument(\n \"--e2e_char_dict_path\", type=str, default=\"./ppocr/utils/ic15_dict.txt\")\n parser.add_argument(\"--e2e_pgnet_valid_set\", type=str, default='totaltext')\n parser.add_argument(\"--e2e_pgnet_polygon\", type=bool, default=True)\n parser.add_argument(\"--e2e_pgnet_mode\", type=str, default='fast')\n\n # params for text classifier\n parser.add_argument(\"--use_angle_cls\", type=str2bool, default=False)\n parser.add_argument(\"--cls_model_dir\", type=str)\n parser.add_argument(\"--cls_image_shape\", type=str, default=\"3, 48, 192\")\n parser.add_argument(\"--label_list\", type=list, default=['0', '180'])\n parser.add_argument(\"--cls_batch_num\", type=int, default=6)\n parser.add_argument(\"--cls_thresh\", type=float, default=0.9)\n\n parser.add_argument(\"--enable_mkldnn\", type=str2bool, default=False)\n parser.add_argument(\"--cpu_threads\", type=int, default=10)\n parser.add_argument(\"--use_pdserving\", type=str2bool, default=False)\n\n parser.add_argument(\"--use_mp\", type=str2bool, default=False)\n parser.add_argument(\"--total_process_num\", type=int, default=1)\n parser.add_argument(\"--process_id\", type=int, default=0)\n\n return parser.parse_args()\n\n\ndef create_predictor(args, mode, logger):\n if mode == \"det\":\n model_dir = args.det_model_dir\n elif mode == 'cls':\n model_dir = args.cls_model_dir\n elif mode == 'rec':\n model_dir = args.rec_model_dir\n else:\n model_dir = args.e2e_model_dir\n\n if model_dir is None:\n logger.info(\"not find {} model file path {}\".format(mode, model_dir))\n sys.exit(0)\n model_file_path = model_dir + \"/inference.pdmodel\"\n params_file_path = model_dir + \"/inference.pdiparams\"\n if not os.path.exists(model_file_path):\n logger.info(\"not find model file path {}\".format(model_file_path))\n sys.exit(0)\n if not os.path.exists(params_file_path):\n logger.info(\"not find params file path {}\".format(params_file_path))\n sys.exit(0)\n\n config = inference.Config(model_file_path, params_file_path)\n\n if args.use_gpu:\n config.enable_use_gpu(args.gpu_mem, 0)\n if args.use_tensorrt:\n config.enable_tensorrt_engine(\n precision_mode=inference.PrecisionType.Half\n if args.use_fp16 else inference.PrecisionType.Float32,\n max_batch_size=args.max_batch_size)\n else:\n config.disable_gpu()\n cpu_threads = args.cpu_threads if hasattr(args, \"cpu_threads\") else 10\n config.set_cpu_math_library_num_threads(cpu_threads)\n if args.enable_mkldnn:\n # cache 10 different shapes for mkldnn to avoid memory leak\n config.set_mkldnn_cache_capacity(10)\n config.enable_mkldnn()\n\n # enable memory optim\n config.enable_memory_optim()\n config.disable_glog_info()\n\n config.delete_pass(\"conv_transpose_eltwiseadd_bn_fuse_pass\")\n config.switch_use_feed_fetch_ops(False)\n\n # create predictor\n predictor = inference.create_predictor(config)\n input_names = predictor.get_input_names()\n for name in input_names:\n input_tensor = predictor.get_input_handle(name)\n output_names = predictor.get_output_names()\n output_tensors = []\n for output_name in output_names:\n output_tensor = predictor.get_output_handle(output_name)\n output_tensors.append(output_tensor)\n return predictor, input_tensor, output_tensors\n\n\ndef draw_e2e_res(dt_boxes, strs, img_path):\n src_im = cv2.imread(img_path)\n for box, str in zip(dt_boxes, strs):\n box = box.astype(np.int32).reshape((-1, 1, 2))\n cv2.polylines(src_im, [box], True, color=(255, 255, 0), thickness=2)\n cv2.putText(\n src_im,\n str,\n org=(int(box[0, 0, 0]), int(box[0, 0, 1])),\n fontFace=cv2.FONT_HERSHEY_COMPLEX,\n fontScale=0.7,\n color=(0, 255, 0),\n thickness=1)\n return src_im\n\n\ndef draw_text_det_res(dt_boxes, img_path):\n src_im = cv2.imread(img_path)\n for box in dt_boxes:\n box = np.array(box).astype(np.int32).reshape(-1, 2)\n cv2.polylines(src_im, [box], True, color=(255, 255, 0), thickness=2)\n return src_im\n\n\ndef resize_img(img, input_size=600):\n \"\"\"\n resize img and limit the longest side of the image to input_size\n \"\"\"\n img = np.array(img)\n im_shape = img.shape\n im_size_max = np.max(im_shape[0:2])\n im_scale = float(input_size) / float(im_size_max)\n img = cv2.resize(img, None, None, fx=im_scale, fy=im_scale)\n return img\n\n\ndef draw_ocr(image,\n boxes,\n txts=None,\n scores=None,\n drop_score=0.5,\n font_path=\"./doc/simfang.ttf\"):\n \"\"\"\n Visualize the results of OCR detection and recognition\n args:\n image(Image|array): RGB image\n boxes(list): boxes with shape(N, 4, 2)\n txts(list): the texts\n scores(list): txxs corresponding scores\n drop_score(float): only scores greater than drop_threshold will be visualized\n font_path: the path of font which is used to draw text\n return(array):\n the visualized img\n \"\"\"\n if scores is None:\n scores = [1] * len(boxes)\n box_num = len(boxes)\n for i in range(box_num):\n if scores is not None and (scores[i] < drop_score or\n math.isnan(scores[i])):\n continue\n box = np.reshape(np.array(boxes[i]), [-1, 1, 2]).astype(np.int64)\n image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2)\n if txts is not None:\n img = np.array(resize_img(image, input_size=600))\n txt_img = text_visual(\n txts,\n scores,\n img_h=img.shape[0],\n img_w=600,\n threshold=drop_score,\n font_path=font_path)\n img = np.concatenate([np.array(img), np.array(txt_img)], axis=1)\n return img\n return image\n\n\ndef draw_ocr_box_txt(image,\n boxes,\n txts,\n scores=None,\n drop_score=0.5,\n font_path=\"./doc/simfang.ttf\"):\n h, w = image.height, image.width\n img_left = image.copy()\n img_right = Image.new('RGB', (w, h), (255, 255, 255))\n\n import random\n\n random.seed(0)\n draw_left = ImageDraw.Draw(img_left)\n draw_right = ImageDraw.Draw(img_right)\n for idx, (box, txt) in enumerate(zip(boxes, txts)):\n if scores is not None and scores[idx] < drop_score:\n continue\n color = (random.randint(0, 255), random.randint(0, 255),\n random.randint(0, 255))\n draw_left.polygon(box, fill=color)\n draw_right.polygon(\n [\n box[0][0], box[0][1], box[1][0], box[1][1], box[2][0],\n box[2][1], box[3][0], box[3][1]\n ],\n outline=color)\n box_height = math.sqrt((box[0][0] - box[3][0])**2 + (box[0][1] - box[3][\n 1])**2)\n box_width = math.sqrt((box[0][0] - box[1][0])**2 + (box[0][1] - box[1][\n 1])**2)\n if box_height > 2 * box_width:\n font_size = max(int(box_width * 0.9), 10)\n font = ImageFont.truetype(font_path, font_size, encoding=\"utf-8\")\n cur_y = box[0][1]\n for c in txt:\n char_size = font.getsize(c)\n draw_right.text(\n (box[0][0] + 3, cur_y), c, fill=(0, 0, 0), font=font)\n cur_y += char_size[1]\n else:\n font_size = max(int(box_height * 0.8), 10)\n font = ImageFont.truetype(font_path, font_size, encoding=\"utf-8\")\n draw_right.text(\n [box[0][0], box[0][1]], txt, fill=(0, 0, 0), font=font)\n img_left = Image.blend(image, img_left, 0.5)\n img_show = Image.new('RGB', (w * 2, h), (255, 255, 255))\n img_show.paste(img_left, (0, 0, w, h))\n img_show.paste(img_right, (w, 0, w * 2, h))\n return np.array(img_show)\n\n\ndef str_count(s):\n \"\"\"\n Count the number of Chinese characters,\n a single English character and a single number\n equal to half the length of Chinese characters.\n args:\n s(string): the input of string\n return(int):\n the number of Chinese characters\n \"\"\"\n import string\n count_zh = count_pu = 0\n s_len = len(s)\n en_dg_count = 0\n for c in s:\n if c in string.ascii_letters or c.isdigit() or c.isspace():\n en_dg_count += 1\n elif c.isalpha():\n count_zh += 1\n else:\n count_pu += 1\n return s_len - math.ceil(en_dg_count / 2)\n\n\ndef text_visual(texts,\n scores,\n img_h=400,\n img_w=600,\n threshold=0.,\n font_path=\"./doc/simfang.ttf\"):\n \"\"\"\n create new blank img and draw txt on it\n args:\n texts(list): the text will be draw\n scores(list|None): corresponding score of each txt\n img_h(int): the height of blank img\n img_w(int): the width of blank img\n font_path: the path of font which is used to draw text\n return(array):\n \"\"\"\n if scores is not None:\n assert len(texts) == len(\n scores), \"The number of txts and corresponding scores must match\"\n\n def create_blank_img():\n blank_img = np.ones(shape=[img_h, img_w], dtype=np.int8) * 255\n blank_img[:, img_w - 1:] = 0\n blank_img = Image.fromarray(blank_img).convert(\"RGB\")\n draw_txt = ImageDraw.Draw(blank_img)\n return blank_img, draw_txt\n\n blank_img, draw_txt = create_blank_img()\n\n font_size = 20\n txt_color = (0, 0, 0)\n font = ImageFont.truetype(font_path, font_size, encoding=\"utf-8\")\n\n gap = font_size + 5\n txt_img_list = []\n count, index = 1, 0\n for idx, txt in enumerate(texts):\n index += 1\n if scores[idx] < threshold or math.isnan(scores[idx]):\n index -= 1\n continue\n first_line = True\n while str_count(txt) >= img_w // font_size - 4:\n tmp = txt\n txt = tmp[:img_w // font_size - 4]\n if first_line:\n new_txt = str(index) + ': ' + txt\n first_line = False\n else:\n new_txt = ' ' + txt\n draw_txt.text((0, gap * count), new_txt, txt_color, font=font)\n txt = tmp[img_w // font_size - 4:]\n if count >= img_h // gap - 1:\n txt_img_list.append(np.array(blank_img))\n blank_img, draw_txt = create_blank_img()\n count = 0\n count += 1\n if first_line:\n new_txt = str(index) + ': ' + txt + ' ' + '%.3f' % (scores[idx])\n else:\n new_txt = \" \" + txt + \" \" + '%.3f' % (scores[idx])\n draw_txt.text((0, gap * count), new_txt, txt_color, font=font)\n # whether add new blank img or not\n if count >= img_h // gap - 1 and idx + 1 < len(texts):\n txt_img_list.append(np.array(blank_img))\n blank_img, draw_txt = create_blank_img()\n count = 0\n count += 1\n txt_img_list.append(np.array(blank_img))\n if len(txt_img_list) == 1:\n blank_img = np.array(txt_img_list[0])\n else:\n blank_img = np.concatenate(txt_img_list, axis=1)\n return np.array(blank_img)\n\n\ndef base64_to_cv2(b64str):\n import base64\n data = base64.b64decode(b64str.encode('utf8'))\n data = np.fromstring(data, np.uint8)\n data = cv2.imdecode(data, cv2.IMREAD_COLOR)\n return data\n\n\ndef draw_boxes(image, boxes, scores=None, drop_score=0.5):\n if scores is None:\n scores = [1] * len(boxes)\n for (box, score) in zip(boxes, scores):\n if score < drop_score:\n continue\n box = np.reshape(np.array(box), [-1, 1, 2]).astype(np.int64)\n image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2)\n return image\n\n\nif __name__ == '__main__':\n test_img = \"./doc/test_v2\"\n predict_txt = \"./doc/predict.txt\"\n f = open(predict_txt, 'r')\n data = f.readlines()\n img_path, anno = data[0].strip().split('\\t')\n img_name = os.path.basename(img_path)\n img_path = os.path.join(test_img, img_name)\n image = Image.open(img_path)\n\n data = json.loads(anno)\n boxes, txts, scores = [], [], []\n for dic in data:\n boxes.append(dic['points'])\n txts.append(dic['transcription'])\n scores.append(round(dic['scores'], 3))\n\n new_img = draw_ocr(image, boxes, txts, scores)\n\n cv2.imwrite(img_name, new_img)\n" ]
[ [ "numpy.ones", "numpy.concatenate", "numpy.max", "numpy.fromstring", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
HamidSajjadi/slr_query_formulation
[ "5164d7ecd1a798089df284459a451e1e3d1e20e5" ]
[ "analyze_results.py" ]
[ "import pandas as pd\nimport plotly.express as px\n\ndf = pd.read_csv('data/query_result.csv')\nmax_df = df.groupby(by='topic_id').max().reset_index()\ndf = df[df['topic_id'].isin(max_df[max_df['recall'] > 0]['topic_id'].to_list())]\nfor t in df['topic_id'].unique().tolist():\n temp_df = df[df['topic_id'] == t]\n fig = px.box(df, x=\"topic_id\", y=\"recall\")\n fig.update_traces(quartilemethod=\"exclusive\") # or \"inclusive\", or \"linear\" by default\n fig.show()\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
videetparekh/latentai-sdk-examples
[ "2104c097045105957ef7403b09b5a2c114677147" ]
[ "inference/tf_inference.py" ]
[ "# Copyright (c) 2019 by LatentAI Inc.\n# All rights reserved.\n# This file is part of the LEIP(tm) SDK,\n# and is released under the \"LatentAI Commercial Software License\".\n# Please see the LICENSE file that should have been included as part of\n# this package.\n#\n# @file tf_inference.py\n#\n# @author Videet Parekh\n#\n# @date Wed 16 Dec 20\n#\n# @brief TF inference engine designed with the same interface as leip_inference for parallel comparison\n\n\n# from time import time\n# import tensorflow as tf\nimport glob\nimport os\nimport logging\nimport utils.common_utils as utils\nimport argparse\nimport numpy as np\n\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n# print(\"Num GPUs Available: \", len(tf.config.experimental.list_physical_devices('GPU')))\n# tf.debugging.set_log_device_placement(True)\n\n\nclass TFModel():\n def __init__(self, base_path, context, config):\n self.context = context\n self.config = config\n self.load(base_path)\n\n def load(self, base):\n h5_path = glob.glob(os.path.join(base, '*.h5'))[0]\n self.model = utils.load_keras_model(h5_path)\n\n def infer(self, data):\n # Here's how you may measure runtime speed\n # start = time()\n output_data = self.model.predict(data)\n # end = time()\n pred = {'label': output_data}\n return pred\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--input_path', type=str, default=None, required=True, help='Path to model directory.')\n parser.add_argument('--test_path', type=str, default=None, required=True, help='Path to output test file')\n parser.add_argument('--class_names', type=str, default=None, required=True, help='Path to class names list.')\n parser.add_argument('--data_type', type=str, default=\"float32\", required=False, help='Data Type.')\n parser.add_argument('--preprocessor', type=str, default=\"none\", required=False, help='Preprocessor function')\n parser.add_argument('--inference_context', type=str, default=\"none\", required=False, help='cpu/gpu/cuda.')\n parser.add_argument('--loglevel', type=str, default=\"WARNING\", required=False, help='Logging verbosity.')\n\n args = parser.parse_args()\n base = args.input_path\n test_path = args.test_path\n class_names = args.class_names\n data_type = args.data_type\n preprocessor = args.preprocessor\n context = args.inference_context\n loglevel = args.loglevel\n\n # Set Logger Parameters\n logging.basicConfig(level=utils.get_numeric_loglevel(loglevel))\n\n # Get class_names for model\n with open(class_names) as f:\n synset = f.readlines()\n\n config = utils.load_json(os.path.join(base, 'model_schema.json'))\n config['input_shapes'] = utils.parse_input_shapes(config['input_shapes'])\n\n # Load dataset and collect preprocessor function\n data_index = utils.load_index(test_path)\n preprocessor = utils.collect_preprocessor(preprocessor)\n\n # Create model object for inference\n model = TFModel(base, context, config)\n\n acc = 0\n\n # Loop over data and call infer()\n for data in data_index:\n # Load and preprocess image\n img = utils.collect_image(data[0], data_type, preprocessor, config['input_shapes'])\n\n # Infer\n pred = model.infer(img)\n pred_label = np.argmax(pred['label'])\n acc += 1 if pred_label == data[1] else 0\n\n print(acc*100/len(data_index))\n" ]
[ [ "numpy.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cldf/cldfviz
[ "c222a735a161b61b755584f62eb1ba1c64f797c0" ]
[ "src/cldfviz/colormap.py" ]
[ "import json\nimport typing\nimport collections\n\nfrom matplotlib import cm\nfrom matplotlib.colors import Normalize, to_hex, CSS4_COLORS, BASE_COLORS\nimport matplotlib.pyplot as plt\nfrom clldutils.color import qualitative_colors, sequential_colors, rgb_as_hex\n\nfrom cldfviz.multiparameter import CONTINUOUS, CATEGORICAL, Parameter\n\n__all__ = ['COLORMAPS', 'hextriplet', 'Colormap']\nCOLORMAPS = {\n CATEGORICAL: ['boynton', 'tol', 'base', 'seq'],\n CONTINUOUS: [cm for cm in plt.colormaps() if not cm.endswith('_r')],\n}\n\n\ndef hextriplet(s):\n \"\"\"\n Wrap clldutils.color.rgb_as_hex to provide unified error handling.\n \"\"\"\n if s in BASE_COLORS:\n return rgb_as_hex([float(d) for d in BASE_COLORS[s]])\n if s in CSS4_COLORS:\n return CSS4_COLORS[s]\n try:\n return rgb_as_hex(s)\n except (AssertionError, ValueError) as e:\n raise ValueError('Invalid color spec: \"{}\" ({})'.format(s, str(e)))\n\n\nclass Colormap:\n def __init__(self, parameter: Parameter, name: typing.Optional[str] = None, novalue=None):\n domain = parameter.domain\n self.explicit_cm = None\n if name and name.startswith('{'):\n self.explicit_cm = collections.OrderedDict()\n raw = json.loads(name, object_pairs_hook=collections.OrderedDict)\n if novalue:\n raw.setdefault('None', novalue)\n label_to_code = {v: k for k, v in parameter.domain.items()}\n for v, c in raw.items():\n if (v not in parameter.value_to_code) and v not in label_to_code:\n raise ValueError('Colormap value \"{}\" not in domain {}'.format(\n v, list(parameter.value_to_code.keys())))\n v = parameter.value_to_code.get(v, label_to_code.get(v))\n self.explicit_cm[v] = hextriplet(c)\n vals = list(parameter.value_to_code)\n if len(vals) > len(self.explicit_cm):\n raise ValueError('Colormap {} does not cover all values {}!'.format(\n dict(raw), vals))\n name = None\n # reorder the domain of the parameter (and prune it to valid values):\n parameter.domain = collections.OrderedDict(\n (c, l) for c, l in sorted(\n [i for i in parameter.domain.items() if i[0] in self.explicit_cm],\n key=lambda i: list(self.explicit_cm.keys()).index(i[0]))\n )\n self.novalue = hextriplet(novalue) if novalue else None\n self._cm = getattr(cm, name or 'yyy', cm.jet)\n\n if isinstance(domain, tuple):\n assert not self.explicit_cm\n # Initialize matplotlib colormap and normalizer:\n norm = Normalize(domain[0], domain[1])\n self.cm = lambda v: to_hex(self._cm(norm(float(v))))\n else:\n if self.explicit_cm:\n self.cm = lambda v: self.explicit_cm[v]\n else:\n if name == 'seq':\n colors = sequential_colors(len(domain))\n else:\n colors = qualitative_colors(len(domain), set=name)\n self.cm = lambda v: dict(zip(domain, colors))[v]\n\n def scalar_mappable(self):\n return cm.ScalarMappable(norm=None, cmap=self._cm)\n\n def __call__(self, value):\n if value is None:\n return self.novalue\n return self.cm(value)\n" ]
[ [ "matplotlib.cm.endswith", "matplotlib.cm.ScalarMappable", "matplotlib.pyplot.colormaps", "matplotlib.colors.Normalize" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
danibene/NeuroKit
[ "df0ab6696e7418cf8b8dcd3ed82dbf879fa61b3a", "df0ab6696e7418cf8b8dcd3ed82dbf879fa61b3a", "df0ab6696e7418cf8b8dcd3ed82dbf879fa61b3a", "df0ab6696e7418cf8b8dcd3ed82dbf879fa61b3a", "df0ab6696e7418cf8b8dcd3ed82dbf879fa61b3a", "df0ab6696e7418cf8b8dcd3ed82dbf879fa61b3a" ]
[ "neurokit2/complexity/entropy_distribution.py", "neurokit2/markov/markov_test_homogeneity.py", "neurokit2/signal/signal_synchrony.py", "neurokit2/misc/intervals_to_peaks.py", "neurokit2/eda/eda_sympathetic.py", "neurokit2/markov/markov_simulate.py" ]
[ "import numpy as np\nimport pandas as pd\nimport scipy.stats\n\nfrom .utils_complexity_embedding import complexity_embedding\nfrom .entropy_shannon import entropy_shannon\n\n\ndef entropy_distribution(signal=None, delay=1, dimension=3, bins=\"Sturges\", base=2):\n \"\"\"**Distribution Entropy (DistrEn)**\n\n Distribution Entropy (**DistrEn**, more commonly known as **DistEn**).\n\n Parameters\n ----------\n signal : Union[list, np.array, pd.Series]\n The signal (i.e., a time series) in the form of a vector of values.\n delay : int\n Time delay (often denoted *Tau* :math:`\\\\tau`, sometimes referred to as *lag*) in samples.\n See :func:`complexity_delay` to estimate the optimal value for this parameter.\n dimension : int\n Embedding Dimension (*m*, sometimes referred to as *d* or *order*). See\n :func:`complexity_dimension` to estimate the optimal value for this parameter.\n bins : int or str\n Method to find the number of bins. Can be a number, or one of ``\"Sturges\"``, ``\"Rice\"``,\n ``\"Doane\"``, or ``\"sqrt\"``.\n base : int\n The logarithmic base to use for :func:`entropy_shannon`.\n\n Returns\n --------\n distren : float\n The Distance Entropy entropy of the signal.\n info : dict\n A dictionary containing additional information regarding the parameters used.\n\n See Also\n --------\n entropy_shannon\n\n Examples\n ----------\n .. ipython:: python\n\n import neurokit2 as nk\n\n signal = nk.signal_simulate(duration=2, frequency=5)\n\n distren, info = nk.entropy_distribution(signal)\n distren\n\n References\n -----------\n * Li, P., Liu, C., Li, K., Zheng, D., Liu, C., & Hou, Y. (2015). Assessing the complexity of\n short-term heartbeat interval series by distribution entropy. Medical & biological\n engineering & computing, 53(1), 77-87.\n\n \"\"\"\n # Sanity checks\n if isinstance(signal, (np.ndarray, pd.DataFrame)) and signal.ndim > 1:\n raise ValueError(\n \"Multidimensional inputs (e.g., matrices or multichannel data) are not supported yet.\"\n )\n\n # Store parameters\n info = {\n \"Dimension\": dimension,\n \"Delay\": delay,\n \"Bins\": bins,\n }\n\n # Time-delay embedding\n embedded = complexity_embedding(signal, delay=delay, dimension=dimension)\n\n # Compute distance\n n = len(embedded)\n d = np.zeros(round(n * (n - 1) / 2))\n for k in range(1, n):\n Ix = (int((k - 1) * (n - k / 2)), int(k * (n - ((k + 1) / 2))))\n d[Ix[0] : Ix[1]] = np.max(\n abs(np.tile(embedded[k - 1, :], (n - k, 1)) - embedded[k:, :]), axis=1\n )\n # TODO: \"D is symmetrical. Only the upper or lower triangular matrix will actually be adequate\n # for the estimation of the ePDF, which can be used to facilitate its fast calculation.\"\n\n n_d = len(d)\n\n # Number of bins\n if isinstance(bins, str):\n bins = bins.lower()\n if bins == \"sturges\":\n n_bins = np.ceil(np.log2(n_d) + 1)\n elif bins == \"rice\":\n n_bins = np.ceil(2 * (n_d ** (1 / 3)))\n elif bins == \"sqrt\":\n n_bins = np.ceil(np.sqrt(n_d))\n elif bins == \"doanes\":\n sigma = np.sqrt(6 * (n_d - 2) / ((n_d + 1) * (n_d + 3)))\n n_bins = np.ceil(1 + np.log2(n_d) + np.log2(1 + abs(scipy.stats.skew(d) / sigma)))\n else:\n raise Exception(\"Please enter a valid binning method\")\n else:\n n_bins = bins\n\n # Get probability\n freq, _ = np.histogram(d, int(n_bins))\n freq = freq / freq.sum()\n\n # Compute Shannon Entropy\n distren, _ = entropy_shannon(freq=freq, base=base)\n\n # Normalize by number of bins (so that the range should be within [0, 1])\n distren = distren / (np.log(n_bins) / np.log(base))\n\n return distren, info\n", "# -*- coding: utf-8 -*-\nimport numpy as np\nimport scipy.stats\n\n\ndef markov_test_homogeneity(sequence, size=10):\n \"\"\"**Is the Markov process homogeneous?**\n\n Performs a homogeneity test that tests the null hypothesis that the samples are\n homogeneous, i.e., from the same - but unspecified - population, against the alternative\n hypothesis that at least one pair of samples is from different populations.\n\n Parameters\n ----------\n sequence : Union[list, np.array, pd.Series]\n A list of discrete states.\n size : int\n The size of the non-overlapping windows to split the sequence.\n\n Returns\n -------\n dict\n Contains indices of the test.\n\n See Also\n --------\n transition_matrix\n\n Examples\n --------\n .. ipython:: python\n\n import neurokit2 as nk\n\n sequence = [0, 0, 1, 2, 2, 2, 1, 0, 0, 3]\n\n result = nk.markov_test_homogeneity(sequence, size=2)\n result[\"Homogeneity_p\"]\n\n References\n ----------\n * Kullback, S., Kupperman, M., & Ku, H. H. (1962). Tests for contingency tables and Markov\n chains. Technometrics, 4(4), 573-608.\n\n \"\"\"\n\n states = np.unique(sequence)\n n_states = len(states)\n n = len(sequence)\n r = int(np.floor(n / size)) # number of blocks\n if r < 5:\n raise ValueError(\"The size of the blocks is too high. Decrease the 'size' argument.\")\n f_ijk = np.zeros((r, n_states, n_states))\n f_ij = np.zeros((r, n_states))\n f_jk = np.zeros((n_states, n_states))\n f_i = np.zeros(r)\n f_j = np.zeros(n_states)\n\n # calculate f_ijk (time / block dep. transition matrix)\n for i in range(r): # block index\n for ii in range(size - 1): # pos. inside the current block\n j = sequence[i * size + ii]\n k = sequence[i * size + ii + 1]\n f_ijk[i, j, k] += 1.0\n f_ij[i, j] += 1.0\n f_jk[j, k] += 1.0\n f_i[i] += 1.0\n f_j[j] += 1.0\n\n # conditional homogeneity (Markovianity stationarity)\n T = 0.0\n for i, j, k in np.ndindex(f_ijk.shape):\n # conditional homogeneity\n f = f_ijk[i, j, k] * f_j[j] * f_ij[i, j] * f_jk[j, k]\n if f > 0:\n T += f_ijk[i, j, k] * np.log((f_ijk[i, j, k] * f_j[j]) / (f_ij[i, j] * f_jk[j, k]))\n\n out = {\"Homogeneity_t\": T * 2.0, \"Homogeneity_df\": (r - 1) * (n_states - 1) * n_states}\n out[\"Homogeneity_p\"] = scipy.stats.chi2.sf(\n out[\"Homogeneity_t\"], out[\"Homogeneity_df\"], loc=0, scale=1\n )\n return out\n", "# -*- coding: utf-8 -*-\nimport numpy as np\nimport pandas as pd\nimport scipy.signal\n\n\ndef signal_synchrony(signal1, signal2, method=\"hilbert\", window_size=50):\n \"\"\"Compute the synchrony (coupling) between two signals.\n\n Compute a continuous index of coupling between two signals either using the ``\"hilbert\"``\n method to get the instantaneous phase synchrony, or using rolling window correlation.\n\n The instantaneous phase synchrony measures the phase similarities between signals at each\n timepoint. The phase refers to the angle of the signal, calculated through the hilbert\n transform, when it is resonating between -pi to pi degrees. When two signals line up in phase\n their angular difference becomes zero.\n\n For less clean signals, windowed correlations are widely used because of their simplicity, and\n can be a good a robust approximation of synchrony between two signals. The limitation is the\n need to select a window.\n\n\n Parameters\n ----------\n signal1 : Union[list, np.array, pd.Series]\n Time series in the form of a vector of values.\n signal2 : Union[list, np.array, pd.Series]\n Time series in the form of a vector of values.\n method : str\n The method to use. Can be one of ``\"hilbert\"`` or ``\"correlation\"``.\n window_size : int\n Only used if ``method='correlation'``. The number of samples to use for rolling correlation.\n\n See Also\n --------\n signal_filter, signal_zerocrossings, signal_findpeaks\n\n Returns\n -------\n array\n A vector containing the phase of the signal, between 0 and 2*pi.\n\n Examples\n --------\n .. ipython:: python\n\n import neurokit2 as nk\n\n signal1 = nk.signal_simulate(duration=10, frequency=1)\n signal2 = nk.signal_simulate(duration=10, frequency=1.5)\n\n coupling_h = nk.signal_synchrony(signal1, signal2, method=\"hilbert\")\n coupling_c = nk.signal_synchrony(signal1, signal2, method=\"correlation\", window_size=1000/2)\n\n @savefig p_signal_synchrony1.png scale=100%\n nk.signal_plot([signal1, signal2, coupling_h, coupling_c])\n @suppress\n plt.close()\n\n References\n ----------\n * http://jinhyuncheong.com/jekyll/update/2017/12/10/Timeseries_synchrony_tutorial_and_simulations.html\n\n \"\"\"\n if method.lower() in [\"hilbert\", \"phase\"]:\n coupling = _signal_synchrony_hilbert(signal1, signal2)\n elif method.lower() in [\"correlation\"]:\n coupling = _signal_synchrony_correlation(signal1, signal2, window_size=int(window_size))\n\n else:\n raise ValueError(\n \"NeuroKit error: signal_synchrony(): 'method' should be one of 'hilbert' or 'correlation'.\"\n )\n\n return coupling\n\n\n# =============================================================================\n# Methods\n# =============================================================================\n\n\ndef _signal_synchrony_hilbert(signal1, signal2):\n\n hill1 = scipy.signal.hilbert(signal1)\n hill2 = scipy.signal.hilbert(signal2)\n\n phase1 = np.angle(hill1, deg=False)\n phase2 = np.angle(hill2, deg=False)\n synchrony = 1 - np.sin(np.abs(phase1 - phase2) / 2)\n\n return synchrony\n\n\ndef _signal_synchrony_correlation(signal1, signal2, window_size, center=False):\n \"\"\"**Calculates pairwise rolling correlation at each time**\n Grabs the upper triangle, at each timepoint.\n\n * window: window size of rolling corr in samples\n * center: whether to center result (Default: False, so correlation values are listed on the\n right.)\n\n \"\"\"\n data = pd.DataFrame({\"y1\": signal1, \"y2\": signal2})\n\n rolled = data.rolling(window=window_size, center=center).corr()\n synchrony = rolled[\"y1\"].loc[rolled.index.get_level_values(1) == \"y2\"].values\n\n # Realign\n synchrony = np.append(synchrony[int(window_size / 2) :], np.full(int(window_size / 2), np.nan))\n synchrony[np.isnan(synchrony)] = np.nanmean(synchrony)\n\n return synchrony\n", "import numpy as np\n\n\ndef intervals_to_peaks(intervals):\n \"\"\"Convenience function to convert intervals to peaks,\n such as from R-R intervals to R-peaks of an ECG signal.\n\n This can be useful if you do not have raw peak indices and have only\n interval data such as breath-to-breath (BBI) or rpeak-to-rpeak (RRI) intervals.\n\n Parameters\n ----------\n intervals : list or array\n List or numpy array of intervals.\n\n Returns\n -------\n array\n An array of integer values indicating the peak indices,\n with the first peak occurring at sample point 0.\n\n Examples\n ---------\n .. ipython:: python\n\n import neurokit2 as nk\n ibi = [500, 400, 700, 500, 300, 800, 500]\n peaks = nk.intervals_to_peaks(ibi)\n @savefig p_intervals_to_peaks.png scale=100%\n hrv_indices = nk.hrv_time(peaks, sampling_rate=100, show=True)\n @suppress\n plt.close()\n hrv_indices\n\n \"\"\"\n peaks = np.append([0], np.cumsum(intervals))\n\n return np.array([int(i) for i in peaks])\n", "# -*- coding: utf-8 -*-\nimport numpy as np\nimport pandas as pd\nimport scipy\n\nfrom ..signal import signal_filter, signal_resample, signal_timefrequency\nfrom ..signal.signal_power import _signal_power_instant_compute\nfrom ..signal.signal_psd import _signal_psd_welch\nfrom ..stats import standardize\n\n\ndef eda_sympathetic(\n eda_signal, sampling_rate=1000, frequency_band=[0.045, 0.25], method=\"posada\", show=False\n):\n \"\"\"**Sympathetic Nervous System Index from Electrodermal activity (EDA)**\n\n Derived from Posada-Quintero et al. (2016), who argue that dynamics of the sympathetic component\n of EDA signal is represented in the frequency band of 0.045-0.25Hz.\n\n Parameters\n ----------\n eda_signal : Union[list, np.array, pd.Series]\n The EDA signal (i.e., a time series) in the form of a vector of values.\n sampling_rate : int\n The sampling frequency of the signal (in Hz, i.e., samples/second).\n frequency_band : list\n List indicating the frequency range to compute the the power spectral density in.\n Defaults to [0.045, 0.25].\n method : str\n Can be one of ``\"ghiasi\"`` or ``\"posada\"``.\n show : bool\n If True, will return a plot of the power spectrum of the EDA signal within the specified\n frequency band.\n\n See Also\n --------\n .signal_filter, .signal_power, .signal_psd\n\n Returns\n -------\n dict\n A dictionary containing the EDA symptathetic indexes, accessible by keys ``\"EDA_Symp\"`` and\n ``\"EDA_SympN\"`` (normalized, obtained by dividing EDA_Symp by total power).\n\n Examples\n --------\n .. ipython:: python\n\n import neurokit2 as nk\n\n eda = nk.data('bio_resting_8min_100hz')['EDA']\n indexes_posada = nk.eda_sympathetic(eda, sampling_rate=100, method='posada', show=True)\n indexes_ghiasi = nk.eda_sympathetic(eda, sampling_rate=100, method='ghiasi', show=True)\n\n References\n ----------\n * Ghiasi, S., Grecol, A., Nardelli, M., Catrambonel, V., Barbieri, R., Scilingo, E., & Valenza,\n G. (2018). A New Sympathovagal Balance Index from Electrodermal Activity and Instantaneous\n Vagal Dynamics: A Preliminary Cold Pressor Study. 2018 40th Annual International Conference\n of the IEEE Engineering in Medicine and Biology Society (EMBC). doi:10.1109/embc.2018.8512932\n * Posada-Quintero, H. F., Florian, J. P., Orjuela-Cañón, A. D., Aljama-Corrales, T.,\n Charleston-Villalobos, S., & Chon, K. H. (2016). Power spectral density analysis of\n electrodermal activity for sympathetic function assessment. Annals of biomedical engineering,\n 44(10), 3124-3135.\n\n \"\"\"\n\n out = {}\n\n if method.lower() in [\"ghiasi\"]:\n out = _eda_sympathetic_ghiasi(\n eda_signal, sampling_rate=sampling_rate, frequency_band=frequency_band, show=show\n )\n elif method.lower() in [\"posada\", \"posada-quintero\", \"quintero\"]:\n out = _eda_sympathetic_posada(eda_signal, frequency_band=frequency_band, show=show)\n else:\n raise ValueError(\n \"NeuroKit error: eda_sympathetic(): 'method' should be \" \"one of 'ghiasi', 'posada'.\"\n )\n\n return out\n\n\n# =============================================================================\n# Methods\n# =============================================================================\n\n\ndef _eda_sympathetic_posada(eda_signal, frequency_band=[0.045, 0.25], show=True, out={}):\n\n # First step of downsampling\n downsampled_1 = scipy.signal.decimate(eda_signal, q=10, n=8) # Keep every 10th sample\n downsampled_2 = scipy.signal.decimate(downsampled_1, q=20, n=8) # Keep every 20th sample\n\n # High pass filter\n eda_filtered = signal_filter(\n downsampled_2, sampling_rate=2, lowcut=0.01, highcut=None, method=\"butterworth\", order=8\n )\n\n nperseg = 128\n overlap = nperseg // 2 # 50 % data overlap\n\n # Compute psd\n frequency, power = _signal_psd_welch(\n eda_filtered, sampling_rate=2, nperseg=nperseg, window_type=\"blackman\", noverlap=overlap\n )\n psd = pd.DataFrame({\"Frequency\": frequency, \"Power\": power})\n\n # Get sympathetic nervous system indexes\n eda_symp = _signal_power_instant_compute(psd, (frequency_band[0], frequency_band[1]))\n\n # Compute normalized psd\n psd[\"Power\"] /= np.max(psd[\"Power\"])\n eda_symp_normalized = _signal_power_instant_compute(psd, (frequency_band[0], frequency_band[1]))\n\n psd_plot = psd.loc[\n np.logical_and(psd[\"Frequency\"] >= frequency_band[0], psd[\"Frequency\"] <= frequency_band[1])\n ]\n\n if show is True:\n ax = psd_plot.plot(x=\"Frequency\", y=\"Power\", title=\"EDA Power Spectral Density (ms^2/Hz)\")\n ax.set(xlabel=\"Frequency (Hz)\", ylabel=\"Spectrum\")\n\n out = {\"EDA_Symp\": eda_symp, \"EDA_SympN\": eda_symp_normalized}\n\n return out\n\n\ndef _eda_sympathetic_ghiasi(\n eda_signal, sampling_rate=1000, frequency_band=[0.045, 0.25], show=True, out={}\n):\n\n min_frequency = frequency_band[0]\n max_frequency = frequency_band[1]\n\n # Downsample, normalize, filter\n desired_sampling_rate = 50\n downsampled = signal_resample(\n eda_signal, sampling_rate=sampling_rate, desired_sampling_rate=desired_sampling_rate\n )\n normalized = standardize(downsampled)\n filtered = signal_filter(\n normalized,\n sampling_rate=desired_sampling_rate,\n lowcut=0.01,\n highcut=0.5,\n method=\"butterworth\",\n )\n\n # Divide the signal into segments and obtain the timefrequency representation\n overlap = 59 * 50 # overlap of 59s in samples\n\n _, _, bins = signal_timefrequency(\n filtered,\n sampling_rate=desired_sampling_rate,\n min_frequency=min_frequency,\n max_frequency=max_frequency,\n method=\"stft\",\n window=60,\n window_type=\"blackman\",\n overlap=overlap,\n show=show,\n )\n\n eda_symp = np.mean(bins)\n eda_symp_normalized = eda_symp / np.max(bins)\n\n out = {\"EDA_Symp\": eda_symp, \"EDA_SympN\": eda_symp_normalized}\n\n return out\n", "# -*- coding: utf-8 -*-\nimport numpy as np\nimport scipy.stats\n\nfrom .transition_matrix import _sanitize_tm_input\n\n\ndef markov_simulate(tm, n=10):\n \"\"\"**Markov Chain Simulation**\n\n Given a :func:`transition_matrix`, this function simulates the corresponding sequence of states\n (also known as a discrete Markov chain).\n\n Parameters\n ----------\n tm : pd.DataFrame\n A probability matrix obtained from :func:`transition_matrix`.\n n : int\n Length of the simulated sequence.\n\n Returns\n -------\n np.ndarray\n Sequence of states.\n\n See Also\n --------\n transition_matrix\n\n Examples\n --------\n .. ipython:: python\n\n import neurokit2 as nk\n\n sequence = [0, 0, 1, 2, 2, 2, 1, 0, 0, 3]\n tm, _ = nk.transition_matrix(sequence)\n\n x = nk.markov_simulate(tm, n=15)\n x\n\n \"\"\"\n # Sanitize input\n tm = _sanitize_tm_input(tm)\n states = tm.columns.values\n\n # Start selection\n _start = np.argmax(tm.sum(axis=1) / tm.sum())\n\n # simulated sequence init\n seq = np.zeros(n, dtype=int)\n seq[0] = _start\n\n # random seeds\n random_states = np.random.randint(0, n, n)\n\n # simulation procedure\n for i in range(1, n):\n _ps = tm.values[seq[i - 1]]\n _sample = np.argmax(scipy.stats.multinomial.rvs(1, _ps, 1, random_state=random_states[i]))\n seq[i] = _sample\n\n return states[seq]\n" ]
[ [ "numpy.log", "numpy.log2", "numpy.sqrt", "numpy.tile", "numpy.ceil" ], [ "numpy.log", "numpy.unique", "numpy.floor", "numpy.ndindex", "numpy.zeros" ], [ "numpy.abs", "numpy.isnan", "pandas.DataFrame", "numpy.nanmean", "numpy.angle" ], [ "numpy.cumsum" ], [ "scipy.signal.decimate", "pandas.DataFrame", "numpy.max", "numpy.mean", "numpy.logical_and" ], [ "numpy.zeros", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
shivgahlout/DenseNet-pytorch
[ "8fd286d9f718d164a4583eebd100dff127263891" ]
[ "data_utils.py" ]
[ "import matplotlib.pyplot as plt\nimport matplotlib\nimport numpy as np\nfrom PIL import Image\nfrom scipy.misc import imsave, imread\n\n\ndef plots(epochs, train_acc, test_acc, train_loss, test_loss, train_error, test_error,filename):\n plt.style.use('bmh')\n\n fig=plt.figure(figsize=(8,6))\n plt.plot(epochs,train_acc, 'r', epochs,test_acc, 'g')\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train_acc', 'test_acc'], loc='upper left')\n fig.savefig(filename + '_accuracy.png')\n\n fig=plt.figure(figsize=(8,6))\n plt.plot(epochs,train_loss, 'r', epochs,test_loss, 'g')\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train_loss', 'test_loss'], loc='upper left')\n fig.savefig(filename + '_loss.png')\n \n fig=plt.figure(figsize=(8,6))\n plt.plot(epochs,train_error, 'r', epochs,test_error, 'g')\n plt.title('model error rate')\n plt.ylabel('error rate')\n plt.xlabel('epoch')\n plt.legend(['train_error', 'test_error'], loc='upper left')\n fig.savefig(filename + '_error.png')\n\n plt.close('all')\n\n\n\ndef write_csv(filename, train_acc,test_acc,train_loss,test_loss,train_error,test_error,epoch):\n if epoch==0:\n \n with open(filename, 'w') as f:\n f.write('train_acc,test_acc,train_loss, test_loss, train_error, test_error\\n') \n f.write('{0},{1},{2},{3},{4},{5}\\n'.format(train_acc[-1],\\\n test_acc[-1],\\\n train_loss[-1],\\\n test_loss[-1],\\\n train_error[-1],\\\n test_error[-1]))\n \n else:\n with open(filename, 'a') as f:\n f.write('{0},{1},{2},{3},{4},{5}\\n'.format(train_acc[-1],\\\n test_acc[-1],\\\n train_loss[-1],\\\n test_loss[-1],\\\n train_error[-1],\\\n test_error[-1]))\n \n\n\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.title", "matplotlib.pyplot.figure", "matplotlib.pyplot.plot", "matplotlib.pyplot.close", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.style.use", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
nsdumont/SemanticMapping
[ "af97a452b3de30a9670536c7fa92c28a70fae44d" ]
[ "semanticmapping/sspspace.py" ]
[ "import numpy as np\nimport scipy\nfrom scipy.stats import qmc\nfrom scipy.stats import special_ortho_group\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import minimize\n\nimport warnings\nfrom .ssp import SSP\n\nclass SSPSpace:\n def __init__(self, domain_dim: int, ssp_dim: int, axis_matrix=None, phase_matrix=None,\n domain_bounds=None, length_scale=1):\n \n \n self.sample_points = None\n self.sample_ssps = None\n self.domain_dim = domain_dim\n self.ssp_dim = ssp_dim\n \n if not isinstance(length_scale, np.ndarray) or length_scale.size == 1:\n self.length_scale = length_scale * np.ones((self.domain_dim,))\n \n if domain_bounds is not None:\n assert domain_bounds.shape[0] == domain_dim\n \n self.domain_bounds = domain_bounds\n \n if (axis_matrix is None) & (phase_matrix is None):\n raise RuntimeError(\"SSP spaces must be defined by either a axis matrix or phase matrix. Use subclasses to construct spaces with predefined axes.\")\n elif (phase_matrix is None):\n assert axis_matrix.shape[0] == ssp_dim, f'Expected ssp_dim {axis_matrix.shape[0]}, got {ssp_dim}.'\n assert axis_matrix.shape[1] == domain_dim\n self.axis_matrix = axis_matrix\n self.phase_matrix = (-1.j*np.log(np.fft.fft(axis_matrix,axis=0))).real\n elif (axis_matrix is None):\n assert phase_matrix.shape[0] == ssp_dim\n assert phase_matrix.shape[1] == domain_dim\n self.phase_matrix = phase_matrix\n self.axis_matrix = np.fft.ifft(np.exp(1.j*phase_matrix), axis=0).real\n \n def update_lengthscale(self, scale):\n if not isinstance(scale, np.ndarray) or scale.size == 1:\n self.length_scale = scale * np.ones((self.domain_dim,))\n else:\n assert scale.size == self.domain_dim\n self.length_scale = scale\n assert self.length_scale.size == self.domain_dim\n \n def encode(self,x):\n assert x.shape[0] == self.domain_dim\n ls_mat = np.atleast_2d(np.diag(1/self.length_scale.flatten()))\n scaled_x = ls_mat @ x\n data = np.fft.ifft( np.exp( 1.j * self.phase_matrix @ scaled_x ), axis=0 ).real\n return data\n \n def encode_and_deriv(self,x):\n ls_mat = np.atleast_2d(np.diag(1 / self.length_scale))\n scaled_x = x @ ls_mat\n fdata = np.exp( 1.j * self.phase_matrix @ scaled_x.T )\n data = np.fft.ifft( fdata, axis=0 ).real\n ddata = np.fft.ifft( 1.j * np.stack([np.diag(fdata[:,j]) for j in range(x.shape[0])]) @ self.phase_matrix @ ls_mat, axis=0 ).real\n\n return data.T, ddata.T\n \n def encode_fourier(self,x):\n assert x.shape[0] == self.domain_dim\n ls_mat = np.atleast_2d(np.diag(1/self.length_scale.flatten()))\n scaled_x = ls_mat @ x\n data = np.exp( 1.j * self.phase_matrix @ scaled_x )\n return data\n \n def encode_as_SSP(self,x):\n assert x.shape[0] == self.domain_dim\n return SSP(self.encode(x),self)\n \n \n def decode(self,ssp,method='from-set', num_sample_pts=10000,from_set_method='grid',num_init_pts =10):\n if method=='least-squares':\n # problems duw to complex log\n x = np.linalg.lstsq(self.phase_matrix, (1.j*np.log(np.fft.fft(ssp,axis=0))).real)[0]\n #raise NotImplementedError()\n #fssp = np.fft.fft(ssp,axis=0)\n #x = np.linalg.lstsq(np.tile(self.phase_matrix,(2,1)), np.hstack([np.arccos(fssp.real), np.arcsin(fssp.imag)]))\n return x\n elif method=='from-set':\n sample_ssps, sample_points = self.get_sample_ssps(num_sample_pts,method=from_set_method)\n sims = sample_ssps.T @ ssp\n return sample_points[:,np.argmax(sims)]\n elif method=='direct-optim':\n x0 = self.decode(ssp, method='from-set',num_sample_pts=num_init_pts)\n def min_func(x,target=ssp):\n x_ssp = self.encode(np.atleast_2d(x))\n return -np.inner(x_ssp, target).flatten()\n soln = minimize(min_func, x0, method='L-BFGS-B')\n return soln.x\n elif method=='grad_descent':\n x = self.decode(ssp, method='from-set',num_sample_pts=num_init_pts)\n fssp = np.fft.fft(ssp,axis=0)\n ls_mat = np.diag(1/self.length_scale.flatten())\n for j in range(10):\n scaled_x = ls_mat @ x\n x_enc = np.exp(1.j * self.phase_matrix @ scaled_x)\n grad_mat = (1.j * (self.phase_matrix @ ls_mat).T * x_enc)\n grad = (grad_mat @ fssp.T).flatten()\n x = x - 0.1*grad.real\n return x\n elif method=='nonlin-reg':\n x = self.decode(ssp, method='from-set',num_sample_pts=num_init_pts)\n fssp = np.fft.fft(ssp,axis=0)\n dy = np.hstack([fssp.real, fssp.imag])\n\n ls_mat = np.diag(1/self.length_scale.flatten())\n for j in range(10):\n J = np.vstack([self.phase_matrix * np.sin(self.phase_matrix @ x @ ls_mat).reshape(1,-1),\n -self.phase_matrix * np.cos(self.phase_matrix @ x @ ls_mat).reshape(1,-1)])\n soln = np.linalg.pinv(J.T @ J) @ J.T @ dy\n x = x + soln\n return x\n else:\n raise NotImplementedError()\n \n def clean_up(self,ssp,**kwargs):\n x = self.decode(ssp,**kwargs)\n return self.encode(x)\n \n \n def get_sample_points(self,num_points,method='grid'):\n if self.domain_bounds is None:\n bounds = np.vstack([-10*np.ones(self.domain_dim), 10*np.ones(self.domain_dim)]).T\n else:\n bounds = self.domain_bounds\n if method=='grid':\n n_per_dim = int(num_points**(1/self.domain_dim))\n if n_per_dim**self.domain_dim != num_points:\n warnings.warn((f'Evenly distributing points over a '\n f'{self.domain_dim} grid requires numbers '\n f'of samples to be powers of {self.domain_dim}.'\n f'Requested {num_points} samples, returning '\n f'{n_per_dim**self.domain_dim}'), RuntimeWarning)\n ### end if\n xs = np.linspace(bounds[:,0],bounds[:,1],n_per_dim)\n xxs = np.meshgrid(*[xs[:,i] for i in range(self.domain_dim)])\n sample_points = np.array([x.reshape(-1) for x in xxs])\n return sample_points\n elif method=='sobol':\n sampler = qmc.Sobol(d=self.domain_dim) \n lbounds = bounds[:,0]\n ubounds = bounds[:,1]\n u_sample_points = sampler.random(num_points)\n sample_points = qmc.scale(u_sample_points, lbounds, ubounds)\n return sample_points.T \n else:\n raise NotImplementedError()\n \n \n \n def get_sample_ssps(self,num_points,**kwargs): # make new if num_pts different than whats stored?\n sample_points = self.get_sample_points(num_points,**kwargs)\n sample_ssps = self.encode(sample_points)\n return sample_ssps, sample_points\n \n def identity(self):\n s = np.zeros(self.ssp_dim)\n s[0] = 1\n return s\n \n def bind(self,a,b):\n return np.fft.ifft(np.fft.fft(a) * np.fft.fft(b)).real\n \n def invert(self,a):\n return a[-np.arange(len(a))]\n \n def normalize(self,ssp):\n return ssp/np.max([1e-6,np.sqrt(np.sum(ssp**2))])\n \n def unitary(self,ssp):\n fssp = np.fft.fft(ssp)\n fssp = fssp/np.sqrt(fssp.real**2 + fssp.imag**2)\n return np.fft.ifft(fssp).real \n \n def unitary_fourier(self,fssp):\n fssp = fssp/np.sqrt(fssp.real**2 + fssp.imag**2)\n return fssp \n\n def decode_path(self, ssp_path, N_ma=None, n_samples = 10000):\n sample_ssps, sample_points = self.get_sample_ssps(n_samples)\n path = np.zeros((ssp_path.shape[0], self.domain_dim))\n max_sims = np.zeros(ssp_path.shape[0])\n for i in range(ssp_path.shape[0]):\n sims = sample_ssps.T @ ssp_path[i,:]\n max_sims[i] = np.max(sims)\n path[i,:] = sample_points[:,np.argmax(sims)]\n \n return path, max_sims\n \n def similarity_plot(self,ssp,n_grid=100,plot_type='heatmap',cmap=\"YlGnBu\",ax=None,**kwargs):\n if ax is None:\n fig = plt.figure()\n ax = fig.add_subplot(111)\n \n if self.domain_dim == 1:\n xs = np.linspace(self.domain_bounds[0,0],self.domain_bounds[0,1], n_grid)\n im=ax.plot(xs, self.encode(xs.reshape(1,-1)).T @ self.data)\n ax.set_xlim(self.domain_bounds[0,0],self.domain_bounds[0,1])\n elif self.domain_dim == 2:\n xs = np.linspace(self.domain_bounds[0,0],self.domain_bounds[0,1], n_grid)\n ys = np.linspace(self.domain_bounds[1,0],self.domain_bounds[1,1], n_grid)\n X,Y = np.meshgrid(xs,ys)\n sims = self.encode(np.vstack([X.reshape(-1),Y.reshape(-1)])).T @ ssp\n if plot_type=='heatmap':\n im=ax.pcolormesh(X,Y,sims.reshape(X.shape),cmap=cmap,**kwargs)\n elif plot_type=='contour':\n im=ax.contour(X,Y,sims.reshape(X.shape),cmap=cmap,**kwargs)\n elif plot_type=='contourf':\n im=ax.contourf(X,Y,sims.reshape(X.shape),cmap=cmap,**kwargs)\n ax.set_xlim(self.domain_bounds[0,0],self.domain_bounds[0,1])\n ax.set_ylim(self.domain_bounds[1,0],self.domain_bounds[1,1])\n else:\n raise NotImplementedError()\n return im\n \n \n \n \nclass RandomSSPSpace(SSPSpace):\n def __init__(self, domain_dim: int, ssp_dim: int, domain_bounds=None, length_scale=1, rng=np.random.default_rng()):\n partial_phases = rng.random.rand(ssp_dim//2,domain_dim)*2*np.pi - np.pi\n axis_matrix = _constructaxisfromphases(partial_phases)\n super().__init__(domain_dim,ssp_dim,axis_matrix=axis_matrix,\n domain_bounds=domain_bounds,length_scale=length_scale)\n \nclass HexagonalSSPSpace(SSPSpace):\n def __init__(self, domain_dim:int,ssp_dim: int=151, n_rotates:int=5, n_scales:int=5, \n scale_min=2*np.pi/np.sqrt(6) - 0.5, scale_max=2*np.pi/np.sqrt(6) + 0.5,\n domain_bounds=None, length_scale=1):\n\n if (n_rotates==5) & (n_scales==5) & (ssp_dim != 151):\n n_rotates = int(np.max([1,np.sqrt((ssp_dim-1)/(2*(domain_dim+1)))]))\n n_scales = n_rotates\n \n phases_hex = np.hstack([np.sqrt(1+ 1/domain_dim)*np.identity(domain_dim) - (domain_dim**(-3/2))*(np.sqrt(domain_dim+1) + 1),\n (domain_dim**(-1/2))*np.ones((domain_dim,1))]).T\n \n self.grid_basis_dim = domain_dim + 1\n self.num_grids = n_rotates*n_scales\n\n scales = np.linspace(scale_min,scale_max,n_scales)\n phases_scaled = np.vstack([phases_hex*i for i in scales])\n \n if (n_rotates==1):\n phases_scaled_rotated = phases_scaled\n elif (domain_dim==1):\n scales = np.linspace(scale_min,scale_max,n_scales+n_rotates)\n phases_scaled_rotated = np.vstack([phases_hex*i for i in scales])\n elif (domain_dim == 2):\n angles = np.linspace(0,2*np.pi/3,n_rotates)\n R_mats = np.stack([np.stack([np.cos(angles), -np.sin(angles)],axis=1),\n np.stack([np.sin(angles), np.cos(angles)], axis=1)], axis=1)\n phases_scaled_rotated = (R_mats @ phases_scaled.T).transpose(0,2,1).reshape(-1,domain_dim)\n else:\n R_mats = special_ortho_group.rvs(domain_dim, size=n_rotates)\n phases_scaled_rotated = (R_mats @ phases_scaled.T).transpose(0,2,1).reshape(-1,domain_dim)\n \n axis_matrix = _constructaxisfromphases(phases_scaled_rotated)\n ssp_dim = axis_matrix.shape[0]\n super().__init__(domain_dim,ssp_dim,axis_matrix=axis_matrix,\n domain_bounds=domain_bounds,length_scale=length_scale)\n \n def sample_grid_encoders(self, n):\n sample_pts = self.get_sample_points(n,method='sobol')\n N = self.num_grids\n if N < n:\n sorts = np.hstack([np.arange(N), np.random.randint(0, N - 1, size = n - N)])\n else:\n sorts = np.arange(n)\n encoders = np.zeros((self.ssp_dim,n))\n for i in range(n):\n sub_mat = _get_sub_SSP(sorts[i],N,sublen=self.grid_basis_dim)\n proj_mat = _proj_sub_SSP(sorts[i],N,sublen=self.grid_basis_dim)\n sub_space = SSPSpace(self.domain_dim,2*self.grid_basis_dim + 1, axis_matrix= sub_mat @ self.axis_matrix)\n encoders[:,i] = N * proj_mat @ sub_space.encode(sample_pts[:,i])\n return encoders\n\n \n \ndef _constructaxisfromphases(K):\n d = K.shape[0]\n n = K.shape[1]\n axes = np.ones((d*2 + 1,n))\n for i in range(n):\n F = np.ones((d*2 + 1,), dtype=\"complex\")\n F[0:d] = np.exp(1.j*K[:,i])\n F[-d:] = np.flip(np.conj(F[0:d]))\n F = np.fft.ifftshift(F)\n axes[:,i] = np.fft.ifft(F).real\n return axes\n\ndef _get_sub_FourierSSP(n, N, sublen=3):\n # Return a matrix, \\bar{A}_n\n # Consider the multi scale representation (S_{total}) and sub vectors (S_n) described in the paper \n # Then\n # \\bar{A}_n F{S_{total}} = F{S_n}\n # i.e. pick out the sub vector in the Fourier domain\n tot_len = 2*sublen*N + 1\n FA = np.zeros((2*sublen + 1, tot_len))\n FA[0:sublen, sublen*n:sublen*(n+1)] = np.eye(sublen)\n FA[sublen, sublen*N] = 1\n FA[sublen+1:, tot_len - np.arange(sublen*(n+1),sublen*n,-1)] = np.eye(sublen)\n return FA\n\ndef _get_sub_SSP(n,N,sublen=3):\n # Return a matrix, A_n\n # Consider the multi scale representation (S_{total}) and sub vectors (S_n) described in the paper \n # Then\n # A_n S_{total} = S_n\n # i.e. pick out the sub vector in the time domain\n tot_len = 2*sublen*N + 1\n FA = _get_sub_FourierSSP(n,N,sublen=sublen)\n W = np.fft.fft(np.eye(tot_len))\n invW = np.fft.ifft(np.eye(2*sublen + 1))\n A = invW @ np.fft.ifftshift(FA) @ W\n return A.real\n\ndef _proj_sub_FourierSSP(n,N,sublen=3):\n # Return a matrix, \\bar{B}_n\n # Consider the multi scale representation (S_{total}) and sub vectors (S_n) described in the paper \n # Then\n # \\sum_n \\bar{B}_n F{S_{n}} = F{S_{total}}\n # i.e. project the sub vector in the Fourier domain such that summing all such projections gives the full vector in Fourier domain\n tot_len = 2*sublen*N + 1\n FB = np.zeros((2*sublen + 1, tot_len))\n FB[0:sublen, sublen*n:sublen*(n+1)] = np.eye(sublen)\n FB[sublen, sublen*N] = 1/N # all sub vectors have a \"1\" zero freq term so scale it so full vector will have 1 \n FB[sublen+1:, tot_len - np.arange(sublen*(n+1),sublen*n,-1)] = np.eye(sublen)\n return FB.T\n\ndef _proj_sub_SSP(n,N,sublen=3):\n # Return a matrix, B_n\n # Consider the multi scale representation (S_{total}) and sub vectors (S_n) described in the paper \n # Then\n # \\sum_n B_n S_{n} = S_{total}\n # i.e. project the sub vector in the time domain such that summing all such projections gives the full vector\n tot_len = 2*sublen*N + 1\n FB = _proj_sub_FourierSSP(n,N,sublen=sublen)\n invW = np.fft.ifft(np.eye(tot_len))\n W = np.fft.fft(np.eye(2*sublen + 1))\n B = invW @ np.fft.ifftshift(FB) @ W\n return B.real\n" ]
[ [ "numpy.diag", "numpy.sqrt", "numpy.linspace", "numpy.max", "scipy.stats.special_ortho_group.rvs", "numpy.exp", "numpy.random.default_rng", "numpy.random.randint", "numpy.hstack", "numpy.arange", "numpy.eye", "numpy.sin", "numpy.fft.ifftshift", "numpy.argmax", "numpy.zeros", "matplotlib.pyplot.figure", "numpy.fft.ifft", "scipy.stats.qmc.Sobol", "numpy.atleast_2d", "scipy.optimize.minimize", "numpy.identity", "scipy.stats.qmc.scale", "numpy.meshgrid", "numpy.sum", "numpy.conj", "numpy.fft.fft", "numpy.inner", "numpy.cos", "numpy.ones", "numpy.linalg.pinv", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.8", "1.7", "1.10", "1.9" ], "tensorflow": [] } ]
ChaseMonsterAway/mmclassification
[ "85d26b8eb2fc799599c42ca33831c40707311bd7", "85d26b8eb2fc799599c42ca33831c40707311bd7" ]
[ "mmcls/models/backbones/mobilenet_v2.py", "mmcls/models/losses/cross_entropy_loss.py" ]
[ "# Copyright (c) OpenMMLab. All rights reserved.\nimport torch.nn as nn\nimport torch.utils.checkpoint as cp\nfrom mmcv.cnn import ConvModule\nfrom mmcv.runner import BaseModule\nfrom torch.nn.modules.batchnorm import _BatchNorm\n\nfrom mmcls.models.utils import make_divisible\nfrom ..builder import BACKBONES\nfrom .base_backbone import BaseBackbone\n\n\nclass InvertedResidual(BaseModule):\n \"\"\"InvertedResidual block for MobileNetV2.\n\n Args:\n in_channels (int): The input channels of the InvertedResidual block.\n out_channels (int): The output channels of the InvertedResidual block.\n stride (int): Stride of the middle (first) 3x3 convolution.\n expand_ratio (int): adjusts number of channels of the hidden layer\n in InvertedResidual by this amount.\n conv_cfg (dict, optional): Config dict for convolution layer.\n Default: None, which means using conv2d.\n norm_cfg (dict): Config dict for normalization layer.\n Default: dict(type='BN').\n act_cfg (dict): Config dict for activation layer.\n Default: dict(type='ReLU6').\n with_cp (bool): Use checkpoint or not. Using checkpoint will save some\n memory while slowing down the training speed. Default: False.\n\n Returns:\n Tensor: The output tensor\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n stride,\n expand_ratio,\n conv_cfg=None,\n norm_cfg=dict(type='BN'),\n act_cfg=dict(type='ReLU'),\n with_cp=False,\n init_cfg=None):\n super(InvertedResidual, self).__init__(init_cfg)\n self.stride = stride\n assert stride in [1, 2], f'stride must in [1, 2]. ' \\\n f'But received {stride}.'\n self.with_cp = with_cp\n self.use_res_connect = self.stride == 1 and in_channels == out_channels\n hidden_dim = int(round(in_channels * expand_ratio))\n\n layers = []\n if expand_ratio != 1:\n layers.append(\n ConvModule(\n in_channels=in_channels,\n out_channels=hidden_dim,\n kernel_size=1,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n act_cfg=act_cfg))\n layers.extend([\n ConvModule(\n in_channels=hidden_dim,\n out_channels=hidden_dim,\n kernel_size=3,\n stride=stride,\n padding=1,\n groups=hidden_dim,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n act_cfg=act_cfg),\n ConvModule(\n in_channels=hidden_dim,\n out_channels=out_channels,\n kernel_size=1,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n act_cfg=None)\n ])\n self.conv = nn.Sequential(*layers)\n\n def forward(self, x):\n\n def _inner_forward(x):\n if self.use_res_connect:\n return x + self.conv(x)\n else:\n return self.conv(x)\n\n if self.with_cp and x.requires_grad:\n out = cp.checkpoint(_inner_forward, x)\n else:\n out = _inner_forward(x)\n\n return out\n\n\[email protected]_module()\nclass MobileNetV2(BaseBackbone):\n \"\"\"MobileNetV2 backbone.\n\n Args:\n widen_factor (float): Width multiplier, multiply number of\n channels in each layer by this amount. Default: 1.0.\n out_indices (None or Sequence[int]): Output from which stages.\n Default: (7, ).\n frozen_stages (int): Stages to be frozen (all param fixed).\n Default: -1, which means not freezing any parameters.\n conv_cfg (dict, optional): Config dict for convolution layer.\n Default: None, which means using conv2d.\n norm_cfg (dict): Config dict for normalization layer.\n Default: dict(type='BN').\n act_cfg (dict): Config dict for activation layer.\n Default: dict(type='ReLU6').\n norm_eval (bool): Whether to set norm layers to eval mode, namely,\n freeze running stats (mean and var). Note: Effect on Batch Norm\n and its variants only. Default: False.\n with_cp (bool): Use checkpoint or not. Using checkpoint will save some\n memory while slowing down the training speed. Default: False.\n \"\"\"\n\n # Parameters to build layers. 4 parameters are needed to construct a\n # layer, from left to right: expand_ratio, channel, num_blocks, stride.\n arch_settings = [[1, 16, 1, 1], [6, 24, 2, 2], [6, 32, 3, 2],\n [6, 64, 4, 2], [6, 96, 3, 1], [6, 160, 3, 2],\n [6, 320, 1, 1]]\n\n def __init__(self,\n widen_factor=1.,\n out_indices=(7, ),\n frozen_stages=-1,\n deep_stem=False,\n conv_cfg=None,\n norm_cfg=dict(type='BN'),\n act_cfg=dict(type='ReLU'),\n norm_eval=False,\n with_cp=False,\n init_cfg=[\n dict(type='Kaiming', layer=['Conv2d']),\n dict(\n type='Constant',\n val=1,\n layer=['_BatchNorm', 'GroupNorm'])\n ]):\n super(MobileNetV2, self).__init__(init_cfg)\n self.widen_factor = widen_factor\n self.out_indices = out_indices\n for index in out_indices:\n if index not in range(0, 8):\n raise ValueError('the item in out_indices must in '\n f'range(0, 8). But received {index}')\n\n if frozen_stages not in range(-1, 8):\n raise ValueError('frozen_stages must be in range(-1, 8). '\n f'But received {frozen_stages}')\n self.out_indices = out_indices\n self.frozen_stages = frozen_stages\n self.conv_cfg = conv_cfg\n self.norm_cfg = norm_cfg\n self.act_cfg = act_cfg\n self.norm_eval = norm_eval\n self.with_cp = with_cp\n\n self.in_channels = make_divisible(32 * widen_factor, 8)\n if deep_stem:\n self.conv0 = ConvModule(in_channels=3, out_channels=16, kernel_size=3, stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, act_cfg=self.act_cfg)\n in_channels_ = 16\n else:\n in_channels_ = 3\n self.conv0 = nn.Sequential()\n self.conv1 = ConvModule(\n in_channels=in_channels_,\n out_channels=self.in_channels,\n kernel_size=3,\n stride=2,\n padding=1,\n conv_cfg=self.conv_cfg,\n norm_cfg=self.norm_cfg,\n act_cfg=self.act_cfg)\n\n self.layers = []\n\n for i, layer_cfg in enumerate(self.arch_settings):\n expand_ratio, channel, num_blocks, stride = layer_cfg\n out_channels = make_divisible(channel * widen_factor, 8)\n inverted_res_layer = self.make_layer(\n out_channels=out_channels,\n num_blocks=num_blocks,\n stride=stride,\n expand_ratio=expand_ratio)\n layer_name = f'layer{i + 1}'\n self.add_module(layer_name, inverted_res_layer)\n self.layers.append(layer_name)\n\n if widen_factor > 1.0:\n self.out_channel = int(1280 * widen_factor)\n else:\n self.out_channel = 1280\n\n layer = ConvModule(\n in_channels=self.in_channels,\n out_channels=self.out_channel,\n kernel_size=1,\n stride=1,\n padding=0,\n conv_cfg=self.conv_cfg,\n norm_cfg=self.norm_cfg,\n act_cfg=self.act_cfg)\n self.add_module('conv2', layer)\n self.layers.append('conv2')\n\n def make_layer(self, out_channels, num_blocks, stride, expand_ratio):\n \"\"\"Stack InvertedResidual blocks to build a layer for MobileNetV2.\n\n Args:\n out_channels (int): out_channels of block.\n num_blocks (int): number of blocks.\n stride (int): stride of the first block. Default: 1\n expand_ratio (int): Expand the number of channels of the\n hidden layer in InvertedResidual by this ratio. Default: 6.\n \"\"\"\n layers = []\n for i in range(num_blocks):\n if i >= 1:\n stride = 1\n layers.append(\n InvertedResidual(\n self.in_channels,\n out_channels,\n stride,\n expand_ratio=expand_ratio,\n conv_cfg=self.conv_cfg,\n norm_cfg=self.norm_cfg,\n act_cfg=self.act_cfg,\n with_cp=self.with_cp))\n self.in_channels = out_channels\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv0(x)\n x = self.conv1(x)\n\n outs = []\n for i, layer_name in enumerate(self.layers):\n layer = getattr(self, layer_name)\n x = layer(x)\n if i in self.out_indices:\n outs.append(x)\n\n return tuple(outs)\n\n def _freeze_stages(self):\n if self.frozen_stages >= 0:\n for param in self.conv1.parameters():\n param.requires_grad = False\n for i in range(1, self.frozen_stages + 1):\n layer = getattr(self, f'layer{i}')\n layer.eval()\n for param in layer.parameters():\n param.requires_grad = False\n\n def train(self, mode=True):\n super(MobileNetV2, self).train(mode)\n self._freeze_stages()\n if mode and self.norm_eval:\n for m in self.modules():\n if isinstance(m, _BatchNorm):\n m.eval()\n", "# Copyright (c) OpenMMLab. All rights reserved.\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom ..builder import LOSSES\nfrom .utils import weight_reduce_loss\n\n\ndef cross_entropy(pred,\n label,\n weight=None,\n reduction='mean',\n avg_factor=None,\n class_weight=None):\n \"\"\"Calculate the CrossEntropy loss.\n\n Args:\n pred (torch.Tensor): The prediction with shape (N, C), C is the number\n of classes.\n label (torch.Tensor): The gt label of the prediction.\n weight (torch.Tensor, optional): Sample-wise loss weight.\n reduction (str): The method used to reduce the loss.\n avg_factor (int, optional): Average factor that is used to average\n the loss. Defaults to None.\n class_weight (torch.Tensor, optional): The weight for each class with\n shape (C), C is the number of classes. Default None.\n\n Returns:\n torch.Tensor: The calculated loss\n \"\"\"\n # element-wise losses\n loss = F.cross_entropy(pred, label, weight=class_weight, reduction='none')\n\n # apply weights and do the reduction\n if weight is not None:\n weight = weight.float()\n loss = weight_reduce_loss(\n loss, weight=weight, reduction=reduction, avg_factor=avg_factor)\n\n return loss\n\n\ndef soft_cross_entropy(pred,\n label,\n weight=None,\n reduction='mean',\n class_weight=None,\n avg_factor=None):\n \"\"\"Calculate the Soft CrossEntropy loss. The label can be float.\n\n Args:\n pred (torch.Tensor): The prediction with shape (N, C), C is the number\n of classes.\n label (torch.Tensor): The gt label of the prediction with shape (N, C).\n When using \"mixup\", the label can be float.\n weight (torch.Tensor, optional): Sample-wise loss weight.\n reduction (str): The method used to reduce the loss.\n avg_factor (int, optional): Average factor that is used to average\n the loss. Defaults to None.\n class_weight (torch.Tensor, optional): The weight for each class with\n shape (C), C is the number of classes. Default None.\n\n Returns:\n torch.Tensor: The calculated loss\n \"\"\"\n # element-wise losses\n loss = -label * F.log_softmax(pred, dim=-1)\n if class_weight is not None:\n loss *= class_weight\n loss = loss.sum(dim=-1)\n\n # apply weights and do the reduction\n if weight is not None:\n weight = weight.float()\n loss = weight_reduce_loss(\n loss, weight=weight, reduction=reduction, avg_factor=avg_factor)\n\n return loss\n\n\ndef binary_cross_entropy(pred,\n label,\n weight=None,\n reduction='mean',\n avg_factor=None,\n class_weight=None):\n r\"\"\"Calculate the binary CrossEntropy loss with logits.\n\n Args:\n pred (torch.Tensor): The prediction with shape (N, \\*).\n label (torch.Tensor): The gt label with shape (N, \\*).\n weight (torch.Tensor, optional): Element-wise weight of loss with shape\n (N, ). Defaults to None.\n reduction (str): The method used to reduce the loss.\n Options are \"none\", \"mean\" and \"sum\". If reduction is 'none' , loss\n is same shape as pred and label. Defaults to 'mean'.\n avg_factor (int, optional): Average factor that is used to average\n the loss. Defaults to None.\n class_weight (torch.Tensor, optional): The weight for each class with\n shape (C), C is the number of classes. Default None.\n\n Returns:\n torch.Tensor: The calculated loss\n \"\"\"\n assert pred.dim() == label.dim()\n # Ensure that the size of class_weight is consistent with pred and label to\n # avoid automatic boracast,\n if class_weight is not None:\n N = pred.size()[0]\n class_weight = class_weight.repeat(N, 1)\n loss = F.binary_cross_entropy_with_logits(\n pred, label, weight=class_weight, reduction='none')\n\n # apply weights and do the reduction\n if weight is not None:\n assert weight.dim() == 1\n weight = weight.float()\n if pred.dim() > 1:\n weight = weight.reshape(-1, 1)\n loss = weight_reduce_loss(\n loss, weight=weight, reduction=reduction, avg_factor=avg_factor)\n return loss\n\n\[email protected]_module()\nclass CrossEntropyLoss(nn.Module):\n \"\"\"Cross entropy loss.\n\n Args:\n use_sigmoid (bool): Whether the prediction uses sigmoid\n of softmax. Defaults to False.\n use_soft (bool): Whether to use the soft version of CrossEntropyLoss.\n Defaults to False.\n reduction (str): The method used to reduce the loss.\n Options are \"none\", \"mean\" and \"sum\". Defaults to 'mean'.\n loss_weight (float): Weight of the loss. Defaults to 1.0.\n class_weight (List[float], optional): The weight for each class with\n shape (C), C is the number of classes. Default None.\n \"\"\"\n\n def __init__(self,\n use_sigmoid=False,\n use_soft=False,\n reduction='mean',\n loss_weight=1.0,\n class_weight=None):\n super(CrossEntropyLoss, self).__init__()\n self.use_sigmoid = use_sigmoid\n self.use_soft = use_soft\n assert not (\n self.use_soft and self.use_sigmoid\n ), 'use_sigmoid and use_soft could not be set simultaneously'\n\n self.reduction = reduction\n self.loss_weight = loss_weight\n self.class_weight = class_weight\n\n if self.use_sigmoid:\n self.cls_criterion = binary_cross_entropy\n elif self.use_soft:\n self.cls_criterion = soft_cross_entropy\n else:\n self.cls_criterion = cross_entropy\n\n def forward(self,\n cls_score,\n label,\n weight=None,\n avg_factor=None,\n reduction_override=None,\n **kwargs):\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n\n if self.class_weight is not None:\n class_weight = cls_score.new_tensor(self.class_weight)\n else:\n class_weight = None\n \n loss_cls = self.loss_weight * self.cls_criterion(\n cls_score,\n label,\n weight,\n class_weight=class_weight,\n reduction=reduction,\n avg_factor=avg_factor,\n **kwargs)\n\n return loss_cls\n" ]
[ [ "torch.nn.Sequential", "torch.utils.checkpoint.checkpoint" ], [ "torch.nn.functional.binary_cross_entropy_with_logits", "torch.nn.functional.cross_entropy", "torch.nn.functional.log_softmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
chemfiles/Chemharp.py
[ "45b8a02b7a0f07d6dcafa52db39df6a39f6f496c" ]
[ "chemfiles/selection.py" ]
[ "# -*- coding=utf-8 -*-\nfrom __future__ import absolute_import, print_function, unicode_literals\n\nfrom ctypes import c_uint64\nimport numpy as np\n\nfrom .utils import CxxPointer, _call_with_growing_buffer\nfrom .ffi import chfl_match\n\n\nclass Selection(CxxPointer):\n \"\"\"\n Select atoms in a :py:class:`Frame` with a selection language.\n\n The selection language is built by combining basic operations. Each basic\n operation follows the ``<selector>[(<variable>)] <operator> <value>``\n structure, where ``<operator>`` is a comparison operator in\n ``== != < <= > >=``. Refer to the `full documentation\n <selections-doc>`_ to know the allowed selectors and how to use them.\n\n .. selections-doc: https://chemfiles.org/chemfiles/latest/selections.html\n \"\"\"\n\n def __init__(self, selection):\n \"\"\"\n Create a new :py:class:`Selection` from the given ``selection`` string.\n \"\"\"\n ptr = self.ffi.chfl_selection(selection.encode(\"utf8\"))\n super(Selection, self).__init__(ptr, is_const=False)\n\n def __copy__(self):\n return Selection.from_mutable_ptr(None, self.ffi.chfl_selection_copy(self.ptr))\n\n def __repr__(self):\n return \"Selection('{}')\".format(self.string)\n\n @property\n def size(self):\n \"\"\"\n Get the size of this :py:class:`Selection`.\n\n The size of a selection is the number of atoms we are selecting\n together. This value is 1 for the 'atom' context, 2 for the 'pair' and\n 'bond' context, 3 for the 'three' and 'angles' contextes and 4 for the\n 'four' and 'dihedral' contextes.\n \"\"\"\n size = c_uint64()\n self.ffi.chfl_selection_size(self.ptr, size)\n return size.value\n\n @property\n def string(self):\n \"\"\"\n Get the selection string used to create this :py:class:`Selection`.\n \"\"\"\n return _call_with_growing_buffer(\n lambda buffer, size: self.ffi.chfl_selection_string(self.ptr, buffer, size),\n initial=128,\n )\n\n def evaluate(self, frame):\n \"\"\"\n Evaluate a :py:class:`Selection` for a given :py:class:`Frame`, and\n return a list of matching atoms, either as a list of index or a list\n of tuples of indexes.\n \"\"\"\n matching = c_uint64()\n self.ffi.chfl_selection_evaluate(self.mut_ptr, frame.ptr, matching)\n\n matches = np.zeros(matching.value, chfl_match)\n self.ffi.chfl_selection_matches(self.mut_ptr, matches, matching)\n\n size = self.size\n result = []\n for match in matches:\n assert match[0] == size\n atoms = match[1]\n if size == 1:\n result.append(atoms[0])\n elif size == 2:\n result.append((atoms[0], atoms[1]))\n elif size == 3:\n result.append((atoms[0], atoms[1], atoms[2]))\n elif size == 4:\n result.append((atoms[0], atoms[1], atoms[2], atoms[3]))\n return result\n" ]
[ [ "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Scartography/mapchete
[ "f7d1a74acb4021adfd3053501416d2b974c40af9" ]
[ "test/test_formats_geotiff.py" ]
[ "\"\"\"Test GeoTIFF as process output.\"\"\"\n\nimport numpy as np\nimport numpy.ma as ma\nimport os\nimport pytest\nimport rasterio\nfrom rasterio.io import MemoryFile\nfrom rio_cogeo.cogeo import cog_validate\nimport shutil\nfrom tilematrix import Bounds\nimport warnings\n\nimport mapchete\nfrom mapchete.errors import MapcheteConfigError\nfrom mapchete.io import path_exists\nfrom mapchete.formats.default import gtiff\nfrom mapchete.tile import BufferedTilePyramid\n\n\ndef test_output_data(mp_tmpdir):\n \"\"\"Check GeoTIFF as output data.\"\"\"\n output_params = dict(\n grid=\"geodetic\",\n format=\"GeoTIFF\",\n path=mp_tmpdir,\n pixelbuffer=0,\n metatiling=1,\n bands=1,\n dtype=\"int16\",\n delimiters=dict(\n bounds=Bounds(-180.0, -90.0, 180.0, 90.0),\n effective_bounds=Bounds(-180.439453125, -90.0, 180.439453125, 90.0),\n zoom=[5],\n process_bounds=Bounds(-180.0, -90.0, 180.0, 90.0),\n ),\n )\n output = gtiff.OutputDataWriter(output_params)\n assert output.path == mp_tmpdir\n assert output.file_extension == \".tif\"\n tp = BufferedTilePyramid(\"geodetic\")\n tile = tp.tile(5, 5, 5)\n # get_path\n assert output.get_path(tile) == os.path.join(*[mp_tmpdir, \"5\", \"5\", \"5\" + \".tif\"])\n # prepare_path\n try:\n temp_dir = os.path.join(*[mp_tmpdir, \"5\", \"5\"])\n output.prepare_path(tile)\n assert os.path.isdir(temp_dir)\n finally:\n shutil.rmtree(temp_dir, ignore_errors=True)\n # profile\n assert isinstance(output.profile(tile), dict)\n # write\n try:\n data = np.ones((1,) + tile.shape) * 128\n output.write(tile, data)\n # tiles_exist\n assert output.tiles_exist(tile)\n # read\n data = output.read(tile)\n assert isinstance(data, np.ndarray)\n assert not data[0].mask.any()\n finally:\n shutil.rmtree(mp_tmpdir, ignore_errors=True)\n # read empty\n try:\n data = output.read(tile)\n assert isinstance(data, np.ndarray)\n assert data[0].mask.all()\n finally:\n shutil.rmtree(mp_tmpdir, ignore_errors=True)\n # empty\n try:\n empty = output.empty(tile)\n assert isinstance(empty, ma.MaskedArray)\n assert not empty.any()\n finally:\n shutil.rmtree(mp_tmpdir, ignore_errors=True)\n # deflate with predictor\n try:\n # with pytest.deprecated_call():\n output_params.update(compress=\"deflate\", predictor=2)\n output = gtiff.OutputDataWriter(output_params)\n assert output.profile(tile)[\"compress\"] == \"deflate\"\n assert output.profile(tile)[\"predictor\"] == 2\n finally:\n shutil.rmtree(mp_tmpdir, ignore_errors=True)\n # using deprecated \"compression\" property\n try:\n with pytest.deprecated_call():\n output_params.update(compression=\"deflate\", predictor=2)\n output = gtiff.OutputDataWriter(output_params)\n assert output.profile(tile)[\"compress\"] == \"deflate\"\n assert output.profile(tile)[\"predictor\"] == 2\n finally:\n shutil.rmtree(mp_tmpdir, ignore_errors=True)\n\n\ndef test_for_web(client, mp_tmpdir):\n \"\"\"Send GTiff via flask.\"\"\"\n tile_base_url = \"/wmts_simple/1.0.0/cleantopo_br/default/WGS84/\"\n for url in [\"/\"]:\n response = client.get(url)\n assert response.status_code == 200\n for url in [\n tile_base_url + \"5/30/62.tif\",\n tile_base_url + \"5/30/63.tif\",\n tile_base_url + \"5/31/62.tif\",\n tile_base_url + \"5/31/63.tif\",\n ]:\n response = client.get(url)\n assert response.status_code == 200\n img = response.data\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n with MemoryFile(img) as memfile:\n with memfile.open() as dataset:\n assert dataset.read().any()\n\n\ndef test_input_data(mp_tmpdir, cleantopo_br):\n \"\"\"Check GeoTIFF proces output as input data.\"\"\"\n with mapchete.open(cleantopo_br.path) as mp:\n tp = BufferedTilePyramid(\"geodetic\")\n # TODO tile with existing but empty data\n tile = tp.tile(5, 5, 5)\n output_params = dict(\n grid=\"geodetic\",\n format=\"GeoTIFF\",\n path=mp_tmpdir,\n pixelbuffer=0,\n metatiling=1,\n bands=2,\n dtype=\"int16\",\n delimiters=dict(\n bounds=Bounds(-180.0, -90.0, 180.0, 90.0),\n effective_bounds=Bounds(-180.439453125, -90.0, 180.439453125, 90.0),\n zoom=[5],\n process_bounds=Bounds(-180.0, -90.0, 180.0, 90.0),\n ),\n )\n output = gtiff.OutputDataWriter(output_params)\n with output.open(tile, mp) as input_tile:\n for data in [\n input_tile.read(),\n input_tile.read(1),\n input_tile.read([1]),\n # TODO assert valid indexes are passed input_tile.read([1, 2])\n ]:\n assert isinstance(data, ma.masked_array)\n assert input_tile.is_empty()\n # open without resampling\n with output.open(tile, mp) as input_tile:\n pass\n\n\ndef test_write_geotiff_tags(mp_tmpdir, cleantopo_br, write_rasterfile_tags_py):\n \"\"\"Pass on metadata tags from user process to rasterio.\"\"\"\n conf = dict(**cleantopo_br.dict)\n conf.update(process=write_rasterfile_tags_py)\n with mapchete.open(conf) as mp:\n for tile in mp.get_process_tiles():\n data, tags = mp.execute(tile)\n assert data.any()\n assert isinstance(tags, dict)\n mp.write(process_tile=tile, data=(data, tags))\n # read data\n out_path = mp.config.output.get_path(tile)\n with rasterio.open(out_path) as src:\n assert \"filewide_tag\" in src.tags()\n assert src.tags()[\"filewide_tag\"] == \"value\"\n assert \"band_tag\" in src.tags(1)\n assert src.tags(1)[\"band_tag\"] == \"True\"\n\n\[email protected]\ndef test_s3_write_output_data(gtiff_s3, s3_example_tile, mp_s3_tmpdir):\n \"\"\"Write and read output.\"\"\"\n with mapchete.open(gtiff_s3.dict) as mp:\n process_tile = mp.config.process_pyramid.tile(*s3_example_tile)\n # basic functions\n assert mp.config.output.profile()\n assert mp.config.output.empty(process_tile).mask.all()\n assert mp.config.output.get_path(process_tile)\n # check if tile exists\n assert not mp.config.output.tiles_exist(process_tile)\n # write\n mp.batch_process(tile=process_tile.id)\n # check if tile exists\n assert mp.config.output.tiles_exist(process_tile)\n # read again, this time with data\n data = mp.config.output.read(process_tile)\n assert isinstance(data, np.ndarray)\n assert not data[0].mask.all()\n\n\ndef test_output_single_gtiff(output_single_gtiff):\n tile_id = (5, 3, 7)\n with mapchete.open(output_single_gtiff.path) as mp:\n process_tile = mp.config.process_pyramid.tile(*tile_id)\n # basic functions\n assert mp.config.output.profile()\n assert mp.config.output.empty(process_tile).mask.all()\n assert mp.config.output.get_path(process_tile)\n # check if tile exists\n assert not mp.config.output.tiles_exist(process_tile)\n # write\n mp.batch_process(multi=2)\n # check if tile exists\n assert mp.config.output.tiles_exist(process_tile)\n # read again, this time with data\n data = mp.config.output.read(process_tile)\n assert isinstance(data, np.ndarray)\n assert not data[0].mask.all()\n # write empty array\n data = ma.masked_array(\n data=np.ones(process_tile.shape),\n mask=np.ones(process_tile.shape),\n )\n mp.config.output.write(process_tile, data)\n assert os.path.isfile(mp.config.output.path)\n\n # error on existing file\n with pytest.raises(MapcheteConfigError):\n mapchete.open(output_single_gtiff.path)\n\n # overwrite existing file\n with mapchete.open(output_single_gtiff.path, mode=\"overwrite\") as mp:\n process_tile = mp.config.process_pyramid.tile(*tile_id)\n assert not mp.config.output.tiles_exist(process_tile)\n # write\n mp.batch_process(tile=process_tile.id)\n # check if tile exists\n assert mp.config.output.tiles_exist(process_tile)\n assert mp.config.output.tiles_exist(\n output_tile=mp.config.output_pyramid.intersecting(process_tile)[0]\n )\n # read again, this time with data\n data = mp.config.output.read(process_tile)\n assert isinstance(data, np.ndarray)\n assert not data[0].mask.all()\n\n\ndef test_output_single_gtiff_errors(output_single_gtiff):\n # single gtiff does not work on multiple zoom levels\n with pytest.raises(ValueError):\n mapchete.open(dict(output_single_gtiff.dict, zoom_levels=[5, 6]))\n\n # provide either process_tile or output_tile\n with mapchete.open(output_single_gtiff.path) as mp:\n tile = mp.config.process_pyramid.tile(5, 3, 7)\n with pytest.raises(ValueError):\n mp.config.output.tiles_exist(process_tile=tile, output_tile=tile)\n\n\ndef test_output_single_gtiff_pixelbuffer(output_single_gtiff):\n tile_id = (5, 3, 7)\n with mapchete.open(\n dict(\n output_single_gtiff.dict,\n output=dict(output_single_gtiff.dict[\"output\"], pixelbuffer=5),\n ),\n ) as mp:\n process_tile = mp.config.process_pyramid.tile(*tile_id)\n # basic functions\n assert mp.config.output.profile()\n assert mp.config.output.empty(process_tile).mask.all()\n assert mp.config.output.get_path(process_tile)\n # check if tile exists\n assert not mp.config.output.tiles_exist(process_tile)\n # write\n mp.batch_process(tile=process_tile.id)\n # check if tile exists\n assert mp.config.output.tiles_exist(process_tile)\n # read again, this time with data\n data = mp.config.output.read(process_tile)\n assert isinstance(data, np.ndarray)\n assert not data[0].mask.all()\n\n\ndef test_output_single_gtiff_compression(output_single_gtiff):\n tile_id = (5, 3, 7)\n with mapchete.open(\n dict(\n output_single_gtiff.dict,\n output=dict(output_single_gtiff.dict[\"output\"], compress=\"deflate\"),\n ),\n ) as mp:\n process_tile = mp.config.process_pyramid.tile(*tile_id)\n assert \"compress\" in mp.config.output.profile()\n assert mp.config.output.profile()[\"compress\"] == \"deflate\"\n mp.batch_process(tile=process_tile.id)\n\n with rasterio.open(mp.config.output.path) as src:\n assert src.profile[\"compress\"] == \"deflate\"\n\n\ndef test_output_single_gtiff_overviews(output_single_gtiff):\n # overwrite existing file\n with mapchete.open(\n dict(\n output_single_gtiff.dict,\n output=dict(\n output_single_gtiff.dict[\"output\"],\n overviews=True,\n overviews_resampling=\"bilinear\",\n ),\n ),\n ) as mp:\n tile_id = (5, 3, 7)\n process_tile = mp.config.process_pyramid.tile(*tile_id)\n mp.batch_process(tile=process_tile.id)\n\n with rasterio.open(mp.config.output.path) as src:\n assert src.overviews(1)\n assert src.tags().get(\"OVR_RESAMPLING_ALG\").lower() == \"bilinear\"\n for o in [1, 2, 4, 8]:\n a = src.read(\n masked=True, out_shape=(1, int(src.height / o), int(src.width / o))\n )\n assert not a.mask.all()\n\n\[email protected]\ndef test_output_single_gtiff_s3(output_single_gtiff, mp_s3_tmpdir):\n tile_id = (5, 3, 7)\n with mapchete.open(\n dict(\n output_single_gtiff.dict,\n output=dict(\n output_single_gtiff.dict[\"output\"],\n path=os.path.join(mp_s3_tmpdir, \"temp.tif\"),\n ),\n )\n ) as mp:\n process_tile = mp.config.process_pyramid.tile(*tile_id)\n # basic functions\n assert mp.config.output.profile()\n assert mp.config.output.empty(process_tile).mask.all()\n assert mp.config.output.get_path(process_tile)\n # check if tile exists\n assert not mp.config.output.tiles_exist(process_tile)\n # write\n mp.batch_process(multi=2)\n # check if tile exists\n assert mp.config.output.tiles_exist(process_tile)\n # read again, this time with data\n data = mp.config.output.read(process_tile)\n assert isinstance(data, np.ndarray)\n assert not data[0].mask.all()\n # write empty array\n data = ma.masked_array(\n data=np.ones(process_tile.shape),\n mask=np.ones(process_tile.shape),\n )\n mp.config.output.write(process_tile, data)\n assert path_exists(mp.config.output.path)\n\n\[email protected]\ndef test_output_single_gtiff_s3_tempfile(output_single_gtiff, mp_s3_tmpdir):\n tile_id = (5, 3, 7)\n with mapchete.open(\n dict(\n output_single_gtiff.dict,\n output=dict(\n output_single_gtiff.dict[\"output\"],\n path=os.path.join(mp_s3_tmpdir, \"temp.tif\"),\n in_memory=False,\n ),\n )\n ) as mp:\n process_tile = mp.config.process_pyramid.tile(*tile_id)\n # basic functions\n assert mp.config.output.profile()\n assert mp.config.output.empty(process_tile).mask.all()\n assert mp.config.output.get_path(process_tile)\n # check if tile exists\n assert not mp.config.output.tiles_exist(process_tile)\n # write\n mp.batch_process(multi=2)\n # check if tile exists\n assert mp.config.output.tiles_exist(process_tile)\n # read again, this time with data\n data = mp.config.output.read(process_tile)\n assert isinstance(data, np.ndarray)\n assert not data[0].mask.all()\n # write empty array\n data = ma.masked_array(\n data=np.ones(process_tile.shape),\n mask=np.ones(process_tile.shape),\n )\n mp.config.output.write(process_tile, data)\n assert path_exists(mp.config.output.path)\n\n\ndef test_output_single_gtiff_cog(output_single_gtiff_cog):\n tile_id = (5, 3, 7)\n with mapchete.open(output_single_gtiff_cog.dict) as mp:\n process_tile = mp.config.process_pyramid.tile(*tile_id)\n # basic functions\n assert mp.config.output.profile()\n assert mp.config.output.empty(process_tile).mask.all()\n assert mp.config.output.get_path(process_tile)\n # check if tile exists\n assert not mp.config.output.tiles_exist(process_tile)\n # write\n mp.batch_process(multi=2)\n # check if tile exists\n assert mp.config.output.tiles_exist(process_tile)\n # read again, this time with data\n data = mp.config.output.read(process_tile)\n assert isinstance(data, np.ndarray)\n assert not data[0].mask.all()\n # write empty array\n data = ma.masked_array(\n data=np.ones(process_tile.shape),\n mask=np.ones(process_tile.shape),\n )\n mp.config.output.write(process_tile, data)\n assert path_exists(mp.config.output.path)\n assert cog_validate(mp.config.output.path, strict=True)\n\n\ndef test_output_single_gtiff_cog_tempfile(output_single_gtiff_cog):\n tile_id = (5, 3, 7)\n with mapchete.open(\n dict(\n output_single_gtiff_cog.dict,\n output=dict(output_single_gtiff_cog.dict[\"output\"], in_memory=False),\n )\n ) as mp:\n process_tile = mp.config.process_pyramid.tile(*tile_id)\n # basic functions\n assert mp.config.output.profile()\n assert mp.config.output.empty(process_tile).mask.all()\n assert mp.config.output.get_path(process_tile)\n # check if tile exists\n assert not mp.config.output.tiles_exist(process_tile)\n # write\n mp.batch_process(multi=2)\n # check if tile exists\n assert mp.config.output.tiles_exist(process_tile)\n # read again, this time with data\n data = mp.config.output.read(process_tile)\n assert isinstance(data, np.ndarray)\n assert not data[0].mask.all()\n # write empty array\n data = ma.masked_array(\n data=np.ones(process_tile.shape),\n mask=np.ones(process_tile.shape),\n )\n mp.config.output.write(process_tile, data)\n assert path_exists(mp.config.output.path)\n assert cog_validate(mp.config.output.path, strict=True)\n\n\[email protected]\ndef test_output_single_gtiff_cog_s3(output_single_gtiff_cog, mp_s3_tmpdir):\n tile_id = (5, 3, 7)\n with mapchete.open(\n dict(\n output_single_gtiff_cog.dict,\n output=dict(\n output_single_gtiff_cog.dict[\"output\"],\n path=os.path.join(mp_s3_tmpdir, \"cog.tif\"),\n ),\n )\n ) as mp:\n process_tile = mp.config.process_pyramid.tile(*tile_id)\n # basic functions\n assert mp.config.output.profile()\n assert mp.config.output.empty(process_tile).mask.all()\n assert mp.config.output.get_path(process_tile)\n # check if tile exists\n assert not mp.config.output.tiles_exist(process_tile)\n # write\n mp.batch_process(multi=2)\n # check if tile exists\n assert mp.config.output.tiles_exist(process_tile)\n # read again, this time with data\n data = mp.config.output.read(process_tile)\n assert isinstance(data, np.ndarray)\n assert not data[0].mask.all()\n # write empty array\n data = ma.masked_array(\n data=np.ones(process_tile.shape),\n mask=np.ones(process_tile.shape),\n )\n mp.config.output.write(process_tile, data)\n assert path_exists(mp.config.output.path)\n assert cog_validate(mp.config.output.path, strict=True)\n" ]
[ [ "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
researchuser7/QWAugmenter
[ "eb70fa27ddb4b90d72c2eae6db2ff65086c3fb69", "eb70fa27ddb4b90d72c2eae6db2ff65086c3fb69" ]
[ "generator_labeler/paper_results/custom_plots.py", "generator_labeler/ActiveModel/ActiveQuantileForest.py" ]
[ "import numpy as np\nfrom sklearn.metrics import r2_score\n\nnp.random.seed(42)\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\n\nfigsize = (8, 4)\n\n\ndef show_r2(results):\n data_size = results[\"data_size\"]\n test_scores = results[\"test_scores\"]\n test_scores_exp = results[\"test_scores_exp\"]\n \n fig, ax = plt.subplots(figsize=(8, 4))\n ax.plot(list(map(lambda x: x[\"r2\"], test_scores)), marker=\"o\", label=\"Log(Exec. time)\", color=\"#777777\")\n ax.plot(list(map(lambda x: x[\"r2\"], test_scores_exp)), marker=\"o\", label=\"Exec. time\", color=\"#111111\")\n ax.set_xticks(list(range(data_size.__len__())))\n ax.set_xticklabels(data_size, rotation=60)\n ax.set_ylim((0, 1))\n ax.set_yticks(np.arange(0, 1, 0.1))\n ax.set_xlabel(\"# Executed Jobs\")\n ax.set_ylabel(\"$R^2$ Score\")\n ax.legend()\n return ax\n\n\ndef compare_r2(results, results_real_card, results_random_sampling=None, exp=True):\n data_size = results[\"data_size\"]\n if exp:\n test_scores_real = results_real_card[\"test_scores_exp\"]\n test_scores = results[\"test_scores_exp\"]\n else:\n test_scores_real = results_real_card[\"test_scores\"]\n test_scores = results[\"test_scores\"]\n\n fig, ax = plt.subplots(figsize=(8, 2))\n\n\n if results_random_sampling:\n if exp:\n test_scores_random = results_random_sampling[\"test_scores_exp\"]\n else:\n test_scores_random = results_random_sampling[\"test_scores\"]\n\n ax.plot(list(map(lambda x: x[\"r2\"], test_scores_random)), marker=\"^\", linestyle=\"dotted\",\n label=\"Rand. samples - Estimated out card. (Baseline)\",\n color=sns.color_palette()[-4])\n\n ax.plot(list(map(lambda x: x[\"r2\"], test_scores)), marker=\"o\", label=\"Active labeling - Estimated out card.\",\n color=\"#111111\")\n\n\n ax.plot(list(map(lambda x: x[\"r2\"], test_scores_real)), linestyle=\"--\", marker=\"s\",\n label=\"Active labeling - Real out card. (Top-line)\",\n color=sns.color_palette()[-3], alpha=0.85)\n\n ax.set_xticks(list(range(data_size.__len__())))\n ax.set_xticklabels(data_size, rotation=60)\n ax.set_ylim((0, 1))\n ax.set_yticks(np.arange(0, 1, 0.2))\n ax.set_xlabel(\"# Cumulated Executed Jobs\")\n ax.set_ylabel(\"$R^2$ of pred.\\nExec. Time\")\n ax.legend()\n return ax\n\n\ndef show_uncertainty(results, show_errors=False):\n data_size = results[\"data_size\"]\n IQRs_RMSE = results[\"model_uncertainty\"]\n \n IQRs_RMSE = np.array([np.mean(np.exp(I[\"uncertainty_high\"]) - np.exp(I[\"uncertainty_low\"])) for I in results[\"iterations_results\"]])\n IQRs_std = np.array([np.std(np.exp(I[\"uncertainty_high\"]) - np.exp(I[\"uncertainty_low\"])) for I in\n results[\"iterations_results\"]])\n \n fig, ax = plt.subplots(figsize=(8, 2))\n\n if show_errors:\n ax.errorbar(np.arange(len(IQRs_RMSE)),\n IQRs_RMSE,\n yerr=IQRs_std, fmt='o', label=\"Uncertainty\")\n else:\n ax.plot(IQRs_RMSE, marker=\"o\", label=\"Uncertainty\")\n ax.set_xticks(list(range(data_size.__len__())))\n ax.set_xticklabels(data_size, rotation=60)\n ax.set_xlabel(\"# Cumulated Executed Jobs\")\n ax.set_ylabel(\"Model\\nUncertainty [ms]\")\n \n final_th = 0.1\n count = 0\n\n min_u = IQRs_RMSE[0]\n min_local_u = IQRs_RMSE[0]\n stops = []\n\n for i in range(1, len(data_size)):\n #print(i, \" -> min_local_u\", min_local_u)\n r = IQRs_RMSE[i] / min_local_u\n #print(r)\n if (r > 1) or (IQRs_RMSE[i]>min_u):\n pass\n elif (1-r) < final_th:\n pass\n else:\n print(i, data_size[i], \"-> STOP!\")\n count += 1\n stops.append({\"iteration\": i, \"data_size\": data_size[i],\n \"uncertainty\": IQRs_RMSE[i],\n \"uncertainty_std\": IQRs_std[i],\n \"cost\": np.sum(np.exp(results[\"iterations_results\"][i][\"train_labels\"]))\n })\n\n print(\"--------------------------------\")\n min_u = min(IQRs_RMSE[:i+1])\n min_local_u = min(IQRs_RMSE[i-1:i+1])\n #min_cost_id = np.argwhere(IQRs_RMSE == min_cost)\n \n if len(stops) == 0:\n stops.append({\"iteration\": len(data_size)-1, \"data_size\": data_size[len(data_size)-1], \"cost\": np.sum(np.exp(results[\"iterations_results\"][len(data_size)-1][\"train_labels\"])) })\n\n ax.errorbar([s[\"iteration\"] for s in stops], [s[\"uncertainty\"] for s in stops], color=\"red\", label=\"Early stop\", linewidth=0, marker=\"o\" )\n \n ax.legend()\n print(pd.DataFrame(stops))\n return ax\n\ndef show_iteration(results, iteration_to_show, exp=False, drop_outliers=False):\n y_test = results[\"iterations_results\"][iteration_to_show][\"test_labels\"]\n y_pred = results[\"iterations_results\"][iteration_to_show][\"pred_labels\"]\n y_pred_lower = results[\"iterations_results\"][iteration_to_show][\"uncertainty_low\"]\n y_pred_upper = results[\"iterations_results\"][iteration_to_show][\"uncertainty_high\"]\n p = y_test.argsort()\n\n if drop_outliers:\n q = np.quantile(y_test, 0.97)\n print(q)\n out_mask = y_test < q\n print(out_mask.shape)\n y_test = y_test[out_mask]\n y_pred = y_pred[out_mask]\n y_pred_lower = y_pred_lower[out_mask]\n y_pred_upper = y_pred_upper[out_mask]\n p = y_test.argsort()\n\n \n fig, ax = plt.subplots(figsize=(6, 3))\n\n\n if exp:\n y_test = np.exp(y_test)\n y_pred = np.exp(y_pred)\n y_pred_lower = np.exp(y_pred_lower)\n y_pred_upper = np.exp(y_pred_upper)\n if drop_outliers:\n new_r2 = r2_score(y_test, y_pred)\n print(\"NEW R2 without outliers:\", new_r2)\n \n ax.plot(y_test[p], marker=\".\", linewidth=1, label=\"Real\", color=\"#777777\", alpha=0.5)\n ax.errorbar(np.arange(len(y_pred)),y_pred[p], yerr=np.array([y_pred[p] - y_pred_lower[p], y_pred_upper[p] - y_pred[p]]), linewidth=0.5, fmt='.', color=\"#ff7f0e\", label=\"Pred. + Interval\", alpha=0.5)\n\n #ax.plot(np.arange(len(y_pred)), (y_pred_lower[p]+y_pred_upper[p])/2, marker=\".\", linewidth=0, label=\"smooth\", color=\"green\")\n\n ax.set_ylabel(\"Exec. Time [ms]\")\n # ax.ticklabel_format(axis='y', style='sci', scilimits=(0, 3))\n #ax.set_yscale(\"log\")\n ax.set_xlabel(\"Non-executed Jobs\")\n ax.legend()\n\n print(results[\"test_scores_exp\"][iteration_to_show])\n\n else:\n ax.plot(y_test[p], marker=\".\", linewidth=1, label=\"Real\", color=\"#777777\", alpha=0.5)\n ax.errorbar(np.arange(len(y_pred)), y_pred[p], yerr=np.array([y_pred[p] - y_pred_lower[p], y_pred_upper[p] - y_pred[p]]), linewidth=0.5, fmt='.', color=\"#ff7f0e\", label=\"Pred. + Interval\", alpha=0.5)\n ax.set_ylabel(\"Log(Exec. Time)\")\n ax.set_xlabel(\"Non-executed Jobs\")\n ax.legend()\n\n print(results[\"test_scores\"][iteration_to_show])\n\n return ax\n\ndef show_iteration_2(results, iteration_to_show, drop_outliers=False):\n y_test = results[\"iterations_results\"][iteration_to_show][\"test_labels\"]\n y_pred = results[\"iterations_results\"][iteration_to_show][\"pred_labels\"]\n y_pred_lower = results[\"iterations_results\"][iteration_to_show][\"uncertainty_low\"]\n y_pred_upper = results[\"iterations_results\"][iteration_to_show][\"uncertainty_high\"]\n p = y_test.argsort()\n\n new_r2 = r2_score(y_test, y_pred)\n print(\"NEW R2 log with outliers:\", new_r2)\n\n if drop_outliers:\n q = np.quantile(y_test, 0.97)\n print(q)\n out_mask = y_test < q\n print(out_mask.shape)\n y_test = y_test[out_mask]\n y_pred = y_pred[out_mask]\n y_pred_lower = y_pred_lower[out_mask]\n y_pred_upper = y_pred_upper[out_mask]\n p = y_test.argsort()\n\n fig, ax = plt.subplots(figsize=(6, 6))\n\n y_test = np.exp(y_test)\n y_pred = np.exp(y_pred)\n y_pred_lower = np.exp(y_pred_lower)\n y_pred_upper = np.exp(y_pred_upper)\n\n if drop_outliers:\n new_r2 = r2_score(y_test, y_pred)\n print(\"NEW R2 without outliers:\", new_r2)\n\n ax.plot(y_test[p], y_test[p], marker=\".\", linewidth=1, label=\"Real\", color=\"#777777\", alpha=0.5)\n ax.errorbar(y_test[p],y_pred[p], yerr=np.array([y_pred[p] - y_pred_lower[p], y_pred_upper[p] - y_pred[p]]), linewidth=0.5, fmt='.', color=\"#ff7f0e\", label=\"Pred. + Interval\", alpha=0.5)\n ax.set_ylabel(\"Forecasted Exec. Time [ms] (Log scale)\")\n ax.set_yscale(\"log\")\n ax.set_xlabel(\"Real Exec. Time [ms] (Log scale)\")\n ax.set_xscale(\"log\")\n ax.legend()\n \n return ax\n\n\ndef show_td_gen(results, iteration_to_show):\n\n y_test = results[list(results.keys())[iteration_to_show]][\"test_labels\"]\n y_pred = results[list(results.keys())[iteration_to_show]][\"pred_labels\"]\n\n from sklearn.metrics import r2_score\n score = r2_score(y_test, y_pred)\n print(\"R2 score:\", score)\n p = y_test.argsort()\n\n fig, ax = plt.subplots(figsize=(6, 3))\n\n ax.plot(y_test[p], y_test[p], marker=\".\", linewidth=1, label=\"Real\", color=\"#777777\", alpha=0.5)\n ax.plot(y_test[p], y_pred[p], marker=\".\", linewidth=0, label=\"TDGen Pred.\", color=sns.color_palette()[4], alpha=0.5)\n\n ax.set_ylabel(\"Forecasted Exec. Time [ms] (Log scale)\")\n ax.set_yscale(\"log\")\n ax.set_xlabel(\"Real Exec. Time [ms] (Log scale)\")\n ax.set_xscale(\"log\")\n ax.legend()\n\n return ax\n\ndef show_our_and_td_gen(our_results, td_gen_results, iteration_to_show):\n\n our_y_test = np.exp(our_results[\"iterations_results\"][iteration_to_show][\"test_labels\"])\n our_y_pred = np.exp(our_results[\"iterations_results\"][iteration_to_show][\"pred_labels\"])\n\n y_test = td_gen_results[list(td_gen_results.keys())[iteration_to_show]][\"test_labels\"]\n y_pred = td_gen_results[list(td_gen_results.keys())[iteration_to_show]][\"pred_labels\"]\n\n from sklearn.metrics import r2_score\n score = r2_score(y_test, y_pred)\n print(\"R2 score:\", score)\n p = y_test.argsort()\n our_p = our_y_test.argsort()\n\n fig, ax = plt.subplots(figsize=(6, 6))\n\n ax.plot(y_test[p], y_test[p], marker=\"\", linewidth=1, label=\"Real\", color=\"#777777\", alpha=0.5)\n\n ax.plot(our_y_test[our_p], our_y_pred[our_p], marker=\".\", linewidth=0, label=\"Our solution\", color=sns.color_palette()[1], alpha=0.2)\n ax.plot(y_test[p], y_pred[p], marker=\".\", linewidth=0, label=\"TDGen Pred.\", color=sns.color_palette()[4], alpha=0.2)\n\n ax.set_ylabel(\"Forecasted Exec. Time [ms] (Log scale)\")\n ax.set_yscale(\"log\")\n ax.set_xlabel(\"Real Exec. Time [ms] (Log scale)\")\n ax.set_xscale(\"log\")\n ax.legend()\n\n return ax\n\n\ndef compare_td_gen_r2(results, results_td_gen):\n data_size = results[\"data_size\"]\n\n test_scores = results[\"test_scores_exp\"]\n\n from sklearn.metrics import r2_score\n td_gen_scores = []\n x = []\n\n for k, v in results_td_gen.items():\n y_test = v[\"test_labels\"]\n y_pred = v[\"pred_labels\"]\n score = r2_score(y_test, y_pred)\n print(k ,\"R2 score:\", score)\n td_gen_scores.append(score)\n x.append(k)\n\n fig, ax = plt.subplots(figsize=(8, 2))\n ax.plot(td_gen_scores, linestyle=\"--\", marker=\"o\", label=\"TDGen\",\n color=sns.color_palette()[4])\n ax.plot(list(map(lambda x: x[\"r2\"], test_scores)), marker=\"o\", label=\"Our solution\",\n color=\"#111111\")\n ax.set_xticks(list(range(data_size.__len__())))\n ax.set_xticklabels(data_size, rotation=60)\n\n print(np.array(list(map(lambda x: x[\"r2\"], test_scores)))/np.array(td_gen_scores))\n #ax.set_ylim((0, 1))\n #ax.set_yticks(np.arange(0, 1, 0.1))\n ax.set_xlabel(\"# Cumulated Executed Jobs\")\n ax.set_ylabel(\"$R^2$ of pred. Exec. Time\")\n ax.legend()\n return ax\n\n\ndef show_centerd_uncertainty(data, iteration, exp=False):\n print(data[\"iterations_results\"][iteration].keys())\n if exp:\n preds = np.exp(np.array(data[\"iterations_results\"][iteration][\"pred_labels\"]))\n upper = np.exp(np.array(data[\"iterations_results\"][iteration][\"uncertainty_high\"]))\n lower = np.exp(np.array(data[\"iterations_results\"][iteration][\"uncertainty_low\"]))\n else:\n preds = np.array(data[\"iterations_results\"][iteration][\"pred_labels\"])\n upper = np.array(data[\"iterations_results\"][iteration][\"uncertainty_high\"])\n lower = np.array(data[\"iterations_results\"][iteration][\"uncertainty_low\"])\n\n IQR_interval = upper - lower\n sort_ind = np.argsort(IQR_interval)\n # y_true_all = y_true_all[sort_ind]\n preds = preds[sort_ind]\n upper = upper[sort_ind]\n lower = lower[sort_ind]\n mean = (upper + lower) / 2\n std = np.std((upper + lower))\n # Center such that the mean of the prediction interval is at 0.0\n # y_true_all_centered = y_true_all.copy()\n upper_centered = upper.copy()\n lower_centered = lower.copy()\n preds_centered = preds.copy()\n\n # y_true_all_centered -= mean\n upper_centered = (upper_centered - mean) # /std\n lower_centered = (lower_centered - mean) # /std\n preds_centered = (preds_centered - mean) # /std\n\n IRQ_th = np.quantile(IQR_interval, 0.95)\n print(IRQ_th)\n x_idx = np.arange(len(upper_centered))\n cut = x_idx[IQR_interval[sort_ind] > IRQ_th]\n print(cut)\n\n fig, ax = plt.subplots(1, 1, figsize=(8, 4))\n\n # ax.plot(y_true_all_centered, \"ro\", markersize=1)\n ax.plot(preds_centered, marker=\".\", color=\"#ff7f0e\", linewidth=0)\n\n ax.fill_between(\n np.arange(len(upper_centered)), lower_centered, upper_centered, alpha=0.2, color=\"#ff7f0e\",\n label=\"Pred. interval (centerd)\")\n ax.axvline(cut[0], color=\"red\", linestyle=\"--\", label=\"Threshold $\\eta$\")\n ax.set_xlabel(\"Non-executed jobs sorted by uncertainty.\")\n ax.set_ylabel(\"Predicted values (centered)\")\n ax.legend()\n #  ax.set_yscale(\"symlog\")\n #  ax.set_ylim([-1.5, 1.5])\n\n\ndef compute_stats_on_pred_errors(results, iteration_to_show):\n y_train = results[\"iterations_results\"][iteration_to_show][\"train_labels\"]\n y_test = results[\"iterations_results\"][iteration_to_show][\"test_labels\"]\n y_pred = results[\"iterations_results\"][iteration_to_show][\"pred_labels\"]\n y_pred_lower = results[\"iterations_results\"][iteration_to_show][\"uncertainty_low\"]\n y_pred_upper = results[\"iterations_results\"][iteration_to_show][\"uncertainty_high\"]\n\n y_train = np.exp(y_train)\n y_test = np.exp(y_test)\n y_pred = np.exp(y_pred)\n y_pred_lower = np.exp(y_pred_lower)\n y_pred_upper = np.exp(y_pred_upper)\n\n print(\"Real values\")\n print(pd.Series(np.hstack((y_train, y_test)) / 1000).describe())\n print(\"highest 5:\", np.sort(np.hstack((y_train, y_test)))[-5:]/1000)\n print()\n print(\"\\nAverage Prediction Error\")\n print(pd.Series(np.abs(y_test - y_pred) / 1000).describe())\n\n # count_true = (y_test <= y_pred_upper) & (y_test >= y_pred_lower)\n # print(len(count_true),len(count_true[count_true==True]))", "# from skgarden import RandomForestQuantileRegressor\nfrom generator_labeler.ActiveModel import RandomForestQuantileRegressor\nfrom sklearn.model_selection import GridSearchCV\nimport numpy as np\n\nfrom sklearn.metrics import r2_score\nfrom sklearn.metrics import mean_tweedie_deviance\nfrom sklearn.model_selection import KFold\n\nimport matplotlib.pyplot as plt\n\n\nclass ActiveQuantileForest:\n def __init__(self):\n pass\n\n\nclass QuantileForestModel:\n\n def __init__(self, random_state=None):\n self.model = RandomForestQuantileRegressor(random_state=random_state)\n self.gs_model = None\n self.scoring_function = \"neg_mean_squared_error\"\n self.param_grid = {\n \"n_estimators\": [10, 50, 100, 200, 500],\n \"max_depth\": [10, 50, 100, 200, 500],\n #\"min_samples_split\": [2, 10],\n \"random_state\": [random_state]\n }\n self.n_folds = 3\n self._is_fitted = False\n\n self.test_scores = None\n self.test_scores_exp = None\n\n self.cross_validation_scores = None\n self.cross_validation_scores_exp = None\n\n def cross_validate(self, X, y, k=None):\n if not self._is_fitted:\n raise Exception(\"Model is not fitted.\")\n\n if self.gs_model is None:\n raise Exception(\"Cross validation requires a grid search model.\")\n\n if k == None:\n k = int(X.shape[0] / 2) if X.shape[0] < 3 else 3\n\n print(f\"Cross validating on '{k}' folds\")\n\n scores = {}\n scores[\"r2\"] = []\n scores[\"mse\"] = []\n scores[\"poisson_deviance\"] = []\n scores[\"gamma_deviance\"] = []\n\n scores_exp = {}\n scores_exp[\"r2\"] = []\n scores_exp[\"mse\"] = []\n scores_exp[\"poisson_deviance\"] = []\n scores_exp[\"gamma_deviance\"] = []\n\n kf = KFold(k)\n\n for train_index, test_index in kf.split(X):\n\n clf_model = RandomForestQuantileRegressor(**self.gs_model.best_params_)\n clf_model.fit(X[train_index, :], y[train_index])\n\n y_pred = clf_model.predict(X[test_index, :])\n y_test = y[test_index]\n\n if test_index.__len__() > 1:\n r2 = r2_score(y_test, y_pred)\n scores[\"r2\"].append(r2)\n\n r2_exp = r2_score(np.exp(y_test), np.exp(y_pred))\n scores_exp[\"r2\"].append(r2_exp)\n\n mse = mean_tweedie_deviance(y_test, y_pred, power=0)\n poisson_deviance = mean_tweedie_deviance(y_test, y_pred, power=1)\n gamma_deviance = mean_tweedie_deviance(y_test, y_pred, power=2)\n\n scores[\"mse\"].append(mse)\n scores[\"poisson_deviance\"].append(poisson_deviance)\n scores[\"gamma_deviance\"].append(gamma_deviance)\n\n mse_exp = mean_tweedie_deviance(np.exp(y_test), np.exp(y_pred), power=0)\n poisson_deviance_exp = mean_tweedie_deviance(np.exp(y_test), np.exp(y_pred), power=1)\n gamma_deviance_exp = mean_tweedie_deviance(np.exp(y_test), np.exp(y_pred), power=2)\n\n scores_exp[\"mse\"].append(mse_exp)\n scores_exp[\"poisson_deviance\"].append(poisson_deviance_exp)\n scores_exp[\"gamma_deviance\"].append(gamma_deviance_exp)\n\n final_scores = {}\n final_scores[\"r2_mean\"] = np.mean([0 if s < 0 else s for s in scores[\"r2\"]])\n final_scores[\"r2_std\"] = np.std([0 if s < 0 else s for s in scores[\"r2\"]])\n final_scores[\"mse_mean\"] = np.mean(scores[\"mse\"])\n final_scores[\"mse_std\"] = np.std(scores[\"mse\"])\n final_scores[\"poisson_deviance_mean\"] = np.mean(scores[\"poisson_deviance\"])\n final_scores[\"poisson_deviance_std\"] = np.std(scores[\"poisson_deviance\"])\n final_scores[\"gamma_deviance_mean\"] = np.mean(scores[\"gamma_deviance\"])\n final_scores[\"gamma_deviance_std\"] = np.std(scores[\"gamma_deviance\"])\n self.cross_validation_scores = final_scores\n\n final_scores_exp = {}\n final_scores_exp[\"r2_mean\"] = np.mean([0 if s < 0 else s for s in scores_exp[\"r2\"]])\n final_scores_exp[\"r2_std\"] = np.std([0 if s < 0 else s for s in scores_exp[\"r2\"]])\n final_scores_exp[\"mse_mean\"] = np.mean(scores_exp[\"mse\"])\n final_scores_exp[\"mse_std\"] = np.std(scores_exp[\"mse\"])\n final_scores_exp[\"poisson_deviance_mean\"] = np.mean(scores_exp[\"poisson_deviance\"])\n final_scores_exp[\"poisson_deviance_std\"] = np.std(scores_exp[\"poisson_deviance\"])\n final_scores_exp[\"gamma_deviance_mean\"] = np.mean(scores_exp[\"gamma_deviance\"])\n final_scores_exp[\"gamma_deviance_std\"] = np.std(scores_exp[\"gamma_deviance\"])\n self.cross_validation_scores_exp = final_scores_exp\n\n return self.cross_validation_scores, self.cross_validation_scores_exp\n\n def validate(self, X_test, y_test):\n if not self._is_fitted:\n raise Exception(\"Model is not fitted.\")\n\n scores = {}\n scores_exp = {}\n\n y_pred = self.model.predict(X_test)\n\n scores[\"r2\"] = r2_score(y_test, y_pred)\n scores[\"mse\"] = mean_tweedie_deviance(y_test, y_pred, power=0)\n scores[\"poisson_deviance\"] = mean_tweedie_deviance(y_test, y_pred, power=1)\n scores[\"gamma_deviance\"] = mean_tweedie_deviance(y_test, y_pred, power=2)\n self.test_scores = scores\n\n scores_exp[\"r2\"] = r2_score(np.exp(y_test), np.exp(y_pred))\n scores_exp[\"mse\"] = mean_tweedie_deviance(np.exp(y_test), np.exp(y_pred), power=0)\n scores_exp[\"poisson_deviance\"] = mean_tweedie_deviance(np.exp(y_test), np.exp(y_pred), power=1)\n scores_exp[\"gamma_deviance\"] = mean_tweedie_deviance(np.exp(y_test), np.exp(y_pred), power=2)\n self.test_scores_exp = scores_exp\n\n return self.test_scores, self.test_scores_exp\n\n def _fit_grid_search(self, X_train, y_train, verbose=False):\n self.gs_model = GridSearchCV(self.model, self.param_grid, cv=self.n_folds,\n scoring=self.scoring_function, verbose=True, n_jobs=4, iid=False)\n self.gs_model.fit(X_train, y_train)\n self.model = self.gs_model.best_estimator_\n\n # self.model = RandomForestQuantileRegressor(**self.gs_model.best_params_)\n # self.model.fit(X_train, y_train)\n return self.model\n\n def predict(self, X, quantile=None):\n if not self._is_fitted:\n raise Exception(\"Model is not fitted.\")\n return self.model.predict(X, quantile=quantile)\n\n def fit(self, X, y, grid_search=True, verbose=False):\n if grid_search:\n self.model = self._fit_grid_search(X, y, verbose)\n else:\n self.model = self.model.fit(X, y)\n\n self._is_fitted = True\n\n return self.model\n\n def predict_model_uncertainty(self, X_test, upper=75, lower=25, verbose=False):\n preds = self.predict(X_test)\n upper = self.predict(X_test, quantile=upper)\n lower = self.predict(X_test, quantile=lower)\n #y_true_all = y_test\n\n IQR_interval = upper - lower\n sort_ind = np.argsort(IQR_interval)\n #y_true_all = y_true_all[sort_ind]\n preds = preds[sort_ind]\n upper = upper[sort_ind]\n lower = lower[sort_ind]\n mean = (upper + lower) / 2\n std = np.std((upper + lower))\n # Center such that the mean of the prediction interval is at 0.0\n #y_true_all_centered = y_true_all.copy()\n upper_centered = upper.copy()\n lower_centered = lower.copy()\n preds_centered = preds.copy()\n\n #y_true_all_centered -= mean\n upper_centered = (upper_centered - mean)#/std\n lower_centered = (lower_centered - mean)#/std\n preds_centered = (preds_centered - mean)#/std\n\n if verbose:\n fig, ax = plt.subplots(1, 1, figsize=(10, 6))\n\n # ax.plot(y_true_all_centered, \"ro\", markersize=1)\n ax.plot(preds_centered, marker=\".\", color=\"#ff7f0e\", linewidth=0)\n\n ax.fill_between(\n np.arange(len(upper_centered)), lower_centered, upper_centered, alpha=0.2, color=\"#ff7f0e\",\n label=\"Pred. interval\")\n ax.set_xlabel(\"Non-executed instances ordered by uncertainty.\")\n ax.set_ylabel(\"Predicted values (centered)\")\n ax.set_ylim([-1.5, 1.5])\n #plt.show()\n\n return IQR_interval\n\n\n" ]
[ [ "numpy.hstack", "sklearn.metrics.r2_score", "numpy.abs", "numpy.random.seed", "numpy.arange", "numpy.quantile", "matplotlib.pyplot.subplots", "pandas.DataFrame", "numpy.std", "numpy.argsort", "numpy.array", "numpy.exp" ], [ "sklearn.model_selection.GridSearchCV", "sklearn.metrics.r2_score", "matplotlib.pyplot.subplots", "sklearn.model_selection.KFold", "sklearn.metrics.mean_tweedie_deviance", "numpy.std", "numpy.mean", "numpy.argsort", "numpy.exp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
DiegoCao/analytics-zoo
[ "31a7c8acee38053b6bb20ccb4dc02f06d1d58900" ]
[ "pyzoo/test/zoo/chronos/model/forecast/test_lstm_forecaster.py" ]
[ "#\n# Copyright 2018 Analytics Zoo 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\nimport numpy as np\nimport tempfile\nimport os\nimport torch\n\nfrom zoo.chronos.model.forecast.lstm_forecaster import LSTMForecaster\nfrom zoo.orca import init_orca_context, stop_orca_context\nfrom unittest import TestCase\nimport pytest\n\n\ndef create_data():\n num_train_samples = 1000\n num_val_samples = 400\n num_test_samples = 400\n input_time_steps = 24\n input_feature_dim = 2\n output_time_steps = 1\n output_feature_dim = 2\n\n def get_x_y(num_samples):\n x = np.random.rand(num_samples, input_time_steps, input_feature_dim).astype(np.float32)\n y = x[:, -output_time_steps:, :]*2 + \\\n np.random.rand(num_samples, output_time_steps, output_feature_dim).astype(np.float32)\n return x, y\n\n train_data = get_x_y(num_train_samples)\n val_data = get_x_y(num_val_samples)\n test_data = get_x_y(num_test_samples)\n return train_data, val_data, test_data\n\n\nclass TestChronosModelLSTMForecaster(TestCase):\n\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n\n def test_tcn_forecaster_fit_eva_pred(self):\n train_data, val_data, test_data = create_data()\n forecaster = LSTMForecaster(past_seq_len=24,\n input_feature_num=2,\n output_feature_num=2,\n loss=\"mae\",\n lr=0.01)\n train_loss = forecaster.fit(train_data, epochs=2)\n test_pred = forecaster.predict(test_data[0])\n assert test_pred.shape == test_data[1].shape\n test_mse = forecaster.evaluate(test_data)\n\n def test_tcn_forecaster_onnx_methods(self):\n train_data, val_data, test_data = create_data()\n forecaster = LSTMForecaster(past_seq_len=24,\n input_feature_num=2,\n output_feature_num=2,\n loss=\"mae\",\n lr=0.01)\n forecaster.fit(train_data, epochs=2)\n try:\n import onnx\n import onnxruntime\n pred = forecaster.predict(test_data[0])\n pred_onnx = forecaster.predict_with_onnx(test_data[0])\n np.testing.assert_almost_equal(pred, pred_onnx, decimal=5)\n mse = forecaster.evaluate(test_data, multioutput=\"raw_values\")\n mse_onnx = forecaster.evaluate_with_onnx(test_data,\n multioutput=\"raw_values\")\n np.testing.assert_almost_equal(mse, mse_onnx, decimal=5)\n mse = forecaster.evaluate(test_data)\n mse_onnx = forecaster.evaluate_with_onnx(test_data)\n np.testing.assert_almost_equal(mse, mse_onnx, decimal=5)\n except ImportError:\n pass\n\n def test_tcn_forecaster_save_load(self):\n train_data, val_data, test_data = create_data()\n forecaster = LSTMForecaster(past_seq_len=24,\n input_feature_num=2,\n output_feature_num=2,\n loss=\"mae\",\n lr=0.01)\n train_mse = forecaster.fit(train_data, epochs=2)\n with tempfile.TemporaryDirectory() as tmp_dir_name:\n ckpt_name = os.path.join(tmp_dir_name, \"ckpt\")\n test_pred_save = forecaster.predict(test_data[0])\n forecaster.save(ckpt_name)\n forecaster.load(ckpt_name)\n test_pred_load = forecaster.predict(test_data[0])\n np.testing.assert_almost_equal(test_pred_save, test_pred_load)\n\n def test_tcn_forecaster_runtime_error(self):\n train_data, val_data, test_data = create_data()\n forecaster = LSTMForecaster(past_seq_len=24,\n input_feature_num=2,\n output_feature_num=2,\n loss=\"mae\",\n lr=0.01)\n with pytest.raises(RuntimeError):\n with tempfile.TemporaryDirectory() as tmp_dir_name:\n ckpt_name = os.path.join(tmp_dir_name, \"ckpt\")\n forecaster.save(ckpt_name)\n with pytest.raises(RuntimeError):\n forecaster.predict(test_data[0])\n with pytest.raises(RuntimeError):\n forecaster.evaluate(test_data)\n\n def test_tcn_forecaster_shape_error(self):\n train_data, val_data, test_data = create_data()\n forecaster = LSTMForecaster(past_seq_len=24,\n input_feature_num=2,\n output_feature_num=1,\n loss=\"mae\",\n lr=0.01)\n with pytest.raises(AssertionError):\n forecaster.fit(train_data, epochs=2)\n\n def test_tcn_forecaster_xshard_input(self):\n train_data, val_data, test_data = create_data()\n print(\"original\", train_data[0].dtype)\n init_orca_context(cores=4, memory=\"2g\")\n from zoo.orca.data import XShards\n\n def transform_to_dict(data):\n return {'x': data[0], 'y': data[1]}\n\n def transform_to_dict_x(data):\n return {'x': data[0]}\n train_data = XShards.partition(train_data).transform_shard(transform_to_dict)\n val_data = XShards.partition(val_data).transform_shard(transform_to_dict)\n test_data = XShards.partition(test_data).transform_shard(transform_to_dict_x)\n for distributed in [True, False]:\n forecaster = LSTMForecaster(past_seq_len=24,\n input_feature_num=2,\n output_feature_num=2,\n loss=\"mae\",\n lr=0.01,\n distributed=distributed)\n forecaster.fit(train_data, epochs=2)\n distributed_pred = forecaster.predict(test_data)\n distributed_eval = forecaster.evaluate(val_data)\n stop_orca_context()\n\n def test_tcn_forecaster_distributed(self):\n train_data, val_data, test_data = create_data()\n init_orca_context(cores=4, memory=\"2g\")\n\n forecaster = LSTMForecaster(past_seq_len=24,\n input_feature_num=2,\n output_feature_num=2,\n loss=\"mae\",\n lr=0.01,\n distributed=True)\n\n forecaster.fit(train_data, epochs=2)\n distributed_pred = forecaster.predict(test_data[0])\n distributed_eval = forecaster.evaluate(val_data)\n\n model = forecaster.get_model()\n assert isinstance(model, torch.nn.Module)\n\n forecaster.to_local()\n local_pred = forecaster.predict(test_data[0])\n local_eval = forecaster.evaluate(val_data)\n\n np.testing.assert_almost_equal(distributed_pred, local_pred, decimal=5)\n\n try:\n import onnx\n import onnxruntime\n local_pred_onnx = forecaster.predict_with_onnx(test_data[0])\n local_eval_onnx = forecaster.evaluate_with_onnx(val_data)\n np.testing.assert_almost_equal(distributed_pred, local_pred_onnx, decimal=5)\n except ImportError:\n pass\n\n model = forecaster.get_model()\n assert isinstance(model, torch.nn.Module)\n\n stop_orca_context()\n" ]
[ [ "numpy.testing.assert_almost_equal", "numpy.random.rand" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
LemonNoel/PGL
[ "c12357b66a105b10dd5a1f034fa21008f053d0f0" ]
[ "apps/Graph4KG/utils.py" ]
[ "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport csv\nimport math\nimport json\nimport time\nimport random\nimport logging\nimport functools\nimport traceback\nfrom collections import defaultdict\nfrom _thread import start_new_thread\nfrom multiprocessing import Queue, Process\n\nimport numpy as np\nfrom tqdm import tqdm\nimport paddle\nimport paddle.distributed as dist\n\n\ndef set_seed(seed):\n \"\"\"Set seed for reproduction.\n \"\"\"\n seed = seed + dist.get_rank()\n random.seed(seed)\n np.random.seed(seed)\n paddle.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n\n\ndef set_logger(args):\n \"\"\"Write logs to console and log file.\n \"\"\"\n log_file = os.path.join(args.save_path, 'train.log')\n logging.basicConfig(\n format='%(asctime)s %(levelname)-8s %(message)s',\n level=logging.INFO,\n datefmt='%Y-%m-%d %H:%M:%S',\n filename=log_file,\n filemode='a+')\n if args.print_on_screen:\n console = logging.StreamHandler()\n console.setLevel(logging.INFO)\n formatter = logging.Formatter(\n '%(asctime)s %(levelname)-8s %(message)s')\n console.setFormatter(formatter)\n logging.getLogger('').addHandler(console)\n\n for arg in vars(args):\n logging.info('{:20}:{}'.format(arg, getattr(args, arg)))\n\n\ndef print_log(step, interval, log, timer, time_sum):\n \"\"\"Print log to logger.\n \"\"\"\n logging.info(\n '[GPU %d] step: %d, loss: %.5f, reg: %.4e, speed: %.2f steps/s, time: %.2f s' %\n (dist.get_rank(), step, log['loss'] / interval, log['reg'] / interval,\n interval / time_sum, time_sum))\n logging.info('sample: %f, forward: %f, backward: %f, update: %f' % (\n timer['sample'], timer['forward'], timer['backward'], timer['update']))\n\n\ndef uniform(low, high, size, dtype=np.float32, seed=0):\n \"\"\"Memory efficient uniform implementation.\n \"\"\"\n rng = np.random.default_rng(seed)\n out = (high - low) * rng.random(size, dtype=dtype) + low\n return out\n\n\ndef timer_wrapper(name):\n \"\"\"Time counter wrapper.\n \"\"\"\n\n def decorate(func):\n \"\"\"decorate func\n \"\"\"\n\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n \"\"\"wrapper func\n \"\"\"\n logging.info(f'[{name}] start...')\n ts = time.time()\n result = func(*args, **kwargs)\n te = time.time()\n costs = te - ts\n if costs < 1e-4:\n cost_str = '%f sec' % costs\n elif costs > 3600:\n cost_str = '%.4f sec (%.4f hours)' % (costs, costs / 3600.)\n else:\n cost_str = '%.4f sec' % costs\n logging.info(f'[{name}] finished! It takes {cost_str} s')\n return result\n\n return wrapper\n\n return decorate\n\n\ndef calculate_metrics(scores, corr_idxs, filter_list):\n \"\"\"Calculate metrics according to scores.\n \"\"\"\n logs = []\n for i in range(scores.shape[0]):\n rank = (scores[i] > scores[i][corr_idxs[i]]).astype('float32')\n if filter_list is not None:\n mask = paddle.ones(rank.shape, dtype='float32')\n mask[filter_list[i]] = 0.\n rank = rank * mask\n rank = paddle.sum(rank) + 1\n logs.append({\n 'MRR': 1.0 / rank,\n 'MR': float(rank),\n 'HITS@1': 1.0 if rank <= 1 else 0.0,\n 'HITS@3': 1.0 if rank <= 3 else 0.0,\n 'HITS@10': 1.0 if rank <= 10 else 0.0,\n })\n return logs\n\n\ndef evaluate_wikikg2(model, loader, mode, save_path):\n from ogb.linkproppred import Evaluator\n evaluator = Evaluator(name='ogbl-wikikg2')\n model.eval()\n with paddle.no_grad():\n y_pred_pos = []\n y_pred_neg = []\n for h, r, t, neg_h, neg_t in tqdm(loader):\n pos_h = model._get_ent_embedding(h)\n pos_r = model._get_rel_embedding(r)\n pos_t = model._get_ent_embedding(t)\n y_pred_pos.append(model(pos_h, pos_r, pos_t).numpy())\n y_neg_head = model.predict(t, r, neg_h, mode='head').numpy()\n y_neg_tail = model.predict(h, r, neg_t, mode='tail').numpy()\n y_pred_neg.append(np.concatenate([y_neg_head, y_neg_tail], axis=1))\n y_pred_pos = np.concatenate(y_pred_pos, axis=0)\n y_pred_neg = np.concatenate(y_pred_neg, axis=0)\n input_dict = {'y_pred_pos': y_pred_pos, 'y_pred_neg': y_pred_neg}\n result = evaluator.eval(input_dict)\n logging.info('-- %s results ------------' % mode)\n logging.info(' ' + ' '.join(\n ['{}: {}'.format(k, v.mean()) for k, v in result.items()]))\n\n\ndef evaluate_wikikg90m(model, loader, mode, save_path):\n from ogb.lsc import WikiKG90MEvaluator\n evaluator = WikiKG90MEvaluator()\n model.eval()\n with paddle.no_grad():\n top_tens = []\n corr_idx = []\n for h, r, t_idx, cand_t in tqdm(loader):\n score = model.predict(h, r, cand_t)\n rank = paddle.argsort(score, axis=1, descending=True)\n top_tens.append(rank[:, :10].numpy())\n corr_idx.append(t_idx.numpy())\n t_pred_top10 = np.concatenate(top_tens, axis=0)\n t_correct_index = np.concatenate(corr_idx, axis=0)\n input_dict = {}\n if mode == 'valid':\n input_dict['h,r->t'] = {\n 't_pred_top10': t_pred_top10,\n 't_correct_index': t_correct_index\n }\n result = evaluator.eval(input_dict)\n logging.info('-- %s results -------------' % mode)\n logging.info(' '.join(\n ['{}: {}'.format(k, v) for k, v in result.items()]))\n else:\n input_dict['h,r->t'] = {'t_pred_top10': t_pred_top10}\n evaluator.save_test_submission(\n input_dict=input_dict, dir_path=save_path)\n\n\n@timer_wrapper('evaluation')\ndef evaluate(model,\n loader,\n evaluate_mode='test',\n filter_dict=None,\n save_path='./tmp/',\n data_mode='hrt'):\n \"\"\"Evaluate given KGE model.\n \"\"\"\n if data_mode == 'wikikg2':\n evaluate_wikikg2(model, loader, evaluate_mode, save_path)\n elif data_mode == 'wikikg90m':\n evaluate_wikikg90m(model, loader, evaluate_mode, save_path)\n else:\n model.eval()\n with paddle.no_grad():\n h_metrics = []\n t_metrics = []\n output = {'h,r->t': {}, 't,r->h': {}, 'average': {}}\n\n for h, r, t in tqdm(loader):\n t_score = model.predict(h, r, mode='tail')\n h_score = model.predict(t, r, mode='head')\n\n if filter_dict is not None:\n h_filter_list = [\n filter_dict['head'][(ti, ri)]\n for ti, ri in zip(t.numpy(), r.numpy())\n ]\n t_filter_list = [\n filter_dict['tail'][(hi, ri)]\n for hi, ri in zip(h.numpy(), r.numpy())\n ]\n else:\n h_filter_list = None\n t_filter_list = None\n\n h_metrics += calculate_metrics(h_score, h, h_filter_list)\n t_metrics += calculate_metrics(t_score, t, t_filter_list)\n\n for metric in h_metrics[0].keys():\n output['t,r->h'][metric] = np.mean(\n [x[metric] for x in h_metrics])\n output['h,r->t'][metric] = np.mean(\n [x[metric] for x in t_metrics])\n output['average'][metric] = (\n output['t,r->h'][metric] + output['h,r->t'][metric]) / 2\n logging.info('-------------- %s result --------------' %\n evaluate_mode)\n logging.info('t,r->h |' + ' '.join(\n ['{}: {}'.format(k, v) for k, v in output['t,r->h'].items()]))\n logging.info('h,r->t |' + ' '.join(\n ['{}: {}'.format(k, v) for k, v in output['h,r->t'].items()]))\n logging.info('average |' + ' '.join(\n ['{}: {}'.format(k, v) for k, v in output['average'].items()]))\n logging.info('-----------------------------------------')\n\n\ndef gram_schimidt_process(embeds, num_elem, use_scale):\n \"\"\" Orthogonalize embeddings.\n \"\"\"\n num_embed = embeds.shape[0]\n assert embeds.shape[1] == num_elem\n assert embeds.shape[2] == (num_elem + int(use_scale))\n if use_scale:\n scales = embeds[:, :, -1]\n embeds = embeds[:, :, :num_elem]\n\n u = [embeds[:, 0]]\n uu = [0] * num_elem\n uu[0] = (u[0] * u[0]).sum(axis=-1)\n u_d = embeds[:, 1:]\n ushape = (num_embed, 1, -1)\n for i in range(1, num_elem):\n tmp_a = (embeds[:, i:] * u[i - 1].reshape(ushape)).sum(axis=-1)\n tmp_b = uu[i - 1].reshape((num_embed, -1))\n tmp_u = (tmp_a / tmp_b).reshape((num_embed, -1, 1))\n u_d = u_d - u[-1].reshape(ushape) * tmp_u\n u_i = u_d[:, 0]\n if u_d.shape[1] > 1:\n u_d = u_d[:, 1:]\n uu[i] = (u_i * u_i).sum(axis=-1)\n u.append(u_i)\n\n u = np.stack(u, axis=1)\n u_norm = np.linalg.norm(u, axis=-1, keepdims=True)\n u = u / u_norm\n if use_scale:\n u = np.concatenate([u, scales.reshape((num_embed, -1, 1))], axis=-1)\n return u\n" ]
[ [ "numpy.random.seed", "numpy.linalg.norm", "numpy.stack", "numpy.concatenate", "numpy.mean", "numpy.random.default_rng" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
EmilienDupont/neural-function-distributions
[ "c034bf79640c6d8922f1c276174b3cb1800d22b4" ]
[ "main.py" ]
[ "import json\nimport os\nimport sys\nimport time\nimport torch\nfrom training.training import Trainer\nfrom data.conversion import GridDataConverter, PointCloudDataConverter, ERA5Converter\nfrom data.dataloaders import mnist, celebahq\nfrom data.dataloaders_era5 import era5\nfrom data.dataloaders3d import shapenet_voxels, shapenet_point_clouds\nfrom models.discriminator import PointConvDiscriminator\nfrom models.function_distribution import HyperNetwork, FunctionDistribution\nfrom models.function_representation import FunctionRepresentation, FourierFeatures\n\n\ndef count_parameters(model):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n# Get config file from command line arguments\nif len(sys.argv) != 2:\n raise(RuntimeError(\"Wrong arguments, use python main.py <config_path>\"))\nconfig_path = sys.argv[1]\n\n# Open config file\nwith open(config_path) as f:\n config = json.load(f)\n\nif config[\"path_to_data\"] == \"\":\n raise(RuntimeError(\"Path to data not specified. Modify path_to_data attribute in config to point to data.\"))\n\n# Create a folder to store experiment results\ntimestamp = time.strftime(\"%Y-%m-%d_%H-%M\")\ndirectory = \"{}_{}\".format(timestamp, config[\"id\"])\nif not os.path.exists(directory):\n os.makedirs(directory)\n\n# Save config file in experiment directory\nwith open(directory + '/config.json', 'w') as f:\n json.dump(config, f)\n\n# Setup dataloader\nis_voxel = False\nis_point_cloud = False\nis_era5 = False\nif config[\"dataset\"] == 'mnist':\n dataloader = mnist(path_to_data=config[\"path_to_data\"],\n batch_size=config[\"training\"][\"batch_size\"],\n size=config[\"resolution\"],\n train=True)\n input_dim = 2\n output_dim = 1\n data_shape = (1, config[\"resolution\"], config[\"resolution\"])\nelif config[\"dataset\"] == 'celebahq':\n dataloader = celebahq(path_to_data=config[\"path_to_data\"],\n batch_size=config[\"training\"][\"batch_size\"],\n size=config[\"resolution\"])\n input_dim = 2\n output_dim = 3\n data_shape = (3, config[\"resolution\"], config[\"resolution\"])\nelif config[\"dataset\"] == 'shapenet_voxels':\n dataloader = shapenet_voxels(path_to_data=config[\"path_to_data\"],\n batch_size=config[\"training\"][\"batch_size\"],\n size=config[\"resolution\"])\n input_dim = 3\n output_dim = 1\n data_shape = (1, config[\"resolution\"], config[\"resolution\"], config[\"resolution\"])\n is_voxel = True\nelif config[\"dataset\"] == 'shapenet_point_clouds':\n dataloader = shapenet_point_clouds(path_to_data=config[\"path_to_data\"],\n batch_size=config[\"training\"][\"batch_size\"])\n input_dim = 3\n output_dim = 1\n data_shape = (1, config[\"resolution\"], config[\"resolution\"], config[\"resolution\"])\n is_point_cloud = True\nelif config[\"dataset\"] == 'era5':\n dataloader = era5(path_to_data=config[\"path_to_data\"],\n batch_size=config[\"training\"][\"batch_size\"])\n input_dim = 3\n output_dim = 1\n data_shape = (46, 90)\n is_era5 = True\n\n\n# Setup data converter\nif is_point_cloud:\n data_converter = PointCloudDataConverter(device, data_shape, normalize_features=True)\nelif is_era5:\n data_converter = ERA5Converter(device, data_shape, normalize_features=True)\nelse:\n data_converter = GridDataConverter(device, data_shape, normalize_features=True)\n\n\n# Setup encoding for function distribution\nnum_frequencies = config[\"generator\"][\"encoding\"][\"num_frequencies\"]\nstd_dev = config[\"generator\"][\"encoding\"][\"std_dev\"]\nif num_frequencies:\n frequency_matrix = torch.normal(mean=torch.zeros(num_frequencies, input_dim),\n std=std_dev).to(device)\n encoding = FourierFeatures(frequency_matrix)\nelse:\n encoding = torch.nn.Identity()\n\n# Setup generator models\nfinal_non_linearity = torch.nn.Tanh()\nnon_linearity = torch.nn.LeakyReLU(0.1)\nfunction_representation = FunctionRepresentation(input_dim, output_dim,\n config[\"generator\"][\"layer_sizes\"],\n encoding, non_linearity,\n final_non_linearity).to(device)\nhypernetwork = HyperNetwork(function_representation, config[\"generator\"][\"latent_dim\"],\n config[\"generator\"][\"hypernet_layer_sizes\"], non_linearity).to(device)\nfunction_distribution = FunctionDistribution(hypernetwork).to(device)\n\n# Setup discriminator\ndiscriminator = PointConvDiscriminator(input_dim, output_dim, config[\"discriminator\"][\"layer_configs\"],\n linear_layer_sizes=config[\"discriminator\"][\"linear_layer_sizes\"],\n norm_order=config[\"discriminator\"][\"norm_order\"],\n add_sigmoid=True,\n add_batchnorm=config[\"discriminator\"][\"add_batchnorm\"],\n add_weightnet_batchnorm=config[\"discriminator\"][\"add_weightnet_batchnorm\"],\n deterministic=config[\"discriminator\"][\"deterministic\"],\n same_coordinates=config[\"discriminator\"][\"same_coordinates\"]).to(device)\n\n\nprint(\"\\nFunction distribution\")\nprint(hypernetwork)\nprint(\"Number of parameters: {}\".format(count_parameters(hypernetwork)))\n\nprint(\"\\nDiscriminator\")\nprint(discriminator)\nprint(\"Number of parameters: {}\".format(count_parameters(discriminator)))\n\n# Setup trainer\ntrainer = Trainer(device, function_distribution, discriminator, data_converter,\n lr=config[\"training\"][\"lr\"], lr_disc=config[\"training\"][\"lr_disc\"],\n r1_weight=config[\"training\"][\"r1_weight\"],\n max_num_points=config[\"training\"][\"max_num_points\"],\n print_freq=config[\"training\"][\"print_freq\"], save_dir=directory,\n model_save_freq=config[\"training\"][\"model_save_freq\"],\n is_voxel=is_voxel, is_point_cloud=is_point_cloud,\n is_era5=is_era5)\ntrainer.train(dataloader, config[\"training\"][\"epochs\"])\n" ]
[ [ "torch.zeros", "torch.nn.Tanh", "torch.nn.Identity", "torch.nn.LeakyReLU", "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
shineyjg/cnn_captcha
[ "1048494895ab6c1e4d5940025c02026386c32912" ]
[ "train_model.py" ]
[ "# -*- coding: utf-8 -*-\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nfrom PIL import Image\nimport random\nimport os\nfrom sample import sample_conf\nfrom tensorflow.python.framework.errors_impl import NotFoundError\n\n# 设置以下环境变量可开启CPU识别\n# os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n\nclass TrainError(Exception):\n pass\n\n\nclass TrainModel(object):\n def __init__(self, img_path, char_set, model_save_dir, verify=False):\n # 模型路径\n self.model_save_dir = model_save_dir\n\n # 打乱文件顺序+校验图片格式\n self.img_path = img_path\n self.img_list = os.listdir(img_path)\n # 校验格式\n if verify:\n self.confirm_image_suffix()\n # 打乱文件顺序\n random.seed(time.time())\n random.shuffle(self.img_list)\n\n # 获得图片宽高和字符长度基本信息\n label, captcha_array = self.gen_captcha_text_image(self.img_list[0])\n\n captcha_shape = captcha_array.shape\n captcha_shape_len = len(captcha_shape)\n if captcha_shape_len == 3:\n image_height, image_width, channel = captcha_shape\n self.channel = channel\n elif captcha_shape_len == 2:\n image_height, image_width = captcha_shape\n else:\n raise TrainError(\"图片转换为矩阵时出错,请检查图片格式\")\n\n # 初始化变量\n # 图片尺寸\n self.image_height = image_height\n self.image_width = image_width\n # 验证码长度(位数)\n self.max_captcha = len(label)\n # 验证码字符类别\n self.char_set = char_set\n self.char_set_len = len(char_set)\n\n # 相关信息打印\n print(\"-->图片尺寸: {} X {}\".format(image_height, image_width))\n print(\"-->验证码长度: {}\".format(self.max_captcha))\n print(\"-->验证码共{}类 {}\".format(self.char_set_len, char_set))\n print(\"-->使用测试集为 {}\".format(img_path))\n\n # tf初始化占位符\n self.X = tf.placeholder(tf.float32, [None, image_height * image_width]) # 特征向量\n self.Y = tf.placeholder(tf.float32, [None, self.max_captcha * self.char_set_len]) # 标签\n self.keep_prob = tf.placeholder(tf.float32) # dropout值\n self.w_alpha = 0.01\n self.b_alpha = 0.1\n\n # test model input and output\n print(\">>> Start model test\")\n batch_x, batch_y = self.get_batch(0, size=100)\n print(\">>> input batch images shape: {}\".format(batch_x.shape))\n print(\">>> input batch labels shape: {}\".format(batch_y.shape))\n\n def gen_captcha_text_image(self, img_name):\n \"\"\"\n 返回一个验证码的array形式和对应的字符串标签\n :return:tuple (str, numpy.array)\n \"\"\"\n # 标签\n label = img_name.split(\"_\")[0]\n # 文件\n img_file = os.path.join(self.img_path, img_name)\n captcha_image = Image.open(img_file)\n captcha_array = np.array(captcha_image) # 向量化\n return label, captcha_array\n\n @staticmethod\n def convert2gray(img):\n \"\"\"\n 图片转为灰度图,如果是3通道图则计算,单通道图则直接返回\n :param img:\n :return:\n \"\"\"\n if len(img.shape) > 2:\n r, g, b = img[:, :, 0], img[:, :, 1], img[:, :, 2]\n gray = 0.2989 * r + 0.5870 * g + 0.1140 * b\n return gray\n else:\n return img\n\n def text2vec(self, text):\n \"\"\"\n 转标签为oneHot编码\n :param text: str\n :return: numpy.array\n \"\"\"\n text_len = len(text)\n if text_len > self.max_captcha:\n raise ValueError('验证码最长{}个字符'.format(self.max_captcha))\n\n vector = np.zeros(self.max_captcha * self.char_set_len)\n\n for i, ch in enumerate(text):\n idx = i * self.char_set_len + self.char_set.index(ch)\n vector[idx] = 1\n return vector\n\n def get_batch(self, n, size=128):\n batch_x = np.zeros([size, self.image_height * self.image_width]) # 初始化\n batch_y = np.zeros([size, self.max_captcha * self.char_set_len]) # 初始化\n\n max_batch = int(len(self.img_list) / size)\n # print(max_batch)\n if max_batch - 1 < 0:\n raise TrainError(\"训练集图片数量需要大于每批次训练的图片数量\")\n if n > max_batch - 1:\n n = n % max_batch\n s = n * size\n e = (n + 1) * size\n this_batch = self.img_list[s:e]\n # print(\"{}:{}\".format(s, e))\n\n for i, img_name in enumerate(this_batch):\n label, image_array = self.gen_captcha_text_image(img_name)\n image_array = self.convert2gray(image_array) # 灰度化图片\n batch_x[i, :] = image_array.flatten() / 255 # flatten 转为一维\n batch_y[i, :] = self.text2vec(label) # 生成 oneHot\n return batch_x, batch_y\n\n def confirm_image_suffix(self):\n # 在训练前校验所有文件格式\n print(\"开始校验所有图片后缀\")\n for index, img_name in enumerate(self.img_list):\n print(\"{} image pass\".format(index), end='\\r')\n if not img_name.endswith(sample_conf['image_suffix']):\n raise TrainError('confirm images suffix:you request [.{}] file but get file [{}]'\n .format(sample_conf['image_suffix'], img_name))\n print(\"所有图片格式校验通过\")\n\n def model(self):\n x = tf.reshape(self.X, shape=[-1, self.image_height, self.image_width, 1])\n print(\">>> input x: {}\".format(x))\n\n # 卷积层1\n wc1 = tf.get_variable(name='wc1', shape=[3, 3, 1, 32], dtype=tf.float32,\n initializer=tf.contrib.layers.xavier_initializer())\n bc1 = tf.Variable(self.b_alpha * tf.random_normal([32]))\n conv1 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(x, wc1, strides=[1, 1, 1, 1], padding='SAME'), bc1))\n conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n conv1 = tf.nn.dropout(conv1, self.keep_prob)\n\n # 卷积层2\n wc2 = tf.get_variable(name='wc2', shape=[3, 3, 32, 64], dtype=tf.float32,\n initializer=tf.contrib.layers.xavier_initializer())\n bc2 = tf.Variable(self.b_alpha * tf.random_normal([64]))\n conv2 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv1, wc2, strides=[1, 1, 1, 1], padding='SAME'), bc2))\n conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n conv2 = tf.nn.dropout(conv2, self.keep_prob)\n\n # 卷积层3\n wc3 = tf.get_variable(name='wc3', shape=[3, 3, 64, 128], dtype=tf.float32,\n initializer=tf.contrib.layers.xavier_initializer())\n bc3 = tf.Variable(self.b_alpha * tf.random_normal([128]))\n conv3 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv2, wc3, strides=[1, 1, 1, 1], padding='SAME'), bc3))\n conv3 = tf.nn.max_pool(conv3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n conv3 = tf.nn.dropout(conv3, self.keep_prob)\n print(\">>> convolution 3: \", conv3.shape)\n next_shape = conv3.shape[1] * conv3.shape[2] * conv3.shape[3]\n\n # 全连接层1\n wd1 = tf.get_variable(name='wd1', shape=[next_shape, 1024], dtype=tf.float32,\n initializer=tf.contrib.layers.xavier_initializer())\n bd1 = tf.Variable(self.b_alpha * tf.random_normal([1024]))\n dense = tf.reshape(conv3, [-1, wd1.get_shape().as_list()[0]])\n dense = tf.nn.relu(tf.add(tf.matmul(dense, wd1), bd1))\n dense = tf.nn.dropout(dense, self.keep_prob)\n\n # 全连接层2\n wout = tf.get_variable('name', shape=[1024, self.max_captcha * self.char_set_len], dtype=tf.float32,\n initializer=tf.contrib.layers.xavier_initializer())\n bout = tf.Variable(self.b_alpha * tf.random_normal([self.max_captcha * self.char_set_len]))\n y_predict = tf.add(tf.matmul(dense, wout), bout)\n return y_predict\n\n def train_cnn(self):\n y_predict = self.model()\n print(\">>> input batch predict shape: {}\".format(y_predict.shape))\n print(\">>> End model test\")\n # 计算概率 损失\n cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=y_predict, labels=self.Y))\n # 梯度下降\n optimizer = tf.train.AdamOptimizer(learning_rate=0.0001).minimize(cost)\n # 计算准确率\n predict = tf.reshape(y_predict, [-1, self.max_captcha, self.char_set_len]) # 预测结果\n max_idx_p = tf.argmax(predict, 2) # 预测结果\n max_idx_l = tf.argmax(tf.reshape(self.Y, [-1, self.max_captcha, self.char_set_len]), 2) # 标签\n # 计算准确率\n correct_pred = tf.equal(max_idx_p, max_idx_l)\n accuracy = tf.reduce_mean(tf.reduce_min(tf.cast(correct_pred, tf.float32), axis=1))\n # 模型保存对象\n saver = tf.train.Saver()\n with tf.Session() as sess:\n init = tf.global_variables_initializer()\n sess.run(init)\n # 恢复模型\n if os.path.exists(self.model_save_dir):\n try:\n saver.restore(sess, self.model_save_dir)\n # 判断捕获model文件夹中没有模型文件的错误\n except NotFoundError:\n print(\"model文件夹为空,将创建新模型\")\n else:\n pass\n step = 1\n for i in range(3000):\n batch_x, batch_y = self.get_batch(i, size=128)\n _, cost_ = sess.run([optimizer, cost], feed_dict={self.X: batch_x, self.Y: batch_y, self.keep_prob: 0.75})\n if step % 10 == 0:\n batch_x_test, batch_y_test = self.get_batch(i, size=100)\n acc = sess.run(accuracy, feed_dict={self.X: batch_x_test, self.Y: batch_y_test, self.keep_prob: 1.})\n print(\"第{}次训练 >>> 准确率为 {} >>> loss {}\".format(step, acc, cost_))\n # 准确率达到99%后保存并停止\n if acc > 0.99:\n saver.save(sess, self.model_save_dir)\n break\n # 每训练500轮就保存一次\n if i % 500 == 0:\n saver.save(sess, self.model_save_dir)\n step += 1\n saver.save(sess, self.model_save_dir)\n\n def recognize_captcha(self):\n label, captcha_array = self.gen_captcha_text_image(random.choice(self.img_list))\n\n f = plt.figure()\n ax = f.add_subplot(111)\n ax.text(0.1, 0.9, \"origin:\" + label, ha='center', va='center', transform=ax.transAxes)\n plt.imshow(captcha_array)\n # 预测图片\n image = self.convert2gray(captcha_array)\n image = image.flatten() / 255\n\n y_predict = self.model()\n\n saver = tf.train.Saver()\n with tf.Session() as sess:\n saver.restore(sess, self.model_save_dir)\n predict = tf.argmax(tf.reshape(y_predict, [-1, self.max_captcha, self.char_set_len]), 2)\n text_list = sess.run(predict, feed_dict={self.X: [image], self.keep_prob: 1.})\n predict_text = text_list[0].tolist()\n\n print(\"正确: {} 预测: {}\".format(label, predict_text))\n # 显示图片和预测结果\n p_text = \"\"\n for p in predict_text:\n p_text += str(self.char_set[p])\n print(p_text)\n plt.text(20, 1, 'predict:{}'.format(p_text))\n plt.show()\n\n\ndef main():\n train_image_dir = sample_conf[\"train_image_dir\"]\n char_set = sample_conf[\"char_set\"]\n model_save_dir = sample_conf[\"model_save_dir\"]\n tm = TrainModel(train_image_dir, char_set, model_save_dir, verify=False)\n tm.train_cnn() # 开始训练模型\n # tm.recognize_captcha() # 识别图片示例\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "matplotlib.pyplot.imshow", "tensorflow.nn.max_pool", "tensorflow.equal", "tensorflow.cast", "tensorflow.nn.sigmoid_cross_entropy_with_logits", "tensorflow.train.AdamOptimizer", "tensorflow.nn.conv2d", "tensorflow.contrib.layers.xavier_initializer", "tensorflow.Session", "tensorflow.train.Saver", "tensorflow.argmax", "numpy.zeros", "matplotlib.pyplot.figure", "tensorflow.nn.dropout", "tensorflow.matmul", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "numpy.array", "matplotlib.pyplot.show", "tensorflow.reshape", "tensorflow.random_normal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
steveazzolin/noiseprint
[ "f42335c3ae641b620583c7dcd89063ca24a6437b" ]
[ "noiseprint/utility/gaussianMixture.py" ]
[ "# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n#\n# Copyright (c) 2017 Image Processing Research Group of University Federico II of Naples ('GRIP-UNINA').\n# This software is delivered with Government Purpose Rights (GPR) under agreement number FA8750-16-2-0204.\n#\n# By downloading and/or using any of these files, you implicitly agree to all the\n# terms of the license, as specified in the document LICENSE.txt\n# (included in this package) \n#\n\nimport numpy as np\nfrom scipy.linalg import eigvalsh\nfrom numpy.linalg import cholesky\nfrom numpy.linalg import eigh\n\nfrom numba import jit\nimport torch\n\nclass gm:\n prioriProb = 0\n outliersProb = 0\n outliersNlogl = 0\n mu = 0\n listSigma = []\n listSigmaInds = []\n listSigmaType = []\n\n # sigmaType = 0 # isotropic covariance\n # sigmaType = 1 # diagonal covariance\n # sigmaType = 2 # full covariance\n\n # outliersProb < 0 # outliers are not managed\n # outliersProb >= 0 # outliers are managed throught fixed nlogl (negative log likelihood)\n # TODO: outliers managed throught fixed probability\n\n def __init__(self, dim, listSigmaInds, listSigmaType, outliersProb = -1, outliersNlogl = 0, dtype = np.float32):\n K = len(listSigmaInds)\n S = len(listSigmaType)\n\n self.listSigmaInds = listSigmaInds\n self.listSigmaType = listSigmaType\n self.outliersProb = outliersProb\n self.outliersNlogl = outliersNlogl\n self.prioriProb = (1.0-self.outliersProb) * np.ones((K, 1), dtype=dtype) / K\n self.mu = np.zeros((K, dim), dtype=dtype)\n self.listSigma = [None, ] * S\n\n for s in range(S):\n sigmaType = self.listSigmaType[s]\n if sigmaType == 2: # full covariance\n self.listSigma[s] = np.ones([dim, dim], dtype = dtype)\n elif sigmaType == 1: # diagonal covariance\n self.listSigma[s] = np.ones([1, dim], dtype = dtype)\n else:\n self.listSigma[s] = np.ones([], dtype = dtype)\n\n def setRandomParams(self, X, regularizer = 0, randomState = np.random.get_state()):\n [N, dim] = X.shape\n K = len(self.listSigmaInds)\n S = len(self.listSigmaType)\n dtype = X.dtype\n\n if self.outliersProb > 0:\n self.prioriProb = (1.0-self.outliersProb) * np.ones((K, 1), dtype=dtype) / K\n else:\n self.prioriProb = np.ones((K, 1), dtype=dtype) / K\n\n inds = randomState.random_integers(low=0,high=(N-1),size=(K,))\n self.mu = X[inds, :]\n varX = np.var(X, axis=0, keepdims=True)\n if regularizer>0:\n varX = varX + regularizer\n elif regularizer<0:\n varX = varX + np.abs(regularizer*np.spacing(np.max(varX)))\n\n for s in range(S):\n sigmaType = self.listSigmaType[s]\n if sigmaType == 2: # full covariance\n self.listSigma[s] = np.diag(varX.flatten())\n elif sigmaType == 1: # diagonal covariance\n self.listSigma[s] = varX\n else:\n self.listSigma[s] = np.mean(varX)\n return inds\n\n def setRandomParamsW(self, X, weights, regularizer = 0, randomState = np.random.get_state(), meanFlag = False):\n [N, dim] = X.shape\n K = len(self.listSigmaInds)\n S = len(self.listSigmaType)\n dtype = X.dtype\n\n if self.outliersProb > 0:\n self.prioriProb = (1.0-self.outliersProb) * np.ones((K, 1), dtype=dtype) / K\n else:\n self.prioriProb = np.ones((K, 1), dtype=dtype) / K\n\n avrX = np.mean(X*weights, axis=0, keepdims=True)/np.mean(weights)\n varX = np.mean(weights *((X - avrX) ** 2), axis=0, keepdims=True)/np.mean(weights)\n\n indsW = np.sum(weights)*randomState.random_sample(size=(K,))\n inds = [None, ] * K\n weights = np.cumsum(weights.flatten())\n for index in range(K):\n inds[index] = np.count_nonzero(weights<=indsW[index])\n\n self.mu = X[inds, :]\n if meanFlag: self.mu[0,:] = avrX\n #varX = np.var(X, axis=0, keepdims=True)\n if regularizer>0:\n varX = varX + regularizer\n elif regularizer<0:\n varX = varX + np.abs(regularizer*np.spacing(np.max(varX)))\n\n for s in range(S):\n sigmaType = self.listSigmaType[s]\n if sigmaType == 2: # full covariance\n self.listSigma[s] = np.diag(varX.flatten())\n elif sigmaType == 1: # diagonal covariance\n self.listSigma[s] = varX\n else:\n self.listSigma[s] = np.mean(varX)\n return inds\n\n def getNlogl(self, X):\n [N, dim] = X.shape\n K = len(self.listSigmaInds)\n S = len(self.listSigmaType)\n dtype = X.dtype\n\n K0 = K\n if self.outliersProb >= 0: K0 = K+1\n\n nlogl = np.zeros([N, K0], dtype = dtype)\n mahal = np.zeros([N, K ], dtype = dtype)\n listLogDet = [None, ] * S\n listLowMtx = [None, ] * S\n for s in range(S):\n sigmaType = self.listSigmaType[s]\n sigma = self.listSigma[s]\n if sigmaType == 2: # full covariance\n try:\n listLowMtx[s] = cholesky(sigma)\n except:\n # exceptional regularization\n sigma_w, sigma_v = eigh(np.real(sigma))\n sigma_w = np.maximum(sigma_w, np.spacing(np.max(sigma_w)))\n sigma = np.matmul(np.matmul(sigma_v, np.diag(sigma_w)), (np.transpose(sigma_v,[1,0])))\n try:\n listLowMtx[s] = cholesky(sigma)\n except:\n sigma_w, sigma_v = eigh(np.real(sigma))\n sigma_w = np.maximum(sigma_w, np.spacing(np.max(sigma_w)))\n #print(np.min(sigma_w))\n sigma = np.matmul(np.matmul(sigma_v, np.diag(sigma_w)), (np.transpose(sigma_v,[1,0])))\n #print(sigma)\n listLowMtx[s] = cholesky(sigma)\n diagLowMtx = np.diag(listLowMtx[s])\n listLogDet[s] = 2 * np.sum(np.log(diagLowMtx))\n elif sigmaType == 1: # diagonal covariance\n listLowMtx[s] = np.sqrt(sigma)\n listLogDet[s] = np.sum(np.log(sigma))\n else: # isotropic covariance\n listLowMtx[s] = np.sqrt(sigma)\n listLogDet[s] = dim * np.log(sigma)\n\n constPi = dim*np.log(2*np.pi)\n for k in range(K):\n s = self.listSigmaInds[k]\n sigmaType = self.listSigmaType[s]\n lowMtx = listLowMtx[s]\n logDet = listLogDet[s]\n\n Xmu = X - self.mu[k,:]\n\n if sigmaType == 2: # full covariance\n Xmu = self.tmp(lowMtx, Xmu) #np.linalg.solve(lowMtx, Xmu.transpose()).transpose()\n elif sigmaType == 1: # diagonal covariance\n Xmu = Xmu / lowMtx\n else: # isotropic covariance\n Xmu = Xmu / lowMtx\n\n mahal[:,k] = np.sum(Xmu * Xmu, axis = 1)\n\n nlogl[:,k] = 0.5 * (mahal[:,k] + logDet + constPi)\n\n if self.outliersProb >= 0:\n nlogl[:, K] = self.outliersNlogl\n return nlogl, mahal\n\n @staticmethod\n def tmp(lowMtx, Xmu):\n return np.linalg.solve(lowMtx, Xmu.transpose()).transpose()\n #lowMtx, Xmu = torch.tensor(lowMtx, device=\"cuda\") , torch.tensor(Xmu, device=\"cuda\")\n #sa = torch.linalg.solve(lowMtx, Xmu.T).T\n #return sa.cpu().numpy()\n\n def getLoglh(self, X):\n nlogl, _ = self.getNlogl(X)\n logPrb = np.log(self.prioriProb)\n if self.outliersProb >= 0:\n #print(self.outliersProb)\n logPrb = np.append(logPrb.squeeze(), np.log(self.outliersProb))\n logPrb = logPrb.reshape((-1,1))\n return logPrb.transpose((1,0)) - nlogl\n\n def getLoglhInlier(self, X):\n nlogl, _ = self.getNlogl(X)\n K = self.prioriProb.size\n logPrb = np.log(self.prioriProb)\n logit = logPrb.transpose((1, 0)) - nlogl[:, :K]\n\n maxll = np.max(logit, axis=1, keepdims=True)\n prob = np.exp(logit - maxll)\n dem = np.sum(prob, axis=1, keepdims=True)\n #return (np.log(dem) + maxll - np.log(np.sum(self.prioriProb)))\n return (np.log(dem) + maxll - np.log(np.sum(self.outliersProb)))\n\n def maximizationParam(self, X, post, regularizer = 0):\n [N, dim] = X.shape\n K = len(self.listSigmaInds)\n S = len(self.listSigmaType)\n dtype = X.dtype\n\n self.prioriProb = np.sum(post[:,:K], axis=0, keepdims=True).transpose([1, 0])\n\n self.mu = np.tensordot(post, X, (0, 0)) / self.prioriProb\n for s in range(S):\n sigmaType = self.listSigmaType[s]\n if sigmaType == 2: # full covariance\n sigma = np.zeros([dim, dim], dtype=dtype)\n sigmadem = np.zeros([], dtype=dtype)\n for k in range(K):\n if s == self.listSigmaInds[k]:\n Xmu = X - self.mu[(k,), :]\n Xmu = np.sqrt(post[:, (k,)]) * Xmu\n sigma = sigma + np.tensordot(Xmu, Xmu, (0, 0))\n sigmadem += self.prioriProb[k, 0]\n sigma = sigma / sigmadem\n if regularizer > 0:\n sigma = sigma + regularizer * np.eye(dim)\n elif regularizer < 0:\n #sigma = sigma - regularizer * np.spacing(np.max(np.linalg.eigvalsh(sigma))) * np.eye(dim)\n sigma = sigma + np.abs(regularizer * np.spacing(eigvalsh(sigma, eigvals=(dim - 1, dim - 1)))) * np.eye(dim)\n elif sigmaType == 1: # diagonal covariance\n sigma = np.zeros([1, dim], dtype=dtype)\n sigmadem = np.zeros([], dtype=dtype)\n for k in range(K):\n if s == self.listSigmaInds[k]:\n Xmu = X - self.mu[(k,), :]\n sigma = sigma + np.tensordot(post[:, (k,)], (Xmu * Xmu), (0, 0))\n sigmadem += self.prioriProb[k, 0]\n sigma = sigma / sigmadem\n if regularizer > 0:\n sigma = sigma + regularizer\n elif regularizer < 0:\n sigma = sigma + + np.abs(regularizer * np.spacing(np.max(sigma)))\n else: # isotropic covariance\n sigma = np.zeros([], dtype=dtype)\n sigmadem = np.zeros([], dtype=dtype)\n for k in range(K):\n if s == self.listSigmaInds[k]:\n Xmu = X - self.mu[(k,), :]\n sigma = sigma + np.dot(post[:, k], np.mean((Xmu * Xmu), axis=1))\n sigmadem += self.prioriProb[k, 0]\n sigma = sigma / sigmadem\n if regularizer > 0:\n sigma = sigma + regularizer\n elif regularizer < 0:\n sigma = sigma + np.abs(regularizer * np.spacing(sigma))\n self.listSigma[s] = sigma\n\n # normalize PComponents\n if self.outliersProb < 0:\n self.prioriProb = self.prioriProb / np.sum(self.prioriProb)\n else:\n self.outliersProb = np.sum(post[:,K])\n dem = self.outliersProb + np.sum(self.prioriProb)\n self.prioriProb = self.prioriProb / dem\n self.outliersProb = self.outliersProb / dem\n\n def expectation(self, X):\n [post, avrLogl] = softmax(self.getLoglh(X))\n return post, avrLogl\n\n def expectationWeighed(self, X, weighed):\n [post, avrLogl] = softmaxWeighed(self.getLoglh(X), weighed)\n return post, avrLogl\n\n def MEstep(self, X, post, regularizer = 0):\n self.maximizationParam(X, post, regularizer = regularizer)\n [post, avrLogl] = self.expectation(X)\n return post, avrLogl\n\n def MEstepWeighed(self, X, weights, post, regularizer = 0):\n self.maximizationParam(X, post * weights, regularizer = regularizer)\n [post, avrLogl] = self.expectationWeighed(X, weights)\n return post, avrLogl\n\n def EM(self, X, regularizer, maxIter, relErr = 1e-5):\n [post, avrLogl_old] = self.expectation(X)\n\n flagExit = 1\n # flagExit = 1 # max number of iteretions\n # flagExit = 0 # converged\n for iter in range(maxIter):\n [post, avrLogl] = self.MEstep(X, post, regularizer = regularizer)\n\n diff = avrLogl - avrLogl_old\n if (diff >= 0) & (diff < relErr * np.abs(avrLogl)):\n flagExit = 0\n break\n avrLogl_old = avrLogl\n\n return avrLogl, flagExit, iter\n\n\n def EMweighed(self, X, weights, regularizer, maxIter, relErr=1e-5):\n [post, avrLogl_old] = self.expectationWeighed(X, weights)\n\n flagExit = 1\n # flagExit = 1 # max number of iteretions\n # flagExit = 0 # converged\n for iter in range(maxIter):\n [post, avrLogl] = self.MEstepWeighed(X, weights, post, regularizer=regularizer)\n\n diff = avrLogl - avrLogl_old\n if (diff >= 0) & (diff < relErr * np.abs(avrLogl)):\n flagExit = 0\n break\n avrLogl_old = avrLogl\n\n return avrLogl, flagExit, iter\n\ndef softmax(logit):\n maxll = np.max(logit, axis = 1, keepdims=True)\n prob = np.exp(logit - maxll)\n dem = np.sum(prob, axis = 1, keepdims=True)\n prob = prob / dem\n avrLogl = np.mean(np.log(dem) + maxll)\n return prob, avrLogl\n\ndef softmaxWeighed(logit, weights):\n maxll = np.max(logit, axis = 1, keepdims=True)\n prob = np.exp(logit - maxll)\n dem = np.sum(prob, axis = 1, keepdims=True)\n prob = prob / dem\n avrLogl = np.mean(weights * (np.log(dem) + maxll)) / np.mean(weights)\n return prob, avrLogl\n" ]
[ [ "numpy.diag", "numpy.sqrt", "numpy.max", "numpy.mean", "numpy.var", "numpy.exp", "numpy.eye", "numpy.real", "numpy.tensordot", "numpy.count_nonzero", "numpy.zeros", "numpy.log", "numpy.spacing", "scipy.linalg.eigvalsh", "numpy.transpose", "numpy.linalg.cholesky", "numpy.sum", "numpy.random.get_state", "numpy.abs", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.14", "0.15", "0.12", "0.10" ], "tensorflow": [] } ]
nasa/airfoil-learning
[ "a76dabc0474485d1e573471e70ec4826aeae0517", "a76dabc0474485d1e573471e70ec4826aeae0517" ]
[ "generate_xfoil/Step4_CreateDataset.py", "pytorch/train_gnn.py" ]
[ "import pickle\nfrom typing import Dict, List, Tuple\nfrom tqdm import trange\nimport numpy as np\nimport random, json\nimport torch, glob, os\nimport os.path as osp\nfrom torch.utils.data import random_split\nimport torch_geometric.transforms as T\nfrom libs.utils import create_edge_adjacency\nfrom torch_geometric.data import Data\nimport sys\nfrom libs.utils import pchip\n\nsys.path.insert(0,'libs')\n\ndef shuffle_and_save(scaled_data: List, process_path:str,file_prefix:str,train_test_split:float=0.7):\n \"\"\"Shuffle the list and save\n\n Args:\n scaled_data (List): [description]\n file_prefix (str): [description]\n train_test_split (float, optional): [description]. Defaults to 0.7.\n \"\"\"\n # Load all the designs \n random.shuffle(scaled_data) # Shuffle the list\n \n train_size = int(len(scaled_data)*train_test_split)\n test_size = len(scaled_data) - train_size \n\n train_subset, test_subset = random_split(scaled_data,[train_size, test_size])\n train_dataset = [scaled_data[i] for i in train_subset.indices] \n test_dataset = [scaled_data[i] for i in test_subset.indices] \n\n torch.save(train_dataset,os.path.join(process_path,f'{file_prefix}_train.pt'))\n torch.save(test_dataset,os.path.join(process_path,f'{file_prefix}_test.pt'))\n\ndef CreateDatasetFromJson(airfoil:Dict,scaler:Dict,scaler_cp:Dict,cp_points:int) -> Tuple[List[Data], List[Data], List[Data], List[Data]]:\n \"\"\"Takes a single json file and creates a tuple containing lists of graph data objects and also deep neural network data objects. These objects are combined together and later used by pytorch dataloader \n\n Args:\n airfoil (Dict): Dictionary containing properties of the airfoil0\n scaler (Dict): Dictionary containing normalization parameters \n scaler_cp (Dict): Dictionary containing normalization parameters for Cp\n\n Returns:\n Tuple containing:\n List[Data], List[Data], List[Data], List[Data]]: [description]\n \"\"\"\n \n '''\n Normalize the x and the y for airfoil \n '''\n xss = airfoil['xss'] \n yss = airfoil['yss']\n\n xps = airfoil['xps']\n yps = airfoil['yps']\n \n x = np.concatenate((xss[0:],np.flip(xps[1:-1]))).reshape(-1,1) # This is already in 0 to 1\n y = np.concatenate((yss[0:],np.flip(yps[1:-1]))).reshape(-1,1) # \n y_scaled = scaler['y'].transform(y) # Do not transform y for gnn. This is for DNN only \n edge_index = create_edge_adjacency(len(x))\n\n graph_scaled_data = list()\n graph_scaled_data_cp = list() \n dnn_scaled = list() \n dnn_scaled_cp = list()\n\n for p in range(len(airfoil['polars'])): \n polar = airfoil['polars'][p]\n\n Cp_ss = np.array(polar['Cp_ss'])\n Cp_ps = np.array(polar['Cp_ps'])\n \n alpha = scaler['alpha'].transform(np.array(polar['alpha']).reshape(-1,1))[0][0]\n Re = scaler['Re'].transform(np.array(polar['Re']).reshape(-1,1))[0][0]\n Ncrit = scaler['Ncrit'].transform(np.array(polar['Ncrit']).reshape(-1,1))[0][0]\n\n # Normalize Cl, Cd, Cdp, Cm\n Cl = scaler['Cl'].transform(np.array(polar['Cl']).reshape(-1,1))\n Cd = scaler['Cd'].transform(np.array(polar['Cd']).reshape(-1,1))\n Cdp = scaler['Cdp'].transform(np.array(polar['Cdp']).reshape(-1,1))\n Cm = scaler['Cm'].transform(np.array(polar['Cm']).reshape(-1,1))\n\n # Scale Cp\n Cp = np.concatenate(( Cp_ss, np.flip(Cp_ps[1:-1]) ))\n Cp = torch.as_tensor(scaler['Cp'].transform(Cp.reshape(-1,1))[0:],dtype=torch.float32) # This has been normalized as a whole\n\n data_y = torch.as_tensor(np.hstack([ Cl, Cd, Cdp, Cm ]), dtype=torch.float32)[0]\n edge_index = np.array(edge_index) # Edge Adjacency \n if (edge_index.shape[0]!=2):\n edge_index = edge_index.transpose()\n edge_index = torch.as_tensor(edge_index,dtype=torch.long).contiguous()\n\n x = torch.as_tensor(np.hstack([x]), dtype=torch.float32)\n y = torch.as_tensor(np.hstack([y]), dtype=torch.float32)\n y_scaled = torch.as_tensor(np.hstack([y_scaled]), dtype=torch.float32)\n conditions=torch.as_tensor(np.hstack([alpha, Re, Ncrit]),dtype=torch.float32)\n pos = torch.as_tensor(np.hstack([x, y]), dtype=torch.float32)\n edge_attr = torch.ones((edge_index.shape[1],pos.shape[1]),dtype=torch.float32)\n '''\n airfoil with all values scaled by global min/max or mean/std \n '''\n # d = Data(x=data_x,edge_index=edge_index,pos=pos,y=data_y,node_labels=Cp,conditions=conditions) \n features = torch.zeros((y.shape[0],3))\n # features[:,0] = x[:,0]\n # features[:,1] = y[:,0]\n features[:,0] = alpha\n features[:,1] = Re\n features[:,2] = Ncrit\n # scaled_data\n graph_scaled_data.append(Data(x=features,edge_index=edge_index,pos=pos,y=data_y,node_labels=Cp,conditions=conditions,edge_attr=edge_attr))\n\n '''\n airfoil with all values except for cp scaled by global min/max or mean/std \n '''\n Cp_ss_scaled = Cp_ss\n Cp_ps_scaled = Cp_ps \n for i in range(len(scaler_cp)): \n Cp_ss_scaled[i] = scaler_cp[i].transform(Cp_ss[i].reshape(-1,1))[0] # Transform Cp for each value of x\n for i in range(len(scaler_cp)):\n Cp_ps_scaled[i] = scaler_cp[i].transform(Cp_ps[i].reshape(-1,1))[0] # Transform Cp for each value of x\n Cp_ps_scaled = np.flip(Cp_ps[1:-1])\n Cp_scaled = np.concatenate(( Cp_ss_scaled, Cp_ps_scaled ))\n Cp_scaled = torch.as_tensor(Cp_scaled.reshape(-1,1)[0:],dtype=torch.float32)\n \n # scaled_data_cp\n graph_scaled_data_cp.append(Data(x=features,edge_index=edge_index,pos=pos,y=data_y,node_labels=Cp_scaled,conditions=conditions,edge_attr=edge_attr))\n\n '''\n Deep Neural Network \n '''\n dnn_features = (torch.cat((y_scaled[:,0], torch.tensor([alpha]), torch.tensor([Re]), torch.tensor([Ncrit])))).float()\n dnn_labels = (torch.cat((data_y,Cp[:,0]))) \n dnn_labels_cp = (torch.cat((data_y,Cp_scaled[:,0]))) \n\n dnn_scaled.append((dnn_features,dnn_labels))\n dnn_scaled_cp.append((dnn_features,dnn_labels_cp))\n\n return graph_scaled_data, graph_scaled_data_cp, dnn_scaled, dnn_scaled_cp\n\ndef CreateDataset(data_folder:str='json',processed_path:str='datasets',\n use_standard_scaler:bool=True):\n \"\"\"Create a dataset that can be used to train a graph neural network \n\n Reference:\n https://pytorch-geometric.readthedocs.io/en/latest/modules/data.html\n\n Args:\n data_folder (str, optional): name of file to be scraped . Defaults to 'json'.\n processed_path (str, optional): path to save the pytorch dataset. Defaults to 'datasets'.\n use_standard_scaler (bool, optional): Whether to use standard scaler or min_max. Defaults to True.\n\n Returns:\n Saves 4 files in the processed_path folder \n graph_scaled_data.pt: Graph Data format with cp all scaled by a common scaler\n graph_scaled_data_cp.pt: Graph Data format with cp individually scaled at each x value\n dnn_scaled.pt: Deep neural format with cp all scaled by a common scaler\n dnn_scaled_cp.pt: Deep neural network format with cp individually scaled at each x value\n\n \"\"\"\n os.makedirs(processed_path,exist_ok=True)\n \n data_files = glob.glob(osp.join(data_folder,'*.json'))\n jsons = list() \n for filename in data_files:\n with open(filename,'r') as f:\n jsons.append(json.load(f))\n with open('scalers.pickle','rb') as f:\n data = pickle.load(f)\n if use_standard_scaler:\n scaler = data['standard']\n scaler_cp = data['standard_cp']\n else:\n scaler = data['min_max']\n scaler_cp = data['min_max_cp']\n \n graph_scaled_data = list() # All airfoil parameters are scaled by the global min and max or mean and standard dev\n graph_scaled_data_cp = list() # All except for Cp is scaled by global min and max. Cp is scaled at each x\n dnn_scaled = list()\n dnn_scaled_cp = list()\n\n pbar = trange(len(jsons),desc='Processing')\n for c in pbar:\n out1, out2, out3, out4 = CreateDatasetFromJson(jsons[c],scaler,scaler_cp,50)\n pbar.desc=\"Extending List\"\n graph_scaled_data.extend(out1)\n graph_scaled_data_cp.extend(out2)\n dnn_scaled.extend(out3)\n dnn_scaled_cp.extend(out4)\n pbar.desc=\"Processing\"\n \n shuffle_and_save(graph_scaled_data,processed_path,'graph_scaled_data',0.7)\n shuffle_and_save(graph_scaled_data_cp,processed_path,'graph_scaled_data_cp',0.7)\n shuffle_and_save(dnn_scaled,processed_path,'dnn_scaled_data',0.7)\n shuffle_and_save(dnn_scaled_cp,processed_path,'dnn_scaled_data_cp',0.7)\n\n\nif __name__ == \"__main__\":\n CreateDataset(data_folder='json_cp_resize',processed_path='datasets/standard/',use_standard_scaler=True)\n CreateDataset(data_folder='json_cp_resize',processed_path='datasets/minmax/',use_standard_scaler=False)\n # transform_test_train()", "'''\n Purpose: In this file only Cl, Cd, Cdp, and Cm are predicted using graph neural networks\n'''\nimport os.path as osp\nfrom typing import Dict\nimport torch\nfrom torch_geometric.loader import DataLoader\nimport logging, datetime\nfrom tqdm import tqdm, trange\nfrom gnn_model import GnnModel\nfrom MultiLayerLinear import MultiLayerLinear\nimport torch.nn.functional as F\nimport json \nimport os\nimport logging\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig()\nlogger.setLevel(logging.INFO)\nNUM_CLASSES = 10\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\ndef get_lr(optimizer):\n for param_group in optimizer.param_groups:\n return param_group['lr']\n\ndef train_one_epoch(train_dl:DataLoader,optimizer:torch.optim.Optimizer, model:torch.nn.Module,output_channels:int):\n \"\"\"Trains a graph neural network for one epoch. This is meant to be called in a loop\n\n Args:\n train_dl (DataLoader): Dataloader containing a list of datasets \n optimizer (torch.optim.Optimizer): Optimizer\n model (torch.nn.Module): Graph neural network model\n output_channels (int): Number of output channels\n\n Returns:\n float: network loss \n \"\"\"\n total_loss = 0\n n = 0\n pbar = tqdm(train_dl)\n accumulation_steps = 10\n i = 0 \n model.train()\n model.zero_grad()\n for _, data in enumerate(pbar): \n try:\n data.to(device)\n num_graphs = data.num_graphs \n # for param in model.parameters(): # Zero the gradients. similar to optimizer.zero_grad(). Less memory operations\n # param.grad = None\n out = model(data)\n target = data.y.reshape(data.num_graphs,output_channels)\n loss = F.mse_loss(out, target)\n total_loss += loss.item() * num_graphs # sum of all loss for all data in batch\n loss = loss / accumulation_steps # Normalize our loss (if averaged)\n loss.backward() \n # Performance improvements taken from https://www.reddit.com/r/MachineLearning/comments/kvs1ex/d_here_are_17_ways_of_making_pytorch_training/ and https://efficientdl.com/faster-deep-learning-in-pytorch-a-guide/\n if (i+1) % accumulation_steps == 0: # Wait for several backward steps\n optimizer.step() # Now we can do an optimizer step \n model.zero_grad() # Reset gradients tensors \n pbar.set_description(f\"Train Mode: Loss {loss:05e}\")\n n += num_graphs\n i+=1 \n except Exception as e:\n logging.error(e, exc_info=True) # log stack trace\n \n return total_loss / n\n\n\ndef evaluate(test_dl:DataLoader,model:torch.nn.Module,output_channels:int):\n \"\"\"Evaluates the graph neural network model on a test dataset \n\n Args:\n dataloader (DataLoader): This is intended to be the test dataloader\n model (torch.nn.Module): this is the neural network model for a graph network. \n output_channels (int): number of output channels\n\n Returns:\n float: Loss\n \"\"\"\n model.eval()\n total_loss = 0\n n = 0\n with torch.no_grad():\n pbar = tqdm(test_dl)\n for _, data in enumerate(pbar): \n data.to(device)\n out = model(data)\n target = data.y.reshape(data.num_graphs,output_channels)\n batch_loss = F.mse_loss(out, target)\n total_loss += batch_loss.item() * data.num_graphs \n n += data.num_graphs\n pbar.set_description(f\"Test Mode: Loss {batch_loss:05e}\")\n return total_loss / n\n\n\ndef save_checkpoint(output_dir:str, state:Dict, model_name:str): \n \"\"\"Saves the model checkpoint to a file \n\n Args:\n output_dir (str): Directory to save the checkpoint\n state (Dict): This contains information needed to resume training. {'state_dict':Model_state/variables, 'optimizer':optimizer state, 'epoch': last epoch run}\n model_name (str): Name describing the model \n \"\"\"\n os.makedirs(output_dir,exist_ok=True)\n filename = osp.join(output_dir,model_name + '_checkpoint.pt.tar')\n torch.save(state, filename)\n\ndef load_checkpoint(output_dir:str, model_name:str):\n \"\"\"Loads a checkpoint for a given model \n\n Args:\n output_dir (str): Directory where to look for saved checkpoints \n model_name (str): name of the model\n\n Returns:\n Dict: dictionary describing the state\n \"\"\"\n\n filename = osp.join(output_dir,model_name + '_checkpoint.pt.tar')\n if osp.exists(filename):\n state = torch.load(filename)\n return state\n else:\n return None\n\nif __name__==\"__main__\":\n \"\"\"Main code execution. Structuring this way allows the use of multiple workers\n \"\"\"\n \n with open('settings.json', 'r') as infile: # Loads the settings for the graph neural network \n args = json.load(infile)\n dataset_type = 'gnn'\n gnn_networks = [a for a in args['networks'] if a['type'] == dataset_type and a['train']['predict_cp']== False]\n for args in gnn_networks:\n data_folder = osp.join('local_dataset',args['scaler_type'])\n \n with open(osp.join(data_folder,f'{dataset_type}_dataset_properties.json'), 'r') as infile:\n data_params = json.load(infile)\n\n train_dataset = torch.load(osp.join(data_folder, 'train_gnn.pt'))\n test_dataset = torch.load(osp.join(data_folder, 'test_gnn.pt'))\n\n train_args = args['train']\n train_args['input_size'] = data_params['input_size']\n train_args['output_size'] = data_params['output_size']\n train_dl = DataLoader(train_dataset, shuffle=True, batch_size=train_args['batch_size'])\n test_dl = DataLoader(test_dataset, shuffle=False, batch_size=train_args['batch_size'])\n # |-------Encoder------|------Decoder-----| \n GnnLayers = train_args['GnnLayers'] # 3 - number of input columns 3 -> 16 -> 32 -> 64 -> 64 -> 32 -> 16 --> Linear -> results \n linear_layer = MultiLayerLinear(in_channels=train_args['input_size']*GnnLayers[1],out_channels=train_args['output_size'],h_sizes=train_args['hiddenLayers'])\n model = GnnModel(train_args['input_size'],GnnLayers,linear_layers=linear_layer)\n \n model.to(device)\n optimizer = torch.optim.AdamW(model.parameters(), lr=train_args['learning_rate'],weight_decay=train_args['weighted_decay']) \n \n checkpoint_data = load_checkpoint(train_args['output_dir'], str(model))\n if (checkpoint_data):\n model.load_state_dict(checkpoint_data['state_dict']) \n optimizer.load_state_dict(checkpoint_data['optimizer'])\n start_epoch = checkpoint_data['epoch'] +1\n logging.info(\"Loaded model state starting epoch\" + str(start_epoch))\n loss_track = checkpoint_data['loss_track']\n else:\n start_epoch = 1\n loss_track = list()\n\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=2, gamma=0.5, verbose=True)\n # for epoch in range(start_epoch): # Advance the scheduler. This is if you resume simulation\n # scheduler.step() \n\n print(f'Starting Epoch: {start_epoch}')\n lr_history = list()\n for epoch in trange(start_epoch, train_args['epochs']+1): \n loss = train_one_epoch(train_dl,optimizer,model,data_params['output_size'])\n if epoch % train_args['validation_epoch'] == 0:\n val_loss = evaluate(test_dl,model,data_params['output_size'])\n logging.info(f\"Validation: Epoch {epoch:03d} Loss {loss:05e}\")\n loss_track.append({'model_name':str(model),'timestamp':datetime.datetime.now(),'epoch':epoch,'loss':loss,'validation_loss':val_loss})\n else:\n loss_track.append({'model_name':str(model),'timestamp':datetime.datetime.now(),'epoch':epoch,'loss':loss,'validation_loss':-1})\n \n scheduler.step()\n lr_history.append({'lr': get_lr(optimizer), 'epoch':epoch})\n \n print(f\"Training: Epoch {epoch:03d} Loss {loss:05e}\")\n logging.info(f\"Training: Epoch {epoch:03d} Loss {loss:05e}\")\n \n save_checkpoint(train_args['output_dir'],{\n 'epoch': epoch,\n 'state_dict': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'loss_track': loss_track,\n 'LR_history':lr_history,\n 'parameters':train_args\n }, str(model))" ]
[ [ "numpy.hstack", "torch.ones", "torch.zeros", "torch.cat", "torch.tensor", "numpy.concatenate", "torch.utils.data.random_split", "numpy.array", "numpy.flip", "torch.as_tensor" ], [ "torch.optim.lr_scheduler.StepLR", "torch.load", "torch.nn.functional.mse_loss", "torch.no_grad", "torch.cuda.is_available", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
btlk/facenet
[ "fd531331b962ec4fd4aac534debf9a5bbf7e8c4a" ]
[ "facenet/align/align_dataset_mtcnn.py" ]
[ "\"\"\"Performs face alignment and stores face thumbnails in the output directory.\"\"\"\n# MIT License\n# \n# Copyright (c) 2016 David Sandberg\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom scipy import misc\nimport sys\nimport os\nimport argparse\nimport tensorflow as tf\nimport numpy as np\nimport facenet\nfrom detect_face import create_mtcnn, detect_face\nimport random\nfrom time import sleep\n\ndef main(args):\n sleep(random.random())\n output_dir = os.path.expanduser(args.output_dir)\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n # Store some git revision info in a text file in the log directory\n src_path,_ = os.path.split(os.path.realpath(__file__))\n facenet.store_revision_info(src_path, output_dir, ' '.join(sys.argv))\n dataset = facenet.get_dataset(args.input_dir, False)\n \n print('Creating networks and loading parameters')\n \n with tf.Graph().as_default():\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_memory_fraction)\n sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))\n with sess.as_default():\n pnet, rnet, onet = create_mtcnn(sess, None)\n \n minsize = 20 # minimum size of face\n threshold = [ 0.6, 0.7, 0.7 ] # three steps's threshold\n factor = 0.709 # scale factor\n\n # Add a random key to the filename to allow alignment using multiple processes\n random_key = np.random.randint(0, high=99999)\n bounding_boxes_filename = os.path.join(output_dir, 'bounding_boxes_%05d.txt' % random_key)\n \n with open(bounding_boxes_filename, \"w\") as text_file:\n nrof_images_total = 0\n nrof_successfully_aligned = 0\n if args.random_order:\n random.shuffle(dataset)\n for cls in dataset:\n output_class_dir = os.path.join(output_dir, cls.name)\n if not os.path.exists(output_class_dir):\n os.makedirs(output_class_dir)\n if args.random_order:\n random.shuffle(cls.image_paths)\n for image_path in cls.image_paths:\n nrof_images_total += 1\n filename = os.path.splitext(os.path.split(image_path)[1])[0]\n output_filename = os.path.join(output_class_dir, filename+'.png')\n print(image_path)\n if not os.path.exists(output_filename):\n try:\n img = misc.imread(image_path)\n except (IOError, ValueError, IndexError) as e:\n errorMessage = '{}: {}'.format(image_path, e)\n print(errorMessage)\n else:\n if img.ndim<2:\n print('Unable to align \"%s\"' % image_path)\n text_file.write('%s\\n' % (output_filename))\n continue\n if img.ndim == 2:\n img = facenet.to_rgb(img)\n img = img[:,:,0:3]\n \n bounding_boxes, _ = detect_face(img, minsize, pnet, rnet, onet, threshold, factor)\n nrof_faces = bounding_boxes.shape[0]\n if nrof_faces>0:\n det = bounding_boxes[:,0:4]\n det_arr = []\n img_size = np.asarray(img.shape)[0:2]\n if nrof_faces>1:\n if args.detect_multiple_faces:\n for i in range(nrof_faces):\n det_arr.append(np.squeeze(det[i]))\n else:\n bounding_box_size = (det[:,2]-det[:,0])*(det[:,3]-det[:,1])\n img_center = img_size / 2\n offsets = np.vstack([ (det[:,0]+det[:,2])/2-img_center[1], (det[:,1]+det[:,3])/2-img_center[0] ])\n offset_dist_squared = np.sum(np.power(offsets,2.0),0)\n index = np.argmax(bounding_box_size-offset_dist_squared*2.0) # some extra weight on the centering\n det_arr.append(det[index,:])\n else:\n det_arr.append(np.squeeze(det))\n\n for i, det in enumerate(det_arr):\n det = np.squeeze(det)\n bb = np.zeros(4, dtype=np.int32)\n bb[0] = np.maximum(det[0]-args.margin/2, 0)\n bb[1] = np.maximum(det[1]-args.margin/2, 0)\n bb[2] = np.minimum(det[2]+args.margin/2, img_size[1])\n bb[3] = np.minimum(det[3]+args.margin/2, img_size[0])\n cropped = img[bb[1]:bb[3],bb[0]:bb[2],:]\n scaled = misc.imresize(cropped, (args.image_size, args.image_size), interp='bilinear')\n nrof_successfully_aligned += 1\n filename_base, file_extension = os.path.splitext(output_filename)\n if args.detect_multiple_faces:\n output_filename_n = \"{}_{}{}\".format(filename_base, i, file_extension)\n else:\n output_filename_n = \"{}{}\".format(filename_base, file_extension)\n misc.imsave(output_filename_n, scaled)\n text_file.write('%s %d %d %d %d\\n' % (output_filename_n, bb[0], bb[1], bb[2], bb[3]))\n else:\n print('Unable to align \"%s\"' % image_path)\n text_file.write('%s\\n' % (output_filename))\n \n print('Total number of images: %d' % nrof_images_total)\n print('Number of successfully aligned images: %d' % nrof_successfully_aligned)\n \n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n \n parser.add_argument('--input_dir', type=str, help='Directory with unaligned images.')\n parser.add_argument('--output_dir', type=str, help='Directory with aligned face thumbnails.')\n parser.add_argument('--image_size', type=int,\n help='Image size (height, width) in pixels.', default=182)\n parser.add_argument('--margin', type=int,\n help='Margin for the crop around the bounding box (height, width) in pixels.', default=44)\n parser.add_argument('--random_order', \n help='Shuffles the order of images to enable alignment using multiple processes.', action='store_true')\n parser.add_argument('--gpu_memory_fraction', type=float,\n help='Upper bound on the amount of GPU memory that will be used by the process.', default=1.0)\n parser.add_argument('--detect_multiple_faces', type=bool,\n help='Detect and align multiple faces per image.', default=False)\n return parser.parse_args(argv)\n\nif __name__ == '__main__':\n main(parse_arguments(sys.argv[1:]))\n" ]
[ [ "tensorflow.Graph", "scipy.misc.imresize", "numpy.maximum", "numpy.minimum", "numpy.power", "numpy.asarray", "scipy.misc.imsave", "numpy.squeeze", "tensorflow.ConfigProto", "numpy.argmax", "tensorflow.GPUOptions", "scipy.misc.imread", "numpy.zeros", "numpy.vstack", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.14", "0.15", "0.10", "0.16", "0.19", "0.18", "0.12", "1.0", "0.17", "1.2" ], "tensorflow": [] } ]
hsfzxjy/ESSNet
[ "6dc2f53b074a0800c17109a1f38a010e3944d96b", "6dc2f53b074a0800c17109a1f38a010e3944d96b" ]
[ "datasets/ade.py", "network/_deeplab.py" ]
[ "from __future__ import print_function, division\nimport json\nimport torch\nfrom torch.utils.data import Dataset\nimport numpy as np\nimport os\nimport sys\nimport collections\nimport torch.utils.data as data\nimport shutil\nfrom PIL import Image\nfrom torchvision.datasets.utils import download_url, check_integrity\n\nclass ADE20KDataset(Dataset):\n def __init__(self,ROOT_DIR, period, transform=None):\n self.root_dir = ROOT_DIR\n self.rst_dir = os.path.join(self.root_dir,'ADEChallengeData2016','result')\n self.period = period\n self.num_categories = 150\n self.transform = transform\n self.odgt = None \n\n if self.period == 'train':\n self.odgt = os.path.join(self.root_dir,'ADEChallengeData2016','train.odgt')\n else:\n self.odgt = os.path.join(self.root_dir,'ADEChallengeData2016','validation.odgt')\n\n self.list_sample = [json.loads(x.rstrip()) for x in open(self.odgt, 'r')]\n\n def __len__(self):\n return len(self.list_sample)\n\n def __getitem__(self, idx):\n image_path = os.path.join(self.root_dir, self.list_sample[idx]['fpath_img'])\n img = Image.open(image_path).convert('RGB')\n r = self.list_sample[idx]['height']\n c = self.list_sample[idx]['width']\n\n name = self.list_sample[idx]['fpath_img'].replace('ADEChallengeData2016/images/','')\n if self.period == 'train':\n name = name.replace('train/','') \n if 'val' in self.period:\n name = name.replace('validation/','') \n assert(self.period != 'test')\n name = name.replace('.jpg','')\n \n sample = {'image': img, 'name': name, 'row': r, 'col': c}\n\n if self.period == 'train' or self.period == 'val':\n seg_path = os.path.join(self.root_dir, self.list_sample[idx]['fpath_segm'])\n seg = Image.open(seg_path)\n sample['segmentation'] = seg\n #assert(seg.ndim == 2)\n assert(img.size[0] == seg.size[0])\n assert(img.size[1] == seg.size[1])\n if self.transform is not None:\n img, target = self.transform(img, seg)\n\n return img, target\n \n def decode_target(self, label):\n m = label.astype(np.uint16)\n r,c = m.shape\n cmap = np.zeros((r,c,3), dtype=np.uint8)\n cmap[:,:,0] = (m&1)<<7 | (m&8)<<3 | (m&64)>>1\n cmap[:,:,1] = (m&2)<<6 | (m&16)<<2 | (m&128)>>2\n cmap[:,:,2] = (m&4)<<5 | (m&32)<<1\n return cmap", "import torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom .utils import _SimpleSegmentationModel\n\n\n__all__ = [\"DeepLabV3\"]\n\n\nclass DeepLabV3(_SimpleSegmentationModel):\n \"\"\"\n Implements DeepLabV3 model from\n `\"Rethinking Atrous Convolution for Semantic Image Segmentation\"\n <https://arxiv.org/abs/1706.05587>`_.\n\n Arguments:\n backbone (nn.Module): the network used to compute the features for the model.\n The backbone should return an OrderedDict[Tensor], with the key being\n \"out\" for the last feature map used, and \"aux\" if an auxiliary classifier\n is used.\n classifier (nn.Module): module that takes the \"out\" element returned from\n the backbone and returns a dense prediction.\n aux_classifier (nn.Module, optional): auxiliary classifier used during training\n \"\"\"\n pass\n\nclass DeepLabHeadV3Plus(nn.Module):\n def __init__(self, in_channels, low_level_channels, num_classes, aspp_dilate=[12, 24, 36],reduce_dim=False):\n super(DeepLabHeadV3Plus, self).__init__()\n self.project = nn.Sequential( \n nn.Conv2d(low_level_channels, 48, 1, bias=False),\n nn.BatchNorm2d(48),\n nn.ReLU(inplace=True),\n )\n self.num_classes = num_classes\n self.aspp = ASPP(in_channels, aspp_dilate)\n\n self.classifier = nn.Sequential(\n nn.Conv2d(304, 256, 3, padding=1, bias=False),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, num_classes[0], 1)\n )\n self.reduce_dim = reduce_dim\n if(self.reduce_dim):\n self.embedding = nn.Embedding(num_classes[1],num_classes[0])\n nn.init.uniform_(self.embedding.weight, -1.0, 1.0)\n self._init_weight()\n\n def forward(self, feature):\n low_level_feature = self.project( feature['low_level'] )\n output_feature = self.aspp(feature['out'])\n output_feature = F.interpolate(output_feature, size=low_level_feature.shape[2:], mode='bilinear', align_corners=False)\n if(self.reduce_dim):\n class_list = torch.LongTensor(torch.arange(self.num_classes[1])).cuda()\n return F.normalize(self.classifier( torch.cat( [ low_level_feature, output_feature ], dim=1 ) ),dim=1),F.normalize(self.embedding(class_list),dim=1)\n return self.classifier( torch.cat( [ low_level_feature, output_feature ], dim=1 ) )\n \n def _init_weight(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\nclass DeepLabHead(nn.Module):\n def __init__(self, in_channels, num_classes, aspp_dilate=[12, 24, 36]):\n super(DeepLabHead, self).__init__()\n\n self.classifier = nn.Sequential(\n ASPP(in_channels, aspp_dilate),\n nn.Conv2d(256, 256, 3, padding=1, bias=False),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, num_classes, 1)\n )\n self._init_weight()\n\n def forward(self, feature):\n return self.classifier( feature['out'] )\n\n def _init_weight(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\nclass AtrousSeparableConvolution(nn.Module):\n \"\"\" Atrous Separable Convolution\n \"\"\"\n def __init__(self, in_channels, out_channels, kernel_size,\n stride=1, padding=0, dilation=1, bias=True):\n super(AtrousSeparableConvolution, self).__init__()\n self.body = nn.Sequential(\n # Separable Conv\n nn.Conv2d( in_channels, in_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=bias, groups=in_channels ),\n # PointWise Conv\n nn.Conv2d( in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=bias),\n )\n \n self._init_weight()\n\n def forward(self, x):\n return self.body(x)\n\n def _init_weight(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\nclass ASPPConv(nn.Sequential):\n def __init__(self, in_channels, out_channels, dilation):\n modules = [\n nn.Conv2d(in_channels, out_channels, 3, padding=dilation, dilation=dilation, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True)\n ]\n super(ASPPConv, self).__init__(*modules)\n\nclass ASPPPooling(nn.Sequential):\n def __init__(self, in_channels, out_channels):\n super(ASPPPooling, self).__init__(\n nn.AdaptiveAvgPool2d(1),\n nn.Conv2d(in_channels, out_channels, 1, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True))\n\n def forward(self, x):\n size = x.shape[-2:]\n x = super(ASPPPooling, self).forward(x)\n return F.interpolate(x, size=size, mode='bilinear', align_corners=False)\n\nclass ASPP(nn.Module):\n def __init__(self, in_channels, atrous_rates):\n super(ASPP, self).__init__()\n out_channels = 256\n modules = []\n modules.append(nn.Sequential(\n nn.Conv2d(in_channels, out_channels, 1, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True)))\n\n rate1, rate2, rate3 = tuple(atrous_rates)\n modules.append(ASPPConv(in_channels, out_channels, rate1))\n modules.append(ASPPConv(in_channels, out_channels, rate2))\n modules.append(ASPPConv(in_channels, out_channels, rate3))\n modules.append(ASPPPooling(in_channels, out_channels))\n\n self.convs = nn.ModuleList(modules)\n\n self.project = nn.Sequential(\n nn.Conv2d(5 * out_channels, out_channels, 1, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True),\n nn.Dropout(0.1),)\n\n def forward(self, x):\n res = []\n for conv in self.convs:\n res.append(conv(x))\n res = torch.cat(res, dim=1)\n return self.project(res)\n\n\n\ndef convert_to_separable_conv(module):\n new_module = module\n if isinstance(module, nn.Conv2d) and module.kernel_size[0]>1:\n new_module = AtrousSeparableConvolution(module.in_channels,\n module.out_channels, \n module.kernel_size,\n module.stride,\n module.padding,\n module.dilation,\n module.bias)\n for name, child in module.named_children():\n new_module.add_module(name, convert_to_separable_conv(child))\n return new_module\n" ]
[ [ "numpy.zeros" ], [ "torch.nn.init.uniform_", "torch.nn.Dropout", "torch.cat", "torch.nn.init.constant_", "torch.nn.ModuleList", "torch.nn.Conv2d", "torch.arange", "torch.nn.Embedding", "torch.nn.AdaptiveAvgPool2d", "torch.nn.functional.interpolate", "torch.nn.BatchNorm2d", "torch.nn.ReLU", "torch.nn.init.kaiming_normal_" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
PurdueMINDS/MCLV-RBM
[ "46b1f90b52447687983113f37a5ce2c66b8f0465" ]
[ "py/util/config.py" ]
[ "# Copyright 2017 Bruno Ribeiro, Mayank Kakodkar, Pedro Savarese\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 argparse\n\nimport torch\n\nfrom bean.phase import Phase\n\n\ndef parse_top_level_arguments():\n parser = argparse.ArgumentParser(description='Fit RBM to MNIST using different gradient estimators')\n parser.add_argument('--local', '-l', dest='LOCAL', action='store_const',\n const=True, default=False,\n help='Enables Local run')\n parser.add_argument('--basefolder', '-b', dest='BASE_FOLDER', action='store'\n , default='/Users/mkakodka/Code/Research/RBM_V1/',\n help='Base Folder for all directory paths')\n parser.add_argument('--phase', '-p', dest='PHASE', action='store'\n , default='DATA',\n help=str(Phase.__dict__))\n parser.add_argument('-n', dest='RUNS', action='store'\n , default='1',\n help='Number of runs')\n parser.add_argument('-iteration', dest='iteration', action='store'\n , default='-1',\n help='iteration')\n parser.add_argument('--method', '-m', dest='method', action='store',\n default=\"MCLV\",\n help='Method to use')\n parser.add_argument('-sfs', dest='sample_from_supernode', action='store_const',\n const=True, default=False,\n help='Sample from supernode for tour distribution')\n parser.add_argument('-cdk', dest='cdk', action='store',\n default=1,\n help='contrastive divergence steps limit')\n parser.add_argument('-mclvk', dest='mclvk', action='store',\n default=1,\n help='tour length limit')\n parser.add_argument('-wm', dest='warmup', action='store',\n default=2,\n help='warmup epochs')\n parser.add_argument('-tot', '--total-epochs', dest='total_epochs', action='store',\n default=100,\n help='total epochs')\n parser.add_argument('-mbs', '--mini-batch-size', dest='mini_batch_size', action='store',\n default=128,\n help='mini batch size')\n parser.add_argument('--learning-rate', '-lr', dest='learning_rate', action='store',\n default=0.1,\n help='learning rate')\n parser.add_argument('--weight-decay', '-wd', dest='weight_decay', action='store',\n default=0.0,\n help='weight decay')\n parser.add_argument('--momentum', '-mm', dest='momentum', action='store',\n default=0.0,\n help='momentum')\n parser.add_argument('--plateau', '-pt', dest='plateau', action='store',\n default=1000,\n help='Robbins Munro Schedule plateau length')\n parser.add_argument('--hidden', dest='num_hidden', action='store',\n default=16,\n help='Number of hidden units')\n parser.add_argument('--supernode-samples', '-ss', dest='supernode_samples', action='store',\n default=1,\n help='Number of samples to include in the supernode')\n\n parser.add_argument('--gpu-id', dest='gpu_id', action='store',\n default=-1,\n help='gpu_id')\n parser.add_argument('--gpu-limit', dest='gpu_limit', action='store',\n default=18,\n help='gpu_limit')\n parser.add_argument('--filename', dest='filename', action='store',\n default='temp_local',\n help='filename')\n\n parser.add_argument('--final-likelihood', dest='final_likelihood', action='store_const',\n const=True, default=False,\n help='compute final likelihood')\n\n parser.add_argument('--log-tour', dest='LOG_TOUR', action='store_const',\n const=True, default=False,\n help='LOG_TOUR')\n\n parser.add_argument('--name', dest='name', action='store',\n default=None,\n help='Name this run')\n args = parser.parse_args()\n return args.LOCAL, args.BASE_FOLDER, args\n\n\nLOCAL, BASE_FOLDER, ARGS = parse_top_level_arguments()\n\nprint(\"Config.BASE_FOLDER=%s\" % BASE_FOLDER)\nprint(\"Config.LOCAL=%s\" % LOCAL)\n\nDATA_FOLDER = BASE_FOLDER + 'data/'\nMODEL_FOLDER = BASE_FOLDER + 'data/model/'\nOUTPUT_FOLDER = BASE_FOLDER + 'output/'\nMNIST_FOLDER = BASE_FOLDER + 'py/MNIST_data/'\n\nPLOT_OUTPUT_FOLDER = BASE_FOLDER + 'plots/'\nSQLITE_FILE = DATA_FOLDER + 'results.db'\nSERVER_SQLITE_FILE = DATA_FOLDER + 'results_server.db' if LOCAL else SQLITE_FILE\n\nGPU_LIMIT = int(ARGS.gpu_limit)\nUSE_GPU = torch.cuda.is_available() and not LOCAL\nLOG_TOUR = ARGS.LOG_TOUR\nTOUR_LENGTHS_TABLE = \"TOUR_LENGTH_DISTRIBUTIONS\"\n\n# These are hardcoded for the MNIST dataset\nWIDTH = 28\nHEIGHT = 28\n\n# These options do not work right now, we'll fix them soon\nPIN = False\nGPU_ID = int(ARGS.gpu_id) if int(ARGS.gpu_id) >= 0 else None\n" ]
[ [ "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
paper2code/rasa
[ "302825e10305a995184b5c0b92fea4813cd3416e" ]
[ "rasa/utils/common.py" ]
[ "import asyncio\nimport logging\nimport os\nimport shutil\nimport warnings\nfrom types import TracebackType\nfrom typing import Any, Coroutine, Dict, List, Optional, Text, Type, TypeVar\n\nimport rasa.core.utils\nimport rasa.utils.io\nfrom rasa.constants import (\n DEFAULT_LOG_LEVEL_LIBRARIES,\n ENV_LOG_LEVEL_LIBRARIES,\n)\nfrom rasa.shared.constants import DEFAULT_LOG_LEVEL, ENV_LOG_LEVEL\nimport rasa.shared.utils.io\n\nlogger = logging.getLogger(__name__)\n\nT = TypeVar(\"T\")\n\n\nclass TempDirectoryPath(str):\n \"\"\"Represents a path to an temporary directory. When used as a context\n manager, it erases the contents of the directory on exit.\n\n \"\"\"\n\n def __enter__(self) -> \"TempDirectoryPath\":\n return self\n\n def __exit__(\n self,\n _exc: Optional[Type[BaseException]],\n _value: Optional[Exception],\n _tb: Optional[TracebackType],\n ) -> bool:\n if os.path.exists(self):\n shutil.rmtree(self)\n\n\ndef read_global_config(path: Text) -> Dict[Text, Any]:\n \"\"\"Read global Rasa configuration.\n\n Args:\n path: Path to the configuration\n Returns:\n The global configuration\n \"\"\"\n # noinspection PyBroadException\n try:\n return rasa.shared.utils.io.read_config_file(path)\n except Exception:\n # if things go south we pretend there is no config\n return {}\n\n\ndef set_log_level(log_level: Optional[int] = None):\n \"\"\"Set log level of Rasa and Tensorflow either to the provided log level or\n to the log level specified in the environment variable 'LOG_LEVEL'. If none is set\n a default log level will be used.\"\"\"\n\n if not log_level:\n log_level = os.environ.get(ENV_LOG_LEVEL, DEFAULT_LOG_LEVEL)\n log_level = logging.getLevelName(log_level)\n\n logging.getLogger(\"rasa\").setLevel(log_level)\n\n update_tensorflow_log_level()\n update_asyncio_log_level()\n update_apscheduler_log_level()\n update_socketio_log_level()\n\n os.environ[ENV_LOG_LEVEL] = logging.getLevelName(log_level)\n\n\ndef update_apscheduler_log_level() -> None:\n log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)\n\n apscheduler_loggers = [\n \"apscheduler\",\n \"apscheduler.scheduler\",\n \"apscheduler.executors\",\n \"apscheduler.executors.default\",\n ]\n\n for logger_name in apscheduler_loggers:\n logging.getLogger(logger_name).setLevel(log_level)\n logging.getLogger(logger_name).propagate = False\n\n\ndef update_socketio_log_level() -> None:\n log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)\n\n socketio_loggers = [\"websockets.protocol\", \"engineio.server\", \"socketio.server\"]\n\n for logger_name in socketio_loggers:\n logging.getLogger(logger_name).setLevel(log_level)\n logging.getLogger(logger_name).propagate = False\n\n\ndef update_tensorflow_log_level() -> None:\n \"\"\"Set the log level of Tensorflow to the log level specified in the environment\n variable 'LOG_LEVEL_LIBRARIES'.\"\"\"\n\n # Disables libvinfer, tensorRT, cuda, AVX2 and FMA warnings (CPU support). This variable needs to be set before the\n # first import since some warnings are raised on the first import.\n os.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"2\"\n\n import tensorflow as tf\n\n log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)\n\n if log_level == \"DEBUG\":\n tf_log_level = tf.compat.v1.logging.DEBUG\n elif log_level == \"INFO\":\n tf_log_level = tf.compat.v1.logging.INFO\n elif log_level == \"WARNING\":\n tf_log_level = tf.compat.v1.logging.WARN\n else:\n tf_log_level = tf.compat.v1.logging.ERROR\n\n tf.compat.v1.logging.set_verbosity(tf_log_level)\n logging.getLogger(\"tensorflow\").propagate = False\n\n\ndef update_sanic_log_level(log_file: Optional[Text] = None):\n \"\"\"Set the log level of sanic loggers to the log level specified in the environment\n variable 'LOG_LEVEL_LIBRARIES'.\"\"\"\n from sanic.log import logger, error_logger, access_logger\n\n log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)\n\n logger.setLevel(log_level)\n error_logger.setLevel(log_level)\n access_logger.setLevel(log_level)\n\n logger.propagate = False\n error_logger.propagate = False\n access_logger.propagate = False\n\n if log_file is not None:\n formatter = logging.Formatter(\"%(asctime)s [%(levelname)-5.5s] %(message)s\")\n file_handler = logging.FileHandler(log_file)\n file_handler.setFormatter(formatter)\n\n logger.addHandler(file_handler)\n error_logger.addHandler(file_handler)\n access_logger.addHandler(file_handler)\n\n\ndef update_asyncio_log_level() -> None:\n \"\"\"Set the log level of asyncio to the log level specified in the environment\n variable 'LOG_LEVEL_LIBRARIES'.\"\"\"\n log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)\n logging.getLogger(\"asyncio\").setLevel(log_level)\n\n\ndef set_log_and_warnings_filters() -> None:\n \"\"\"\n Set log filters on the root logger, and duplicate filters for warnings.\n\n Filters only propagate on handlers, not loggers.\n \"\"\"\n for handler in logging.getLogger().handlers:\n handler.addFilter(RepeatedLogFilter())\n\n warnings.filterwarnings(\"once\", category=UserWarning)\n\n\ndef obtain_verbosity() -> int:\n \"\"\"Returns a verbosity level according to the set log level.\"\"\"\n log_level = os.environ.get(ENV_LOG_LEVEL, DEFAULT_LOG_LEVEL)\n\n verbosity = 0\n if log_level == \"DEBUG\":\n verbosity = 2\n if log_level == \"INFO\":\n verbosity = 1\n\n return verbosity\n\n\ndef sort_list_of_dicts_by_first_key(dicts: List[Dict]) -> List[Dict]:\n \"\"\"Sorts a list of dictionaries by their first key.\"\"\"\n return sorted(dicts, key=lambda d: list(d.keys())[0])\n\n\ndef write_global_config_value(name: Text, value: Any) -> None:\n \"\"\"Read global Rasa configuration.\"\"\"\n\n # need to use `rasa.constants.GLOBAL_USER_CONFIG_PATH` to allow patching\n # in tests\n config_path = rasa.constants.GLOBAL_USER_CONFIG_PATH\n try:\n os.makedirs(os.path.dirname(config_path), exist_ok=True)\n\n c = read_global_config(config_path)\n c[name] = value\n rasa.core.utils.dump_obj_as_yaml_to_file(\n rasa.constants.GLOBAL_USER_CONFIG_PATH, c\n )\n except Exception as e:\n logger.warning(f\"Failed to write global config. Error: {e}. Skipping.\")\n\n\ndef read_global_config_value(name: Text, unavailable_ok: bool = True) -> Any:\n \"\"\"Read a value from the global Rasa configuration.\"\"\"\n\n def not_found():\n if unavailable_ok:\n return None\n else:\n raise ValueError(f\"Configuration '{name}' key not found.\")\n\n # need to use `rasa.constants.GLOBAL_USER_CONFIG_PATH` to allow patching\n # in tests\n config_path = rasa.constants.GLOBAL_USER_CONFIG_PATH\n\n if not os.path.exists(config_path):\n return not_found()\n\n c = read_global_config(config_path)\n\n if name in c:\n return c[name]\n else:\n return not_found()\n\n\ndef update_existing_keys(\n original: Dict[Any, Any], updates: Dict[Any, Any]\n) -> Dict[Any, Any]:\n \"\"\"Iterate through all the updates and update a value in the original dictionary.\n\n If the updates contain a key that is not present in the original dict, it will\n be ignored.\"\"\"\n\n updated = original.copy()\n for k, v in updates.items():\n if k in updated:\n updated[k] = v\n return updated\n\n\nclass RepeatedLogFilter(logging.Filter):\n \"\"\"Filter repeated log records.\"\"\"\n\n last_log = None\n\n def filter(self, record):\n current_log = (\n record.levelno,\n record.pathname,\n record.lineno,\n record.msg,\n record.args,\n )\n if current_log != self.last_log:\n self.last_log = current_log\n return True\n return False\n\n\ndef run_in_loop(\n f: Coroutine[Any, Any, T], loop: Optional[asyncio.AbstractEventLoop] = None\n) -> T:\n \"\"\"Execute the awaitable in the passed loop.\n\n If no loop is passed, the currently existing one is used or a new one is created\n if no loop has been started in the current context.\n\n After the awaitable is finished, all remaining tasks on the loop will be\n awaited as well (background tasks).\n\n WARNING: don't use this if there are never ending background tasks scheduled.\n in this case, this function will never return.\n\n Args:\n f: function to execute\n loop: loop to use for the execution\n\n Returns:\n return value from the function\n \"\"\"\n\n if loop is None:\n try:\n loop = asyncio.get_event_loop()\n except RuntimeError:\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n result = loop.run_until_complete(f)\n\n # Let's also finish all running tasks:\n pending = asyncio.Task.all_tasks()\n loop.run_until_complete(asyncio.gather(*pending))\n\n return result\n" ]
[ [ "tensorflow.compat.v1.logging.set_verbosity" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
brungcm/health-hack-2019
[ "3f537ea40ceefdcf5f3044b6931bfa3951c351f7" ]
[ "ml/train_net.py" ]
[ "# -*- coding: utf-8 -*-\n\nimport tensorflow as tf\n\nimport logging\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\nimport argparse\nfrom aquaman_net import AquamanNet\n\nfrom utils import IMAGE_SIZE\n\nEPOCHS = 1000\nBATCH_SIZE = 4\n\n\ndef preproc(image_bytes):\n image_jpg = tf.image.decode_jpeg(image_bytes, channels=3)\n image_jpg = tf.image.resize_images(image_jpg, IMAGE_SIZE)\n image_jpg = tf.to_float(image_jpg) / 255.0\n image_jpg = tf.reshape(\n image_jpg, [IMAGE_SIZE[0], IMAGE_SIZE[1], 3], name=\"Reshape_Preproc\")\n\n return image_jpg\n\n\ndef input_fn(tf_records_list, epochs=10, batch_size=8, n_frames=16):\n\n def _parse_proto(example_proto):\n parsed_dict = {\n \"target\": tf.FixedLenFeature((), tf.float32, default_value=0)\n }\n\n for i in range(n_frames):\n parsed_dict['frame_{}'.format(i)] = tf.FixedLenFeature(\n (), tf.string, default_value=\"\")\n parsed_features = tf.parse_single_example(example_proto, parsed_dict)\n\n return parsed_features\n\n def _split_xy(feat_dict):\n target = tf.one_hot(tf.to_int32(\n feat_dict['target']), depth=2, dtype=tf.float32)\n\n input_frames = {}\n for i in range(n_frames):\n frame_id = 'frame_{}'.format(i)\n input_frames[frame_id] = feat_dict[frame_id]\n\n return input_frames, {'target': target}\n\n def _input_fn():\n dataset = tf.data.TFRecordDataset(\n tf_records_list, compression_type='GZIP')\n dataset = dataset.map(_parse_proto)\n dataset = dataset.map(_split_xy)\n dataset = dataset.shuffle(buffer_size=2 * batch_size)\n dataset = dataset.repeat(epochs)\n dataset = dataset.batch(batch_size)\n\n return dataset\n return _input_fn\n\n\ndef metrics(logits, labels):\n argmax_logits = tf.argmax(logits, axis=1)\n argmax_labels = tf.argmax(labels, axis=1)\n\n return {'accuracy': tf.metrics.accuracy(argmax_labels, argmax_logits)}\n\n\ndef get_serving_fn(window_size):\n input_tensor = {\"frame_{}\".format(i): tf.placeholder(\n dtype=tf.string, shape=[None]) for i in range(window_size)}\n return tf.estimator.export.build_raw_serving_input_receiver_fn(input_tensor)\n\n\ndef model_fn(n_frames):\n\n def _model_fn(features, labels, mode, params):\n\n input_tensors_list = []\n\n for i in range(n_frames):\n frame_id = 'frame_{}'.format(i)\n frame_tensor = tf.map_fn(preproc, features[frame_id], tf.float32)\n frame_tensor = tf.expand_dims(frame_tensor, axis=-1)\n frame_tensor = tf.transpose(frame_tensor, [0, 1, 2, 4, 3])\n print(frame_tensor)\n input_tensors_list.append(frame_tensor)\n\n input_tensor_stream = tf.concat(input_tensors_list, axis=3)\n print(input_tensor_stream)\n\n is_training = mode == tf.estimator.ModeKeys.TRAIN\n\n logits = AquamanNet(input_tensor_stream, is_training, 2)\n\n # Loss, training and eval operations are not needed during inference.\n total_loss = None\n loss = None\n train_op = None\n eval_metric_ops = {}\n export_outputs = None\n\n prediction_dict = {'class': tf.argmax(\n logits, axis=1, name=\"predictions\")}\n\n if mode != tf.estimator.ModeKeys.PREDICT:\n\n # IT IS VERY IMPORTANT TO RETRIEVE THE REGULARIZATION LOSSES\n reg_loss = tf.losses.get_regularization_loss()\n\n # This summary is automatically caught by the Estimator API\n tf.summary.scalar(\"Regularization_Loss\", tensor=reg_loss)\n\n loss = tf.losses.softmax_cross_entropy(\n onehot_labels=labels['target'], logits=logits)\n\n tf.summary.scalar(\"XEntropy_LOSS\", tensor=loss)\n\n total_loss = loss + reg_loss\n\n learning_rate = tf.constant(1e-4, name='fixed_learning_rate')\n #optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\n vars_to_train = tf.trainable_variables()\n tf.logging.info(\"Variables to train: {}\".format(vars_to_train))\n\n if is_training:\n # You DO must get this collection in order to perform updates on batch_norm variables\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_op = optimizer.minimize(\n loss=total_loss, global_step=tf.train.get_global_step(), var_list=vars_to_train)\n\n eval_metric_ops = metrics(logits, labels['target'])\n\n else:\n # pass\n export_outputs = {\n 'logits': tf.estimator.export.PredictOutput(outputs=logits)}\n\n return tf.estimator.EstimatorSpec(\n mode=mode,\n predictions=prediction_dict,\n loss=total_loss,\n train_op=train_op,\n eval_metric_ops=eval_metric_ops,\n export_outputs=export_outputs)\n\n return _model_fn\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--train-tf-list',\n dest='train_tf_list',\n type=str,\n required=True)\n parser.add_argument('--test-tf-list',\n dest='test_tf_list',\n type=str,\n required=True)\n parser.add_argument('--output-dir',\n dest='output_dir',\n type=str,\n required=True)\n parser.add_argument('--window-size',\n dest='window_size',\n type=int,\n required=True)\n args = parser.parse_args()\n\n tfrecord_list_train = args.train_tf_list.split(',')\n tfrecord_list_test = args.test_tf_list.split(',')\n\n session_config = tf.ConfigProto(\n allow_soft_placement=True,\n log_device_placement=False\n )\n\n run_config = tf.estimator.RunConfig(\n model_dir=args.output_dir,\n save_summary_steps=100,\n session_config=session_config,\n save_checkpoints_steps=100,\n save_checkpoints_secs=None,\n keep_checkpoint_max=1\n )\n\n estimator = tf.estimator.Estimator(\n model_fn=model_fn(args.window_size),\n config=run_config\n )\n\n train_input_fn = input_fn(\n batch_size=BATCH_SIZE, tf_records_list=tfrecord_list_train, epochs=EPOCHS, n_frames=args.window_size)\n test_input_fn = input_fn(\n batch_size=BATCH_SIZE, tf_records_list=tfrecord_list_test, epochs=1, n_frames=args.window_size)\n\n train_spec = tf.estimator.TrainSpec(\n input_fn=train_input_fn, max_steps=10000)\n\n # eval_steps = math.ceil(EVAL_SET_SIZE / FLAGS.batch_size)\n\n eval_spec = tf.estimator.EvalSpec(\n input_fn=test_input_fn,\n # steps=eval_steps,\n start_delay_secs=60,\n throttle_secs=60)\n\n tf.estimator.train_and_evaluate(\n estimator=estimator, train_spec=train_spec, eval_spec=eval_spec)\n\n estimator.export_savedmodel(\n export_dir_base=args.output_dir, serving_input_receiver_fn=get_serving_fn(args.window_size))\n" ]
[ [ "tensorflow.metrics.accuracy", "tensorflow.concat", "tensorflow.FixedLenFeature", "tensorflow.control_dependencies", "tensorflow.estimator.export.build_raw_serving_input_receiver_fn", "tensorflow.map_fn", "tensorflow.train.AdamOptimizer", "tensorflow.estimator.RunConfig", "tensorflow.to_int32", "tensorflow.summary.scalar", "tensorflow.estimator.train_and_evaluate", "tensorflow.get_collection", "tensorflow.data.TFRecordDataset", "tensorflow.estimator.export.PredictOutput", "tensorflow.train.get_global_step", "tensorflow.ConfigProto", "tensorflow.losses.softmax_cross_entropy", "tensorflow.to_float", "tensorflow.estimator.EvalSpec", "tensorflow.trainable_variables", "tensorflow.parse_single_example", "tensorflow.argmax", "tensorflow.image.decode_jpeg", "tensorflow.image.resize_images", "tensorflow.placeholder", "tensorflow.estimator.TrainSpec", "tensorflow.transpose", "tensorflow.constant", "tensorflow.losses.get_regularization_loss", "tensorflow.reshape", "tensorflow.expand_dims", "tensorflow.estimator.EstimatorSpec" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mukul54/Flipkart-Grid-Challenge
[ "ae193490304c60cfc074e2f31f4db1a0b8e0e0f4" ]
[ "codes/write_csv.py" ]
[ "import numpy as np\nimport pandas as pd\nX = np.load('preds.npy')\nimg = pd.read_csv('test.csv')\nimg['x1'] = X[:,0]*640\nimg['x2'] = X[:,1]*640\nimg['y1'] = X[:,2]*480\nimg['y2'] = X[:,3]*480\n\"\"\" img['x1'] = 0.05*640\nimg['x2'] = 0.95*640\nimg['y1'] = 0.05*480\nimg['y2'] = 0.95*480 \"\"\"\nimg.to_csv('subbigles.csv',index = False)" ]
[ [ "numpy.load", "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
jzuhone/glue-vispy-viewers
[ "6993accf0cb85e23013bf7ae6b04145724a6dbd2", "6993accf0cb85e23013bf7ae6b04145724a6dbd2", "6993accf0cb85e23013bf7ae6b04145724a6dbd2" ]
[ "glue_vispy_viewers/extern/vispy/gloo/buffer.py", "glue_vispy_viewers/extern/vispy/geometry/triangulation.py", "glue_vispy_viewers/extern/vispy/scene/widgets/console.py" ]
[ "# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# Copyright (c) 2015, Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n# -----------------------------------------------------------------------------\n\nimport numpy as np\nfrom os import path as op\nfrom traceback import extract_stack, format_list\nimport weakref\n\nfrom . globject import GLObject\nfrom ..util import logger\nfrom ..ext.six import string_types\n\n\n# ------------------------------------------------------------ Buffer class ---\nclass Buffer(GLObject):\n \"\"\" Generic GPU buffer.\n\n A generic buffer is an interface used to upload data to a GPU array buffer\n (ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER). It keeps track of\n buffer size but does not have any CPU storage. You can consider it as\n write-only.\n\n The `set_data` is a deferred operation: you can call it even if an OpenGL\n context is not available. The `update` function is responsible to upload\n pending data to GPU memory and requires an active GL context.\n\n The Buffer class only deals with data in terms of bytes; it is not\n aware of data type or element size.\n\n Parameters\n ----------\n data : ndarray | None\n Buffer data.\n nbytes : int | None\n Buffer byte size.\n \"\"\"\n \n def __init__(self, data=None, nbytes=None):\n GLObject.__init__(self)\n self._views = [] # Views on this buffer (stored using weakrefs)\n self._valid = True # To invalidate buffer views\n self._nbytes = 0 # Bytesize in bytes, set in resize_bytes()\n \n # Set data\n if data is not None:\n if nbytes is not None:\n raise ValueError(\"Cannot specify both data and nbytes.\")\n self.set_data(data, copy=False)\n elif nbytes is not None:\n self.resize_bytes(nbytes)\n \n @property\n def nbytes(self):\n \"\"\" Buffer size in bytes \"\"\"\n\n return self._nbytes\n\n def set_subdata(self, data, offset=0, copy=False):\n \"\"\" Set a sub-region of the buffer (deferred operation).\n\n Parameters\n ----------\n\n data : ndarray\n Data to be uploaded\n offset: int\n Offset in buffer where to start copying data (in bytes)\n copy: bool\n Since the operation is deferred, data may change before\n data is actually uploaded to GPU memory.\n Asking explicitly for a copy will prevent this behavior.\n \"\"\"\n data = np.array(data, copy=copy)\n nbytes = data.nbytes\n\n if offset < 0:\n raise ValueError(\"Offset must be positive\")\n elif (offset + nbytes) > self._nbytes:\n raise ValueError(\"Data does not fit into buffer\")\n\n # If the whole buffer is to be written, we clear any pending data\n # (because they will be overwritten anyway)\n if nbytes == self._nbytes and offset == 0:\n self._glir.command('SIZE', self._id, nbytes)\n self._glir.command('DATA', self._id, offset, data)\n\n def set_data(self, data, copy=False):\n \"\"\" Set data in the buffer (deferred operation).\n\n This completely resets the size and contents of the buffer.\n\n Parameters\n ----------\n data : ndarray\n Data to be uploaded\n copy: bool\n Since the operation is deferred, data may change before\n data is actually uploaded to GPU memory.\n Asking explicitly for a copy will prevent this behavior.\n \"\"\"\n data = np.array(data, copy=copy)\n nbytes = data.nbytes\n\n if nbytes != self._nbytes:\n self.resize_bytes(nbytes)\n else:\n # Use SIZE to discard any previous data setting\n self._glir.command('SIZE', self._id, nbytes)\n \n if nbytes: # Only set data if there *is* data\n self._glir.command('DATA', self._id, 0, data)\n \n def resize_bytes(self, size):\n \"\"\" Resize this buffer (deferred operation). \n \n Parameters\n ----------\n size : int\n New buffer size in bytes.\n \"\"\"\n self._nbytes = size\n self._glir.command('SIZE', self._id, size)\n # Invalidate any view on this buffer\n for view in self._views:\n if view() is not None:\n view()._valid = False\n self._views = []\n\n\n# -------------------------------------------------------- DataBuffer class ---\nclass DataBuffer(Buffer):\n \"\"\" GPU data buffer that is aware of data type and elements size\n\n Parameters\n ----------\n data : ndarray | None\n Buffer data.\n \"\"\"\n\n def __init__(self, data=None):\n self._size = 0 # number of elements in buffer, set in resize_bytes()\n self._dtype = None\n self._stride = 0\n self._itemsize = 0\n self._last_dim = None\n Buffer.__init__(self, data)\n\n def _prepare_data(self, data):\n # Can be overrriden by subclasses\n if not isinstance(data, np.ndarray):\n raise TypeError(\"DataBuffer data must be numpy array.\")\n return data\n\n def set_subdata(self, data, offset=0, copy=False, **kwargs):\n \"\"\" Set a sub-region of the buffer (deferred operation).\n\n Parameters\n ----------\n\n data : ndarray\n Data to be uploaded\n offset: int\n Offset in buffer where to start copying data (in bytes)\n copy: bool\n Since the operation is deferred, data may change before\n data is actually uploaded to GPU memory.\n Asking explicitly for a copy will prevent this behavior.\n **kwargs : dict\n Additional keyword arguments.\n \"\"\"\n data = self._prepare_data(data, **kwargs)\n offset = offset * self.itemsize\n Buffer.set_subdata(self, data=data, offset=offset, copy=copy)\n\n def set_data(self, data, copy=False, **kwargs):\n \"\"\" Set data (deferred operation)\n\n Parameters\n ----------\n data : ndarray\n Data to be uploaded\n copy: bool\n Since the operation is deferred, data may change before\n data is actually uploaded to GPU memory.\n Asking explicitly for a copy will prevent this behavior.\n **kwargs : dict\n Additional arguments.\n \"\"\"\n data = self._prepare_data(data, **kwargs)\n self._dtype = data.dtype\n self._stride = data.strides[-1]\n self._itemsize = self._dtype.itemsize\n Buffer.set_data(self, data=data, copy=copy)\n\n @property\n def dtype(self):\n \"\"\" Buffer dtype \"\"\"\n\n return self._dtype\n\n @property\n def offset(self):\n \"\"\" Buffer offset (in bytes) relative to base \"\"\"\n\n return 0\n\n @property\n def stride(self):\n \"\"\" Stride of data in memory \"\"\"\n\n return self._stride\n\n @property\n def size(self):\n \"\"\" Number of elements in the buffer \"\"\"\n return self._size\n\n @property\n def itemsize(self):\n \"\"\" The total number of bytes required to store the array data \"\"\"\n\n return self._itemsize\n\n @property\n def glsl_type(self):\n \"\"\" GLSL declaration strings required for a variable to hold this data.\n \"\"\"\n if self.dtype is None:\n return None\n dtshape = self.dtype[0].shape\n n = dtshape[0] if dtshape else 1\n if n > 1:\n dtype = 'vec%d' % n\n else:\n dtype = 'float' if 'f' in self.dtype[0].base.kind else 'int'\n return 'attribute', dtype\n\n def resize_bytes(self, size):\n \"\"\" Resize the buffer (in-place, deferred operation)\n\n Parameters\n ----------\n size : integer\n New buffer size in bytes\n\n Notes\n -----\n This clears any pending operations.\n \"\"\"\n Buffer.resize_bytes(self, size)\n self._size = size // self.itemsize\n\n def __getitem__(self, key):\n \"\"\" Create a view on this buffer. \"\"\"\n\n view = DataBufferView(self, key)\n self._views.append(weakref.ref(view))\n return view\n\n def __setitem__(self, key, data):\n \"\"\" Set data (deferred operation) \"\"\"\n\n # Setting a whole field of the buffer: only allowed if we have CPU\n # storage. Note this case (key is string) only happen with base buffer\n if isinstance(key, string_types):\n raise ValueError(\"Cannot set non-contiguous data on buffer\")\n \n # Setting one or several elements\n elif isinstance(key, int):\n if key < 0:\n key += self.size\n if key < 0 or key > self.size:\n raise IndexError(\"Buffer assignment index out of range\")\n start, stop, step = key, key + 1, 1\n elif isinstance(key, slice):\n start, stop, step = key.indices(self.size)\n if stop < start:\n start, stop = stop, start\n elif key == Ellipsis:\n start, stop, step = 0, self.size, 1\n else:\n raise TypeError(\"Buffer indices must be integers or strings\")\n\n # Contiguous update?\n if step != 1:\n raise ValueError(\"Cannot set non-contiguous data on buffer\")\n\n # Make sure data is an array\n if not isinstance(data, np.ndarray):\n data = np.array(data, dtype=self.dtype, copy=False)\n\n # Make sure data is big enough\n if data.size < stop - start:\n data = np.resize(data, stop - start)\n elif data.size > stop - start:\n raise ValueError('Data too big to fit GPU data.')\n \n # Set data\n offset = start # * self.itemsize\n self.set_subdata(data=data, offset=offset, copy=True)\n\n def __repr__(self):\n return (\"<%s size=%s last_dim=%s>\" % \n (self.__class__.__name__, self.size, self._last_dim))\n\n\nclass DataBufferView(DataBuffer):\n \"\"\" View on a sub-region of a DataBuffer.\n\n Parameters\n ----------\n base : DataBuffer\n The buffer accessed by this view.\n key : str, int, slice, or Ellpsis\n The index into the base buffer that defines a sub-region of the buffer\n to view. String arguments select a single field from multi-field \n dtypes, and other allowed types select a subset of rows. \n \n Notes\n -----\n \n It is generally not necessary to instantiate this class manually; use \n ``base_buffer[key]`` instead.\n \"\"\"\n \n # Note that this class is a bit evil: it is a subclass of GLObject,\n # Buffer and DataBuffer, but any of these __init__'s are not called ...\n \n def __init__(self, base, key):\n # Note how this never runs the super's __init__,\n # all attributes must thus be set here ...\n \n self._base = base\n self._key = key\n self._stride = base.stride\n\n if isinstance(key, string_types):\n self._dtype = base.dtype[key]\n self._offset = base.dtype.fields[key][1]\n self._nbytes = base.size * self._dtype.itemsize\n self._size = base.size\n self._itemsize = self._dtype.itemsize\n return\n \n if isinstance(key, int):\n if key < 0:\n key += base.size\n if key < 0 or key > base.size:\n raise IndexError(\"Buffer assignment index out of range\")\n start, stop, step = key, key + 1, 1\n elif isinstance(key, slice):\n start, stop, step = key.indices(base.size)\n if stop < start:\n start, stop = stop, start\n elif key == Ellipsis:\n start, stop, step = 0, base.size, 1\n else:\n raise TypeError(\"Buffer indices must be integers or strings\")\n\n if step != 1:\n raise ValueError(\"Cannot access non-contiguous data\")\n\n self._itemsize = base.itemsize\n self._offset = start * self.itemsize\n self._size = stop - start\n self._dtype = base.dtype\n self._nbytes = self.size * self.itemsize\n \n @property\n def glir(self):\n return self._base.glir\n \n @property\n def id(self):\n return self._base.id\n\n @property\n def _last_dim(self):\n return self._base._last_dim\n \n def set_subdata(self, data, offset=0, copy=False, **kwargs):\n raise RuntimeError(\"Cannot set data on buffer view.\")\n \n def set_data(self, data, copy=False, **kwargs):\n raise RuntimeError(\"Cannot set data on buffer view.\")\n \n @property\n def offset(self):\n \"\"\" Buffer offset (in bytes) relative to base \"\"\"\n\n return self._offset\n\n @property\n def base(self):\n \"\"\"Buffer base if this buffer is a view on another buffer. \"\"\"\n return self._base\n \n def resize_bytes(self, size):\n raise RuntimeError(\"Cannot resize buffer view.\")\n\n def __getitem__(self, key):\n raise RuntimeError(\"Can only access data from a base buffer\")\n\n def __setitem__(self, key, data):\n raise RuntimeError(\"Cannot set data on Buffer view\")\n\n def __repr__(self):\n return (\"<DataBufferView on %r at offset=%d size=%d>\" % \n (self.base, self.offset, self.size))\n\n \n# ------------------------------------------------------ VertexBuffer class ---\nclass VertexBuffer(DataBuffer):\n \"\"\" Buffer for vertex attribute data\n\n Parameters\n ----------\n data : ndarray\n Buffer data (optional)\n \"\"\"\n\n _GLIR_TYPE = 'VertexBuffer'\n\n def _prepare_data(self, data, convert=False):\n # Build a structured view of the data if:\n # -> it is not already a structured array\n # -> shape if 1-D or last dimension is 1,2,3 or 4\n if isinstance(data, list):\n data = np.array(data, dtype=np.float32)\n if not isinstance(data, np.ndarray):\n raise ValueError('Data must be a ndarray (got %s)' % type(data))\n if data.dtype.isbuiltin:\n if convert is True:\n data = data.astype(np.float32)\n if data.dtype in (np.float64, np.int64):\n raise TypeError('data must be 32-bit not %s'\n % data.dtype)\n c = data.shape[-1] if data.ndim > 1 else 1\n if c in [2, 3, 4]:\n if not data.flags['C_CONTIGUOUS']:\n logger.warning('Copying discontiguous data for struct '\n 'dtype:\\n%s' % _last_stack_str())\n data = data.copy()\n else:\n c = 1\n if self._last_dim and c != self._last_dim:\n raise ValueError('Last dimension should be %s not %s'\n % (self._last_dim, c))\n data = data.view(dtype=[('f0', data.dtype.base, c)])\n self._last_dim = c\n return data\n\n\ndef _last_stack_str():\n \"\"\"Print stack trace from call that didn't originate from here\"\"\"\n stack = extract_stack()\n for s in stack[::-1]:\n if op.join('vispy', 'gloo', 'buffer.py') not in __file__:\n break\n return format_list([s])[0]\n\n\n# ------------------------------------------------------- IndexBuffer class ---\nclass IndexBuffer(DataBuffer):\n \"\"\" Buffer for index data\n\n Parameters\n ----------\n\n data : ndarray | None\n Buffer data.\n \"\"\"\n \n _GLIR_TYPE = 'IndexBuffer'\n\n def __init__(self, data=None):\n DataBuffer.__init__(self, data)\n self._last_dim = 1\n\n def _prepare_data(self, data, convert=False):\n if isinstance(data, list):\n data = np.array(data, dtype=np.uint32)\n if not isinstance(data, np.ndarray):\n raise ValueError('Data must be a ndarray (got %s)' % type(data))\n if not data.dtype.isbuiltin:\n raise TypeError(\"Element buffer dtype cannot be structured\")\n else:\n if convert:\n if data.dtype is not np.uint32:\n data = data.astype(np.uint32)\n else:\n if data.dtype not in [np.uint32, np.uint16, np.uint8]:\n raise TypeError(\"Invalid dtype for IndexBuffer: %r\" %\n data.dtype)\n return data\n", "# -*- coding: utf8 -*-\n\nfrom __future__ import division, print_function\nimport sys\n\nfrom itertools import permutations\nimport numpy as np\n\nfrom ..ext.ordereddict import OrderedDict\n\ntry:\n # Try to use the C++ triangle library, faster than the\n # pure Python version.\n # The latest stable release only works with Python 2. The GitHub version\n # works on Python 3 though, but the release has yet to be done.\n import triangle\n assert sys.version_info.major == 2\n _TRIANGLE_AVAILABLE = True\nexcept (ImportError, AssertionError):\n _TRIANGLE_AVAILABLE = False\n\n\nclass Triangulation(object):\n \"\"\"Constrained delaunay triangulation\n\n Implementation based on [1]_.\n\n Parameters\n ----------\n pts : array\n Nx2 array of points.\n edges : array\n Nx2 array of edges (dtype=int).\n\n Notes\n -----\n * Delaunay legalization is not yet implemented. This produces a proper\n triangulation, but adding legalisation would produce fewer thin\n triangles.\n * The pts and edges arrays may be modified.\n\n References\n ----------\n .. [1] Domiter, V. and Žalik, B. Sweep‐line algorithm for constrained\n Delaunay triangulation\n\n\n \"\"\"\n def __init__(self, pts, edges):\n self.pts = pts[:, :2].astype(np.float32)\n self.edges = edges\n if self.pts.ndim != 2 or self.pts.shape[1] != 2:\n raise TypeError('pts argument must be ndarray of shape (N, 2).')\n if self.edges.ndim != 2 or self.edges.shape[1] != 2:\n raise TypeError('edges argument must be ndarray of shape (N, 2).')\n \n # described in initialize()\n self._front = None\n self.tris = OrderedDict()\n self._edges_lookup = {}\n \n def _normalize(self):\n # Clean up data (not discussed in original publication)\n \n # (i) Split intersecting edges. Every edge that intersects another \n # edge or point is split. This extends self.pts and self.edges.\n self._split_intersecting_edges()\n \n # (ii) Merge identical points. If any two points are found to be equal,\n # the second is removed and the edge table is updated accordingly. \n self._merge_duplicate_points()\n\n # (iii) Remove duplicate edges\n # TODO\n\n def _initialize(self):\n self._normalize()\n ## Initialization (sec. 3.3)\n\n # sort points by y, then x\n flat_shape = self.pts.shape[0] * self.pts.shape[1]\n pts = self.pts.reshape(flat_shape).view([('x', np.float32), \n ('y', np.float32)])\n order = np.argsort(pts, order=('y', 'x'))\n pts = pts[order]\n # update edges to match new point order\n invorder = np.argsort(order)\n self.edges = invorder[self.edges]\n self.pts = pts.view(np.float32).reshape(len(pts), 2)\n\n # make artificial points P-1 and P-2\n xmax = self.pts[:, 0].max()\n xmin = self.pts[:, 0].min()\n ymax = self.pts[:, 1].max()\n ymin = self.pts[:, 1].min()\n xa = (xmax-xmin) * 0.3\n ya = (ymax-ymin) * 0.3\n p1 = (xmin - xa, ymin - ya)\n p2 = (xmax + xa, ymin - ya)\n\n # prepend artificial points to point list\n newpts = np.empty((self.pts.shape[0]+2, 2), dtype=float)\n newpts[0] = p1\n newpts[1] = p2\n newpts[2:] = self.pts\n self.pts = newpts\n self.edges += 2\n\n # find topmost point in each edge\n self._tops = self.edges.max(axis=1)\n self._bottoms = self.edges.min(axis=1)\n\n # inintialize sweep front\n # values in this list are indexes into self.pts\n self._front = [0, 2, 1]\n \n # empty triangle list. \n # This will contain [(a, b, c), ...] where a,b,c are indexes into \n # self.pts\n self.tris = OrderedDict()\n\n # For each triangle, maps (a, b): c\n # This is used to look up the thrid point in a triangle, given any \n # edge. Since each edge has two triangles, they are independently \n # stored as (a, b): c and (b, a): d\n self._edges_lookup = {}\n\n def triangulate(self):\n \"\"\"Do the triangulation\n \"\"\"\n self._initialize()\n \n pts = self.pts\n front = self._front\n \n ## Begin sweep (sec. 3.4)\n for i in range(3, pts.shape[0]):\n pi = pts[i]\n #debug(\"========== New point %d: %s ==========\" % (i, pi))\n \n # First, triangulate from front to new point\n # This applies to both \"point events\" (3.4.1) \n # and \"edge events\" (3.4.2).\n\n # get index along front that intersects pts[i]\n l = 0\n while pts[front[l+1], 0] <= pi[0]:\n l += 1\n pl = pts[front[l]]\n \n # \"(i) middle case\"\n if pi[0] > pl[0]: \n #debug(\" mid case\")\n # Add a single triangle connecting pi,pl,pr\n self._add_tri(front[l], front[l+1], i)\n front.insert(l+1, i)\n # \"(ii) left case\"\n else:\n #debug(\" left case\")\n # Add triangles connecting pi,pl,ps and pi,pl,pr\n self._add_tri(front[l], front[l+1], i)\n self._add_tri(front[l-1], front[l], i)\n front[l] = i\n \n #debug(front)\n \n # Continue adding triangles to smooth out front\n # (heuristics shown in figs. 9, 10)\n #debug(\"Smoothing front...\")\n for direction in -1, 1:\n while True:\n # Find point connected to pi\n ind0 = front.index(i)\n ind1 = ind0 + direction\n ind2 = ind1 + direction\n if ind2 < 0 or ind2 >= len(front):\n break\n \n # measure angle made with front\n p1 = pts[front[ind1]]\n p2 = pts[front[ind2]]\n err = np.geterr()\n np.seterr(invalid='ignore')\n try:\n angle = np.arccos(self._cosine(pi, p1, p2))\n finally:\n np.seterr(**err)\n \n # if angle is < pi/2, make new triangle\n #debug(\"Smooth angle:\", pi, p1, p2, angle)\n if angle > np.pi/2. or np.isnan(angle):\n break\n \n assert (i != front[ind1] and \n front[ind1] != front[ind2] and \n front[ind2] != i)\n self._add_tri(i, front[ind1], front[ind2],\n source='smooth1')\n front.pop(ind1)\n #debug(\"Finished smoothing front.\")\n \n # \"edge event\" (sec. 3.4.2)\n # remove any triangles cut by completed edges and re-fill \n # the holes.\n if i in self._tops:\n for j in self._bottoms[self._tops == i]:\n # Make sure edge (j, i) is present in mesh\n # because edge event may have created a new front list\n self._edge_event(i, j) \n front = self._front \n \n self._finalize()\n \n self.tris = np.array(list(self.tris.keys()), dtype=int)\n \n #debug(\"Finished with %d tris:\" % self.tris.shape[0])\n #debug(str(self.tris))\n \n def _finalize(self):\n ## Finalize (sec. 3.5)\n\n # (i) Add bordering triangles to fill hull\n #debug(\"== Fill hull\")\n front = list(OrderedDict.fromkeys(self._front))\n\n l = len(front) - 2\n k = 1\n while k < l-1:\n # if edges lie in counterclockwise direction, then signed area \n # is positive\n if self._iscounterclockwise(front[k], front[k+1], front[k+2]):\n self._add_tri(front[k], front[k+1], front[k+2], legal=False, \n source='fill_hull')\n front.pop(k+1)\n l -= 1\n continue\n k += 1\n\n # (ii) Remove all triangles not inside the hull \n # (not described in article)\n #debug(\"== Remove triangles outside hull\")\n\n tris = [] # triangles to check\n tri_state = {} # 0 for outside, 1 for inside\n \n # find a starting triangle\n for t in self.tris:\n if 0 in t or 1 in t:\n tri_state[t] = 0\n tris.append(t)\n break\n \n while tris:\n #debug(\"iterate:\", tris)\n next_tris = []\n for t in tris:\n v = tri_state[t]\n for i in (0, 1, 2):\n edge = (t[i], t[(i + 1) % 3])\n pt = t[(i + 2) % 3]\n t2 = self._adjacent_tri(edge, pt)\n if t2 is None:\n continue\n t2a = t2[1:3] + t2[0:1]\n t2b = t2[2:3] + t2[0:2]\n if t2 in tri_state or t2a in tri_state or t2b in tri_state:\n continue\n if self._is_constraining_edge(edge):\n tri_state[t2] = 1 - v\n else:\n tri_state[t2] = v\n next_tris.append(t2)\n tris = next_tris\n \n for t, v in tri_state.items():\n if v == 0:\n self._remove_tri(*t)\n\n def _edge_event(self, i, j):\n \"\"\"\n Force edge (i, j) to be present in mesh. \n This works by removing intersected triangles and filling holes up to\n the cutting edge.\n \"\"\"\n front_index = self._front.index(i)\n \n #debug(\" == edge event ==\")\n front = self._front\n\n # First just see whether this edge is already present\n # (this is not in the published algorithm)\n if (i, j) in self._edges_lookup or (j, i) in self._edges_lookup:\n #debug(\" already added.\")\n return\n #debug(\" Edge (%d,%d) not added yet. Do edge event. (%s - %s)\" % \n # (i, j, pts[i], pts[j]))\n \n # traverse in two different modes:\n # 1. If cutting edge is below front, traverse through triangles. These\n # must be removed and the resulting hole re-filled. (fig. 12)\n # 2. If cutting edge is above the front, then follow the front until \n # crossing under again. (fig. 13)\n # We must be able to switch back and forth between these \n # modes (fig. 14)\n\n # Collect points that draw the open polygons on either side of the \n # cutting edge. Note that our use of 'upper' and 'lower' is not strict;\n # in some cases the two may be swapped.\n upper_polygon = [i]\n lower_polygon = [i]\n \n # Keep track of which section of the front must be replaced\n # and with what it should be replaced\n front_holes = [] # contains indexes for sections of front to remove\n \n next_tri = None # next triangle to cut (already set if in mode 1)\n last_edge = None # or last triangle edge crossed (if in mode 1)\n \n # Which direction to traverse front\n front_dir = 1 if self.pts[j][0] > self.pts[i][0] else -1\n \n # Initialize search state\n if self._edge_below_front((i, j), front_index):\n mode = 1 # follow triangles\n tri = self._find_cut_triangle((i, j))\n last_edge = self._edge_opposite_point(tri, i)\n next_tri = self._adjacent_tri(last_edge, i)\n assert next_tri is not None\n self._remove_tri(*tri)\n # todo: does this work? can we count on last_edge to be clockwise\n # around point i?\n lower_polygon.append(last_edge[1])\n upper_polygon.append(last_edge[0])\n else:\n mode = 2 # follow front\n\n # Loop until we reach point j\n while True:\n #debug(\" == edge_event loop: mode %d ==\" % mode)\n #debug(\" front_holes:\", front_holes, front)\n #debug(\" front_index:\", front_index)\n #debug(\" next_tri:\", next_tri)\n #debug(\" last_edge:\", last_edge)\n #debug(\" upper_polygon:\", upper_polygon)\n #debug(\" lower_polygon:\", lower_polygon)\n #debug(\" =====\")\n if mode == 1:\n # crossing from one triangle into another\n if j in next_tri:\n #debug(\" -> hit endpoint!\")\n # reached endpoint! \n # update front / polygons\n upper_polygon.append(j)\n lower_polygon.append(j)\n #debug(\" Appended to upper_polygon:\", upper_polygon)\n #debug(\" Appended to lower_polygon:\", lower_polygon)\n self._remove_tri(*next_tri)\n break\n else:\n # next triangle does not contain the end point; we will\n # cut one of the two far edges.\n tri_edges = self._edges_in_tri_except(next_tri, last_edge)\n \n # select the edge that is cut\n last_edge = self._intersected_edge(tri_edges, (i, j))\n #debug(\" set last_edge to intersected edge:\", last_edge)\n last_tri = next_tri\n next_tri = self._adjacent_tri(last_edge, last_tri)\n #debug(\" set next_tri:\", next_tri)\n self._remove_tri(*last_tri)\n\n # Crossing an edge adds one point to one of the polygons\n if lower_polygon[-1] == last_edge[0]:\n upper_polygon.append(last_edge[1])\n #debug(\" Appended to upper_polygon:\", upper_polygon)\n elif lower_polygon[-1] == last_edge[1]:\n upper_polygon.append(last_edge[0])\n #debug(\" Appended to upper_polygon:\", upper_polygon)\n elif upper_polygon[-1] == last_edge[0]:\n lower_polygon.append(last_edge[1])\n #debug(\" Appended to lower_polygon:\", lower_polygon)\n elif upper_polygon[-1] == last_edge[1]:\n lower_polygon.append(last_edge[0])\n #debug(\" Appended to lower_polygon:\", lower_polygon)\n else:\n raise RuntimeError(\"Something went wrong..\")\n \n # If we crossed the front, go to mode 2\n x = self._edge_in_front(last_edge)\n if x >= 0: # crossing over front\n #debug(\" -> crossed over front, prepare for mode 2\")\n mode = 2\n next_tri = None\n #debug(\" set next_tri: None\")\n \n # where did we cross the front?\n # nearest to new point\n front_index = x + (1 if front_dir == -1 else 0)\n #debug(\" set front_index:\", front_index)\n \n # Select the correct polygon to be lower_polygon\n # (because mode 2 requires this). \n # We know that last_edge is in the front, and \n # front[front_index] is the point _above_ the front. \n # So if this point is currently the last element in\n # lower_polygon, then the polys must be swapped.\n if lower_polygon[-1] == front[front_index]:\n tmp = lower_polygon, upper_polygon\n upper_polygon, lower_polygon = tmp\n #debug(' Swap upper/lower polygons')\n else:\n assert upper_polygon[-1] == front[front_index]\n \n else:\n assert next_tri is not None\n \n else: # mode == 2\n # At each iteration, we require:\n # * front_index is the starting index of the edge _preceding_\n # the edge that will be handled in this iteration\n # * lower_polygon is the polygon to which points should be\n # added while traversing the front\n \n front_index += front_dir\n #debug(\" Increment front_index: %d\" % front_index)\n next_edge = (front[front_index], front[front_index+front_dir])\n #debug(\" Set next_edge: %s\" % repr(next_edge))\n \n assert front_index >= 0\n if front[front_index] == j:\n # found endpoint!\n #debug(\" -> hit endpoint!\")\n lower_polygon.append(j)\n upper_polygon.append(j)\n #debug(\" Appended to upper_polygon:\", upper_polygon)\n #debug(\" Appended to lower_polygon:\", lower_polygon)\n break\n\n # Add point to lower_polygon. \n # The conditional is because there are cases where the \n # point was already added if we just crossed from mode 1.\n if lower_polygon[-1] != front[front_index]:\n lower_polygon.append(front[front_index])\n #debug(\" Appended to lower_polygon:\", lower_polygon)\n\n front_holes.append(front_index)\n #debug(\" Append to front_holes:\", front_holes)\n\n if self._edges_intersect((i, j), next_edge):\n # crossing over front into triangle\n #debug(\" -> crossed over front, prepare for mode 1\")\n mode = 1\n \n last_edge = next_edge\n #debug(\" Set last_edge:\", last_edge)\n \n # we are crossing the front, so this edge only has one\n # triangle. \n next_tri = self._tri_from_edge(last_edge)\n #debug(\" Set next_tri:\", next_tri)\n \n upper_polygon.append(front[front_index+front_dir])\n #debug(\" Appended to upper_polygon:\", upper_polygon)\n #else:\n #debug(\" -> did not cross front..\")\n \n #debug(\"Finished edge_event:\")\n #debug(\" front_holes:\", front_holes)\n #debug(\" upper_polygon:\", upper_polygon)\n #debug(\" lower_polygon:\", lower_polygon)\n\n # (iii) triangluate empty areas\n \n #debug(\"Filling edge_event polygons...\")\n for polygon in [lower_polygon, upper_polygon]:\n dist = self._distances_from_line((i, j), polygon)\n #debug(\"Distances:\", dist)\n while len(polygon) > 2:\n ind = np.argmax(dist)\n #debug(\"Next index: %d\" % ind)\n self._add_tri(polygon[ind], polygon[ind-1],\n polygon[ind+1], legal=False, \n source='edge_event')\n polygon.pop(ind)\n dist.pop(ind)\n\n #debug(\"Finished filling edge_event polygons.\")\n \n # update front by removing points in the holes (places where front \n # passes below the cut edge)\n front_holes.sort(reverse=True)\n for i in front_holes:\n front.pop(i)\n\n #debug(\"Finished updating front after edge_event.\")\n \n def _find_cut_triangle(self, edge):\n \"\"\"\n Return the triangle that has edge[0] as one of its vertices and is \n bisected by edge.\n \n Return None if no triangle is found.\n \"\"\"\n edges = [] # opposite edge for each triangle attached to edge[0]\n for tri in self.tris:\n if edge[0] in tri:\n edges.append(self._edge_opposite_point(tri, edge[0]))\n \n for oedge in edges:\n o1 = self._orientation(edge, oedge[0])\n o2 = self._orientation(edge, oedge[1]) \n #debug(edge, oedge, o1, o2)\n #debug(self.pts[np.array(edge)])\n #debug(self.pts[np.array(oedge)])\n if o1 != o2:\n return (edge[0], oedge[0], oedge[1])\n \n return None\n\n def _edge_in_front(self, edge):\n \"\"\" Return the index where *edge* appears in the current front.\n If the edge is not in the front, return -1\n \"\"\"\n e = (list(edge), list(edge)[::-1])\n for i in range(len(self._front)-1):\n if self._front[i:i+2] in e:\n return i\n return -1\n\n def _edge_opposite_point(self, tri, i):\n \"\"\" Given a triangle, return the edge that is opposite point i.\n Vertexes are returned in the same orientation as in tri.\n \"\"\"\n ind = tri.index(i)\n return (tri[(ind+1) % 3], tri[(ind+2) % 3])\n\n def _adjacent_tri(self, edge, i):\n \"\"\"\n Given a triangle formed by edge and i, return the triangle that shares\n edge. *i* may be either a point or the entire triangle.\n \"\"\"\n if not np.isscalar(i):\n i = [x for x in i if x not in edge][0]\n\n try:\n pt1 = self._edges_lookup[edge]\n pt2 = self._edges_lookup[(edge[1], edge[0])]\n except KeyError:\n return None\n \n if pt1 == i:\n return (edge[1], edge[0], pt2)\n elif pt2 == i:\n return (edge[1], edge[0], pt1)\n else:\n raise RuntimeError(\"Edge %s and point %d do not form a triangle \"\n \"in this mesh.\" % (edge, i))\n\n def _tri_from_edge(self, edge):\n \"\"\"Return the only tri that contains *edge*. If two tris share this\n edge, raise an exception.\n \"\"\"\n edge = tuple(edge)\n p1 = self._edges_lookup.get(edge, None)\n p2 = self._edges_lookup.get(edge[::-1], None)\n if p1 is None:\n if p2 is None:\n raise RuntimeError(\"No tris connected to edge %r\" % (edge,))\n return edge + (p2,)\n elif p2 is None:\n return edge + (p1,)\n else:\n raise RuntimeError(\"Two triangles connected to edge %r\" % (edge,))\n\n def _edges_in_tri_except(self, tri, edge):\n \"\"\"Return the edges in *tri*, excluding *edge*.\n \"\"\"\n edges = [(tri[i], tri[(i+1) % 3]) for i in range(3)]\n try:\n edges.remove(tuple(edge))\n except ValueError:\n edges.remove(tuple(edge[::-1]))\n return edges\n\n def _edge_below_front(self, edge, front_index):\n \"\"\"Return True if *edge* is below the current front. \n \n One of the points in *edge* must be _on_ the front, at *front_index*.\n \"\"\"\n f0 = self._front[front_index-1]\n f1 = self._front[front_index+1]\n return (self._orientation(edge, f0) > 0 and \n self._orientation(edge, f1) < 0)\n\n def _is_constraining_edge(self, edge):\n mask1 = self.edges == edge[0]\n mask2 = self.edges == edge[1]\n return (np.any(mask1[:, 0] & mask2[:, 1]) or \n np.any(mask2[:, 0] & mask1[:, 1]))\n \n def _intersected_edge(self, edges, cut_edge):\n \"\"\" Given a list of *edges*, return the first that is intersected by\n *cut_edge*.\n \"\"\"\n for edge in edges:\n if self._edges_intersect(edge, cut_edge):\n return edge\n\n def _find_edge_intersections(self):\n \"\"\"\n Return a dictionary containing, for each edge in self.edges, a list\n of the positions at which the edge should be split.\n \"\"\"\n edges = self.pts[self.edges]\n cuts = {} # { edge: [(intercept, point), ...], ... }\n for i in range(edges.shape[0]-1):\n # intersection of edge i onto all others\n int1 = self._intersect_edge_arrays(edges[i:i+1], edges[i+1:])\n # intersection of all edges onto edge i\n int2 = self._intersect_edge_arrays(edges[i+1:], edges[i:i+1])\n \n # select for pairs that intersect\n err = np.geterr()\n np.seterr(divide='ignore', invalid='ignore')\n try:\n mask1 = (int1 >= 0) & (int1 <= 1)\n mask2 = (int2 >= 0) & (int2 <= 1)\n mask3 = mask1 & mask2 # all intersections\n finally:\n np.seterr(**err)\n \n # compute points of intersection\n inds = np.argwhere(mask3)[:, 0]\n if len(inds) == 0:\n continue\n h = int2[inds][:, np.newaxis]\n pts = (edges[i, 0][np.newaxis, :] * (1.0 - h) + \n edges[i, 1][np.newaxis, :] * h)\n \n # record for all edges the location of cut points\n edge_cuts = cuts.setdefault(i, [])\n for j, ind in enumerate(inds):\n if 0 < int2[ind] < 1:\n edge_cuts.append((int2[ind], pts[j]))\n if 0 < int1[ind] < 1:\n other_cuts = cuts.setdefault(ind+i+1, [])\n other_cuts.append((int1[ind], pts[j]))\n \n # sort all cut lists by intercept, remove duplicates\n for k, v in cuts.items():\n v.sort(key=lambda x: x[0])\n for i in range(len(v)-2, -1, -1):\n if v[i][0] == v[i+1][0]:\n v.pop(i+1)\n return cuts\n\n def _split_intersecting_edges(self):\n # we can do all intersections at once, but this has excessive memory\n # overhead.\n #int1 = self._intersection_matrix(edges)\n #int2 = int1.T\n \n # measure intersection point between all pairs of edges\n all_cuts = self._find_edge_intersections()\n\n # cut edges at each intersection\n add_pts = []\n add_edges = []\n for edge, cuts in all_cuts.items():\n if len(cuts) == 0:\n continue\n \n #debug(\"Edge intersections:\", edge, self.edges[edge], \n # self.pts[self.edges[edge]], cuts)\n \n # add new points\n pt_offset = self.pts.shape[0] + len(add_pts)\n new_pts = [x[1] for x in cuts]\n add_pts.extend(new_pts)\n #debug(\"Add new points:\", new_pts)\n \n # list of point indexes for all new edges\n pt_indexes = list(range(pt_offset, pt_offset + len(cuts)))\n pt_indexes.append(self.edges[edge, 1])\n \n # modify original edge\n self.edges[edge, 1] = pt_indexes[0]\n \n # add new edges\n new_edges = [[pt_indexes[i-1], pt_indexes[i]] \n for i in range(1, len(pt_indexes))] \n add_edges.extend(new_edges)\n \n #debug(\"Adding %d points and %d edges to remove intersections.\" % \n # (len(add_pts), len(add_edges)))\n if add_pts:\n add_pts = np.array(add_pts, dtype=self.pts.dtype)\n self.pts = np.append(self.pts, add_pts, axis=0)\n if add_edges:\n add_edges = np.array(add_edges, dtype=self.edges.dtype)\n self.edges = np.append(self.edges, add_edges, axis=0)\n\n def _merge_duplicate_points(self):\n # generate a list of all pairs (i,j) of identical points\n dups = []\n for i in range(self.pts.shape[0]-1):\n test_pt = self.pts[i:i+1]\n comp_pts = self.pts[i+1:]\n eq = test_pt == comp_pts\n eq = eq[:, 0] & eq[:, 1]\n for j in np.argwhere(eq)[:, 0]:\n dups.append((i, i+1+j))\n\n dups_arr = np.array(dups)\n # remove duplicate points\n pt_mask = np.ones(self.pts.shape[0], dtype=bool)\n for i, inds in enumerate(dups_arr):\n # remove j from points\n # (note we pull the index from the original dups instead of \n # dups_arr because the indexes in pt_mask do not change)\n pt_mask[dups[i][1]] = False\n \n i, j = inds\n \n # rewrite edges to use i instead of j\n self.edges[self.edges == j] = i\n \n #assert not np.any(self.edges[:,0] == self.edges[:,1])\n \n # decrement all point indexes > j\n self.edges[self.edges > j] -= 1\n dups_arr[dups_arr > j] -= 1\n #assert not np.any(self.edges[:,0] == self.edges[:,1])\n \n self.pts = self.pts[pt_mask]\n \n # remove zero-length edges\n mask = self.edges[:, 0] != self.edges[:, 1]\n self.edges = self.edges[mask]\n \n def _distance(self, A, B):\n # Distance between points A and B\n n = len(A)\n assert len(B) == n\n return np.linalg.norm(np.array(list(A)) - np.array(list(B)))\n\n def _distances_from_line(self, edge, points):\n # Distance of a set of points from a given line\n #debug(\"distance from %r to %r\" % (points, edge))\n e1 = self.pts[edge[0]]\n e2 = self.pts[edge[1]]\n distances = []\n for i in points:\n p = self.pts[i]\n proj = self._projection(e1, p, e2)\n distances.append(((p - proj)**2).sum()**0.5)\n assert distances[0] == 0 and distances[-1] == 0\n return distances\n\n def _projection(self, a, b, c):\n \"\"\"Return projection of (a,b) onto (a,c)\n Arguments are point locations, not indexes.\n \"\"\"\n ab = b - a\n ac = c - a\n return a + ((ab*ac).sum() / (ac*ac).sum()) * ac\n\n def _cosine(self, A, B, C):\n # Cosine of angle ABC\n a = ((C - B)**2).sum()\n b = ((C - A)**2).sum()\n c = ((B - A)**2).sum()\n d = (a + c - b) / ((4 * a * c)**0.5)\n return d\n\n #def _barycentric(self, A, B, C, p, q, r):\n ## Cartesian coordinates of the point whose barycentric coordinates\n ## with respect to the triangle ABC are [p,q,r]\n #n = len(A)\n #assert len(B) == len(C) == n\n #s = p+q+r\n #p, q, r = p/s, q/s, r/s\n #return tuple([p*A[i]+q*B[i]+r*C[i] for i in range(n)])\n\n #def _trilinear(self, A, B, C, alpha, beta, gamma):\n ## Cartesian coordinates of the point whose trilinear coordinates\n ## with respect to the triangle ABC are [alpha,beta,gamma]\n #a = distance(B, C)\n #b = distance(A, C)\n #c = distance(A, B)\n #return barycentric(A, B, C, a*alpha, b*beta, c*gamma)\n \n #def _circuminfo(self, A, B, C):\n ## Cartesian coordinates of the circumcenter of triangle ABC\n #cosA = cosine(C, A, B)\n #cosB = cosine(A, B, C)\n #cosC = cosine(B, C, A)\n #cc = trilinear(A, B, C, cosA, cosB, cosC)\n ## returns circumcenter and circumradius\n #return cc, distance(cc, A)\n\n def _iscounterclockwise(self, a, b, c):\n # Check if the points lie in counter-clockwise order or not\n A = self.pts[a]\n B = self.pts[b]\n C = self.pts[c]\n return np.cross(B-A, C-B) > 0\n\n def _edges_intersect(self, edge1, edge2):\n \"\"\"\n Return 1 if edges intersect completely (endpoints excluded)\n \"\"\"\n h12 = self._intersect_edge_arrays(self.pts[np.array(edge1)], \n self.pts[np.array(edge2)])\n h21 = self._intersect_edge_arrays(self.pts[np.array(edge2)], \n self.pts[np.array(edge1)])\n err = np.geterr()\n np.seterr(divide='ignore', invalid='ignore')\n try:\n out = (0 < h12 < 1) and (0 < h21 < 1)\n finally:\n np.seterr(**err)\n return out\n\n def _intersection_matrix(self, lines):\n \"\"\"\n Return a 2D array of intercepts such that \n intercepts[i, j] is the intercept of lines[i] onto lines[j].\n \n *lines* must be an array of point locations with shape (N, 2, 2), where\n the axes are (lines, points_per_line, xy_per_point).\n \n The intercept is described in intersect_edge_arrays().\n \"\"\"\n return self._intersect_edge_arrays(lines[:, np.newaxis, ...], \n lines[np.newaxis, ...])\n \n def _intersect_edge_arrays(self, lines1, lines2):\n \"\"\"Return the intercepts of all lines defined in *lines1* as they \n intersect all lines in *lines2*. \n \n Arguments are of shape (..., 2, 2), where axes are:\n \n 0: number of lines\n 1: two points per line\n 2: x,y pair per point\n\n Lines are compared elementwise across the arrays (lines1[i] is compared\n against lines2[i]). If one of the arrays has N=1, then that line is\n compared against all lines in the other array.\n \n Returns an array of shape (N,) where each value indicates the intercept\n relative to the defined line segment. A value of 0 indicates \n intersection at the first endpoint, and a value of 1 indicates \n intersection at the second endpoint. Values between 1 and 0 are on the\n segment, whereas values outside 1 and 0 are off of the segment. \n \"\"\"\n # vector for each line in lines1\n l1 = lines1[..., 1, :] - lines1[..., 0, :]\n # vector for each line in lines2\n l2 = lines2[..., 1, :] - lines2[..., 0, :]\n # vector between first point of each line\n diff = lines1[..., 0, :] - lines2[..., 0, :]\n \n p = l1.copy()[..., ::-1] # vectors perpendicular to l1\n p[..., 0] *= -1\n \n f = (l2 * p).sum(axis=-1) # l2 dot p\n # tempting, but bad idea! \n #f = np.where(f==0, 1, f)\n err = np.geterr()\n np.seterr(divide='ignore', invalid='ignore')\n try:\n h = (diff * p).sum(axis=-1) / f # diff dot p / f\n finally:\n np.seterr(**err)\n \n return h\n\n def _orientation(self, edge, point):\n \"\"\" Returns +1 if edge[0]->point is clockwise from edge[0]->edge[1], \n -1 if counterclockwise, and 0 if parallel.\n \"\"\"\n v1 = self.pts[point] - self.pts[edge[0]]\n v2 = self.pts[edge[1]] - self.pts[edge[0]]\n c = np.cross(v1, v2) # positive if v1 is CW from v2\n return 1 if c > 0 else (-1 if c < 0 else 0)\n\n #def _legalize(self, p):\n ### Legalize recursively - incomplete\n #return p # disabled for now\n \n #f00, f11, p = p\n\n #debug(\"Legalizing points = {}, {}, {}\".format(f00, f11, p))\n #a = pts[f00]\n #b = pts[f11]\n #c = pts[p]\n #cc, cr = circuminfo(a, b, c)\n #for point in pts:\n # if np.all(point == a) or np.all(point == b) or np.all(point == c):\n # continue\n # elif distance(cc, point) < cr:\n # #debug(\"Illegal point\")\n # #debug(point)\n # pass\n\n #return (f00, f11, p)\n\n def _add_tri(self, a, b, c, legal=True, source=None):\n # source is just used for #debugging\n #debug(\"Add triangle [%s]:\" % source, (a, b, c))\n \n # sanity check\n assert a != b and b != c and c != a\n \n # ignore flat tris\n pa = self.pts[a]\n pb = self.pts[b]\n pc = self.pts[c]\n if np.all(pa == pb) or np.all(pb == pc) or np.all(pc == pa):\n #debug(\" Triangle is flat; refusing to add.\")\n return\n \n # check this tri is unique\n for t in permutations((a, b, c)):\n if t in self.tris:\n raise Exception(\"Cannot add %s; already have %s\" % \n ((a, b, c), t))\n \n # TODO: should add to edges_lookup after legalization??\n if self._iscounterclockwise(a, b, c):\n #debug(\" \", (a, b), (b, c), (c, a))\n assert (a, b) not in self._edges_lookup\n assert (b, c) not in self._edges_lookup\n assert (c, a) not in self._edges_lookup\n self._edges_lookup[(a, b)] = c\n self._edges_lookup[(b, c)] = a\n self._edges_lookup[(c, a)] = b\n else:\n #debug(\" \", (b, a), (c, b), (a, c))\n assert (b, a) not in self._edges_lookup\n assert (c, b) not in self._edges_lookup\n assert (a, c) not in self._edges_lookup\n self._edges_lookup[(b, a)] = c\n self._edges_lookup[(c, b)] = a\n self._edges_lookup[(a, c)] = b\n \n #if legal:\n #tri = self._legalize((a, b, c))\n #else:\n tri = (a, b, c)\n \n self.tris[tri] = None\n\n def _remove_tri(self, a, b, c):\n #debug(\"Remove triangle:\", (a, b, c))\n \n for k in permutations((a, b, c)):\n if k in self.tris:\n break\n del self.tris[k]\n (a, b, c) = k\n\n if self._edges_lookup.get((a, b), -1) == c:\n #debug(\" \", (a,b), (b,c), (c,a))\n del self._edges_lookup[(a, b)]\n del self._edges_lookup[(b, c)]\n del self._edges_lookup[(c, a)]\n elif self._edges_lookup.get((b, a), -1) == c:\n #debug(\" \", (b,a), (c,b), (a,c))\n del self._edges_lookup[(b, a)]\n del self._edges_lookup[(a, c)]\n del self._edges_lookup[(c, b)]\n else:\n raise RuntimeError(\"Lost edges_lookup for tri (%d, %d, %d)\" % \n (a, b, c))\n\n return k\n\n\ndef _triangulate_python(vertices_2d, segments):\n segments = segments.reshape(len(segments) / 2, 2)\n T = Triangulation(vertices_2d, segments)\n T.triangulate()\n vertices_2d = T.pts\n triangles = T.tris.ravel()\n return vertices_2d, triangles\n\n\ndef _triangulate_cpp(vertices_2d, segments):\n T = triangle.triangulate({'vertices': vertices_2d,\n 'segments': segments}, \"p\")\n vertices_2d = T[\"vertices\"]\n triangles = T[\"triangles\"]\n return vertices_2d, triangles\n\n\ndef triangulate(vertices):\n \"\"\"Triangulate a set of vertices\n\n Parameters\n ----------\n vertices : array-like\n The vertices.\n\n Returns\n -------\n vertices : array-like\n The vertices.\n tringles : array-like\n The triangles.\n \"\"\"\n n = len(vertices)\n vertices = np.asarray(vertices)\n zmean = vertices[:, 2].mean()\n vertices_2d = vertices[:, :2]\n segments = np.repeat(np.arange(n + 1), 2)[1:-1]\n segments[-2:] = n - 1, 0\n\n if _TRIANGLE_AVAILABLE:\n vertices_2d, triangles = _triangulate_cpp(vertices_2d, segments)\n else:\n vertices_2d, triangles = _triangulate_python(vertices_2d, segments)\n\n vertices = np.empty((len(vertices_2d), 3))\n vertices[:, :2] = vertices_2d\n vertices[:, 2] = zmean\n return vertices, triangles\n\n\n# Note: using custom #debug instead of logging because\n# there are MANY messages and logger might be too expensive.\n# After this becomes stable, we might just remove them altogether.\ndef debug(*args):\n print(*args)\n", "# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# Copyright (c) 2015, Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n# -----------------------------------------------------------------------------\n\"\"\" Fast and failsafe GL console \"\"\"\n\n# Code translated from glumpy\n\nimport numpy as np\n\nfrom .widget import Widget\nfrom ...visuals import Visual\nfrom ...gloo import VertexBuffer\nfrom ...color import Color\nfrom ...ext.six import string_types\n\n\n# Translated from\n# http://www.piclist.com/tecHREF/datafile/charset/\n# extractor/charset_extractor.htm\n__font_6x8__ = np.array([\n (0x00, 0x00, 0x00, 0x00, 0x00, 0x00), (0x10, 0xE3, 0x84, 0x10, 0x01, 0x00),\n (0x6D, 0xB4, 0x80, 0x00, 0x00, 0x00), (0x00, 0xA7, 0xCA, 0x29, 0xF2, 0x80),\n (0x20, 0xE4, 0x0C, 0x09, 0xC1, 0x00), (0x65, 0x90, 0x84, 0x21, 0x34, 0xC0),\n (0x21, 0x45, 0x08, 0x55, 0x23, 0x40), (0x30, 0xC2, 0x00, 0x00, 0x00, 0x00),\n (0x10, 0x82, 0x08, 0x20, 0x81, 0x00), (0x20, 0x41, 0x04, 0x10, 0x42, 0x00),\n (0x00, 0xA3, 0x9F, 0x38, 0xA0, 0x00), (0x00, 0x41, 0x1F, 0x10, 0x40, 0x00),\n (0x00, 0x00, 0x00, 0x00, 0xC3, 0x08), (0x00, 0x00, 0x1F, 0x00, 0x00, 0x00),\n (0x00, 0x00, 0x00, 0x00, 0xC3, 0x00), (0x00, 0x10, 0x84, 0x21, 0x00, 0x00),\n (0x39, 0x14, 0xD5, 0x65, 0x13, 0x80), (0x10, 0xC1, 0x04, 0x10, 0x43, 0x80),\n (0x39, 0x10, 0x46, 0x21, 0x07, 0xC0), (0x39, 0x10, 0x4E, 0x05, 0x13, 0x80),\n (0x08, 0x62, 0x92, 0x7C, 0x20, 0x80), (0x7D, 0x04, 0x1E, 0x05, 0x13, 0x80),\n (0x18, 0x84, 0x1E, 0x45, 0x13, 0x80), (0x7C, 0x10, 0x84, 0x20, 0x82, 0x00),\n (0x39, 0x14, 0x4E, 0x45, 0x13, 0x80), (0x39, 0x14, 0x4F, 0x04, 0x23, 0x00),\n (0x00, 0x03, 0x0C, 0x00, 0xC3, 0x00), (0x00, 0x03, 0x0C, 0x00, 0xC3, 0x08),\n (0x08, 0x42, 0x10, 0x20, 0x40, 0x80), (0x00, 0x07, 0xC0, 0x01, 0xF0, 0x00),\n (0x20, 0x40, 0x81, 0x08, 0x42, 0x00), (0x39, 0x10, 0x46, 0x10, 0x01, 0x00),\n (0x39, 0x15, 0xD5, 0x5D, 0x03, 0x80), (0x39, 0x14, 0x51, 0x7D, 0x14, 0x40),\n (0x79, 0x14, 0x5E, 0x45, 0x17, 0x80), (0x39, 0x14, 0x10, 0x41, 0x13, 0x80),\n (0x79, 0x14, 0x51, 0x45, 0x17, 0x80), (0x7D, 0x04, 0x1E, 0x41, 0x07, 0xC0),\n (0x7D, 0x04, 0x1E, 0x41, 0x04, 0x00), (0x39, 0x14, 0x17, 0x45, 0x13, 0xC0),\n (0x45, 0x14, 0x5F, 0x45, 0x14, 0x40), (0x38, 0x41, 0x04, 0x10, 0x43, 0x80),\n (0x04, 0x10, 0x41, 0x45, 0x13, 0x80), (0x45, 0x25, 0x18, 0x51, 0x24, 0x40),\n (0x41, 0x04, 0x10, 0x41, 0x07, 0xC0), (0x45, 0xB5, 0x51, 0x45, 0x14, 0x40),\n (0x45, 0x95, 0x53, 0x45, 0x14, 0x40), (0x39, 0x14, 0x51, 0x45, 0x13, 0x80),\n (0x79, 0x14, 0x5E, 0x41, 0x04, 0x00), (0x39, 0x14, 0x51, 0x55, 0x23, 0x40),\n (0x79, 0x14, 0x5E, 0x49, 0x14, 0x40), (0x39, 0x14, 0x0E, 0x05, 0x13, 0x80),\n (0x7C, 0x41, 0x04, 0x10, 0x41, 0x00), (0x45, 0x14, 0x51, 0x45, 0x13, 0x80),\n (0x45, 0x14, 0x51, 0x44, 0xA1, 0x00), (0x45, 0x15, 0x55, 0x55, 0x52, 0x80),\n (0x45, 0x12, 0x84, 0x29, 0x14, 0x40), (0x45, 0x14, 0x4A, 0x10, 0x41, 0x00),\n (0x78, 0x21, 0x08, 0x41, 0x07, 0x80), (0x38, 0x82, 0x08, 0x20, 0x83, 0x80),\n (0x01, 0x02, 0x04, 0x08, 0x10, 0x00), (0x38, 0x20, 0x82, 0x08, 0x23, 0x80),\n (0x10, 0xA4, 0x40, 0x00, 0x00, 0x00), (0x00, 0x00, 0x00, 0x00, 0x00, 0x3F),\n (0x30, 0xC1, 0x00, 0x00, 0x00, 0x00), (0x00, 0x03, 0x81, 0x3D, 0x13, 0xC0),\n (0x41, 0x07, 0x91, 0x45, 0x17, 0x80), (0x00, 0x03, 0x91, 0x41, 0x13, 0x80),\n (0x04, 0x13, 0xD1, 0x45, 0x13, 0xC0), (0x00, 0x03, 0x91, 0x79, 0x03, 0x80),\n (0x18, 0x82, 0x1E, 0x20, 0x82, 0x00), (0x00, 0x03, 0xD1, 0x44, 0xF0, 0x4E),\n (0x41, 0x07, 0x12, 0x49, 0x24, 0x80), (0x10, 0x01, 0x04, 0x10, 0x41, 0x80),\n (0x08, 0x01, 0x82, 0x08, 0x24, 0x8C), (0x41, 0x04, 0x94, 0x61, 0x44, 0x80),\n (0x10, 0x41, 0x04, 0x10, 0x41, 0x80), (0x00, 0x06, 0x95, 0x55, 0x14, 0x40),\n (0x00, 0x07, 0x12, 0x49, 0x24, 0x80), (0x00, 0x03, 0x91, 0x45, 0x13, 0x80),\n (0x00, 0x07, 0x91, 0x45, 0x17, 0x90), (0x00, 0x03, 0xD1, 0x45, 0x13, 0xC1),\n (0x00, 0x05, 0x89, 0x20, 0x87, 0x00), (0x00, 0x03, 0x90, 0x38, 0x13, 0x80),\n (0x00, 0x87, 0x88, 0x20, 0xA1, 0x00), (0x00, 0x04, 0x92, 0x49, 0x62, 0x80),\n (0x00, 0x04, 0x51, 0x44, 0xA1, 0x00), (0x00, 0x04, 0x51, 0x55, 0xF2, 0x80),\n (0x00, 0x04, 0x92, 0x31, 0x24, 0x80), (0x00, 0x04, 0x92, 0x48, 0xE1, 0x18),\n (0x00, 0x07, 0x82, 0x31, 0x07, 0x80), (0x18, 0x82, 0x18, 0x20, 0x81, 0x80),\n (0x10, 0x41, 0x00, 0x10, 0x41, 0x00), (0x30, 0x20, 0x83, 0x08, 0x23, 0x00),\n (0x29, 0x40, 0x00, 0x00, 0x00, 0x00), (0x10, 0xE6, 0xD1, 0x45, 0xF0, 0x00)\n], dtype=np.float32)\n\nVERTEX_SHADER = \"\"\"\nuniform vec2 u_logical_scale;\nuniform float u_physical_scale;\nuniform vec4 u_color;\nuniform vec4 u_origin; \n\nattribute vec2 a_position;\nattribute vec3 a_bytes_012;\nattribute vec3 a_bytes_345;\n\nvarying vec4 v_color;\nvarying vec3 v_bytes_012, v_bytes_345;\n\nvoid main (void)\n{\n gl_Position = u_origin + vec4(a_position * u_logical_scale, 0., 0.);\n gl_PointSize = 8.0 * u_physical_scale;\n v_color = u_color;\n v_bytes_012 = a_bytes_012;\n v_bytes_345 = a_bytes_345;\n}\n\"\"\"\n\nFRAGMENT_SHADER = \"\"\"\nfloat segment(float edge0, float edge1, float x)\n{\n return step(edge0,x) * (1.0-step(edge1,x));\n}\n\nvarying vec4 v_color;\nvarying vec3 v_bytes_012, v_bytes_345;\n\nvec4 glyph_color(vec2 uv) {\n if(uv.x > 5.0 || uv.y > 7.0)\n return vec4(0, 0, 0, 0);\n else {\n float index = floor( (uv.y*6.0+uv.x)/8.0 );\n float offset = floor( mod(uv.y*6.0+uv.x,8.0));\n float byte = segment(0.0,1.0,index) * v_bytes_012.x\n + segment(1.0,2.0,index) * v_bytes_012.y\n + segment(2.0,3.0,index) * v_bytes_012.z\n + segment(3.0,4.0,index) * v_bytes_345.x\n + segment(4.0,5.0,index) * v_bytes_345.y\n + segment(5.0,6.0,index) * v_bytes_345.z;\n if( floor(mod(byte / (128.0/pow(2.0,offset)), 2.0)) > 0.0 )\n return v_color;\n else\n return vec4(0, 0, 0, 0);\n }\n}\n\nvoid main(void)\n{\n vec2 loc = gl_PointCoord.xy * 8.0;\n vec2 uv = floor(loc);\n // use multi-sampling to make the text look nicer\n vec2 dxy = 0.25*(abs(dFdx(loc)) + abs(dFdy(loc)));\n vec4 box = floor(vec4(loc-dxy, loc+dxy));\n vec4 color = glyph_color(floor(loc)) +\n 0.25 * glyph_color(box.xy) +\n 0.25 * glyph_color(box.xw) +\n 0.25 * glyph_color(box.zy) +\n 0.25 * glyph_color(box.zw);\n gl_FragColor = color / 2.;\n}\n\"\"\"\n\n\nclass Console(Widget):\n \"\"\"Fast and failsafe text console\n\n Parameters\n ----------\n text_color : instance of Color\n Color to use.\n font_size : float\n Point size to use.\n \"\"\"\n def __init__(self, text_color='black', font_size=12., **kwargs):\n self._visual = ConsoleVisual(text_color, font_size)\n Widget.__init__(self, **kwargs)\n self.add_subvisual(self._visual)\n \n def on_resize(self, event):\n \"\"\"Resize event handler\n\n Parameters\n ----------\n event : instance of Event\n The event.\n \"\"\"\n self._visual.size = self.size\n \n def clear(self):\n \"\"\"Clear the console\"\"\"\n self._visual.clear()\n\n def write(self, text='', wrap=True):\n \"\"\"Write text and scroll\n\n Parameters\n ----------\n text : str\n Text to write. ``''`` can be used for a blank line, as a newline\n is automatically added to the end of each line.\n wrap : str\n If True, long messages will be wrapped to span multiple lines.\n \"\"\"\n self._visual.write(text)\n \n @property\n def text_color(self):\n \"\"\"The color of the text\"\"\"\n return self._visual._text_color\n\n @text_color.setter\n def text_color(self, color):\n self._visual._text_color = Color(color)\n\n @property\n def font_size(self):\n \"\"\"The font size (in points) of the text\"\"\"\n return self._visual._font_size\n\n @font_size.setter\n def font_size(self, font_size):\n self._visual._font_size = float(font_size)\n\n \nclass ConsoleVisual(Visual):\n def __init__(self, text_color, font_size, **kwargs):\n # Harcoded because of font above and shader program\n self.text_color = text_color\n self.font_size = font_size\n self._char_width = 6\n self._char_height = 10\n self._pending_writes = []\n self._text_lines = []\n self._col = 0\n self._current_sizes = (-1,) * 3\n self._size = (100, 100)\n Visual.__init__(self, VERTEX_SHADER, FRAGMENT_SHADER)\n self._draw_mode = 'points'\n self.set_gl_state(depth_test=False, blend=True,\n blend_func=('src_alpha', 'one_minus_src_alpha'))\n\n @property\n def size(self):\n return self._size\n \n @size.setter\n def size(self, s):\n self._size = s\n\n @property\n def text_color(self):\n \"\"\"The color of the text\"\"\"\n return self._text_color\n\n @text_color.setter\n def text_color(self, color):\n self._text_color = Color(color)\n\n @property\n def font_size(self):\n \"\"\"The font size (in points) of the text\"\"\"\n return self._font_size\n\n @font_size.setter\n def font_size(self, font_size):\n self._font_size = float(font_size)\n\n def _resize_buffers(self, font_scale):\n \"\"\"Resize buffers only if necessary\"\"\"\n new_sizes = (font_scale,) + self.size\n if new_sizes == self._current_sizes: # don't need resize\n return\n self._n_rows = int(max(self.size[1] /\n (self._char_height * font_scale), 1))\n self._n_cols = int(max(self.size[0] /\n (self._char_width * font_scale), 1))\n self._bytes_012 = np.zeros((self._n_rows, self._n_cols, 3), np.float32)\n self._bytes_345 = np.zeros((self._n_rows, self._n_cols, 3), np.float32)\n pos = np.empty((self._n_rows, self._n_cols, 2), np.float32)\n C, R = np.meshgrid(np.arange(self._n_cols), np.arange(self._n_rows))\n # We are in left, top orientation\n x_off = 4.\n y_off = 4 - self.size[1] / font_scale\n pos[..., 0] = x_off + self._char_width * C\n pos[..., 1] = y_off + self._char_height * R\n self._position = VertexBuffer(pos)\n\n # Restore lines\n for ii, line in enumerate(self._text_lines[:self._n_rows]):\n self._insert_text_buf(line, ii)\n self._current_sizes = new_sizes\n\n def _prepare_draw(self, view):\n xform = view.get_transform()\n tr = view.get_transform('document', 'render')\n logical_scale = np.diff(tr.map(([0, 1], [1, 0])), axis=0)[0, :2]\n tr = view.get_transform('document', 'framebuffer')\n log_to_phy = np.mean(np.diff(tr.map(([0, 1], [1, 0])), axis=0)[0, :2])\n n_pix = (self.font_size / 72.) * 92. # num of pixels tall\n # The -2 here is because the char_height has a gap built in\n font_scale = max(n_pix / float((self._char_height-2)), 1)\n self._resize_buffers(font_scale)\n self._do_pending_writes()\n self._program['u_origin'] = xform.map((0, 0, 0, 1))\n self._program['u_logical_scale'] = font_scale * logical_scale\n self._program['u_color'] = self.text_color.rgba\n self._program['u_physical_scale'] = font_scale * log_to_phy\n self._program['a_position'] = self._position\n self._program['a_bytes_012'] = VertexBuffer(self._bytes_012)\n self._program['a_bytes_345'] = VertexBuffer(self._bytes_345)\n\n def _prepare_transforms(self, view):\n pass\n\n def clear(self):\n \"\"\"Clear the console\"\"\"\n if hasattr(self, '_bytes_012'):\n self._bytes_012.fill(0)\n self._bytes_345.fill(0)\n self._text_lines = [] * self._n_rows\n self._pending_writes = []\n\n def write(self, text='', wrap=True):\n \"\"\"Write text and scroll\n\n Parameters\n ----------\n text : str\n Text to write. ``''`` can be used for a blank line, as a newline\n is automatically added to the end of each line.\n wrap : str\n If True, long messages will be wrapped to span multiple lines.\n \"\"\"\n # Clear line\n if not isinstance(text, string_types):\n raise TypeError('text must be a string')\n # ensure we only have ASCII chars\n text = text.encode('utf-8').decode('ascii', errors='replace')\n self._pending_writes.append((text, wrap))\n self.update()\n\n def _do_pending_writes(self):\n \"\"\"Do any pending text writes\"\"\"\n for text, wrap in self._pending_writes:\n # truncate in case of *really* long messages\n text = text[-self._n_cols*self._n_rows:]\n text = text.split('\\n')\n text = [t if len(t) > 0 else '' for t in text]\n nr, nc = self._n_rows, self._n_cols\n for para in text:\n para = para[:nc] if not wrap else para\n lines = [para[ii:(ii+nc)] for ii in range(0, len(para), nc)]\n lines = [''] if len(lines) == 0 else lines\n for line in lines:\n # Update row and scroll if necessary\n self._text_lines.insert(0, line)\n self._text_lines = self._text_lines[:nr]\n self._bytes_012[1:] = self._bytes_012[:-1]\n self._bytes_345[1:] = self._bytes_345[:-1]\n self._insert_text_buf(line, 0)\n self._pending_writes = []\n\n def _insert_text_buf(self, line, idx):\n \"\"\"Insert text into bytes buffers\"\"\"\n self._bytes_012[idx] = 0\n self._bytes_345[idx] = 0\n # Crop text if necessary\n I = np.array([ord(c) - 32 for c in line[:self._n_cols]])\n I = np.clip(I, 0, len(__font_6x8__)-1)\n if len(I) > 0:\n b = __font_6x8__[I]\n self._bytes_012[idx, :len(I)] = b[:, :3]\n self._bytes_345[idx, :len(I)] = b[:, 3:]\n" ]
[ [ "numpy.array", "numpy.resize" ], [ "numpy.geterr", "numpy.asarray", "numpy.arange", "numpy.isnan", "numpy.ones", "numpy.all", "numpy.seterr", "numpy.append", "numpy.argmax", "numpy.argwhere", "numpy.any", "numpy.isscalar", "numpy.cross", "numpy.argsort", "numpy.array", "numpy.empty" ], [ "numpy.arange", "numpy.array", "numpy.zeros", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
gifuni/nistats
[ "8f0b606f6da6dc7f55e25cc0fa903fdfcc007145", "8f0b606f6da6dc7f55e25cc0fa903fdfcc007145" ]
[ "nistats/tests/test_check_events_file_uses_tab_separators.py", "nistats/tests/test_regression.py" ]
[ "import pandas as pd\n\nfrom nibabel.tmpdirs import InTemporaryDirectory\nfrom nose.tools import (assert_raises,\n assert_true,\n )\n\nfrom nistats.utils import _check_events_file_uses_tab_separators\n\n\ndef make_data_for_test_runs():\n data_for_temp_datafile = [\n ['csf', 'constant', 'linearTrend', 'wm'],\n [13343.032102491035, 1.0, 0.0, 9486.199545677482],\n [13329.224068063204, 1.0, 1.0, 9497.003324892803],\n [13291.755627241291, 1.0, 2.0, 9484.012965365506],\n ]\n \n delimiters = {\n 'tab': '\\t',\n 'comma': ',',\n 'space': ' ',\n 'semicolon': ';',\n 'hyphen': '-',\n }\n \n return data_for_temp_datafile, delimiters\n\n\ndef _create_test_file(temp_csv, test_data, delimiter):\n test_data = pd.DataFrame(test_data)\n test_data.to_csv(temp_csv, sep=delimiter)\n \n\ndef _run_test_for_invalid_separator(filepath, delimiter_name):\n if delimiter_name not in ('tab', 'comma'):\n with assert_raises(ValueError):\n _check_events_file_uses_tab_separators(events_files=filepath)\n else:\n result = _check_events_file_uses_tab_separators(events_files=filepath)\n assert_true(result is None)\n\n\ndef test_for_invalid_separator():\n data_for_temp_datafile, delimiters = make_data_for_test_runs()\n for delimiter_name, delimiter_char in delimiters.items():\n with InTemporaryDirectory():\n temp_tsv_file = 'tempfile.{} separated values'.format(\n delimiter_name)\n _create_test_file(temp_csv=temp_tsv_file ,\n test_data=data_for_temp_datafile,\n delimiter=delimiter_char)\n _run_test_for_invalid_separator(filepath=temp_tsv_file ,\n delimiter_name=delimiter_name)\n\n\ndef test_with_2D_dataframe():\n data_for_pandas_dataframe, _ = make_data_for_test_runs()\n events_pandas_dataframe = pd.DataFrame(data_for_pandas_dataframe)\n result = _check_events_file_uses_tab_separators(\n events_files=events_pandas_dataframe)\n assert_true(result is None)\n\n\ndef test_with_1D_dataframe():\n data_for_pandas_dataframe, _ = make_data_for_test_runs()\n for dataframe_ in data_for_pandas_dataframe:\n events_pandas_dataframe = pd.DataFrame(dataframe_)\n result = _check_events_file_uses_tab_separators(\n events_files=events_pandas_dataframe)\n assert_true(result is None)\n\ndef test_for_invalid_filepath():\n filepath = 'junk_file_path.csv'\n result = _check_events_file_uses_tab_separators(events_files=filepath)\n assert_true(result is None)\n\n\ndef test_for_pandas_dataframe():\n events_pandas_dataframe = pd.DataFrame([['a', 'b', 'c'], [0, 1, 2]])\n result = _check_events_file_uses_tab_separators(\n events_files=events_pandas_dataframe)\n assert_true(result is None)\n \n\ndef test_binary_opening_an_image():\n img_data = bytearray(\n b'GIF87a\\x01\\x00\\x01\\x00\\xe7*\\x00\\x00\\x00\\x00\\x01\\x01\\x01\\x02\\x02'\n b'\\x07\\x08\\x08\\x08\\x0b\\x0b\\x0b\\x0c\\x0c\\x0c\\r;')\n with InTemporaryDirectory():\n temp_img_file = 'temp_img.gif'\n with open(temp_img_file, 'wb') as temp_img_obj:\n temp_img_obj.write(img_data)\n with assert_raises(ValueError):\n _check_events_file_uses_tab_separators(\n events_files=temp_img_file)\n\n\ndef test_binary_bytearray_of_ints_data():\n temp_data_bytearray_from_ints = bytearray([0, 1, 0, 11, 10])\n with InTemporaryDirectory():\n temp_bin_file = 'temp_bin.bin'\n with open(temp_bin_file, 'wb') as temp_bin_obj:\n temp_bin_obj.write(temp_data_bytearray_from_ints)\n with assert_raises(ValueError):\n _check_events_file_uses_tab_separators(\n events_files=temp_bin_file)\n\n\nif __name__ == '__main__':\n\n def _run_tests_print_test_messages(test_func):\n from pprint import pprint\n pprint(['Running', test_func.__name__])\n test_func()\n pprint('... complete')\n \n \n def run_test_suite():\n tests = [\n test_for_invalid_filepath,\n test_with_2D_dataframe,\n test_with_1D_dataframe,\n test_for_invalid_filepath,\n test_for_pandas_dataframe,\n test_binary_opening_an_image,\n test_binary_bytearray_of_ints_data,\n ]\n for test_ in tests:\n _run_tests_print_test_messages(test_func=test_)\n\n\n run_test_suite()\n", "\"\"\"\nTest functions for models.regression\n\"\"\"\n\nimport numpy as np\n\nfrom nose.tools import assert_equal\n\nfrom nistats.regression import OLSModel, ARModel\n\n\nRNG = np.random.RandomState(20110902)\nX = RNG.standard_normal((40, 10))\nY = RNG.standard_normal((40,))\n\n\ndef test_OLS():\n model = OLSModel(design=X)\n results = model.fit(Y)\n assert_equal(results.df_resid, 30)\n\n\ndef test_AR():\n model = ARModel(design=X, rho=0.4)\n results = model.fit(Y)\n assert_equal(results.df_resid, 30)\n\n\ndef test_OLS_degenerate():\n Xd = X.copy()\n Xd[:, 0] = Xd[:, 1] + Xd[:, 2]\n model = OLSModel(design=Xd)\n results = model.fit(Y)\n assert_equal(results.df_resid, 31)\n\n\ndef test_AR_degenerate():\n Xd = X.copy()\n Xd[:, 0] = Xd[:, 1] + Xd[:, 2]\n model = ARModel(design=Xd, rho=0.9)\n results = model.fit(Y)\n assert_equal(results.df_resid, 31)\n" ]
[ [ "pandas.DataFrame" ], [ "numpy.random.RandomState" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Bob-Yeah/kaolin
[ "7ad34f8158000499a30b8dfa14fb3ed86d2e57a6", "7ad34f8158000499a30b8dfa14fb3ed86d2e57a6", "7ad34f8158000499a30b8dfa14fb3ed86d2e57a6", "7ad34f8158000499a30b8dfa14fb3ed86d2e57a6", "7ad34f8158000499a30b8dfa14fb3ed86d2e57a6", "7ad34f8158000499a30b8dfa14fb3ed86d2e57a6", "7ad34f8158000499a30b8dfa14fb3ed86d2e57a6" ]
[ "examples/ImageRecon/OccNet/architectures.py", "tests/rep/test_mesh_representation.py", "examples/ImageRecon/Image_Mesh_Recon_Direct/eval.py", "kaolin/engine/classification.py", "examples/GANs/3D-IWGAN/eval.py", "kaolin/graphics/dib_renderer/renderer/texrender.py", "examples/SuperResolution/voxel-ShapeNet/architectures.py" ]
[ "# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport math\n\nimport torch \nfrom torch import nn \nfrom torch.nn.parameter import Parameter\nimport torch.nn.functional as F\nfrom torchvision import models\nimport torch.distributions as dist\n\nimport torch\nfrom torch.nn import Parameter\n\nclass Resnet18(nn.Module):\n r''' ResNet-18 encoder network for image input.\n Args:\n c_dim (int): output dimension of the latent embedding\n normalize (bool): whether the input images should be normalized\n use_linear (bool): whether a final linear layer should be used\n '''\n\n def __init__(self, c_dim, normalize=True, use_linear=True):\n super().__init__()\n self.normalize = normalize\n self.use_linear = use_linear\n self.features = models.resnet18(pretrained=True)\n self.features.fc = nn.Sequential()\n if use_linear:\n self.fc = nn.Linear(512, c_dim)\n elif c_dim == 512:\n self.fc = nn.Sequential()\n else:\n raise ValueError('c_dim must be 512 if use_linear is False')\n\n def forward(self, x):\n if self.normalize:\n x = normalize_imagenet(x)\n net = self.features(x)\n out = self.fc(net)\n return out\n\ndef normalize_imagenet(x):\n ''' Normalize input images according to ImageNet standards.\n Args:\n x (tensor): input images\n '''\n x = x.clone()\n x[:, 0] = (x[:, 0] - 0.485) / 0.229\n x[:, 1] = (x[:, 1] - 0.456) / 0.224\n x[:, 2] = (x[:, 2] - 0.406) / 0.225\n return x\n\n\nclass DecoderCBatchNorm(nn.Module):\n ''' Decoder with conditional batch normalization (CBN) class.\n Args:\n dim (int): input dimension\n z_dim (int): dimension of latent code z\n c_dim (int): dimension of latent conditioned code c\n hidden_size (int): hidden size of Decoder network\n leaky (bool): whether to use leaky ReLUs\n legacy (bool): whether to use the legacy structure\n '''\n\n def __init__(self, dim=3, z_dim=128, c_dim=128,\n hidden_size=256, leaky=False, legacy=False):\n super().__init__()\n self.z_dim = z_dim\n if not z_dim == 0:\n self.fc_z = nn.Linear(z_dim, hidden_size)\n\n self.fc_p = nn.Conv1d(dim, hidden_size, 1)\n self.block0 = CResnetBlockConv1d(c_dim, hidden_size, legacy=legacy)\n self.block1 = CResnetBlockConv1d(c_dim, hidden_size, legacy=legacy)\n self.block2 = CResnetBlockConv1d(c_dim, hidden_size, legacy=legacy)\n self.block3 = CResnetBlockConv1d(c_dim, hidden_size, legacy=legacy)\n self.block4 = CResnetBlockConv1d(c_dim, hidden_size, legacy=legacy)\n\n if not legacy:\n self.bn = CBatchNorm1d(c_dim, hidden_size)\n else:\n self.bn = CBatchNorm1d_legacy(c_dim, hidden_size)\n\n self.fc_out = nn.Conv1d(hidden_size, 1, 1)\n\n if not leaky:\n self.actvn = F.relu\n else:\n self.actvn = lambda x: F.leaky_relu(x, 0.2)\n\n def forward(self, p, z, c, **kwargs):\n p = p.transpose(1, 2)\n batch_size, D, T = p.size()\n net = self.fc_p(p)\n\n if self.z_dim != 0:\n net_z = self.fc_z(z).unsqueeze(2)\n net = net + net_z\n\n net = self.block0(net, c)\n net = self.block1(net, c)\n net = self.block2(net, c)\n net = self.block3(net, c)\n net = self.block4(net, c)\n\n out = self.fc_out(self.actvn(self.bn(net, c)))\n out = out.squeeze(1)\n\n return out\n\n\ndef get_prior_z(device):\n ''' Returns prior distribution for latent code z.\n Args:\n cfg (dict): imported yaml config\n device (device): pytorch device\n '''\n z_dim = 0\n p0_z = dist.Normal(\n torch.zeros(z_dim, device = device),\n torch.ones(z_dim, device = device)\n )\n\n return p0_z\n\nclass CBatchNorm1d(nn.Module):\n ''' Conditional batch normalization layer class.\n Args:\n c_dim (int): dimension of latent conditioned code c\n f_dim (int): feature dimension\n norm_method (str): normalization method\n '''\n\n def __init__(self, c_dim, f_dim, norm_method='batch_norm'):\n super().__init__()\n self.c_dim = c_dim\n self.f_dim = f_dim\n self.norm_method = norm_method\n # Submodules\n self.conv_gamma = nn.Conv1d(c_dim, f_dim, 1)\n self.conv_beta = nn.Conv1d(c_dim, f_dim, 1)\n if norm_method == 'batch_norm':\n self.bn = nn.BatchNorm1d(f_dim, affine=False)\n elif norm_method == 'instance_norm':\n self.bn = nn.InstanceNorm1d(f_dim, affine=False)\n elif norm_method == 'group_norm':\n self.bn = nn.GroupNorm1d(f_dim, affine=False)\n else:\n raise ValueError('Invalid normalization method!')\n self.reset_parameters()\n\n def reset_parameters(self):\n nn.init.zeros_(self.conv_gamma.weight)\n nn.init.zeros_(self.conv_beta.weight)\n nn.init.ones_(self.conv_gamma.bias)\n nn.init.zeros_(self.conv_beta.bias)\n\n def forward(self, x, c):\n assert(x.size(0) == c.size(0))\n assert(c.size(1) == self.c_dim)\n\n # c is assumed to be of size batch_size x c_dim x T\n if len(c.size()) == 2:\n c = c.unsqueeze(2)\n\n # Affine mapping\n gamma = self.conv_gamma(c)\n beta = self.conv_beta(c)\n\n # Batchnorm\n net = self.bn(x)\n out = gamma * net + beta\n\n return out\n\n\nclass CResnetBlockConv1d(nn.Module):\n ''' Conditional batch normalization-based Resnet block class.\n Args:\n c_dim (int): dimension of latend conditioned code c\n size_in (int): input dimension\n size_out (int): output dimension\n size_h (int): hidden dimension\n norm_method (str): normalization method\n legacy (bool): whether to use legacy blocks \n '''\n\n def __init__(self, c_dim, size_in, size_h=None, size_out=None,\n norm_method='batch_norm', legacy=False):\n super().__init__()\n # Attributes\n if size_h is None:\n size_h = size_in\n if size_out is None:\n size_out = size_in\n\n self.size_in = size_in\n self.size_h = size_h\n self.size_out = size_out\n # Submodules\n if not legacy:\n self.bn_0 = CBatchNorm1d(\n c_dim, size_in, norm_method=norm_method)\n self.bn_1 = CBatchNorm1d(\n c_dim, size_h, norm_method=norm_method)\n else:\n self.bn_0 = CBatchNorm1d_legacy(\n c_dim, size_in, norm_method=norm_method)\n self.bn_1 = CBatchNorm1d_legacy(\n c_dim, size_h, norm_method=norm_method)\n\n self.fc_0 = nn.Conv1d(size_in, size_h, 1)\n self.fc_1 = nn.Conv1d(size_h, size_out, 1)\n self.actvn = nn.ReLU()\n\n if size_in == size_out:\n self.shortcut = None\n else:\n self.shortcut = nn.Conv1d(size_in, size_out, 1, bias=False)\n # Initialization\n nn.init.zeros_(self.fc_1.weight)\n\n def forward(self, x, c):\n net = self.fc_0(self.actvn(self.bn_0(x, c)))\n dx = self.fc_1(self.actvn(self.bn_1(net, c)))\n\n if self.shortcut is not None:\n x_s = self.shortcut(x)\n else:\n x_s = x\n\n return x_s + dx\n\n\n\nclass OccupancyNetwork(nn.Module):\n ''' Occupancy Network class.\n Args:\n decoder (nn.Module): decoder network\n encoder (nn.Module): encoder network\n p0_z (dist): prior distribution for latent code z\n device (device): torch device\n '''\n\n def __init__(self, device):\n super().__init__()\n self.device = device\n self.decoder = DecoderCBatchNorm(dim=3, z_dim=0, c_dim=256,\n hidden_size=256).to(self.device)\n self.encoder = Resnet18(256, normalize=True, use_linear=True).to(self.device)\n\n self.p0_z = get_prior_z(self.device)\n\n def forward(self, p, inputs, sample=True, **kwargs):\n ''' Performs a forward pass through the network.\n Args:\n p (tensor): sampled points\n inputs (tensor): conditioning input\n sample (bool): whether to sample for z\n '''\n batch_size = p.size(0)\n c = self.encode_inputs(inputs)\n z = self.get_z_from_prior((batch_size,), sample=sample)\n p_r = self.decode(p, z, c, **kwargs)\n return p_r\n\n def compute_elbo(self, p, occ, inputs, **kwargs):\n ''' Computes the expectation lower bound.\n Args:\n p (tensor): sampled points\n occ (tensor): occupancy values for p\n inputs (tensor): conditioning input\n '''\n c = self.encode_inputs(inputs)\n q_z = self.infer_z(p, occ, c, **kwargs)\n z = q_z.rsample()\n p_r = self.decode(p, z, c, **kwargs)\n\n rec_error = -p_r.log_prob(occ).sum(dim=-1)\n kl = dist.kl_divergence(q_z, self.p0_z).sum(dim=-1)\n elbo = -rec_error - kl\n\n return elbo, rec_error, kl\n\n def encode_inputs(self, inputs):\n ''' Encodes the input.\n Args:\n input (tensor): the input\n '''\n c = self.encoder(inputs)\n \n\n return c\n\n def decode(self, p, z, c, **kwargs):\n ''' Returns occupancy probabilities for the sampled points.\n Args:\n p (tensor): points\n z (tensor): latent code z\n c (tensor): latent conditioned code c\n '''\n\n logits = self.decoder(p, z, c, **kwargs)\n p_r = dist.Bernoulli(logits=logits)\n return p_r\n\n def infer_z(self, p, occ, c, **kwargs):\n ''' Infers z.\n Args:\n p (tensor): points tensor\n occ (tensor): occupancy values for occ\n c (tensor): latent conditioned code c\n '''\n \n batch_size = p.size(0)\n mean_z = torch.empty(batch_size, 0).to(self.device)\n logstd_z = torch.empty(batch_size, 0).to(self.device)\n\n q_z = dist.Normal(mean_z, torch.exp(logstd_z))\n\n return q_z\n\n def get_z_from_prior(self, size=torch.Size([]), sample=True):\n ''' Returns z from prior distribution.\n Args:\n size (Size): size of z\n sample (bool): whether to sample\n '''\n if sample:\n z = self.p0_z.sample(size).to(self.device)\n else:\n z = self.p0_z.mean.to(self.device)\n z = z.expand(*size, *z.size())\n\n return z\n\n ", "# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport pytest\n\nimport torch\nimport sys\nimport os\n\nimport kaolin as kal\nfrom kaolin.rep import TriangleMesh\nfrom kaolin.rep import QuadMesh\n\n\ndef test_load_obj(device = 'cpu'): \n\tmesh = TriangleMesh.from_obj(('tests/model.obj') )\n\tif device == 'cuda': \n\t\tmesh.cuda()\n\tassert mesh.vertices.shape[0] > 0 \n\tassert mesh.vertices.shape[1] == 3 \n\tassert mesh.faces.shape[0] > 0 \n\tassert mesh.faces.shape[1] == 3 \n\n\tmesh = TriangleMesh.from_obj('tests/model.obj', with_vt=True, texture_res = 4) \n\tif device == 'cuda': \n\t\tmesh.cuda()\n\tassert mesh.textures.shape[0] > 0 \n\n\tmesh = TriangleMesh.from_obj('tests/model.obj', with_vt=True, texture_res = 4, enable_adjacency = True)\n\tassert mesh.vv.shape[0] > 0 \n\tassert mesh.edges.shape[0] > 0\n\tassert mesh.vv_count.shape[0] > 0\n\tassert mesh.ve.shape[0] > 0\n\tassert mesh.ve_count.shape[0] > 0\n\tassert mesh.ff.shape[0] > 0\n\tassert mesh.ff_count.shape[0] > 0\n\tassert mesh.ef.shape[0] > 0\n\tassert mesh.ef_count.shape[0] > 0\n\tassert mesh.ee.shape[0] > 0\n\tassert mesh.ee_count.shape[0] > 0\n\tif device == 'cuda': \n\t\tmesh.cuda()\n\ndef test_from_tensors(device='cpu'): \n\tmesh = TriangleMesh.from_obj('tests/model.obj', with_vt=True, texture_res = 4)\n\tif device == 'cuda': \n\t\tmesh.cuda()\n\n\tverts = mesh.vertices.clone()\n\tfaces = mesh.faces.clone() \n\tuvs = mesh.uvs.clone()\n\tface_textures = mesh.face_textures.clone()\n\ttextures = mesh.textures.clone()\n\t\n\tmesh = TriangleMesh.from_tensors(verts, faces, uvs = uvs, face_textures = face_textures,\n\t\t\t textures=textures)\n\n\t\ndef test_sample_mesh( device = 'cpu'):\n\tmesh = TriangleMesh.from_obj('tests/model.obj')\n\tif device == 'cuda': \n\t\tmesh.cuda() \n\t\n\tpoints, choices = mesh.sample(100)\n\tassert (set(points.shape) == set([100, 3])) \n\tpoints, choices = mesh.sample(10000)\n\tassert (set(points.shape) == set([10000, 3])) \n\ndef test_laplacian_smoothing(device = 'cpu'): \n\tmesh = TriangleMesh.from_obj(('tests/model.obj'))\n\tif device == 'cuda': \n\t\tmesh.cuda()\n\tv1 = mesh.vertices.clone()\n\tmesh.laplacian_smoothing(iterations = 3)\n\tv2 = mesh.vertices.clone()\n\tassert (torch.abs(v1 - v2)).sum() >0 \n\ndef test_compute_laplacian(device = 'cpu'): \n\tmesh = TriangleMesh.from_obj(('tests/model.obj'))\n\tif device == 'cuda': \n\t\tmesh.cuda()\n\tlap = mesh.compute_laplacian()\n\tassert ((lap**2).sum(dim=1) > .1).sum() == 0 # asserting laplacian of sphere is small\n\ndef test_load_and_save_Tensors(device = 'cpu'): \n\tmesh1 = TriangleMesh.from_obj(('tests/model.obj'))\n\tif device == 'cuda': \n\t\tmesh1.cuda()\n\tmesh1.save_tensors('copy.npz')\n\tassert os.path.isfile('copy.npz')\n\tmesh2 = TriangleMesh.load_tensors ('copy.npz')\n\tif device == 'cuda': \n\t\tmesh2.cuda()\n\tassert (torch.abs(mesh1.vertices - mesh2.vertices)).sum() ==0\n\tassert (torch.abs(mesh1.faces - mesh2.faces)).sum() ==0\n\tos.remove(\"copy.npz\")\n\ndef test_adj_computations(device = 'cpu'): \n\tmesh = TriangleMesh.from_obj(('tests/model.obj'))\n\tif device == 'cuda': \n\t\tmesh.cuda()\n\n\tadj_full = mesh.compute_adjacency_matrix_full()\n\tadj_sparse = mesh.compute_adjacency_matrix_sparse().coalesce()\n\n\tassert adj_full.shape[0] == mesh.vertices.shape[0]\n\tassert ((adj_full-adj_sparse.to_dense()) != 0).sum() == 0 \n\n\n\ndef test_load_obj_gpu(): \n\ttest_load_obj(\"cuda\")\ndef test_from_tensors_gpu(): \n\ttest_from_tensors(\"cuda\")\ndef test_sample_mesh_gpu(): \n\ttest_sample_mesh(\"cuda\")\ndef test_laplacian_smoothing_gpu(): \n\ttest_laplacian_smoothing(\"cuda\")\ndef test_compute_laplacian_gpu(): \n\ttest_compute_laplacian(\"cuda\")\ndef test_load_and_save_Tensors_gpu(): \n\ttest_load_and_save_Tensors(\"cuda\")\ndef test_adj_computations_gpu(): \n\ttest_adj_computations(\"cuda\")", "# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport argparse\nimport os\nimport torch\nimport sys\nfrom tqdm import tqdm\nfrom PIL import Image\nimport numpy as np\n\nfrom torch.utils.data import DataLoader\n\nfrom utils import preprocess\nfrom architectures import Encoder\nimport kaolin as kal \n\nparser = argparse.ArgumentParser()\nparser.add_argument('-expid', type=str, default='Direct', help='Unique experiment identifier.')\nparser.add_argument('-device', type=str, default='cuda', help='Device to use')\nparser.add_argument('-categories', type=str,nargs='+', default=['chair'], help='list of object classes to use')\nparser.add_argument('-vis', action='store_true', help='Visualize each model while evaluating')\nparser.add_argument('-batchsize', type=int, default=16, help='Batch size.')\nparser.add_argument('-f_score', action='store_true', help='compute F-score')\nargs = parser.parse_args()\n\n\n# Data\npoints_set_valid = kal.dataloader.ShapeNet.Points(root ='../../datasets/',categories =args.categories , \\\n\tdownload = True, train = False, split = .7, num_points=5000 )\nimages_set_valid = kal.dataloader.ShapeNet.Images(root ='../../datasets/',categories =args.categories , \\\n\tdownload = True, train = False, split = .7, views=1, transform= preprocess )\nmeshes_set_valid = kal.dataloader.ShapeNet.Meshes(root ='../../datasets/', categories =args.categories , \\\n\tdownload = True, train = False, split = .7)\n\nvalid_set = kal.dataloader.ShapeNet.Combination([points_set_valid, images_set_valid], root='../../datasets/')\ndataloader_val = DataLoader(valid_set, batch_size=args.batchsize, shuffle=False, \n\tnum_workers=8)\n# Model\nmesh = kal.rep.TriangleMesh.from_obj('386.obj')\nif args.device == \"cuda\": \n\tmesh.cuda()\ninitial_verts = mesh.vertices.clone()\n\n\nmodel = Encoder(4, 5, args.batchsize, 137, mesh.vertices.shape[0] ).to(args.device)\n# Load saved weights\nmodel.load_state_dict(torch.load('log/{0}/best.pth'.format(args.expid)))\n\nloss_epoch = 0.\nf_epoch = 0.\nnum_batches = 0\nnum_items = 0\nloss_fn = kal.metrics.point.chamfer_distance\n\nmodel.eval()\nwith torch.no_grad():\n\tfor data in tqdm(dataloader_val): \n\t\t# data creation\n\t\ttgt_points = data['points'].to(args.device)\n\t\tinp_images = data['imgs'].to(args.device)\n\n\t\t# inference \n\t\tdelta_verts = model(inp_images)\n\n\t\t# eval \n\t\t\n\t\tloss = 0. \n\t\tfor deltas, tgt, img in zip(delta_verts, tgt_points, inp_images): \t\n\t\t\tmesh.vertices = deltas + initial_verts\n\t\t\tpred_points, _ = mesh.sample(3000)\n\t\t\tloss += 3000* loss_fn(pred_points, tgt) / float(args.batchsize)\n\n\t\t\tif args.f_score: \n\t\t\t\n\t\t\t\tf_score = kal.metrics.point.f_score(tgt, pred_points, extend = False)\n\t\t\t\tf_epoch += (f_score / float(args.batchsize)).item()\n\n\t\t\tif args.vis: \n\t\t\t\ttgt_mesh = meshes_set_valid[num_items]\n\t\t\t\ttgt_verts = tgt_mesh['verts']\n\t\t\t\ttgt_faces = tgt_mesh['faces']\n\t\t\t\ttgt_mesh = kal.rep.TriangleMesh.from_tensors(tgt_verts, tgt_faces)\n\n\t\t\t\tprint ('Displaying input image')\n\t\t\t\timg = img.data.cpu().numpy().transpose((1, 2, 0))\n\t\t\t\timg = (img*255.).astype(np.uint8)\n\t\t\t\tImage.fromarray(img).show()\n\t\t\t\tprint ('Rendering Target Mesh')\n\t\t\t\tkal.visualize.show_mesh(tgt_mesh)\n\t\t\t\tprint ('Rendering Predicted Mesh')\n\t\t\t\tkal.visualize.show_mesh(mesh)\n\t\t\t\tprint('----------------------')\n\t\t\t\tnum_items += 1\n\n\n\t\tloss_epoch += loss.item()\n\t\t\n\t\t\n\t\tnum_batches += 1.\n\nout_loss = loss_epoch / float(num_batches)\nprint ('Loss over validation set is {0}'.format(out_loss))\nif args.f_score: \n\tout_f = f_epoch / float(num_batches)\n\tprint ('F-score over validation set is {0}'.format(out_f))\n", "# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Dict, Optional, Union\n\nimport torch\n\nfrom .engine import Engine\n\n\nclass ClassificationEngine(Engine):\n r\"\"\"An ``Engine`` that runs the training/validation/inference process for\n a classification task.\n\n Example:\n >>> engine = ClassificationEngine(model, train_loader, val_loader)\n\n \"\"\"\n\n def __init__(self, model: torch.nn.Module,\n train_loader: torch.utils.data.DataLoader,\n val_loader: torch.utils.data.DataLoader,\n optimizer: Optional[torch.optim.Optimizer] = None,\n hyperparams: Optional[Dict] = {},\n engineparams: Optional[Dict] = {},\n criterion: Optional[torch.nn.Module] = None,\n device: Optional[Union[torch.device, str]] = None\n ):\n # Model to be trained.\n self.model = model\n # Train dataloader.\n self.train_loader = train_loader\n # Validataion dataloader.\n self.val_loader = val_loader\n # Hyperaparameters (learning rate, momentum, etc.).\n self.hyperparams = self.initialize_hyperparams(hyperparams)\n # Engine parameters (number of epochs to train for, etc.)\n self.engineparams = self.initialize_engineparams(engineparams)\n # Optimizer.\n if optimizer is None:\n self.optimizer = self.initialize_optimizer()\n else:\n self.optimizer = optimizer\n # Loss function to use\n if criterion is None:\n self.criterion = torch.nn.CrossEntropyLoss()\n else:\n self.criterion = criterion\n # Device\n if device is None:\n self.device = 'cpu'\n else:\n self.device = device\n\n # Cast model to device.\n self.model = self.model.to(self.device)\n\n \"\"\"\n Engine stats.\n \"\"\"\n\n self.current_epoch = 0\n # Train loss/accuracy for the current epoch.\n self.train_loss_cur_epoch = 0.\n self.train_accuracy_cur_epoch = 0.\n # Validation loss/accuracy for the current epoch.\n self.val_loss_cur_epoch = 0.\n self.val_accuracy_cur_epoch = 0.\n # Number of minibatches thus far, in the current epoch.\n # This variable is reused across train/val phases.\n self.batch_idx = 0\n # Train loss/accuracy history.\n self.train_loss = []\n self.train_accuracy = []\n # Validation loss/accuracy history.\n self.val_loss = []\n self.val_accuracy = []\n\n def initialize_hyperparams(self, hyperparams: Dict):\n r\"\"\"Initializes hyperparameters for the training process. Uses defaults\n wherever user specifications are unavailable.\n\n Args:\n hyperparams (dict): User-specified hyperparameters ('lr', 'beta1',\n 'beta2' for Adam).\n\n \"\"\"\n paramdict = {}\n\n if 'lr' in hyperparams:\n paramdict['lr'] = hyperparams['lr']\n else:\n paramdict['lr'] = 1e-3\n if 'beta1' in hyperparams:\n paramdict['beta1'] = hyperparams['beta1']\n else:\n paramdict['beta1'] = 0.9\n if 'beta2' in hyperparams:\n paramdict['beta2'] = hyperparams['beta2']\n else:\n paramdict['beta2'] = 0.999\n\n return paramdict\n\n def initialize_engineparams(self, engineparams: Dict):\n r\"\"\"Initializes engine parameters. Uses defaults wherever user\n specified values are unavilable.\n\n Args:\n engineparams (dict): User-specified engine parameters ('epochs',\n 'validate-every', 'print-every', 'save', 'savedir').\n 'epochs': number of epochs to train for.\n 'validate-every': number of epochs after which validation\n occurs.\n 'print-every': number of iterations (batches) after which to\n keep printing progress to stdout.\n 'save': whether or not to save trained models.\n 'savedir': directory to save trained models to.\n\n \"\"\"\n paramdict = {}\n\n if 'epochs' in engineparams:\n paramdict['epochs'] = engineparams['epochs']\n else:\n paramdict['epochs'] = 10\n if 'validate-every' in engineparams:\n paramdict['validate-every'] =\\\n engineparams['validate-every']\n else:\n paramdict['validate-every'] = 2\n if 'print-every' in engineparams:\n paramdict['print-every'] = engineparams['print-every']\n else:\n paramdict['print-every'] = 10\n if 'save' in engineparams:\n paramdict['save'] = engineparams['save']\n else:\n paramdict['save'] = False\n # Currently, we do not set a default 'savedir'.\n if 'savedir' in engineparams:\n paramdict['savedir'] = engineparams['savedir']\n\n return paramdict\n\n def initialize_optimizer(self):\n r\"\"\"Initializes the optimizer. By default, uses the Adam optimizer with\n the specified hyperparameter for learning-rates, beta1, and beta2.\n\n \"\"\"\n return torch.optim.Adam(self.model.parameters(),\n lr=self.hyperparams['lr'],\n betas=(self.hyperparams['beta1'],\n self.hyperparams['beta2']))\n\n def train_batch(self, batch):\n r\"\"\"Train for one mini-batch.\n\n Args:\n batch (tuple): One mini-batch of training data.\n\n \"\"\"\n data, attr = batch\n data = data.to(self.device)\n label = attr['category'].to(self.device)\n pred = self.model(data)\n loss = self.criterion(pred, label.view(-1))\n self.train_loss_cur_epoch += loss.item()\n predlabel = torch.argmax(pred, dim=1)\n accuracy = torch.mean((predlabel == label.view(-1)).float())\n self.train_accuracy_cur_epoch += accuracy.detach().cpu().item()\n self.batch_idx += 1\n return loss, accuracy\n\n def validate_batch(self, batch):\n r\"\"\"Validate for one mini-batch.\n\n Args:\n batch (tuple): One mini-batch of validateion data.\n\n \"\"\"\n data, attr = batch\n data = data.to(self.device)\n label = attr['category'].to(self.device)\n pred = self.model(data)\n loss = self.criterion(pred, label.view(-1))\n self.val_loss_cur_epoch += loss.item()\n predlabel = torch.argmax(pred, dim=1)\n accuracy = torch.mean((predlabel == label.view(-1)).float())\n self.val_accuracy_cur_epoch += accuracy.detach().cpu().item()\n self.batch_idx += 1\n return loss, accuracy\n\n def optimize_batch(self, loss):\n r\"\"\"Optimize model parameters for one mini-batch.\n\n Args:\n loss: training loss computed over the mini-batch.\n \"\"\"\n loss.backward()\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n def fit(self):\n r\"\"\"Train the model using the specified engine parameters.\n \"\"\"\n\n for epoch in range(self.engineparams['epochs']):\n\n # Train phase\n \n self.train_loss_cur_epoch = 0.\n self.train_accuracy_cur_epoch = 0.\n self.batch_idx = 0\n\n self.model.train()\n\n for idx, batch in enumerate(self.train_loader):\n loss, accuracy = self.train_batch(batch)\n self.optimize_batch(loss)\n self.print_train_stats()\n self.train_accuracy.append(self.train_accuracy_cur_epoch\\\n / self.batch_idx)\n\n # Validation phase\n\n self.val_loss_cur_epoch = 0.\n self.val_accuracy_cur_epoch = 0.\n self.batch_idx = 0\n\n self.model.eval()\n\n with torch.no_grad():\n for idx, batch in enumerate(self.val_loader):\n loss, accuracy = self.validate_batch(batch)\n self.print_validation_stats()\n self.val_accuracy.append(self.val_accuracy_cur_epoch\\\n / self.batch_idx)\n\n self.current_epoch += 1\n\n def print_train_stats(self):\n r\"\"\"Print current stats.\n \"\"\"\n print('Epoch: {0}, Train loss: {1}, Train accuracy: {2}'.format(\n self.current_epoch, self.train_loss_cur_epoch / self.batch_idx,\n self.train_accuracy_cur_epoch / self.batch_idx))\n\n def print_validation_stats(self):\n r\"\"\"Print current stats.\n \"\"\"\n print('Epoch: {0}, Val loss: {1}, Val accuracy: {2}'.format(\n self.current_epoch, self.val_loss_cur_epoch / self.batch_idx,\n self.val_accuracy_cur_epoch / self.batch_idx))\n", "# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport os\nimport argparse\nimport torch\n\nfrom architectures import Generator\nimport kaolin as kal \n\n\ntorch.manual_seed(0)\ntorch.cuda.manual_seed(0)\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--logdir', type=str, default='log', help='Directory to log data to.')\nparser.add_argument('--expid', type=str, default='3D_IWGAN', help='Unique experiment identifier.')\nparser.add_argument('--device', type=str, default='cuda', help='Device to use.')\nparser.add_argument('--batchsize', type=int, default=50, help='Batch size.')\nargs = parser.parse_args()\n\nlogdir = os.path.join(args.logdir, args.expid)\n\ngen = Generator().to(args.device)\ngen.load_state_dict(torch.load(os.path.join(logdir, 'gen.pth')))\ngen.eval()\n\nz = torch.normal(torch.zeros(args.batchsize, 200), torch.ones(args.batchsize, 200)).to(args.device)\n\nfake_voxels = gen(z)\n\nfor i, model in enumerate(fake_voxels): \n print('Rendering model {}'.format(i))\n model = model[:-2, :-2, :-2]\n model = kal.transforms.voxelfunc.max_connected(model, .7)\n verts, faces = kal.conversions.voxelgrid_to_quadmesh(model)\n mesh = kal.rep.QuadMesh.from_tensors(verts, faces)\n mesh.laplacian_smoothing(iterations=3)\n mesh.show()\n", "# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is 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\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n\nfrom __future__ import print_function\nfrom __future__ import division\n\nfrom ..rasterizer import linear_rasterizer\nfrom ..utils import datanormalize\nfrom .fragment_shaders.frag_tex import fragmentshader\nfrom .vertex_shaders.perpsective import perspective_projection\nimport torch\nimport torch.nn as nn\n\n\n##################################################################\nclass TexRender(nn.Module):\n\n def __init__(self, height, width, filtering='nearest'):\n super(TexRender, self).__init__()\n\n self.height = height\n self.width = width\n self.filtering = filtering\n\n def forward(self,\n points,\n cameras,\n uv_bxpx2,\n texture_bx3xthxtw,\n ft_fx3=None):\n\n ##############################################################\n # first, MVP projection in vertexshader\n points_bxpx3, faces_fx3 = points\n\n # use faces_fx3 as ft_fx3 if not given\n if ft_fx3 is None:\n ft_fx3 = faces_fx3\n\n # camera_rot_bx3x3, camera_pos_bx3, camera_proj_3x1 = cameras\n\n points3d_bxfx9, points2d_bxfx6, normal_bxfx3 = \\\n perspective_projection(points_bxpx3, faces_fx3, cameras)\n\n ################################################################\n # normal\n\n # decide which faces are front and which faces are back\n normalz_bxfx1 = normal_bxfx3[:, :, 2:3]\n # normalz_bxfx1 = torch.abs(normalz_bxfx1)\n\n # normalize normal\n normal1_bxfx3 = datanormalize(normal_bxfx3, axis=2)\n\n ############################################################\n # second, rasterization\n c0 = uv_bxpx2[:, ft_fx3[:, 0], :]\n c1 = uv_bxpx2[:, ft_fx3[:, 1], :]\n c2 = uv_bxpx2[:, ft_fx3[:, 2], :]\n mask = torch.ones_like(c0[:, :, :1])\n uv_bxfx9 = torch.cat((c0, mask, c1, mask, c2, mask), dim=2)\n\n imfeat, improb_bxhxwx1 = linear_rasterizer(\n self.height,\n self.width,\n points3d_bxfx9,\n points2d_bxfx6,\n normalz_bxfx1,\n uv_bxfx9\n )\n\n imtexcoords = imfeat[:, :, :, :2]\n hardmask = imfeat[:, :, :, 2:3]\n\n # fragrement shader\n imrender = fragmentshader(imtexcoords, texture_bx3xthxtw, hardmask,\n filtering=self.filtering)\n\n return imrender, improb_bxhxwx1, normal1_bxfx3\n", "\"\"\"\nNetwork architecture definitions\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass EncoderDecoder_32_128(nn.Module):\n def __init__(self):\n super(EncoderDecoder_32_128, self).__init__()\n\n self.encoder = nn.Sequential(\n nn.Conv3d(1, 16, 3, stride=2, padding=0),\n nn.BatchNorm3d(16),\n nn.ReLU(),\n nn.Conv3d(16, 32, 3, stride=2, padding=1),\n nn.BatchNorm3d(32),\n nn.ReLU()\n )\n self.decoder = nn.Sequential(\n nn.ConvTranspose3d(32, 16, 3, stride=2, padding=0),\n nn.BatchNorm3d(16),\n nn.ReLU(),\n nn.ConvTranspose3d(16, 8, 3, stride=2, padding=0),\n nn.BatchNorm3d(8),\n nn.ReLU(),\n nn.ConvTranspose3d(8, 4, 3, stride=2, padding=0),\n nn.BatchNorm3d(4),\n nn.ReLU(),\n nn.ConvTranspose3d(4, 1, 3, stride=2, padding=0),\n )\n\n def forward(self, x):\n\n x = self.encoder(x)\n x = self.decoder(x)\n\n return torch.sigmoid(x)[:, 0, :128, :128, :128]\n\n\nclass EncoderDecoderForNLL_32_128(nn.Module):\n def __init__(self):\n super(EncoderDecoderForNLL_32_128, self).__init__()\n\n self.encoder = nn.Sequential(\n nn.Conv3d(1, 16, 3, stride=2, padding=1),\n nn.BatchNorm3d(16),\n nn.ReLU(),\n nn.Conv3d(16, 32, 3, stride=2, padding=1),\n nn.BatchNorm3d(32),\n nn.ReLU()\n )\n self.decoder = nn.Sequential(\n nn.ConvTranspose3d(32, 16, 3, stride=2, padding=0),\n nn.BatchNorm3d(16),\n nn.ReLU(),\n nn.ConvTranspose3d(16, 8, 3, stride=2, padding=0),\n nn.BatchNorm3d(8),\n nn.ReLU(),\n nn.ConvTranspose3d(8, 4, 3, stride=2, padding=0),\n nn.BatchNorm3d(4),\n nn.ReLU(),\n nn.ConvTranspose3d(4, 2, 3, stride=2, padding=0),\n )\n self.log_softmax = nn.LogSoftmax(dim=1)\n\n def forward(self, x):\n x = self.encoder(x)\n x = self.decoder(x)[:, :, :128, :128, :128]\n\n return torch.exp(self.log_softmax(x))\n" ]
[ [ "torch.nn.Sequential", "torch.Size", "torch.nn.BatchNorm1d", "torch.ones", "torch.empty", "torch.zeros", "torch.nn.InstanceNorm1d", "torch.distributions.Bernoulli", "torch.nn.GroupNorm1d", "torch.exp", "torch.nn.init.ones_", "torch.nn.Conv1d", "torch.nn.Linear", "torch.nn.functional.leaky_relu", "torch.nn.init.zeros_", "torch.distributions.kl_divergence", "torch.nn.ReLU" ], [ "torch.abs" ], [ "torch.no_grad", "torch.utils.data.DataLoader" ], [ "torch.nn.CrossEntropyLoss", "torch.no_grad", "torch.argmax" ], [ "torch.manual_seed", "torch.ones", "torch.cuda.manual_seed", "torch.zeros" ], [ "torch.ones_like", "torch.cat" ], [ "torch.sigmoid", "torch.nn.LogSoftmax", "torch.nn.ConvTranspose3d", "torch.nn.Conv3d", "torch.nn.ReLU", "torch.nn.BatchNorm3d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
DFKI-NLP/RelEx
[ "0826c02f793b78bf8b7b7001c2e3fdfdb25c1ad2", "0826c02f793b78bf8b7b7001c2e3fdfdb25c1ad2" ]
[ "relex/modules/offset_embedders/sine_offset_embedder.py", "relex/modules/offset_embedders/relative_offset_embedder.py" ]
[ "import torch\nimport numpy as np\nfrom allennlp.nn import util\nfrom relex.modules.offset_embedders import OffsetEmbedder\n\n\ndef position_encoding_init(n_position: int, embedding_dim: int):\n position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / embedding_dim)\n for j in range(embedding_dim)]\n if pos != 0 else np.zeros(embedding_dim)\n for pos in range(n_position)])\n\n # apply sin on 0th,2nd,4th...embedding_dim\n position_enc[1:, 0::2] = np.sin(position_enc[1:, 0::2])\n # apply cos on 1st,3rd,5th...embedding_dim\n position_enc[1:, 1::2] = np.cos(position_enc[1:, 1::2])\n return torch.from_numpy(position_enc).type(torch.FloatTensor)\n\n\[email protected](\"sine\")\nclass SineOffsetEmbedder(OffsetEmbedder):\n def __init__(self, n_position: int, embedding_dim: int) -> None:\n super(SineOffsetEmbedder, self).__init__()\n\n self._n_position = n_position\n self._embedding_dim = embedding_dim\n self._embedding = torch.nn.Embedding(2 * n_position + 1,\n embedding_dim,\n padding_idx=0)\n self._embedding.weight.data = position_encoding_init(2 * n_position + 1,\n embedding_dim)\n # TODO: add zero vector for padding\n\n def get_output_dim(self) -> int:\n return self._embedding_dim\n\n def is_additive(self) -> bool:\n return True\n\n def forward(self,\n inputs: torch.Tensor,\n mask: torch.Tensor,\n span: torch.Tensor) -> torch.Tensor:\n # pylint: disable=arguments-differ\n\n # input -> [B x seq_len x d], offset -> [B x 2]\n batch_size, seq_len, _ = inputs.size()\n\n offset = span[:, 0]\n position_range = util.get_range_vector(\n seq_len, util.get_device_of(inputs)).repeat((batch_size, 1))\n\n relative_positions = (1 + self._n_position\n + position_range\n - offset.unsqueeze(dim=1))\n\n # mask padding so it won't receive a positional embedding\n relative_positions = relative_positions * mask.long()\n\n return self._embedding(relative_positions)\n", "import torch\nfrom allennlp.nn import util\nfrom relex.modules.offset_embedders import OffsetEmbedder\n\n\[email protected](\"relative\")\nclass RelativeOffsetEmbedder(OffsetEmbedder):\n def __init__(self, n_position: int, embedding_dim: int) -> None:\n super(RelativeOffsetEmbedder, self).__init__()\n\n self._n_position = n_position\n self._embedding_dim = embedding_dim\n self._embedding = torch.nn.Embedding(2 * n_position + 1,\n embedding_dim,\n padding_idx=0)\n torch.nn.init.xavier_uniform_(self._embedding.weight.data)\n self._embedding.weight.data[self._embedding.padding_idx].fill_(0)\n\n def get_output_dim(self) -> int:\n return self._embedding_dim\n\n def is_additive(self) -> bool:\n return False\n\n def forward(self,\n inputs: torch.Tensor,\n mask: torch.Tensor,\n span: torch.Tensor) -> torch.Tensor:\n # pylint: disable=arguments-differ\n\n # input -> [B x seq_len x d], offset -> [B x 2]\n batch_size, seq_len, _ = inputs.size()\n\n pos_range = util.get_range_vector(\n seq_len, util.get_device_of(inputs)).repeat((batch_size, 1))\n\n start_offset = span[:, 0].unsqueeze(dim=1)\n end_offset = span[:, 1].unsqueeze(dim=1)\n\n left_mask = torch.lt(pos_range, start_offset).long()\n middle_mask = (torch.ge(pos_range, start_offset)\n * torch.le(pos_range, end_offset)).long()\n right_mask = torch.gt(pos_range, end_offset).long()\n\n offsets = start_offset * left_mask + end_offset * right_mask\n\n relative_positions = (1 + self._n_position\n + (pos_range - offsets) * (1 - middle_mask))\n\n # mask padding so it won't receive a positional embedding\n relative_positions = relative_positions * mask.long()\n\n return self._embedding(relative_positions)\n" ]
[ [ "numpy.power", "torch.from_numpy", "numpy.cos", "torch.nn.Embedding", "numpy.sin", "numpy.zeros" ], [ "torch.ge", "torch.lt", "torch.nn.Embedding", "torch.le", "torch.nn.init.xavier_uniform_", "torch.gt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
johnarban/arban
[ "dcd2d0838f72c39bf3a52aabfa74d6ea28933d02" ]
[ "schmidt_funcs.py" ]
[ "import numpy as np\nfrom PIL import Image, ImageDraw\nfrom scipy import interpolate, ndimage, stats, signal, integrate, misc\nfrom astropy.io import ascii, fits\nfrom astropy.wcs import WCS\nfrom astropy.coordinates import SkyCoord\nimport astropy.units as u\nimport astropy.constants as c\nimport corner as triangle # formerly dfm/triangle\n# from astropy.modeling import models, fitting\nfrom astropy.modeling.models import custom_model\nfrom astropy.modeling.fitting import LevMarLSQFitter # , SimplexLSQFitter\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport emcee\n#import ipdb;\nimport pdb\n\n# # # # # # # # # # # # # # # # # # # # # #\n# make iPython print immediately\nimport sys\noldsysstdout = sys.stdout\n\n\nclass flushfile():\n\n def __init__(self, f):\n self.f = f\n\n def __getattr__(self, name):\n return object.__getattribute__(self.f, name)\n\n def write(self, x):\n self.f.write(x)\n self.f.flush()\n\n def flush(self):\n self.f.flush()\n# sys.stdout = flushfile(sys.stdout)\n# sys.stdout = oldsysstdout\n\n\ndef rot_matrix(theta):\n '''\n rot_matrix(theta)\n 2D rotation matrix for theta in radians\n returns numpy matrix\n '''\n c, s = np.cos(theta), np.sin(theta)\n return np.matrix([[c, -s], [s, c]])\n\n\ndef rectangle(c, w, h, angle=0, center=True):\n '''\n create rotated rectangle\n for input into PIL ImageDraw.polygon\n to make a rectangle polygon mask\n\n Rectagle is created and rotated with center\n at zero, and then translated to center position\n\n accepters centers\n Default : center\n tl, tr, bl, br\n '''\n cx, cy = c\n # define initial polygon irrespective of center\n x = -w / 2., +w / 2., +w / 2., -w / 2.\n y = +h / 2., +h / 2., -h / 2., -h / 2.\n # correct center if starting from corner\n if center is not True:\n if center[0] == 'b':\n # y = tuple([i + h/2. for i in y])\n cy = cy + h / 2.\n else:\n # y = tuple([i - h/2. for i in y])\n cy = cy - h / 2.\n if center[1] == 'l':\n # x = tuple([i + w/2 for i in x])\n cx = cx + w / 2.\n else:\n # x = tuple([i - w/2 for i in x])\n cx = cx - w / 2.\n\n R = rot_matrix(angle * np.pi / 180.)\n c = []\n\n for i in range(4):\n xr, yr = np.dot(R, np.asarray([x[i], y[i]])).A.ravel()\n # coord switch to match ordering of FITs dimensions\n c.append((cx + xr, cy + yr))\n # print (cx,cy)\n return c\n\n\ndef comp(arr):\n '''\n returns the compressed version\n of the input array if it is a\n numpy MaskedArray\n '''\n try:\n return arr.compressed()\n except:\n return arr\n\n\ndef mavg(arr, n=2, mode='valid'):\n '''\n returns the moving average of an array.\n returned array is shorter by (n-1)\n '''\n if len(arr) > 400:\n return signal.fftconvolve(arr, [1. / float(n)] * n, mode=mode)\n else:\n return signal.convolve(arr, [1. / float(n)] * n, mode=mode)\n\n\ndef mgeo(arr, n=2):\n '''\n Returns array of lenth len(arr) - (n-1)\n\n # # written by me\n # # slower for short loops\n # # faster for n ~ len(arr) and large arr\n a = []\n for i in xrange(len(arr)-(n-1)):\n a.append(stats.gmean(arr[i:n+i]))\n\n # # Original method# #\n # # written by me ... ~10x faster for short arrays\n b = np.array([np.roll(np.pad(arr,(0,n),mode='constant',constant_values=1),i)\n for i in xrange(n)])\n return np.product(b,axis=0)[n-1:-n]**(1./float(n))\n '''\n a = []\n for i in range(len(arr) - (n - 1)):\n a.append(stats.gmean(arr[i:n + i]))\n\n return np.asarray(a)\n\n\ndef avg(arr, n=2):\n '''\n NOT a general averaging function\n return bin centers (lin and log)\n '''\n diff = np.diff(arr)\n # 2nd derivative of linear bin is 0\n if np.allclose(diff, diff[::-1]):\n return mavg(arr, n=n)\n else:\n return np.power(10., mavg(np.log10(arr), n=n))\n # return mgeo(arr, n=n) # equivalent methods, only easier\n\ndef shift_bins(arr,phase=0,nonneg=False):\n # assume original bins are nonneg\n if phase != 0:\n diff = np.diff(arr)\n if np.allclose(diff,diff[::-1]):\n diff = diff[0]\n arr = arr + phase*diff\n #pre = arr[0] + phase*diff\n return arr\n else:\n arr = np.log10(arr)\n diff = np.diff(arr)[0]\n arr = arr + phase * diff\n return np.power(10.,arr)\n else:\n return arr\n\ndef llspace(xmin, xmax, n=None, log=False, dx=None, dex=None):\n '''\n llspace(xmin, xmax, n = None, log = False, dx = None, dex = None)\n get values evenly spaced in linear or log spaced\n n [10] -- Optional -- number of steps\n log [false] : switch for log spacing\n dx : spacing for linear bins\n dex : spacing for log bins (in base 10)\n dx and dex override n\n '''\n xmin, xmax = float(xmin), float(xmax)\n nisNone = n is None\n dxisNone = dx is None\n dexisNone = dex is None\n if nisNone & dxisNone & dexisNone:\n print('Error: Defaulting to 10 linears steps')\n n = 10.\n nisNone = False\n\n # either user specifies log or gives dex and not dx\n log = log or (dxisNone and (not dexisNone))\n if log:\n if xmin == 0:\n print(\"log(0) is -inf. xmin must be > 0 for log spacing\")\n xmin, xmax = np.log10(xmin), np.log10(xmax)\n # print nisNone, dxisNone, dexisNone, log # for debugging logic\n if not nisNone: # this will make dex or dx if they are not specified\n if log and dexisNone: # if want log but dex not given\n dex = (xmax - xmin) / n\n # print dex\n elif (not log) and dxisNone: # else if want lin but dx not given\n dx = (xmax - xmin) / n # takes floor\n #print dx\n\n if log:\n #return np.power(10, np.linspace(xmin, xmax , (xmax - xmin)/dex + 1))\n return np.power(10, np.arange(xmin, xmax + dex, dex))\n else:\n #return np.linspace(xmin, xmax, (xmax-xmin)/dx + 1)\n return np.arange(xmin, xmax + dx, dx)\n\n\ndef nametoradec(name):\n '''\n Get names formatted as\n hhmmss.ss+ddmmss to Decimal Degree\n only works for dec > 0 (splits on +, not -)\n Will fix this eventually...\n '''\n if 'string' not in str(type(name)):\n rightascen = []\n declinatio = []\n for n in name:\n ra, de = n.split('+')\n ra = ra[0:2] + ':' + ra[2:4] + ':' + ra[4:6] + '.' + ra[6:8]\n de = de[0:2] + ':' + de[2:4] + ':' + de[4:6]\n coord = SkyCoord(ra, de, frame='icrs',\n unit=('hourangle', 'degree'))\n rightascen.append(coord.ra.value)\n declinatio.append(coord.dec.value)\n return np.array(rightascen), np.array(declinatio)\n else:\n ra, de = name.split('+')\n ra = ra[0:2] + ':' + ra[2:4] + ':' + ra[4:6] + '.' + ra[6:8]\n de = de[0:2] + ':' + de[2:4] + ':' + de[4:6]\n coord = SkyCoord(ra, de, frame='icrs', unit=('hourangle', 'degree'))\n return np.array(coord.ra.value), np.array(coord.dec.value)\n\n\ndef get_ext(extmap, errmap, extwcs, ra, de):\n '''\n Get the extinction (errors) for a particular position or\n list of positions\n More generally get the value (error) for a particular\n position given a wcs and world coordinates\n '''\n try:\n xp, yp = extwcs.all_world2pix(\n np.array([ra]).flatten(), np.array([de]).flatten(), 0)\n except:\n xp, yp = WCS(extwcs).all_world2pix(\n np.array([ra]).flatten(), np.array([de]).flatten(), 0)\n ext = []\n err = []\n for i in range(len(np.array(xp))):\n try:\n ext.append(extmap[yp[int(round(i))], xp[int(round(i))]])\n if errmap is not None:\n err.append(errmap[yp[int(round(i))], xp[int(round(i))]])\n except IndexError:\n ext.append(np.nan)\n if errmap is not None:\n err.append(np.nan)\n if errmap is not None:\n return np.array(ext), np.array(err)\n else:\n return np.array(ext), None\n\n\ndef pdf(values, bins):\n '''\n ** Normalized differential area function. **\n (statistical) probability denisty function\n normalized so that the integral is 1\n and. The integral over a range is the\n probability of the value is within\n that range.\n\n Returns array of size len(bins)-1\n Plot versus bins[:-1]\n '''\n if hasattr(bins,'__getitem__'):\n range=(np.nanmin(bins),np.nanmax(bins))\n else:\n range = None\n\n h, x = np.histogram(values, bins=bins, range=range, density=False)\n # From the definition of Pr(x) = dF(x)/dx this\n # is the correct form. It returns the correct\n # probabilities when tested\n pdf = h / (np.sum(h, dtype=float) * np.diff(x))\n return pdf, avg(x)\n\n\ndef pdf2(values, bins):\n '''\n The ~ PDF normalized so that\n the integral is equal to the\n total amount of a quantity.\n The integral over a range is the\n total amount within that range.\n\n Returns array of size len(bins)-1\n Plot versus bins[:-1]\n '''\n if hasattr(bins,'__getitem__'):\n range=(np.nanmin(bins),np.nanmax(bins))\n else:\n range = None\n\n pdf, x = np.histogram(values, bins=bins, range=range, density=False)\n pdf = pdf.astype(float) / np.diff(x)\n return pdf, avg(x)\n\n\ndef edf(data, pdf=False):\n y = np.arange(len(data), dtype=float)\n x = np.sort(data).astype(float)\n return y, x\n\n\ndef cdf(values, bins):\n '''\n (statistical) cumulative distribution function\n Integral on [-inf, b] is the fraction below b.\n CDF is invariant to binning.\n This assumes you are using the entire range in the binning.\n Returns array of size len(bins)\n Plot versus bins[:-1]\n '''\n if hasattr(bins,'__getitem__'):\n range = (np.nanmin(bins),np.nanmax(bins))\n else:\n range = None\n\n h, bins = np.histogram(values, bins=bins, range=range, density=False) # returns int\n\n c = np.cumsum(h / np.sum(h, dtype=float)) # cumulative fraction below bin_k\n # append 0 to beginning because P( X < min(x)) = 0\n return np.append(0, c), bins\n\n\ndef cdf2(values, bins):\n '''\n # # Exclusively for area_function which needs to be unnormalized\n (statistical) cumulative distribution function\n Value at b is total amount below b.\n CDF is invariante to binning\n\n Plot versus bins[:-1]\n Not normalized to 1\n '''\n if hasattr(bins,'__getitem__'):\n range=(np.nanmin(bins),np.nanmax(bins))\n else:\n range = None\n\n h, bins = np.histogram(values, bins=bins, range=range, density=False)\n c = np.cumsum(h).astype(float)\n return np.append(0., c), bins\n\n\ndef area_function(extmap, bins):\n '''\n Complimentary CDF for cdf2 (not normalized to 1)\n Value at b is total amount above b.\n '''\n c, bins = cdf2(extmap, bins)\n return c.max() - c, bins\n\n\ndef diff_area_function(extmap, bins,scale=1):\n '''\n See pdf2\n '''\n s, bins = area_function(extmap, bins)\n dsdx = -np.diff(s) / np.diff(bins)\n return dsdx*scale, avg(bins)\n\ndef log_diff_area_function(extmap, bins):\n '''\n See pdf2\n '''\n s, bins = diff_area_function(extmap, bins)\n g=s>0\n dlnsdlnx = np.diff(np.log(s[g])) / np.diff(np.log(bins[g]))\n return dlnsdlnx, avg(bins[g])\n\ndef mass_function(values, bins, scale=1, aktomassd=183):\n '''\n M(>Ak), mass weighted complimentary cdf\n '''\n if hasattr(bins,'__getitem__'):\n range=(np.nanmin(bins),np.nanmax(bins))\n else:\n range = None\n\n h, bins = np.histogram(values, bins=bins, range=range, density=False, weights=values*aktomassd*scale)\n c = np.cumsum(h).astype(float)\n return c.max() - c, bins\n\n\ndef hist(values, bins, err=False, density=False, **kwargs):\n '''\n really just a wrapper for numpy.histogram\n '''\n if hasattr(bins,'__getitem__'):\n range=(np.nanmin(bins),np.nanmax(bins))\n else:\n range = None\n\n hist, x = np.histogram(values, bins=bins, range=range, density=density, **kwargs)\n if (err is None) or (err is False):\n return hist.astype(np.float), avg(x)\n else:\n return hist.astype(np.float), avg(x), np.sqrt(hist)\n\n\ndef bootstrap(X, X_err=None, n=None, smooth=False):\n '''\n (smooth) bootstrap\n bootstrap(X,Xerr,n,smooth=True)\n X : array to be resampled\n X_err [optional]: errors to perturb data for smooth bootstrap\n only provide is doing smooth bootstrapping\n n : number of samples. Default - len(X)\n smooth: optionally use smooth bootstrapping.\n will be set to False if no X_err is provided\n '''\n\n if X_err is None:\n smooth = False\n\n if n is None: # default n\n n = len(X)\n\n resample_i = np.random.randint(0,len(X),size=(n,))\n X_resample = np.asarray(X)[resample_i]\n\n if smooth:\n X_resample = np.random.normal(X_resample, \\\n np.asarray(X_err)[resample_i])\n\n return X_resample\n\n\ndef num_above(values, level):\n return np.sum((values >= level) & np.isfinite(values), dtype=np.float)\n\n\ndef num_below(values, level):\n return np.sum((values < level) & np.isfinite(values), dtype=np.float)\n\n\ndef alpha_ML(data, xmin,xmax):\n '''\n uses maximum likelihood to estimation\n to determine power-law and error\n From Clauset et al. 2010\n '''\n data = data[np.isfinite(data)]\n data = data[(data >= xmin) & (data <= xmax)]\n alpha = 1 + len(data) * (np.sum(np.log(data / xmin))**(-1))\n error = (alpha -1 )/np.sqrt(len(data))\n #loglike = np.sum((-1+alpha)*np.log(xmin)-alpha*np.log(data)+np.log(-1+alpha))\n N = len(data)\n loglike = N*np.log(alpha-1) - N*np.log(xmin) - alpha * np.sum(np.log(data/xmin))\n return alpha , error, loglike, xmin, xmax\n\ndef sigconf1d(n):\n cdf = (1/2.)*(1+special.erf(n/np.sqrt(2)))\n return (1-cdf)*100,100* cdf,100*special.erf(n/np.sqrt(2))\n\n\n\ndef surfd(X, Xmap, bins, Xerr = None, Xmaperr = None, boot=False, scale=1., return_err=False, smooth=False):\n '''\n call: surfd(X, map, bins,\n xerr = None, merr = None, scale = 1.)\n calculates H(X)/H(M) = Nx pdf(x) dx / Nm pdf(m) dm ; dm = dx\n so it is independent of whether dx or dlog(x)\n '''\n # get dn/dx\n if boot:\n n = np.histogram(bootstrap(X,Xerr,smooth=True), bins = bins, range=(bins.min(),bins.max()))[0]\n s = np.histogram(bootstrap(Xmap,Xmaperr,smooth=True), bins = bins, range=(bins.min(),bins.max()))[0] * scale\n else:\n n = np.histogram(X, bins = bins, range=(bins.min(),bins.max()))[0]\n s = np.histogram(Xmap, bins = bins, range=(bins.min(),bins.max()))[0] * scale\n\n\n if not return_err:\n return n / s\n else:\n return n / s, n / s * np.sqrt(1. / n - scale / s)\n\n\ndef alpha(y, x, err=None, return_kappa=False, cov=False):\n '''\n this returns -1*alpha, and optionally kappa and errors\n '''\n a1 = set(np.nonzero(np.multiply(x, y))[0])\n a2 = set(np.where(np.isfinite(np.add(x, y, err)))[0])\n a = np.asarray(list(a1 & a2))\n y = np.log(y[a])\n x = np.log(x[a])\n if err is None:\n p, covar = np.polyfit(x, y, 1, cov=True)\n m, b = p\n me, be = np.sqrt(np.sum(covar * [[1, 0], [0, 1]], axis=1))\n me, be\n else:\n err = err[a]\n err = err / y\n p, covar = np.polyfit(x, y, 1, w=1. / err**2, cov=True)\n m, b = p\n me, be = np.sqrt(np.sum(covar * [[1, 0], [0, 1]], axis=1))\n me, be\n if return_kappa:\n if cov:\n return m, np.exp(b), me, be\n else:\n return m, np.exp(b)\n else:\n if cov:\n return m, me\n else:\n return m\n\n\ndef Heaviside(x):\n return 0.5 * (np.sign(x) + 1.)\n\n\ndef schmidt_law(Ak, theta):\n '''\n schmidt_law(Ak,(beta,kappa))\n beta is the power law index (same as alpha)\n '''\n if len(theta) == 2:\n beta, kappa = theta\n return kappa * (Ak ** beta)\n elif len(theta) == 3:\n beta, kappa, Ak0 = theta\n sfr = Heaviside(Ak - Ak0) * kappa * (Ak ** beta)\n sfr[Ak < Ak0] = 0#np.nan # kappa * (Ak0 ** beta)\n return sfr\n\n\ndef lmfit_powerlaw(x, y, yerr=None, xmin=-np.inf, xmax=np.inf, init=None, maxiter=1000000):\n @custom_model\n def model(x, beta=init[0], kappa=init[1]):\n return np.log(kappa * (np.exp(x) ** beta))\n keep = np.isfinite(1. / y) & (x >= xmin) & (x <= xmax)\n if yerr is not None:\n keep = keep & np.isfinite(1. / yerr)\n m_init = model()\n fit = LevMarLSQFitter()\n #weights = (yerr / y)[keep]**(-2.)\n m = fit(m_init, np.log(x[keep]), np.log(y[keep]), maxiter=maxiter)\n return m, fit\n\n\ndef fit_lmfit_schmidt(x, y, yerr, init=None):\n m, _ = lmfit_powerlaw(x,y,yerr,init=init)\n return m.parameters\n\n\ndef emcee_schmidt(x, y, yerr, pos=None, pose=None,\n nwalkers=None, nsteps=None, burnin=200,verbose=True):\n '''\n emcee_schmidt provides a convenient wrapper for fitting the schimdt law\n to binned x,log(y) data. Generally, it fits a normalization and a slope\n '''\n def model(x, theta):\n '''\n theta = (beta, kappa)\n '''\n return np.log(schmidt_law(x, theta))\n\n def lnlike(theta, x, y, yerr):\n mod = model(x, theta)\n\n inv_sigma2 = 1 / yerr**2\n # Poisson statistics -- not using this\n #mu = (yerr)**2 # often called lambda = poisson variance for bin x_i\n #resid = np.abs(y - mod) # where w calculate the poisson probability\n #return np.sum(resid * np.log(mu) - mu) - np.sum(np.log(misc.factorial(resid)))\n #######################################################\n ########## CHI^2 log-likelihood #######################\n return -0.5 * (np.sum((y - mod)**2 * inv_sigma2))# - 0.5 * 3 * np.log(np.sum(k))\n\n def lnprior(theta):\n # different priors for different version of\n # the schmidt law\n if len(theta) == 3:\n beta, kappa, Ak0 = theta\n c3 = 0. < Ak0 <= 5.\n c4 = True\n else:\n beta, kappa = theta\n c3 = True\n c4 = True\n c1 = 0 <= beta <= 6# Never run's into this region\n c2 = 0 <= kappa # Never run's into this region\n if c1 and c2 and c3 and c4:\n return 0.0\n return -np.inf\n\n def lnprob(theta, x, y, yerr):\n ## update likelihood\n lp = lnprior(theta)\n if not np.isfinite(lp):\n return -np.inf\n return lp + lnlike(theta, x, y, yerr)\n\n ndim, nwalkers = len(pos), nwalkers\n\n pos = [np.array(pos) + np.array(pose) * 0.5 *\n (0.5 - np.random.rand(ndim)) for i in range(nwalkers)]\n\n sampler = emcee.EnsembleSampler(\n nwalkers, ndim, lnprob, args=(x, y, yerr))\n\n sampler.run_mcmc(pos, nsteps)\n\n # Get input values\n # x, y, yerr = sampler.args\n samples = sampler.chain[:, burnin:, :].reshape((-1, sampler.ndim))\n\n # # Print out final values # #\n theta_mcmc = np.percentile(samples, [16, 50, 84], axis=0).T\n\n if verbose: print(sampler.acor)\n\n if verbose:\n for i, item in enumerate(theta_mcmc):\n j = ['beta', 'kappa', 'A_{K,0}', 'A_{K,f}']\n inserts = (j[i], item[1], item[2] - item[1], item[1] - item[0])\n print('%s = %0.2f (+%0.2f,-%0.2f)' % inserts)\n\n return sampler, np.median(samples, axis=0), np.std(samples, axis=0)\n\n\n\ndef fit(bins, samp, samperr, maps, mapserr, scale=1., sampler=None, log=False,\n pos=None, pose=None, nwalkers=100, nsteps=1e4, boot=1000, burnin=200,\n threshold=False, threshold2=False,verbose=True):\n '''\n # # # A Schmidt Law fitting Function using EMCEE by D.F.M.\n fit(bins, samp, samperr, maps, mapserr, scale=1.,\n pos=None, pose=None, nwalkers=100, nsteps=1e4)\n bins: bin edges for binning data (I know it's bad to bin)\n samp : values for your sample\n samperr : errors on values for you sample\n maps: map of values from which you drew your sample\n mapserr: error on maps...\n pos : initial location of ball of walkers\n pose : initial spread of walkers\n '''\n\n #print 'Hi!. It\\'s hammer time...'\n\n # x values are bin midpoints\n x = avg(bins) # assume if log=True, then bins are already log\n # x = bins[:-1]\n # y = np.asarray([surfd(samp,maps,bins,boot=True,scale=scale) for i in xrange(boot)])\n # yerr = np.nanstd(y,axis=0)\n #if log:\n # samp = np.log10(samp)\n # maps = np.log10(maps)\n # bins = np.log10(bins) # because bins doesn't get used again after surfd\n y, yerr = surfd(samp, maps, bins, scale=scale, return_err=True)\n ###########################################+\n ###### ADDED FOR SHIFTING EXPERIMENT ######+\n ###########################################+\n\n bins2 = shift_bins(bins,0.5)\n bin\n x2 = avg(bins2)\n y2, yerr2 = surfd(samp, maps, bins2, scale=scale, return_err=True)\n concatx = np.concatenate((x,x2))\n concaty = np.concatenate((y,y2))\n concatyerr = np.concatenate((yerr,yerr2))\n srt = np.argsort(concatx)\n x = concatx[srt]\n y = concaty[srt]\n yerr = concatyerr[srt]\n\n nonzero = np.isfinite(1. / y) & np.isfinite(yerr) & np.isfinite(1./yerr)\n\n y = y[nonzero]\n yerr = yerr[nonzero]\n x = x[nonzero]\n # initialize walker positions and walker bundle size\n init = alpha(y, x, return_kappa=True, cov=True)\n if pos is None:\n pos = init[:2]\n if pose is None:\n if np.isnan(init[2] + init[3]):\n pose = (1, 1)\n else:\n pose = (init[2], init[3])\n if threshold | threshold2:\n pos = pos + (0.4,)\n pose = pose + (0.2,)\n if threshold2:\n pos = pos + (8.,)\n pose = pose + (.5,)\n #print pos\n #print pose\n pos = np.asarray(pos)\n pose = .1*pos#np.asarray(pose)\n\n # This function only fits sources, it doesn't plot, so don't pass\n # and emcee sampler type. it will spit it back out\n # # # # # # # RUN EMCEE # # # # # # #\n # pdb.set_trace()\n if sampler is None:\n if verbose: print('Sampler autocorrelation times . . .')\n sampler, theta, theta_std = emcee_schmidt(x, np.log(y), yerr/y,\n pos=pos, pose=pose,\n nwalkers=nwalkers,\n nsteps=nsteps, burnin=burnin,verbose=verbose)\n else:\n print('Next time don\\'t give me a ' + str(type(sampler)) + '.')\n\n #\n try:\n return sampler, x, y, yerr, theta, theta_std\n except:\n return sampler, x, y, yerr\n\ndef schmidt_results_plots(sampler, model, x, y, yerr, burnin=200, akmap=None,\n bins=None, scale=None, triangle_plot=True):\n '''\n model: should pass schmidt_law()\n '''\n try:\n mpl.style.use('john')\n except:\n None\n # Get input values\n # x, y, yerr = sampler.args\n if hasattr(sampler,'__getitem__'):\n chain = sampler\n dim = chain.shape[-1]\n else:\n chain = sampler.chain\n dim = sampler.dim\n\n samples = chain[:, burnin:, :].reshape((-1, dim))\n # # Print out final values # #\n theta_mcmc = np.percentile(samples, [16, 50, 84], axis=0).T # Get percentiles for each parameter\n n_params = len(theta_mcmc[:,1])\n #print n_params\n for i, item in enumerate(theta_mcmc):\n j = ['beta', 'kappa', 'A_{K,0}','A_{K,f}']\n inserts = (j[i], item[1], item[2] - item[1], item[1] - item[0])\n print('%s = %0.2f (+%0.2f,-%0.2f)' % inserts)\n # Plot corner plot\n if triangle_plot:\n if n_params == 3:\n labels = ['beta', 'kappa', 'A_{K,0}']\n elif n_params == 4:\n labels = ['beta', 'kappa', 'A_{K,0}', 'A_{K,f}']\n else:\n labels = ['beta', 'kappa']\n #print labels\n _ = triangle.corner(samples, labels=labels,\n truths=theta_mcmc[:, 1], quantiles=[.16, .84],\n verbose=False)\n # generate schmidt laws from parameter samples\n xln = np.logspace(np.log10(x.min()*.5),np.log10(x.max()*2.),100)\n smlaw_samps = np.asarray([schmidt_law(xln, samp) for samp in samples])\n # get percentile bands\n percent = lambda x: np.nanpercentile(smlaw_samps, x, interpolation='linear', axis=0)\n # Plot fits\n fig = plt.figure()\n # Plot data with errorbars\n plt.plot(xln, percent(50), 'k') # 3 sigma band\n # yperr = np.abs(np.exp(np.log(y)+yerr/y) - y)\n # ynerr = np.abs(np.exp(np.log(y)-yerr/y) - y)\n plt.errorbar(x, y, yerr, fmt='rs', alpha=0.7, mec='none')\n plt.legend(['Median', 'Data'],\n loc='upper left', fontsize=12)\n # draw 1,2,3 sigma bands\n plt.fill_between(xln, percent(1), percent(99), color='0.9') # 1 sigma band\n plt.fill_between(xln, percent(2), percent(98), color='0.75') # 2 sigma band\n plt.fill_between(xln, percent(16), percent(84), color='0.5') # 3 sigma band\n\n plt.loglog(nonposy='clip')\n\n return plt.gca()\n\ndef flatchain(chain):\n return chain.reshape((-1,chain.shape[-1]))\n\ndef norm_chain(chain, axis=0):\n std = np.std(flatchain(chain), axis=axis)\n med = np.median(flatchain(chain), axis=axis)\n return (chain-med)/std\n\ndef plot_walkers(sampler,limits = None, bad = None):\n '''\n sampler : emcee Sampler class\n '''\n\n if hasattr(sampler,'__getitem__'):\n chain = sampler\n ndim = chain.shape[-1]\n else:\n chain = sampler.chain\n ndim = sampler.ndim\n\n fig = plt.figure(figsize=(8 * ndim, 4 * ndim))\n\n if hasattr(limits,'__getitem__'):\n limits += [None] * (3-len(limits))\n slices = slice(limits[0],limits[1],limits[2])\n else:\n slices = slice(None,limits,None)\n\n\n for w,walk in enumerate(chain[:,slices,:]):\n if bad is None:\n color = 'k'\n elif bad[w]:\n color = 'r'\n else:\n color = 'k'\n for p, param in enumerate(walk.T):\n ax = plt.subplot(ndim, 1, p + 1)\n ax.plot(param, color, alpha=.75, lw=0.75)\n # ax.set_ylim(param.min()*0.5,param.max()*1.5)\n # ax.semilogy()\n plt.tight_layout()\n return fig\n\n\ndef tester():\n print('hi ya\\'ll')\n\n\n" ]
[ [ "numpy.matrix", "matplotlib.pyplot.legend", "numpy.polyfit", "numpy.nanmax", "numpy.sqrt", "numpy.asarray", "numpy.nanmin", "matplotlib.pyplot.loglog", "numpy.cumsum", "numpy.concatenate", "numpy.exp", "numpy.histogram", "matplotlib.pyplot.gca", "matplotlib.pyplot.tight_layout", "numpy.allclose", "matplotlib.style.use", "numpy.arange", "numpy.sin", "numpy.std", "matplotlib.pyplot.subplot", "numpy.diff", "matplotlib.pyplot.errorbar", "matplotlib.pyplot.figure", "scipy.stats.gmean", "numpy.log", "numpy.multiply", "numpy.power", "numpy.isnan", "numpy.median", "numpy.append", "numpy.log10", "numpy.random.rand", "numpy.argsort", "numpy.array", "numpy.sum", "numpy.nanpercentile", "numpy.isfinite", "numpy.cos", "numpy.percentile", "numpy.sort", "numpy.sign", "numpy.add" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] } ]
noboevbo/PedRec
[ "891d19bd6a2c7a7d71c2e41d37e7b4c4bfc7762e", "891d19bd6a2c7a7d71c2e41d37e7b4c4bfc7762e" ]
[ "pedrec/visualizers/skeleton_3d_visualizer.py", "pedrec/utils/numpy_helper.py" ]
[ "import matplotlib.pyplot as plt\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfrom pedrec.models.constants.skeleton_pedrec import SKELETON_PEDREC, SKELETON_PEDREC_JOINT_COLORS, SKELETON_PEDREC_LIMB_COLORS\nfrom pedrec.visualizers.visualization_helper_3d import draw_origin_3d, draw_grid_3d\n\n\ndef add_skeleton_3d_to_axes(ax: Axes3D, skeleton_3d: np.ndarray, size: float = 2, min_score: float = 0.3):\n # Joints\n xs = skeleton_3d[:, 0]\n ys = skeleton_3d[:, 2]\n zs = skeleton_3d[:, 1]\n colors = []\n for idx, joint in enumerate(skeleton_3d):\n if joint[3] < min_score: # score\n colors.append([0, 0, 0, 0])\n else:\n colors.append(SKELETON_PEDREC_JOINT_COLORS[idx].rgba_float_list)\n ax.scatter(xs, ys, zs, c=colors, s=size)\n\n # Limbs\n for idx, pair in enumerate(SKELETON_PEDREC):\n if (skeleton_3d[pair[0:2], 3] >= min_score).all():\n ax.plot(skeleton_3d[pair[0:2], 0], skeleton_3d[pair[0:2], 2], skeleton_3d[pair[0:2], 1], linewidth=size, c=SKELETON_PEDREC_LIMB_COLORS[idx].rgba_float_list)\n\n\ndef get_skeleton_3d_figure(skeleton_3d: np.ndarray):\n # Preparation\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n draw_grid_3d(ax)\n draw_origin_3d(ax)\n add_skeleton_3d_to_axes(ax, skeleton_3d)\n return fig, ax\n\n\ndef plot_skeleton_3d(skeleton_3d: np.ndarray):\n fig, ax = get_skeleton_3d_figure(skeleton_3d)\n plt.show()\n", "from typing import Optional\n\nimport numpy as np\n\n\ndef set_or_vstack(a: np.ndarray, b: np.ndarray, expand_dim_on_set: bool = True):\n \"\"\"\n If a exists it vstacks b, if not it sets a to b.\n :param a:\n :param b:\n :return:\n \"\"\"\n if expand_dim_on_set:\n b = np.expand_dims(b, axis=0)\n if a is None:\n return b\n else:\n return np.vstack((a, b))\n\n\ndef fill_array(array: np.ndarray, array_size: int, fill_value: int):\n if array.shape[0] < array_size:\n shape = [array_size - array.shape[0]]\n for shape_idx in range(1, len(array.shape)):\n shape.append(array.shape[shape_idx])\n fill_array = np.ones(tuple(shape)) * fill_value\n return np.concatenate((array, fill_array))\n else:\n return array\n\n\ndef split_numpy_array(input_array: np.ndarray, split_size: int, fill_value: int = None):\n \"\"\"\n Currently only supports split on axis=0\n \"\"\"\n output_splits: np.ndarray = None\n for i in range(0, input_array.shape[0] // split_size):\n idx_from = i * split_size\n idx_to = idx_from + split_size\n output_splits = set_or_vstack(output_splits, input_array[idx_from:idx_to])\n if fill_value is not None:\n rest = input_array.shape[0] % split_size\n if rest != 0:\n rest_array = fill_array(input_array[-rest:], split_size, fill_value)\n output_splits = set_or_vstack(output_splits, rest_array)\n return output_splits\n\n\ndef split_numpy_array_stepwise(input_array: np.ndarray, split_size: int, step_size: int,\n fill_value: int = None) -> np.ndarray:\n \"\"\"\n Currently only supports split on axis=0\n \"\"\"\n assert fill_value is not None or input_array.shape[0] >= split_size, \\\n \"Input list of length '{}' is less than split size '{}' and no fill_value is given\".format(input_array.shape[0],\n split_size)\n # TODO: Create a handler which checks for splits which contain only zeros or so and removes them\n output_splits: np.ndarray = None\n if input_array.shape[0] < split_size:\n filled_array = fill_array(input_array, split_size, fill_value)\n return np.expand_dims(filled_array, axis=0)\n\n for input_list_index in range(0, input_array.shape[0] - (split_size - 1), step_size): # TODO: is this -1 correct?\n output_split = input_array[input_list_index:input_list_index + split_size]\n output_splits = set_or_vstack(output_splits, output_split)\n return output_splits\n\ndef create_meshgrid_np(\n x: np.ndarray,\n normalized_coordinates: Optional[bool]) -> np.ndarray:\n # assert len(x.shape) == 4, x.shape\n # _, _, height, width = x.shape\n height, width = x.shape\n _dtype = x.dtype\n if normalized_coordinates:\n xs = np.linspace(0.0, 1.0, width, dtype=_dtype)\n ys = np.linspace(0.0, 1.0, height, dtype=_dtype)\n else:\n xs = np.linspace(0, width - 1, width, dtype=_dtype)\n ys = np.linspace(0, height - 1, height, dtype=_dtype)\n return np.meshgrid(ys, xs)\n" ]
[ [ "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ], [ "numpy.expand_dims", "numpy.linspace", "numpy.concatenate", "numpy.meshgrid", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vishalbelsare/Passage
[ "af6e100804dfe332c88bd2cd192e93a807377887" ]
[ "passage/theano_utils.py" ]
[ "import numpy as np\nimport theano\n\ndef intX(X):\n return np.asarray(X, dtype=np.int32)\n\ndef floatX(X):\n return np.asarray(X, dtype=theano.config.floatX)\n\ndef sharedX(X, dtype=theano.config.floatX, name=None):\n return theano.shared(np.asarray(X, dtype=dtype), name=name)\n\ndef shared0s(shape, dtype=theano.config.floatX, name=None):\n return sharedX(np.zeros(shape), dtype=dtype, name=name)\n\ndef sharedNs(shape, n, dtype=theano.config.floatX, name=None):\n return sharedX(np.ones(shape)*n, dtype=dtype, name=name)\n\ndef downcast_float(X):\n return np.asarray(X, dtype=np.float32)\n" ]
[ [ "numpy.asarray", "numpy.zeros", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
leomauro/history-of-interpretation
[ "6235f4b875505ac7a6efb10f3c4e5a6d3c7b25ec" ]
[ "saliency/guided_backprop.py" ]
[ "# Copyright 2017 Google Inc. 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\"\"\"Utilites to computed GuidedBackprop SaliencyMasks\"\"\"\n\nfrom .base import SaliencyMask\nimport tensorflow.compat.v1 as tf\n\nclass GuidedBackprop(SaliencyMask):\n \"\"\"A SaliencyMask class that computes saliency masks with GuidedBackProp.\n\n This implementation copies the TensorFlow graph to a new graph with the ReLU\n gradient overwritten as in the paper:\n https://arxiv.org/abs/1412.6806\n\n Thanks to Chris Olah for generously sharing his implementation of the ReLU\n backprop.\n \"\"\"\n\n GuidedReluRegistered = False\n\n def __init__(self,\n graph,\n session,\n y,\n x,\n tmp_ckpt_path='/tmp/guided_backprop_ckpt'):\n \"\"\"Constructs a GuidedBackprop SaliencyMask.\"\"\"\n super(GuidedBackprop, self).__init__(graph, session, y, x)\n\n self.x = x\n\n if GuidedBackprop.GuidedReluRegistered is False:\n #### Acknowledgement to Chris Olah ####\n @tf.RegisterGradient(\"GuidedRelu\")\n def _GuidedReluGrad(op, grad):\n gate_g = tf.cast(grad > 0, \"float32\")\n gate_y = tf.cast(op.outputs[0] > 0, \"float32\")\n return gate_y * gate_g * grad\n GuidedBackprop.GuidedReluRegistered = True\n\n with graph.as_default():\n saver = tf.train.Saver()\n saver.save(session, tmp_ckpt_path)\n\n graph_def = graph.as_graph_def()\n\n self.guided_graph = tf.Graph()\n with self.guided_graph.as_default():\n self.guided_sess = tf.Session(graph = self.guided_graph)\n with self.guided_graph.gradient_override_map({'Relu': 'GuidedRelu'}):\n # Import the graph def, and all the variables.\n tf.import_graph_def(graph_def, name='')\n saver.restore(self.guided_sess, tmp_ckpt_path)\n\n imported_y = self.guided_graph.get_tensor_by_name(y.name)\n imported_x = self.guided_graph.get_tensor_by_name(x.name)\n\n self.guided_grads_node = tf.gradients(imported_y, imported_x)[0]\n\n def GetMask(self, x_value, feed_dict = {}):\n \"\"\"Returns a GuidedBackprop mask.\"\"\"\n with self.guided_graph.as_default():\n # Move all the feed dict tensor keys to refer to the same tensor on the\n # new graph.\n guided_feed_dict = {}\n for tensor in feed_dict:\n guided_feed_dict[tensor.name] = feed_dict[tensor]\n guided_feed_dict[self.x.name] = [x_value]\n\n return self.guided_sess.run(\n self.guided_grads_node, feed_dict = guided_feed_dict)[0]\n" ]
[ [ "tensorflow.compat.v1.import_graph_def", "tensorflow.compat.v1.Session", "tensorflow.compat.v1.gradients", "tensorflow.compat.v1.Graph", "tensorflow.compat.v1.RegisterGradient", "tensorflow.compat.v1.cast", "tensorflow.compat.v1.train.Saver" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
NoellePatterson/func-flow-plot
[ "196d58ac87c137b42063ac718ea296faaf148307" ]
[ "utils/calc_fall_flush.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.interpolate as ip\nfrom scipy.ndimage import gaussian_filter1d\nfrom utils.helpers import find_index, peakdet, replace_nan\nfrom params import fall_params\n\ndef calc_fall_flush_timings_durations(flow_matrix, summer_timings):\n max_zero_allowed_per_year = fall_params['max_zero_allowed_per_year']\n max_nan_allowed_per_year = fall_params['max_nan_allowed_per_year']\n min_flow_rate = fall_params['min_flow_rate']\n sigma = fall_params['sigma'] # Smaller filter to find fall flush peak\n wet_sigma = fall_params['wet_sigma'] # Larger filter to find wet season peak\n peak_sensitivity = fall_params['peak_sensitivity'] # smaller is more peak\n max_flush_duration = fall_params['max_flush_duration'] # Maximum duration from start to end, for fall flush peak\n wet_threshold_perc = fall_params['wet_threshold_perc'] # Return to wet season flow must be certain percentage of that year's max flow\n flush_threshold_perc = fall_params['flush_threshold_perc'] # Size of flush peak, from rising limb to top of peak, has great enough change\n min_flush_threshold = fall_params['min_flush_threshold']\n date_cutoff = fall_params['date_cutoff'] # Latest accepted date for fall flush, in Julian Date counting from Oct 1st = 0. (i.e. Dec 15th = 75)\n\n start_dates = []\n wet_dates = []\n durations = []\n mags = []\n\n for column_number, column_flow in enumerate(flow_matrix[0]):\n\n start_dates.append(None)\n wet_dates.append(None)\n durations.append(None)\n mags.append(None)\n\n \"\"\"Check to see if water year has more than allowed nan or zeros\"\"\"\n if np.isnan(flow_matrix[:, column_number]).sum() > max_nan_allowed_per_year or np.count_nonzero(flow_matrix[:, column_number]==0) > max_zero_allowed_per_year or max(flow_matrix[:, column_number]) < min_flow_rate:\n continue;\n\n \"\"\"Get flow data\"\"\"\n flow_data = flow_matrix[:, column_number]\n x_axis = list(range(len(flow_data)))\n\n \"\"\"Interpolate between None values\"\"\"\n flow_data = replace_nan(flow_data)\n\n \"\"\"Return to Wet Season\"\"\"\n wet_filter_data = gaussian_filter1d(flow_data, wet_sigma)\n return_date = return_to_wet_date(wet_filter_data, wet_threshold_perc)\n wet_dates[-1] = return_date + 10\n\n \"\"\"Filter noise data with small sigma to find fall flush hump\"\"\"\n filter_data = gaussian_filter1d(flow_data, sigma)\n\n \"\"\"Fit spline\"\"\"\n x_axis = list(range(len(filter_data)))\n spl = ip.UnivariateSpline(x_axis, filter_data, k=3, s=3)\n\n \"\"\"Find the peaks and valleys of the filtered data\"\"\"\n mean_flow = np.nanmean(filter_data)\n maxarray, minarray = peakdet(spl(x_axis), mean_flow * peak_sensitivity)\n\n \"\"\"Find max and min of filtered flow data\"\"\"\n max_flow = max(filter_data[20:])\n max_flow_index = find_index(filter_data[20:], max_flow) + 20\n min_flow = min(wet_filter_data[:max_flow_index])\n\n \"\"\"If could not find any max and find\"\"\"\n if not list(maxarray) or not list(minarray) or minarray[0][0] > max_flow_index:\n continue;\n\n \"\"\"Get flow magnitude threshold from previous summer's baseflow\"\"\"\n baseflows = []\n if column_number == 0:\n wet_date = wet_dates[0]\n baseflow = list(flow_matrix[:wet_date, column_number])\n bs_mean = np.mean(baseflow)\n bs_med = np.nanpercentile(baseflow, 50)\n else:\n summer_date = summer_timings[column_number -1]\n if wet_dates[column_number] > 20:\n wet_date = wet_dates[column_number] - 20\n baseflow = list(flow_matrix[summer_date:,column_number -1]) + list(flow_matrix[:wet_date, column_number])\n bs_mean = np.mean(baseflow)\n bs_med = np.nanpercentile(baseflow, 50)\n\n \"\"\"Get fall flush peak\"\"\"\n counter = 0\n half_duration = int(max_flush_duration/2) # Only test duration for first half of fall flush peak\n if bs_med > 25:\n min_flush_magnitude = bs_med * 1.5 # if median baseflow is large (>25), magnitude threshold is 50% above median baseflow of previous summer\n else:\n min_flush_magnitude = bs_med * 2 # otherwise magnitude threshold is 100% above median baseflow of previous summer\n if min_flush_magnitude < min_flush_threshold:\n min_flush_magnitude = min_flush_threshold\n for flow_index in maxarray:\n\n if counter == 0:\n if flow_index[0] < half_duration and flow_index[0] != 0 and flow_index[1] > wet_filter_data[int(flow_index[0])] and flow_index[1] > min_flush_magnitude:\n \"\"\"if index found is before the half duration allowed\"\"\"\n start_dates[-1]=int(flow_index[0])\n mags[-1]=flow_index[1]\n break\n elif bool((flow_index[1] - spl(maxarray[counter][0] - half_duration)) / flow_index[1] > flush_threshold_perc or minarray[counter][0] - maxarray[counter][0] < half_duration) and flow_index[1] > wet_filter_data[int(flow_index[0])] and flow_index[1] > min_flush_magnitude:\n \"\"\"If peak and valley is separted by half duration, or half duration to the left is less than 30% of its value\"\"\"\n start_dates[-1]=int(flow_index[0])\n mags[-1]=flow_index[1]\n break\n elif counter == len(minarray):\n start_dates[-1]=None\n mags[-1]=None\n break;\n elif bool(minarray[counter][0] - maxarray[counter][0] < half_duration or maxarray[counter][0] - minarray[counter-1][0] < half_duration) and bool(flow_index[1] > wet_filter_data[int(flow_index[0])] and flow_index[1] > min_flush_magnitude and flow_index[0] <= date_cutoff):\n \"\"\"valley and peak are distanced by less than half dur from either side\"\"\"\n start_dates[-1]=int(flow_index[0])\n mags[-1]=flow_index[1]\n break\n elif (spl(flow_index[0] - half_duration) - min_flow) / (flow_index[1] - min_flow) < flush_threshold_perc and (spl(flow_index[0] + half_duration) - min_flow) / (flow_index[1] - min_flow) < flush_threshold_perc and flow_index[1] > wet_filter_data[int(flow_index[0])] and flow_index[1] > min_flush_magnitude and flow_index[0] <= date_cutoff:\n \"\"\"both side of flow value at the peak + half duration index fall below flush_threshold_perc\"\"\"\n start_dates[-1]=int(flow_index[0])\n mags[-1]=flow_index[1]\n break\n counter = counter + 1\n\n \"\"\"Check to see if last start_date falls behind the max_allowed_date\"\"\"\n if bool(start_dates[-1] is None or start_dates[-1] > wet_dates[-1]) and wet_dates[-1]:\n start_dates[-1] = None\n mags[-1] = None\n\n \"\"\"Get duration of each fall flush\"\"\"\n current_duration, left, right = calc_fall_flush_durations_2(filter_data, start_dates[-1])\n durations[-1] = current_duration\n _plotter(x_axis, flow_data, filter_data, wet_filter_data, start_dates, wet_dates, column_number, left, right, maxarray, minarray, min_flush_magnitude)\n\n return start_dates, mags, wet_dates, durations\n\ndef calc_fall_flush_durations(flow_data, wet_filter_data, date):\n\n duration_left = None\n duration_right = None\n duration = None\n\n if date:\n date = int(date)\n for index_left, flow_left in enumerate(reversed(flow_data[:date])):\n if flow_left < wet_filter_data[date - index_left]:\n duration_left = index_left\n break\n for index_right, flow_right in enumerate(flow_data[date:]):\n if flow_right < wet_filter_data[date + index_right]:\n duration_right = index_right\n break\n\n if duration_left and duration_right:\n duration = duration_left + duration_right\n else:\n duration = None\n\n return duration\n\n\ndef calc_fall_flush_durations_2(filter_data, date):\n\n \"\"\"Left side sharp\"\"\"\n der_percent_threshold_left = 50 # Slope of rising limb (i.e. derivative) must be \"sharp\"\n flow_percent_threshold_left = 80\n\n \"\"\"Right side mellow\"\"\"\n der_percent_threshold_right = 30 # Slope of falling limb (i.e. derivative) has lower requirement to be part of flush duration\n flow_percent_threshold_right = 80\n\n duration = None\n left = 0\n right = 0\n\n if date or date == 0:\n date = int(date)\n left_maxarray, left_minarray = peakdet(filter_data[:date], 0.01)\n right_maxarray, right_minarray = peakdet(filter_data[date:], 0.01)\n\n if not list(left_minarray):\n left = 0\n else:\n left = int(left_minarray[-1][0])\n\n if not list(right_minarray):\n right = 0\n else:\n right = int(date - 2 + right_minarray[0][0])\n\n if date - left > 10:\n \"\"\"create spline, and find derivative\"\"\"\n x_axis_left = list(range(len(filter_data[left:date])))\n spl_left = ip.UnivariateSpline(x_axis_left, filter_data[left:date], k=3, s=3)\n spl_first_left = spl_left.derivative(1)\n\n \"\"\"check if derivative value falls below certain threshold\"\"\"\n spl_first_left_median = np.nanpercentile(spl_first_left(x_axis_left), der_percent_threshold_left)\n\n \"\"\"check if actual value falls below threshold, avoiding the rounded peak\"\"\"\n median_left = np.nanpercentile(list(set(filter_data[left:date])), flow_percent_threshold_left)\n\n for index_left, der in enumerate(reversed(spl_first_left(x_axis_left))):\n # print(der < spl_first_left_median, filter_data[date - index_left] < median_left)\n if der < spl_first_left_median and filter_data[date - index_left] < median_left:\n left = date - index_left\n break\n\n if right - date > 10:\n x_axis_right = list(range(len(filter_data[date:right])))\n spl_right = ip.UnivariateSpline(x_axis_right, filter_data[date:right], k=3, s=3)\n spl_first_right = spl_right.derivative(1)\n\n spl_first_right_median = abs(np.nanpercentile(spl_first_right(x_axis_right), der_percent_threshold_right))\n median_right = np.nanpercentile(list(set(filter_data[date:right])), flow_percent_threshold_right)\n\n for index_right, der in enumerate(spl_first_right(x_axis_right)):\n # print(date+index_right, der < spl_first_right_median, filter_data[date + index_right] < median_right)\n if abs(der) < spl_first_right_median and filter_data[date + index_right] < median_right:\n right = date + index_right\n break\n\n if left:\n duration = int(date - left)\n elif not left and right:\n duration = int(right - date)\n else:\n duration = 0\n\n return duration, left, right\n\n\ndef return_to_wet_date(wet_filter_data, wet_threshold_perc):\n max_wet_peak_mag = max(wet_filter_data[20:])\n max_wet_peak_index = find_index(wet_filter_data, max_wet_peak_mag)\n min_wet_peak_mag = min(wet_filter_data[:max_wet_peak_index])\n \"\"\"Loop backwards from max flow index to beginning, to search for wet season\"\"\"\n for index, value in enumerate(reversed(wet_filter_data[:max_wet_peak_index])):\n if index == len(wet_filter_data[:max_wet_peak_index] - 1):\n return None\n elif (value - min_wet_peak_mag) / (max_wet_peak_mag - min_wet_peak_mag) < wet_threshold_perc:\n \"\"\"If value percentage falls below wet_threshold_perc\"\"\"\n return_date = max_wet_peak_index - index\n return return_date\n\ndef _plotter(x_axis, flow_data, filter_data, wet_filter_data, start_dates, wet_dates, column_number, left, right, maxarray, minarray, min_flush_magnitude):\n plt.figure()\n #plt.plot(x_axis, flow_data, '-')\n plt.plot(x_axis, filter_data, '-', color='#5993E5') #greyish blue\n #plt.plot(x_axis, wet_filter_data)\n # for data in maxarray:\n # plt.plot(data[0], data[1], '^')\n # for data in minarray:\n # plt.plot(data[0], data[1], 'v')\n if start_dates[-1] is not None:\n plt.axvline(start_dates[-1], color='blue', ls=':')\n plt.axvline(wet_dates[-1], color=\"green\", ls=':')\n #plt.axvline(left, ls=\":\")\n #plt.axvline(right, ls=\":\")\n if min_flush_magnitude is not None:\n plt.axhline(min_flush_magnitude, ls=':', color = 'red')\n #plt.yscale('log')\n plt.savefig('post_processedFiles/Boxplots/{}.png'.format(column_number))\n" ]
[ [ "scipy.interpolate.UnivariateSpline", "matplotlib.pyplot.axvline", "matplotlib.pyplot.axhline", "numpy.nanpercentile", "numpy.isnan", "scipy.ndimage.gaussian_filter1d", "matplotlib.pyplot.plot", "numpy.mean", "numpy.nanmean", "numpy.count_nonzero", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
yhpengtu/CenterIMask
[ "7e046964db11df78c93cb88f50b9c4b6ddf0c9bc" ]
[ "tools/convet_voc2coco/voc2coco.py" ]
[ "import os\nimport sys\nimport json\nimport datetime\nimport numpy as np\nimport skimage.draw\nfrom bs4 import BeautifulSoup as bs\nimport cv2\nimport imgaug\nfrom utils import *\n# Root directory of the project\nROOT_DIR = os.path.abspath(\"../../\")\n# Inference result directory\nRESULTS_DIR = os.path.abspath(\"./inference/\")\n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom configs import Config\n# from mrcnn import model as modellib, utils\n# from mrcnn import visualize\n\nimport matplotlib\n# Agg backend runs without a display\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nDEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, \"logs\")\nDEFAULT_DATASET_YEAR = '2012'\n\nCOCO_WEIGHTS_PATH = os.path.join(ROOT_DIR, \"mask_rcnn_coco.h5\")\n\n\n# VOC DATASET MASK MAP FUNCTION\n# Following codes are mapping each mask color(SegmentationClass) to ground truth index.\n# - reference: https://d2l.ai/chapter_computer-vision/semantic-segmentation-and-dataset.html\nVOC_COLORMAP = [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0],\n [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128],\n [64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0],\n [64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128],\n [0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0],\n [0, 64, 128]]\nVOC_CLASSES = ['background', 'aeroplane', 'bicycle', 'bird', 'boat',\n 'bottle', 'bus', 'car', 'cat', 'chair', 'cow',\n 'diningtable', 'dog', 'horse', 'motorbike', 'person',\n 'potted plant', 'sheep', 'sofa', 'train', 'tv/monitor']\n\ndef build_colormap2label():\n \"\"\"Build a RGB color to label mapping for segmentation.\"\"\"\n colormap2label = np.zeros(256 ** 3)\n for i, colormap in enumerate(VOC_COLORMAP):\n colormap2label[(colormap[0]*256 + colormap[1])*256 + colormap[2]] = i\n return colormap2label\n\ndef voc_label_indices(colormap, colormap2label):\n \"\"\"Map a RGB color to a label.\"\"\"\n colormap = colormap.astype('int32')\n idx = ((colormap[:, :, 0] * 256 + colormap[:, :, 1]) * 256\n + colormap[:, :, 2])\n return colormap2label[idx]\n# VOC DATASET MASK MAP FUNCTION\n\n\nclass VocConfig(Config):\n NAME = \"voc\"\n\n IMAGE_PER_GPU = 2\n\n NUM_CLASSES = 1 + 20 # VOC 2012 have 20 classes. \"1\" is for background.\n\nclass InferenceConfig(VocConfig):\n # Set batch size to 1 since we'll be running inference on\n # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n DETECTION_MIN_CONFIDENCE = 0\n\n\nclass VocDataset(Dataset):\n def load_voc(self, dataset_dir, trainval, year='2012'):\n \"\"\"Load a voc_year of the VOC dataset.\n dataset_dir: The root directory of the VOC dataset, example: '/mnt/disk1/VOCdevkit'\n trainval: 'train' or 'val' for Training or Validation\n year: '2007' or '2012' for VOC dataset\n \"\"\"\n\n voc_year = 'VOC' + year\n Segmentation = os.path.join(dataset_dir, voc_year, 'ImageSets', 'Segmentation')\n JPEGImages = os.path.join(dataset_dir, voc_year, 'JPEGImages')\n Annotations = os.path.join(dataset_dir, voc_year, 'Annotations')\n SegmentationClass = os.path.join(dataset_dir, voc_year, 'SegmentationClass')\n SegmentationObject = os.path.join(dataset_dir, voc_year, 'SegmentationObject')\n\n # load classes of VOC, BG is initialed in parent class.\n for idx, class_name in enumerate(VOC_CLASSES[1:]):\n self.add_class(\"voc\", idx + 1, class_name)\n\n assert trainval in ['train', 'val']\n # read segmentation annotation file\n annotation_file = os.path.join(Segmentation, trainval + '.txt')\n image_ids = []\n with open(annotation_file) as f:\n image_id_list = [line.strip() for line in f]\n image_ids += image_id_list\n\n for image_id in image_ids:\n image_file_name = '{}.jpg'.format(image_id)\n mask_file_name = '{}.png'.format(image_id)\n xml_file_name = '{}.xml'.format(image_id)\n image_path = os.path.join(JPEGImages, image_file_name)\n\n # Parse Annotations XML File\n with open(os.path.join(Annotations, xml_file_name)) as f:\n soup = bs(f, 'lxml')\n objects = soup.find_all('object')\n image_contains_class_flag = False\n for obj in objects:\n class_name = obj.find('name').text\n if class_name in VOC_CLASSES:\n image_contains_class_flag = True\n continue\n if image_contains_class_flag:\n class_mask_path = os.path.join(SegmentationClass, mask_file_name)\n object_mask_path = os.path.join(SegmentationObject, mask_file_name)\n self.add_image(\"voc\",\n image_id=image_file_name,\n path=image_path,\n class_mask_path=class_mask_path,\n object_mask_path=object_mask_path)\n\n\n\n def load_raw_mask(self, image_id, class_or_object):\n '''load two kinds of mask of VOC dataset.\n image_id: id of mask\n class_or_object: 'class_mask' or 'object_mask' for SegmentationClass or SegmentationObject\n Returns:\n image: numpy of mask image.\n '''\n assert class_or_object in ['class_mask', 'object_mask']\n image = skimage.io.imread(self.image_info[image_id][class_or_object+'_path'])\n if image.ndim != 3:\n image = skimage.color.gray2rgb(image)\n # If has an alpha channel, remove it for consistency\n if image.shape[-1] == 4:\n image = image[..., :3]\n return image\n\n def load_class_label(self, image_id):\n '''Mapping SegmentationClass image's color to indice of ground truth \n image_id: id of mask\n Return:\n class_label: [height, width] matrix contains values form 0 to 20\n '''\n raw_mask = self.load_raw_mask(image_id, 'class_mask')\n class_label = voc_label_indices(raw_mask, build_colormap2label())\n return class_label\n\n def load_mask(self, image_id):\n '''Mapping annotation images to real Masks(MRCNN needed)\n image_id: id of mask\n Returns:\n masks: A bool array of shape [height, width, instance count] with\n one mask per instance.\n class_ids: a 1D array of class IDs of the instance masks.\n '''\n class_label = self.load_class_label(image_id)\n instance_mask = self.load_raw_mask(image_id, 'object_mask')\n max_indice = int(np.max(class_label))\n\n instance_label = []\n instance_class = []\n for i in range(1, max_indice+1):\n if not np.any(class_label==i):\n continue\n gt_indice = i\n object_filter = class_label == i\n object_filter = object_filter.astype(np.uint8)\n object_filter = np.dstack((object_filter,object_filter,object_filter))\n filtered = np.multiply(object_filter, instance_mask)\n gray = cv2.cvtColor(filtered, cv2.COLOR_RGB2GRAY)\n max_gray = np.max(gray)\n for sub_index in range(1, max_gray+1):\n if not np.any(gray==sub_index):\n continue\n instance_filter = gray == sub_index\n instance_label += [instance_filter]\n instance_class += [gt_indice]\n masks = np.asarray(instance_label).transpose((1,2,0))\n classes_ids = np.asarray(instance_class)\n return masks, classes_ids\n\n\n############################################################\n# Inference\n############################################################\n\ndef inference(model, dataset, limit):\n \"\"\"Run detection on images in the given directory.\"\"\"\n\n # Create directory\n if not os.path.exists(RESULTS_DIR):\n os.makedirs(RESULTS_DIR)\n time_dir = \"{:%Y%m%dT%H%M%S}\".format(datetime.datetime.now())\n time_dir = os.path.join(RESULTS_DIR, time_dir)\n os.makedirs(time_dir)\n\n # Load over images\n for image_id in dataset.image_ids[:limit]:\n # Load image and run detection\n image = dataset.load_image(image_id)\n # Detect objects\n r = model.detect([image], verbose=0)[0]\n # Encode image to RLE. Returns a string of multiple lines\n source_id = dataset.image_info[image_id][\"id\"]\n # Save image with masks\n if len(r['class_ids']) > 0:\n print('[*] {}th image has {} instance(s).'.format(image_id, len(r['class_ids'])))\n visualize.display_instances(\n image, r['rois'], r['masks'], r['class_ids'],\n dataset.class_names, r['scores'],\n show_bbox=True, show_mask=True,\n title=\"Predictions\")\n plt.savefig(\"{}/{}\".format(time_dir, dataset.image_info[image_id][\"id\"]))\n plt.close()\n else:\n plt.imshow(image)\n plt.savefig(\"{}/noinstance_{}\".format(time_dir, dataset.image_info[image_id][\"id\"]))\n print('[*] {}th image have no instance.'.format(image_id))\n plt.close()\n\n\n\nif __name__ == '__main__':\n import argparse\n\n # Parse command line arguments\n parser = argparse.ArgumentParser(\n description='Train Mask R-CNN on PASCAL VOC.')\n parser.add_argument(\"--command\",\n metavar=\"<command>\",\n default='train',\n help=\"'train' or 'inference' on PASCAL VOC\")\n parser.add_argument('--dataset',\n default=\"/data/lktime-seg-tp/dataset/PASCALVOC/VOCdevkit/\",\n help='Directory of the PASCAL VOC dataset')\n parser.add_argument('--year',\n default='2012',\n help='Year of the PASCAL VOC dataset (2007 or 2012) (default=2012)')\n parser.add_argument('--model',\n default=\"/path/to/weights.h5\",\n help=\"Path to weights .h5 file or 'voc'\")\n parser.add_argument('--logs', \n default='./logs',\n metavar=\"/path/to/logs/\",\n help='Logs and checkpoints directory (default=logs/)')\n parser.add_argument('--limit', required=False,\n default=10,\n metavar=\"<image count>\",\n help='Images to use for evaluation (default=10)')\n\n # TODO\n '''\n parser.add_argument('--download', required=False,\n default=False,\n metavar=\"<True|False>\",\n help='Automatically download and unzip PASCAL VOC files (default=False)',\n type=bool)\n '''\n args = parser.parse_args()\n print(\"Command: \", args.command)\n print(\"Model: \", args.model)\n print(\"Dataset: \", args.dataset)\n print(\"Year: \", args.year)\n print(\"Logs: \", args.logs)\n #print(\"Auto Download: \", args.download)\n\n\n # Configurations\n if args.command == \"train\":\n config = VocConfig()\n else:\n config = InferenceConfig()\n config.display()\n\n # Create model\n # if args.command == \"train\":\n # model = modellib.MaskRCNN(mode=\"training\", config=config,\n # model_dir=args.logs)\n # else:\n # model = modellib.MaskRCNN(mode=\"inference\", config=config,\n # model_dir=args.logs)\n\n\n # Select weights file to load\n # if args.model.lower() == \"coco\":\n # model_path = COCO_WEIGHTS_PATH\n # elif args.model.lower() == \"last\":\n # # Find last trained weights\n # model_path = model.find_last()\n # elif args.model.lower() == \"imagenet\":\n # # Start from ImageNet trained weights\n # model_path = model.get_imagenet_weights()\n # else:\n # model_path = args.model\n\n # Load weights\n # if args.model.lower() == \"coco\":\n # # Exclude the last layers because they require a matching\n # # number of classes\n # model.load_weights(model_path, by_name=True, exclude=[\n # \"mrcnn_class_logits\", \"mrcnn_bbox_fc\",\n # \"mrcnn_bbox\", \"mrcnn_mask\"])\n # else:\n # print(\"Loading weights \", model_path)\n # model.load_weights(model_path, by_name=True)\n\n\n # Train or evaluate\n if args.command == \"train\":\n # Training dataset. Use the training set and 35K from the\n # validation set, as as in the Mask RCNN paper.\n dataset_train = VocDataset()\n dataset_train.load_voc(args.dataset, \"train\", year=args.year)\n dataset_train.prepare()\n\n # Validation dataset\n dataset_val = VocDataset()\n dataset_val.load_voc(args.dataset, \"val\", year=args.year)\n dataset_val.prepare()\n\n # Image Augmentation\n # Right/Left flip 50% of the time\n augmentation = imgaug.augmenters.Fliplr(0.5)\n\n # *** This training schedule is an example. Update to your needs ***\n\n # # Training - Stage 1\n # print(\"Training network heads\")\n # model.train(dataset_train, dataset_val,\n # learning_rate=config.LEARNING_RATE,\n # epochs=40,\n # layers='heads',\n # augmentation=augmentation)\n\n # # Training - Stage 2\n # # Finetune layers from ResNet stage 4 and up\n # print(\"Fine tune Resnet stage 4 and up\")\n # model.train(dataset_train, dataset_val,\n # learning_rate=config.LEARNING_RATE,\n # epochs=120,\n # layers='4+',\n # augmentation=augmentation)\n\n # # Training - Stage 3\n # # Fine tune all layers\n # print(\"Fine tune all layers\")\n # model.train(dataset_train, dataset_val,\n # learning_rate=config.LEARNING_RATE / 10,\n # epochs=160,\n # layers='all',\n # augmentation=augmentation)\n\n # elif args.command == \"inference\":\n # #print(\"evaluate have not been implemented\")\n # # Validation dataset\n # dataset_val = VocDataset()\n # voc = dataset_val.load_voc(args.dataset, \"val\", year=args.year)\n # dataset_val.prepare()\n # print(\"Running voc inference on {} images.\".format(args.limit))\n # inference(model, dataset_val, int(args.limit))\n # else:\n # print(\"'{}' is not recognized. \"\n # \"Use 'train' or 'inference'\".format(args.command))" ]
[ [ "matplotlib.pyplot.imshow", "numpy.multiply", "numpy.asarray", "matplotlib.use", "numpy.dstack", "numpy.max", "numpy.any", "matplotlib.pyplot.close", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
HongyangGao/PixelDeconv
[ "71964b6b2594d1a888435d3fb42572ffb4096165" ]
[ "network.py" ]
[ "import os\nimport numpy as np\nimport tensorflow as tf\nfrom utils.data_reader import H5DataLoader, H53DDataLoader\nfrom utils.img_utils import imsave\nfrom utils import ops\n\n\n\"\"\"\nThis module builds a standard U-NET for semantic segmentation.\nIf want VAE using pixelDCL, please visit this code:\nhttps://github.com/HongyangGao/UVAE\n\"\"\"\n\n\nclass PixelDCN(object):\n\n def __init__(self, sess, conf):\n self.sess = sess\n self.conf = conf\n self.def_params()\n if not os.path.exists(conf.modeldir):\n os.makedirs(conf.modeldir)\n if not os.path.exists(conf.logdir):\n os.makedirs(conf.logdir)\n if not os.path.exists(conf.sampledir):\n os.makedirs(conf.sampledir)\n self.configure_networks()\n self.train_summary = self.config_summary('train')\n self.valid_summary = self.config_summary('valid')\n\n def def_params(self):\n self.data_format = 'NHWC'\n if self.conf.data_type == '3D':\n self.conv_size = (3, 3, 3)\n self.pool_size = (2, 2, 2)\n self.axis, self.channel_axis = (1, 2, 3), 4\n self.input_shape = [\n self.conf.batch, self.conf.depth, self.conf.height,\n self.conf.width, self.conf.channel]\n self.output_shape = [\n self.conf.batch, self.conf.depth, self.conf.height,\n self.conf.width]\n else:\n self.conv_size = (3, 3)\n self.pool_size = (2, 2)\n self.axis, self.channel_axis = (1, 2), 3\n self.input_shape = [\n self.conf.batch, self.conf.height, self.conf.width,\n self.conf.channel]\n self.output_shape = [\n self.conf.batch, self.conf.height, self.conf.width]\n\n def configure_networks(self):\n self.build_network()\n optimizer = tf.train.AdamOptimizer(self.conf.learning_rate)\n self.train_op = optimizer.minimize(self.loss_op, name='train_op')\n tf.set_random_seed(self.conf.random_seed)\n self.sess.run(tf.global_variables_initializer())\n trainable_vars = tf.trainable_variables()\n self.saver = tf.train.Saver(var_list=trainable_vars, max_to_keep=0)\n self.writer = tf.summary.FileWriter(self.conf.logdir, self.sess.graph)\n\n def build_network(self):\n self.inputs = tf.placeholder(\n tf.float32, self.input_shape, name='inputs')\n self.labels = tf.placeholder(\n tf.int64, self.output_shape, name='labels')\n self.predictions = self.inference(self.inputs)\n self.cal_loss()\n\n def cal_loss(self):\n one_hot_labels = tf.one_hot(\n self.labels, depth=self.conf.class_num,\n axis=self.channel_axis, name='labels/one_hot')\n losses = tf.losses.softmax_cross_entropy(\n one_hot_labels, self.predictions, scope='loss/losses')\n self.loss_op = tf.reduce_mean(losses, name='loss/loss_op')\n self.decoded_preds = tf.argmax(\n self.predictions, self.channel_axis, name='accuracy/decode_pred')\n correct_prediction = tf.equal(\n self.labels, self.decoded_preds,\n name='accuracy/correct_pred')\n self.accuracy_op = tf.reduce_mean(\n tf.cast(correct_prediction, tf.float32, name='accuracy/cast'),\n name='accuracy/accuracy_op')\n # weights = tf.cast(\n # tf.greater(self.decoded_preds, 0, name='m_iou/greater'),\n # tf.int32, name='m_iou/weights')\n weights = tf.cast(\n tf.less(self.labels, self.conf.channel, name='m_iou/greater'),\n tf.int64, name='m_iou/weights')\n labels = tf.multiply(self.labels, weights, name='m_iou/mul')\n self.m_iou, self.miou_op = tf.metrics.mean_iou(\n self.labels, self.decoded_preds, self.conf.class_num,\n weights, name='m_iou/m_ious')\n\n def config_summary(self, name):\n summarys = []\n summarys.append(tf.summary.scalar(name+'/loss', self.loss_op))\n summarys.append(tf.summary.scalar(name+'/accuracy', self.accuracy_op))\n if name == 'valid' and self.conf.data_type == '2D':\n summarys.append(\n tf.summary.image(name+'/input', self.inputs, max_outputs=100))\n summarys.append(\n tf.summary.image(\n name+'/annotation',\n tf.cast(tf.expand_dims(self.labels, -1),\n tf.float32), max_outputs=100))\n summarys.append(\n tf.summary.image(\n name+'/prediction',\n tf.cast(tf.expand_dims(self.decoded_preds, -1),\n tf.float32), max_outputs=100))\n summary = tf.summary.merge(summarys)\n return summary\n\n def inference(self, inputs):\n outputs = inputs\n down_outputs = []\n for layer_index in range(self.conf.network_depth-1):\n is_first = True if not layer_index else False\n name = 'down%s' % layer_index\n outputs = self.build_down_block(\n outputs, name, down_outputs, is_first)\n outputs = self.build_bottom_block(outputs, 'bottom')\n for layer_index in range(self.conf.network_depth-2, -1, -1):\n is_final = True if layer_index == 0 else False\n name = 'up%s' % layer_index\n down_inputs = down_outputs[layer_index]\n outputs = self.build_up_block(\n outputs, down_inputs, name, is_final)\n return outputs\n\n def build_down_block(self, inputs, name, down_outputs, first=False):\n out_num = self.conf.start_channel_num if first else 2 * \\\n inputs.shape[self.channel_axis].value\n conv1 = ops.conv(inputs, out_num, self.conv_size,\n name+'/conv1', self.conf.data_type)\n conv2 = ops.conv(conv1, out_num, self.conv_size,\n name+'/conv2', self.conf.data_type)\n down_outputs.append(conv2)\n pool = ops.pool(conv2, self.pool_size, name +\n '/pool', self.conf.data_type)\n return pool\n\n def build_bottom_block(self, inputs, name):\n out_num = inputs.shape[self.channel_axis].value\n conv1 = ops.conv(\n inputs, 2*out_num, self.conv_size, name+'/conv1',\n self.conf.data_type)\n conv2 = ops.conv(\n conv1, out_num, self.conv_size, name+'/conv2', self.conf.data_type)\n return conv2\n\n def build_up_block(self, inputs, down_inputs, name, final=False):\n out_num = inputs.shape[self.channel_axis].value\n conv1 = self.deconv_func()(\n inputs, out_num, self.conv_size, name+'/conv1',\n self.conf.data_type, action=self.conf.action)\n conv1 = tf.concat(\n [conv1, down_inputs], self.channel_axis, name=name+'/concat')\n conv2 = self.conv_func()(\n conv1, out_num, self.conv_size, name+'/conv2', self.conf.data_type)\n out_num = self.conf.class_num if final else out_num/2\n conv3 = ops.conv(\n conv2, out_num, self.conv_size, name+'/conv3', self.conf.data_type,\n not final)\n return conv3\n\n def deconv_func(self):\n return getattr(ops, self.conf.deconv_name)\n\n def conv_func(self):\n return getattr(ops, self.conf.conv_name)\n\n def save_summary(self, summary, step):\n print('---->summarizing', step)\n self.writer.add_summary(summary, step)\n\n def train(self):\n if self.conf.reload_step > 0:\n self.reload(self.conf.reload_step)\n if self.conf.data_type == '2D':\n train_reader = H5DataLoader(\n self.conf.data_dir+self.conf.train_data)\n valid_reader = H5DataLoader(\n self.conf.data_dir+self.conf.valid_data)\n else:\n train_reader = H53DDataLoader(\n self.conf.data_dir+self.conf.train_data, self.input_shape)\n valid_reader = H53DDataLoader(\n self.conf.data_dir+self.conf.valid_data, self.input_shape)\n for epoch_num in range(self.conf.max_step+1):\n if epoch_num and epoch_num % self.conf.test_interval == 0:\n inputs, labels = valid_reader.next_batch(self.conf.batch)\n feed_dict = {self.inputs: inputs,\n self.labels: labels}\n loss, summary = self.sess.run(\n [self.loss_op, self.valid_summary], feed_dict=feed_dict)\n self.save_summary(summary, epoch_num+self.conf.reload_step)\n print('----testing loss', loss)\n if epoch_num and epoch_num % self.conf.summary_interval == 0:\n inputs, labels = train_reader.next_batch(self.conf.batch)\n feed_dict = {self.inputs: inputs,\n self.labels: labels}\n loss, _, summary = self.sess.run(\n [self.loss_op, self.train_op, self.train_summary],\n feed_dict=feed_dict)\n self.save_summary(summary, epoch_num+self.conf.reload_step)\n else:\n inputs, labels = train_reader.next_batch(self.conf.batch)\n feed_dict = {self.inputs: inputs,\n self.labels: labels}\n loss, _ = self.sess.run(\n [self.loss_op, self.train_op], feed_dict=feed_dict)\n print('----training loss', loss)\n if epoch_num and epoch_num % self.conf.save_interval == 0:\n self.save(epoch_num+self.conf.reload_step)\n\n def test(self):\n print('---->testing ', self.conf.test_step)\n if self.conf.test_step > 0:\n self.reload(self.conf.test_step)\n else:\n print(\"please set a reasonable test_step\")\n return\n if self.conf.data_type == '2D':\n test_reader = H5DataLoader(\n self.conf.data_dir+self.conf.test_data, False)\n else:\n test_reader = H53DDataLoader(\n self.conf.data_dir+self.conf.test_data, self.input_shape)\n self.sess.run(tf.local_variables_initializer())\n count = 0\n losses = []\n accuracies = []\n m_ious = []\n while True:\n inputs, labels = test_reader.next_batch(self.conf.batch)\n if inputs.shape[0] < self.conf.batch:\n break\n feed_dict = {self.inputs: inputs, self.labels: labels}\n loss, accuracy, m_iou, _ = self.sess.run(\n [self.loss_op, self.accuracy_op, self.m_iou, self.miou_op],\n feed_dict=feed_dict)\n print('values----->', loss, accuracy, m_iou)\n count += 1\n losses.append(loss)\n accuracies.append(accuracy)\n m_ious.append(m_iou)\n print('Loss: ', np.mean(losses))\n print('Accuracy: ', np.mean(accuracies))\n print('M_iou: ', m_ious[-1])\n\n def predict(self):\n print('---->predicting ', self.conf.test_step)\n if self.conf.test_step > 0:\n self.reload(self.conf.test_step)\n else:\n print(\"please set a reasonable test_step\")\n return\n if self.conf.data_type == '2D':\n test_reader = H5DataLoader(\n self.conf.data_dir+self.conf.test_data, False)\n else:\n test_reader = H53DDataLoader(\n self.conf.data_dir+self.conf.test_data, self.input_shape)\n predictions = []\n while True:\n inputs, labels = test_reader.next_batch(self.conf.batch)\n if inputs.shape[0] < self.conf.batch:\n break\n feed_dict = {self.inputs: inputs, self.labels: labels}\n predictions.append(self.sess.run(\n self.decoded_preds, feed_dict=feed_dict))\n print('----->saving predictions')\n for index, prediction in enumerate(predictions):\n for i in range(prediction.shape[0]):\n imsave(prediction[i], self.conf.sampledir +\n str(index*prediction.shape[0]+i)+'.png')\n\n def save(self, step):\n print('---->saving', step)\n checkpoint_path = os.path.join(\n self.conf.modeldir, self.conf.model_name)\n self.saver.save(self.sess, checkpoint_path, global_step=step)\n\n def reload(self, step):\n checkpoint_path = os.path.join(\n self.conf.modeldir, self.conf.model_name)\n model_path = checkpoint_path+'-'+str(step)\n if not os.path.exists(model_path+'.meta'):\n print('------- no such checkpoint', model_path)\n return\n self.saver.restore(self.sess, model_path)\n" ]
[ [ "tensorflow.concat", "tensorflow.equal", "tensorflow.cast", "numpy.mean", "tensorflow.train.AdamOptimizer", "tensorflow.summary.scalar", "tensorflow.summary.image", "tensorflow.losses.softmax_cross_entropy", "tensorflow.trainable_variables", "tensorflow.train.Saver", "tensorflow.argmax", "tensorflow.less", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.one_hot", "tensorflow.set_random_seed", "tensorflow.summary.merge", "tensorflow.metrics.mean_iou", "tensorflow.multiply", "tensorflow.summary.FileWriter", "tensorflow.local_variables_initializer", "tensorflow.reduce_mean", "tensorflow.expand_dims" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
archmagethanos/raven
[ "d727cc3da3dff5254b418fb3691a2e45deb20136" ]
[ "framework/TSA/PolynomialRegression.py" ]
[ "\n# Copyright 2017 Battelle Energy Alliance, LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\n Polynomial Regression\n\"\"\"\nimport numpy as np\nimport utils.importerUtils\nstatsmodels = utils.importerUtils.importModuleLazy(\"statsmodels\", globals())\n\nfrom utils import InputData, InputTypes, randomUtils, xmlUtils, mathUtils, utils\nfrom .TimeSeriesAnalyzer import TimeSeriesCharacterizer, TimeSeriesGenerator\n\n\nclass PolynomialRegression(TimeSeriesGenerator, TimeSeriesCharacterizer):\n \"\"\"\n \"\"\"\n\n @classmethod\n def getInputSpecification(cls):\n \"\"\"\n Method to get a reference to a class that specifies the input data for\n class cls.\n @ Out, inputSpecification, InputData.ParameterInput, class to use for\n specifying input of cls.\n \"\"\"\n specs = super(PolynomialRegression, cls).getInputSpecification()\n specs.name = 'PolynomialRegression'\n specs.description = \"\"\"TimeSeriesAnalysis algorithm for fitting data of degree one or greater.\"\"\"\n specs.addSub(InputData.parameterInputFactory('degree', contentType=InputTypes.IntegerType,\n descr=\"Specifies the degree polynomial to fit the data with.\"))\n return specs\n\n #\n # API Methods\n #\n def __init__(self, *args, **kwargs):\n \"\"\"\n A constructor that will appropriately intialize a supervised learning object\n @ In, args, list, an arbitrary list of positional values\n @ In, kwargs, dict, an arbitrary dictionary of keywords and values\n @ Out, None\n \"\"\"\n # general infrastructure\n super().__init__(*args, **kwargs)\n\n def handleInput(self, spec):\n \"\"\"\n Reads user inputs into this object.\n @ In, inp, InputData.InputParams, input specifications\n @ Out, settings, dict, initialization settings for this algorithm\n \"\"\"\n settings = super().handleInput(spec)\n settings['degree'] = spec.findFirst('degree').value\n return settings\n\n def characterize(self, signal, pivot, targets, settings):\n \"\"\"\n Determines the charactistics of the signal based on this algorithm.\n @ In, signal, np.ndarray, time series with dims [time, target]\n @ In, pivot, np.1darray, time-like parameter values\n @ In, targets, list(str), names of targets in same order as signal\n @ In, settings, dict, additional settings specific to this algorithm\n @ Out, params, dict, characteristic parameters\n \"\"\"\n from sklearn.preprocessing import PolynomialFeatures\n import statsmodels.api as sm\n\n params = {target: {'model': {}} for target in targets}\n\n degree = settings['degree']\n features = PolynomialFeatures(degree=degree)\n xp = features.fit_transform(pivot.reshape(-1, 1))\n\n for target in targets:\n results = sm.OLS(signal, xp).fit()\n params[target]['model']['intercept'] = results.params[0]\n for i, value in enumerate(results.params[1:]):\n params[target]['model'][f'coef{i+1}'] = value\n params[target]['model']['object'] = results\n return params\n\n def getParamNames(self, settings):\n \"\"\"\n Return list of expected variable names based on the parameters\n @ In, settings, dict, training parameters for this algorithm\n @ Out, names, list, string list of names\n \"\"\"\n names = []\n for target in settings['target']:\n base = f'{self.name}__{target}'\n names.append(f'{base}__intercept')\n for i in range(1,settings['degree']):\n names.append(f'{base}__coef{i}')\n return names\n\n def getParamsAsVars(self, params):\n \"\"\"\n Map characterization parameters into flattened variable format\n @ In, params, dict, trained parameters (as from characterize)\n @ Out, rlz, dict, realization-style response\n \"\"\"\n rlz = {}\n for target, info in params.items():\n base = f'{self.name}__{target}'\n for name, value in info['model'].items():\n if name == 'object':\n continue\n rlz[f'{base}__{name}'] = value\n return rlz\n\n def generate(self, params, pivot, settings):\n \"\"\"\n Generates a synthetic history from fitted parameters.\n @ In, params, dict, characterization such as otained from self.characterize()\n @ In, pivot, np.array(float), pivot parameter values\n @ In, settings, dict, additional settings specific to algorithm\n @ Out, synthetic, np.array(float), synthetic estimated model signal\n \"\"\"\n from sklearn.preprocessing import PolynomialFeatures\n synthetic = np.zeros((len(pivot), len(params)))\n degree = settings['degree']\n features = PolynomialFeatures(degree=degree)\n xp = features.fit_transform(pivot.reshape(-1, 1))\n\n for t, (target, _) in enumerate(params.items()):\n model = params[target]['model']['object']\n synthetic[:, t] = model.predict(xp)\n\n return synthetic\n\n\n def writeXML(self, writeTo, params):\n \"\"\"\n Allows the engine to put whatever it wants into an XML to print to file.\n @ In, writeTo, xmlUtils.StaticXmlElement, entity to write to\n @ In, params, dict, trained parameters as from self.characterize\n @ Out, None\n \"\"\"\n for target, info in params.items():\n base = xmlUtils.newNode(target)\n writeTo.append(base)\n for name, value in info['model'].items():\n if name == 'object':\n continue\n base.append(xmlUtils.newNode(name, text=f'{float(value):1.9e}'))\n" ]
[ [ "sklearn.preprocessing.PolynomialFeatures" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
esyyes/featuretools
[ "7d96bd221bad71c70b5d79ce7f7a8885c298f6df" ]
[ "featuretools/entityset/entityset.py" ]
[ "import copy\nimport logging\nfrom collections import defaultdict\n\nimport dask.dataframe as dd\nimport numpy as np\nimport pandas as pd\nfrom pandas.api.types import is_dtype_equal, is_numeric_dtype\n\nimport featuretools.variable_types.variable as vtypes\nfrom featuretools.entityset import deserialize, serialize\nfrom featuretools.entityset.entity import Entity\nfrom featuretools.entityset.relationship import Relationship, RelationshipPath\nfrom featuretools.utils.gen_utils import import_or_raise\n\npd.options.mode.chained_assignment = None # default='warn'\nlogger = logging.getLogger('featuretools.entityset')\n\n\nclass EntitySet(object):\n \"\"\"\n Stores all actual data for a entityset\n\n Attributes:\n id\n entity_dict\n relationships\n time_type\n\n Properties:\n metadata\n\n \"\"\"\n\n def __init__(self, id=None, entities=None, relationships=None):\n \"\"\"Creates EntitySet\n\n Args:\n id (str) : Unique identifier to associate with this instance\n\n entities (dict[str -> tuple(pd.DataFrame, str, str, dict[str -> Variable])]): dictionary of\n entities. Entries take the format\n {entity id -> (dataframe, id column, (time_index), (variable_types), (make_index))}.\n Note that time_index, variable_types and make_index are optional.\n\n relationships (list[(str, str, str, str)]): List of relationships\n between entities. List items are a tuple with the format\n (parent entity id, parent variable, child entity id, child variable).\n\n Example:\n\n .. code-block:: python\n\n entities = {\n \"cards\" : (card_df, \"id\"),\n \"transactions\" : (transactions_df, \"id\", \"transaction_time\")\n }\n\n relationships = [(\"cards\", \"id\", \"transactions\", \"card_id\")]\n\n ft.EntitySet(\"my-entity-set\", entities, relationships)\n \"\"\"\n self.id = id\n self.entity_dict = {}\n self.relationships = []\n self.time_type = None\n\n entities = entities or {}\n relationships = relationships or []\n for entity in entities:\n df = entities[entity][0]\n index_column = entities[entity][1]\n time_index = None\n variable_types = None\n make_index = None\n if len(entities[entity]) > 2:\n time_index = entities[entity][2]\n if len(entities[entity]) > 3:\n variable_types = entities[entity][3]\n if len(entities[entity]) > 4:\n make_index = entities[entity][4]\n self.entity_from_dataframe(entity_id=entity,\n dataframe=df,\n index=index_column,\n time_index=time_index,\n variable_types=variable_types,\n make_index=make_index)\n\n for relationship in relationships:\n parent_variable = self[relationship[0]][relationship[1]]\n child_variable = self[relationship[2]][relationship[3]]\n self.add_relationship(Relationship(parent_variable,\n child_variable))\n self.reset_data_description()\n\n def __sizeof__(self):\n return sum([entity.__sizeof__() for entity in self.entities])\n\n def __dask_tokenize__(self):\n return (EntitySet, serialize.entityset_to_description(self.metadata))\n\n def __eq__(self, other, deep=False):\n if len(self.entity_dict) != len(other.entity_dict):\n return False\n for eid, e in self.entity_dict.items():\n if eid not in other.entity_dict:\n return False\n if not e.__eq__(other[eid], deep=deep):\n return False\n for r in other.relationships:\n if r not in other.relationships:\n return False\n return True\n\n def __ne__(self, other, deep=False):\n return not self.__eq__(other, deep=deep)\n\n def __getitem__(self, entity_id):\n \"\"\"Get entity instance from entityset\n\n Args:\n entity_id (str): Id of entity.\n\n Returns:\n :class:`.Entity` : Instance of entity. None if entity doesn't\n exist.\n \"\"\"\n if entity_id in self.entity_dict:\n return self.entity_dict[entity_id]\n name = self.id or \"entity set\"\n raise KeyError('Entity %s does not exist in %s' % (entity_id, name))\n\n @property\n def entities(self):\n return list(self.entity_dict.values())\n\n @property\n def metadata(self):\n '''Returns the metadata for this EntitySet. The metadata will be recomputed if it does not exist.'''\n if self._data_description is None:\n description = serialize.entityset_to_description(self)\n self._data_description = deserialize.description_to_entityset(description)\n\n return self._data_description\n\n def reset_data_description(self):\n self._data_description = None\n\n def to_pickle(self, path, compression=None, profile_name=None):\n '''Write entityset in the pickle format, location specified by `path`.\n Path could be a local path or a S3 path.\n If writing to S3 a tar archive of files will be written.\n\n Args:\n path (str): location on disk to write to (will be created as a directory)\n compression (str) : Name of the compression to use. Possible values are: {'gzip', 'bz2', 'zip', 'xz', None}.\n profile_name (str) : Name of AWS profile to use, False to use an anonymous profile, or None.\n '''\n serialize.write_data_description(self, path, format='pickle', compression=compression, profile_name=profile_name)\n return self\n\n def to_parquet(self, path, engine='auto', compression=None, profile_name=None):\n '''Write entityset to disk in the parquet format, location specified by `path`.\n Path could be a local path or a S3 path.\n If writing to S3 a tar archive of files will be written.\n\n Args:\n path (str): location on disk to write to (will be created as a directory)\n engine (str) : Name of the engine to use. Possible values are: {'auto', 'pyarrow', 'fastparquet'}.\n compression (str) : Name of the compression to use. Possible values are: {'snappy', 'gzip', 'brotli', None}.\n profile_name (str) : Name of AWS profile to use, False to use an anonymous profile, or None.\n '''\n serialize.write_data_description(self, path, format='parquet', engine=engine, compression=compression, profile_name=profile_name)\n return self\n\n def to_csv(self, path, sep=',', encoding='utf-8', engine='python', compression=None, profile_name=None):\n '''Write entityset to disk in the csv format, location specified by `path`.\n Path could be a local path or a S3 path.\n If writing to S3 a tar archive of files will be written.\n\n Args:\n path (str) : Location on disk to write to (will be created as a directory)\n sep (str) : String of length 1. Field delimiter for the output file.\n encoding (str) : A string representing the encoding to use in the output file, defaults to 'utf-8'.\n engine (str) : Name of the engine to use. Possible values are: {'c', 'python'}.\n compression (str) : Name of the compression to use. Possible values are: {'gzip', 'bz2', 'zip', 'xz', None}.\n profile_name (str) : Name of AWS profile to use, False to use an anonymous profile, or None.\n '''\n serialize.write_data_description(self, path, format='csv', index=False, sep=sep, encoding=encoding, engine=engine, compression=compression, profile_name=profile_name)\n return self\n\n def to_dictionary(self):\n return serialize.entityset_to_description(self)\n\n ###########################################################################\n # Public getter/setter methods #########################################\n ###########################################################################\n\n def __repr__(self):\n repr_out = u\"Entityset: {}\\n\".format(self.id)\n repr_out += u\" Entities:\"\n for e in self.entities:\n if e.df.shape:\n repr_out += u\"\\n {} [Rows: {}, Columns: {}]\".format(\n e.id, e.df.shape[0], e.df.shape[1])\n else:\n repr_out += u\"\\n {} [Rows: None, Columns: None]\".format(\n e.id)\n repr_out += \"\\n Relationships:\"\n\n if len(self.relationships) == 0:\n repr_out += u\"\\n No relationships\"\n\n for r in self.relationships:\n repr_out += u\"\\n %s.%s -> %s.%s\" % \\\n (r._child_entity_id, r._child_variable_id,\n r._parent_entity_id, r._parent_variable_id)\n\n return repr_out\n\n def add_relationships(self, relationships):\n \"\"\"Add multiple new relationships to a entityset\n\n Args:\n relationships (list[Relationship]) : List of new\n relationships.\n \"\"\"\n return [self.add_relationship(r) for r in relationships][-1]\n\n def add_relationship(self, relationship):\n \"\"\"Add a new relationship between entities in the entityset\n\n Args:\n relationship (Relationship) : Instance of new\n relationship to be added.\n \"\"\"\n if relationship in self.relationships:\n logger.warning(\n \"Not adding duplicate relationship: %s\", relationship)\n return self\n\n # _operations?\n\n # this is a new pair of entities\n child_e = relationship.child_entity\n child_v = relationship.child_variable.id\n parent_e = relationship.parent_entity\n parent_v = relationship.parent_variable.id\n if not isinstance(child_e[child_v], vtypes.Id):\n child_e.convert_variable_type(variable_id=child_v,\n new_type=vtypes.Id,\n convert_data=False)\n\n if not isinstance(parent_e[parent_v], vtypes.Index):\n parent_e.convert_variable_type(variable_id=parent_v,\n new_type=vtypes.Index,\n convert_data=False)\n # Empty dataframes (as a result of accessing Entity.metadata)\n # default to object dtypes for discrete variables, but\n # indexes/ids default to ints. In this case, we convert\n # the empty column's type to int\n if isinstance(child_e.df, pd.DataFrame) and \\\n (child_e.df.empty and child_e.df[child_v].dtype == object and\n is_numeric_dtype(parent_e.df[parent_v])):\n child_e.df[child_v] = pd.Series(name=child_v, dtype=np.int64)\n\n parent_dtype = parent_e.df[parent_v].dtype\n child_dtype = child_e.df[child_v].dtype\n msg = u\"Unable to add relationship because {} in {} is Pandas dtype {}\"\\\n u\" and {} in {} is Pandas dtype {}.\"\n if not is_dtype_equal(parent_dtype, child_dtype):\n raise ValueError(msg.format(parent_v, parent_e.id, parent_dtype,\n child_v, child_e.id, child_dtype))\n\n self.relationships.append(relationship)\n self.reset_data_description()\n return self\n\n ###########################################################################\n # Relationship access/helper methods ###################################\n ###########################################################################\n\n def find_forward_paths(self, start_entity_id, goal_entity_id):\n \"\"\"\n Generator which yields all forward paths between a start and goal\n entity. Does not include paths which contain cycles.\n\n Args:\n start_entity_id (str) : id of entity to start the search from\n goal_entity_id (str) : if of entity to find forward path to\n\n See Also:\n :func:`BaseEntitySet.find_backward_paths`\n \"\"\"\n for sub_entity_id, path in self._forward_entity_paths(start_entity_id):\n if sub_entity_id == goal_entity_id:\n yield path\n\n def find_backward_paths(self, start_entity_id, goal_entity_id):\n \"\"\"\n Generator which yields all backward paths between a start and goal\n entity. Does not include paths which contain cycles.\n\n Args:\n start_entity_id (str) : Id of entity to start the search from.\n goal_entity_id (str) : Id of entity to find backward path to.\n\n See Also:\n :func:`BaseEntitySet.find_forward_paths`\n \"\"\"\n for path in self.find_forward_paths(goal_entity_id, start_entity_id):\n # Reverse path\n yield path[::-1]\n\n def _forward_entity_paths(self, start_entity_id, seen_entities=None):\n \"\"\"\n Generator which yields the ids of all entities connected through forward\n relationships, and the path taken to each. An entity will be yielded\n multiple times if there are multiple paths to it.\n\n Implemented using depth first search.\n \"\"\"\n if seen_entities is None:\n seen_entities = set()\n\n if start_entity_id in seen_entities:\n return\n\n seen_entities.add(start_entity_id)\n\n yield start_entity_id, []\n\n for relationship in self.get_forward_relationships(start_entity_id):\n next_entity = relationship.parent_entity.id\n # Copy seen entities for each next node to allow multiple paths (but\n # not cycles).\n descendants = self._forward_entity_paths(next_entity, seen_entities.copy())\n for sub_entity_id, sub_path in descendants:\n yield sub_entity_id, [relationship] + sub_path\n\n def get_forward_entities(self, entity_id, deep=False):\n \"\"\"\n Get entities that are in a forward relationship with entity\n\n Args:\n entity_id (str): Id entity of entity to search from.\n deep (bool): if True, recursively find forward entities.\n\n Yields a tuple of (descendent_id, path from entity_id to descendant).\n \"\"\"\n for relationship in self.get_forward_relationships(entity_id):\n parent_eid = relationship.parent_entity.id\n direct_path = RelationshipPath([(True, relationship)])\n yield parent_eid, direct_path\n\n if deep:\n sub_entities = self.get_forward_entities(parent_eid, deep=True)\n for sub_eid, path in sub_entities:\n yield sub_eid, direct_path + path\n\n def get_backward_entities(self, entity_id, deep=False):\n \"\"\"\n Get entities that are in a backward relationship with entity\n\n Args:\n entity_id (str): Id entity of entity to search from.\n deep (bool): if True, recursively find backward entities.\n\n Yields a tuple of (descendent_id, path from entity_id to descendant).\n \"\"\"\n for relationship in self.get_backward_relationships(entity_id):\n child_eid = relationship.child_entity.id\n direct_path = RelationshipPath([(False, relationship)])\n yield child_eid, direct_path\n\n if deep:\n sub_entities = self.get_backward_entities(child_eid, deep=True)\n for sub_eid, path in sub_entities:\n yield sub_eid, direct_path + path\n\n def get_forward_relationships(self, entity_id):\n \"\"\"Get relationships where entity \"entity_id\" is the child\n\n Args:\n entity_id (str): Id of entity to get relationships for.\n\n Returns:\n list[:class:`.Relationship`]: List of forward relationships.\n \"\"\"\n return [r for r in self.relationships if r.child_entity.id == entity_id]\n\n def get_backward_relationships(self, entity_id):\n \"\"\"\n get relationships where entity \"entity_id\" is the parent.\n\n Args:\n entity_id (str): Id of entity to get relationships for.\n\n Returns:\n list[:class:`.Relationship`]: list of backward relationships\n \"\"\"\n return [r for r in self.relationships if r.parent_entity.id == entity_id]\n\n def has_unique_forward_path(self, start_entity_id, end_entity_id):\n \"\"\"\n Is the forward path from start to end unique?\n\n This will raise if there is no such path.\n \"\"\"\n paths = self.find_forward_paths(start_entity_id, end_entity_id)\n\n next(paths)\n second_path = next(paths, None)\n\n return not second_path\n\n ###########################################################################\n # Entity creation methods ##############################################\n ###########################################################################\n\n def entity_from_dataframe(self,\n entity_id,\n dataframe,\n index=None,\n variable_types=None,\n make_index=False,\n time_index=None,\n secondary_time_index=None,\n already_sorted=False):\n \"\"\"\n Load the data for a specified entity from a Pandas DataFrame.\n\n Args:\n entity_id (str) : Unique id to associate with this entity.\n\n dataframe (pandas.DataFrame) : Dataframe containing the data.\n\n index (str, optional): Name of the variable used to index the entity.\n If None, take the first column.\n\n variable_types (dict[str -> Variable/str], optional):\n Keys are of variable ids and values are variable types or type_strings. Used to to\n initialize an entity's store.\n\n make_index (bool, optional) : If True, assume index does not\n exist as a column in dataframe, and create a new column of that name\n using integers. Otherwise, assume index exists.\n\n time_index (str, optional): Name of the variable containing\n time data. Type must be in :class:`variables.DateTime` or be\n able to be cast to datetime (e.g. str, float, or numeric.)\n\n secondary_time_index (dict[str -> Variable]): Name of variable\n containing time data to use a second time index for the entity.\n\n already_sorted (bool, optional) : If True, assumes that input dataframe\n is already sorted by time. Defaults to False.\n\n Notes:\n\n Will infer variable types from Pandas dtype\n\n Example:\n .. ipython:: python\n\n import featuretools as ft\n import pandas as pd\n transactions_df = pd.DataFrame({\"id\": [1, 2, 3, 4, 5, 6],\n \"session_id\": [1, 2, 1, 3, 4, 5],\n \"amount\": [100.40, 20.63, 33.32, 13.12, 67.22, 1.00],\n \"transaction_time\": pd.date_range(start=\"10:00\", periods=6, freq=\"10s\"),\n \"fraud\": [True, False, True, False, True, True]})\n es = ft.EntitySet(\"example\")\n es.entity_from_dataframe(entity_id=\"transactions\",\n index=\"id\",\n time_index=\"transaction_time\",\n dataframe=transactions_df)\n\n es[\"transactions\"]\n es[\"transactions\"].df\n\n \"\"\"\n variable_types = variable_types or {}\n\n if time_index is not None and time_index == index:\n raise ValueError(\"time_index and index cannot be the same value, %s\" % (time_index))\n\n if time_index is None:\n for variable, variable_type in variable_types.items():\n if variable_type == vtypes.DatetimeTimeIndex:\n raise ValueError(\"DatetimeTimeIndex variable %s must be set using time_index parameter\" % (variable))\n\n if len(self.entities) > 0:\n if not isinstance(dataframe, type(self.entities[0].df)):\n raise ValueError(\"All entity dataframes must be of the same type. \"\n \"Cannot add entity of type {} to an entityset with existing entities \"\n \"of type {}\".format(type(dataframe), type(self.entities[0].df)))\n\n entity = Entity(\n entity_id,\n dataframe,\n self,\n variable_types=variable_types,\n index=index,\n time_index=time_index,\n secondary_time_index=secondary_time_index,\n already_sorted=already_sorted,\n make_index=make_index)\n self.entity_dict[entity.id] = entity\n self.reset_data_description()\n return self\n\n def normalize_entity(self, base_entity_id, new_entity_id, index,\n additional_variables=None, copy_variables=None,\n make_time_index=None,\n make_secondary_time_index=None,\n new_entity_time_index=None,\n new_entity_secondary_time_index=None):\n \"\"\"Create a new entity and relationship from unique values of an existing variable.\n\n Args:\n base_entity_id (str) : Entity id from which to split.\n\n new_entity_id (str): Id of the new entity.\n\n index (str): Variable in old entity\n that will become index of new entity. Relationship\n will be created across this variable.\n\n additional_variables (list[str]):\n List of variable ids to remove from\n base_entity and move to new entity.\n\n copy_variables (list[str]): List of\n variable ids to copy from old entity\n and move to new entity.\n\n make_time_index (bool or str, optional): Create time index for new entity based\n on time index in base_entity, optionally specifying which variable in base_entity\n to use for time_index. If specified as True without a specific variable,\n uses the primary time index. Defaults to True if base entity has a time index.\n\n make_secondary_time_index (dict[str -> list[str]], optional): Create a secondary time index\n from key. Values of dictionary\n are the variables to associate with the secondary time index. Only one\n secondary time index is allowed. If None, only associate the time index.\n\n new_entity_time_index (str, optional): Rename new entity time index.\n\n new_entity_secondary_time_index (str, optional): Rename new entity secondary time index.\n\n \"\"\"\n base_entity = self.entity_dict[base_entity_id]\n additional_variables = additional_variables or []\n copy_variables = copy_variables or []\n\n # Check base entity to make sure time index is valid\n if base_entity.time_index is not None:\n t_index = base_entity[base_entity.time_index]\n if not isinstance(t_index, (vtypes.NumericTimeIndex, vtypes.DatetimeTimeIndex)):\n base_error = \"Time index '{0}' is not a NumericTimeIndex or DatetimeTimeIndex, but type {1}. Use set_time_index on entity '{2}' to set the time_index.\"\n raise TypeError(base_error.format(base_entity.time_index, type(t_index), str(base_entity.id)))\n\n if not isinstance(additional_variables, list):\n raise TypeError(\"'additional_variables' must be a list, but received type {}\"\n .format(type(additional_variables)))\n\n if len(additional_variables) != len(set(additional_variables)):\n raise ValueError(\"'additional_variables' contains duplicate variables. All variables must be unique.\")\n\n if not isinstance(copy_variables, list):\n raise TypeError(\"'copy_variables' must be a list, but received type {}\"\n .format(type(copy_variables)))\n\n if len(copy_variables) != len(set(copy_variables)):\n raise ValueError(\"'copy_variables' contains duplicate variables. All variables must be unique.\")\n\n for v in additional_variables + copy_variables:\n if v == index:\n raise ValueError(\"Not copying {} as both index and variable\".format(v))\n\n for v in additional_variables:\n if v == base_entity.time_index:\n raise ValueError(\"Not moving {} as it is the base time index variable. Perhaps, move the variable to the copy_variables.\".format(v))\n\n if isinstance(make_time_index, str):\n if make_time_index not in base_entity.df.columns:\n raise ValueError(\"'make_time_index' must be a variable in the base entity\")\n elif make_time_index not in additional_variables + copy_variables:\n raise ValueError(\"'make_time_index' must be specified in 'additional_variables' or 'copy_variables'\")\n if index == base_entity.index:\n raise ValueError(\"'index' must be different from the index column of the base entity\")\n\n transfer_types = {}\n transfer_types[index] = type(base_entity[index])\n for v in additional_variables + copy_variables:\n if type(base_entity[v]) == vtypes.DatetimeTimeIndex:\n transfer_types[v] = vtypes.Datetime\n elif type(base_entity[v]) == vtypes.NumericTimeIndex:\n transfer_types[v] = vtypes.Numeric\n else:\n transfer_types[v] = type(base_entity[v])\n\n # create and add new entity\n new_entity_df = self[base_entity_id].df.copy()\n\n if make_time_index is None and base_entity.time_index is not None:\n make_time_index = True\n\n if isinstance(make_time_index, str):\n # Set the new time index to make_time_index.\n base_time_index = make_time_index\n new_entity_time_index = make_time_index\n already_sorted = (new_entity_time_index == base_entity.time_index)\n elif make_time_index:\n # Create a new time index based on the base entity time index.\n base_time_index = base_entity.time_index\n if new_entity_time_index is None:\n new_entity_time_index = \"first_%s_time\" % (base_entity.id)\n\n already_sorted = True\n\n assert base_entity.time_index is not None, \\\n \"Base entity doesn't have time_index defined\"\n\n if base_time_index not in [v for v in additional_variables]:\n copy_variables.append(base_time_index)\n\n transfer_types[new_entity_time_index] = type(base_entity[base_entity.time_index])\n else:\n new_entity_time_index = None\n already_sorted = False\n\n if new_entity_time_index is not None and new_entity_time_index == index:\n raise ValueError(\"time_index and index cannot be the same value, %s\" % (new_entity_time_index))\n\n selected_variables = [index] +\\\n [v for v in additional_variables] +\\\n [v for v in copy_variables]\n\n new_entity_df2 = new_entity_df. \\\n drop_duplicates(index, keep='first')[selected_variables]\n\n if make_time_index:\n new_entity_df2 = new_entity_df2.rename(columns={base_time_index: new_entity_time_index})\n if make_secondary_time_index:\n assert len(make_secondary_time_index) == 1, \"Can only provide 1 secondary time index\"\n secondary_time_index = list(make_secondary_time_index.keys())[0]\n\n secondary_variables = [index, secondary_time_index] + list(make_secondary_time_index.values())[0]\n secondary_df = new_entity_df. \\\n drop_duplicates(index, keep='last')[secondary_variables]\n if new_entity_secondary_time_index:\n secondary_df = secondary_df.rename(columns={secondary_time_index: new_entity_secondary_time_index})\n secondary_time_index = new_entity_secondary_time_index\n else:\n new_entity_secondary_time_index = secondary_time_index\n secondary_df = secondary_df.set_index(index)\n new_entity_df = new_entity_df2.join(secondary_df, on=index)\n else:\n new_entity_df = new_entity_df2\n\n base_entity_index = index\n\n transfer_types[index] = vtypes.Categorical\n if make_secondary_time_index:\n old_ti_name = list(make_secondary_time_index.keys())[0]\n ti_cols = list(make_secondary_time_index.values())[0]\n ti_cols = [c if c != old_ti_name else secondary_time_index for c in ti_cols]\n make_secondary_time_index = {secondary_time_index: ti_cols}\n\n self.entity_from_dataframe(\n new_entity_id,\n new_entity_df,\n index,\n already_sorted=already_sorted,\n time_index=new_entity_time_index,\n secondary_time_index=make_secondary_time_index,\n variable_types=transfer_types)\n\n self.entity_dict[base_entity_id].delete_variables(additional_variables)\n\n new_entity = self.entity_dict[new_entity_id]\n base_entity.convert_variable_type(base_entity_index, vtypes.Id, convert_data=False)\n self.add_relationship(Relationship(new_entity[index], base_entity[base_entity_index]))\n self.reset_data_description()\n return self\n\n ###########################################################################\n # Data wrangling methods ###############################################\n ###########################################################################\n\n def concat(self, other, inplace=False):\n '''Combine entityset with another to create a new entityset with the\n combined data of both entitysets.\n '''\n assert_string = \"Entitysets must have the same entities, relationships\"\\\n \", and variable_ids\"\n assert (self.__eq__(other) and\n self.relationships == other.relationships), assert_string\n\n for entity in self.entities:\n assert entity.id in other.entity_dict, assert_string\n assert (len(self[entity.id].variables) ==\n len(other[entity.id].variables)), assert_string\n other_variable_ids = [o_variable.id for o_variable in\n other[entity.id].variables]\n assert (all([variable.id in other_variable_ids\n for variable in self[entity.id].variables])), assert_string\n\n if inplace:\n combined_es = self\n else:\n combined_es = copy.deepcopy(self)\n\n has_last_time_index = []\n for entity in self.entities:\n self_df = entity.df\n other_df = other[entity.id].df\n combined_df = pd.concat([self_df, other_df])\n if entity.created_index == entity.index:\n columns = [col for col in combined_df.columns if\n col != entity.index or col != entity.time_index]\n else:\n columns = [entity.index]\n combined_df.drop_duplicates(columns, inplace=True)\n\n if entity.time_index:\n combined_df.sort_values([entity.time_index, entity.index], inplace=True)\n else:\n combined_df.sort_index(inplace=True)\n if (entity.last_time_index is not None or\n other[entity.id].last_time_index is not None):\n has_last_time_index.append(entity.id)\n combined_es[entity.id].update_data(df=combined_df,\n recalculate_last_time_indexes=False)\n\n combined_es.add_last_time_indexes(updated_entities=has_last_time_index)\n self.reset_data_description()\n return combined_es\n\n ###########################################################################\n # Indexing methods ###############################################\n ###########################################################################\n def add_last_time_indexes(self, updated_entities=None):\n \"\"\"\n Calculates the last time index values for each entity (the last time\n an instance or children of that instance were observed). Used when\n calculating features using training windows\n Args:\n updated_entities (list[str]): List of entity ids to update last_time_index for\n (will update all parents of those entities as well)\n \"\"\"\n # Generate graph of entities to find leaf entities\n children = defaultdict(list) # parent --> child mapping\n child_vars = defaultdict(dict)\n for r in self.relationships:\n children[r.parent_entity.id].append(r.child_entity)\n child_vars[r.parent_entity.id][r.child_entity.id] = r.child_variable\n\n updated_entities = updated_entities or []\n if updated_entities:\n # find parents of updated_entities\n parent_queue = updated_entities[:]\n parents = set()\n while len(parent_queue):\n e = parent_queue.pop(0)\n if e in parents:\n continue\n parents.add(e)\n\n for parent_id, _ in self.get_forward_entities(e):\n parent_queue.append(parent_id)\n\n queue = [self[p] for p in parents]\n to_explore = parents\n else:\n to_explore = set([e.id for e in self.entities[:]])\n queue = self.entities[:]\n\n explored = set()\n\n for e in queue:\n e.last_time_index = None\n\n # We will explore children of entities on the queue,\n # which may not be in the to_explore set. Therefore,\n # we check whether all elements of to_explore are in\n # explored, rather than just comparing length\n while not to_explore.issubset(explored):\n entity = queue.pop(0)\n\n if entity.last_time_index is None:\n if entity.time_index is not None:\n lti = entity.df[entity.time_index].copy()\n if isinstance(entity.df, dd.DataFrame):\n # The current Dask implementation doesn't set the index of the dataframe\n # to the entity's index, so we have to do it manually here\n lti.index = entity.df[entity.index].copy()\n else:\n lti = entity.df[entity.index].copy()\n if isinstance(entity.df, dd.DataFrame):\n lti.index = entity.df[entity.index].copy()\n lti = lti.apply(lambda x: None)\n else:\n lti[:] = None\n entity.last_time_index = lti\n\n if entity.id in children:\n child_entities = children[entity.id]\n\n # if all children not explored, skip for now\n if not set([e.id for e in child_entities]).issubset(explored):\n # Now there is a possibility that a child entity\n # was not explicitly provided in updated_entities,\n # and never made it onto the queue. If updated_entities\n # is None then we just load all entities onto the queue\n # so we didn't need this logic\n for e in child_entities:\n if e.id not in explored and e.id not in [q.id for q in queue]:\n queue.append(e)\n queue.append(entity)\n continue\n\n # updated last time from all children\n for child_e in child_entities:\n if child_e.last_time_index is None:\n continue\n link_var = child_vars[entity.id][child_e.id].id\n\n if isinstance(child_e.last_time_index, dd.Series):\n to_join = child_e.df[link_var]\n to_join.index = child_e.df[child_e.index]\n\n lti_df = child_e.last_time_index.to_frame(name='last_time').join(\n to_join.to_frame(name=entity.index)\n )\n new_index = lti_df.index.copy()\n new_index.name = None\n lti_df.index = new_index\n lti_df = lti_df.groupby(lti_df[entity.index]).agg('max')\n\n lti_df = entity.last_time_index.to_frame(name='last_time_old').join(lti_df)\n\n else:\n lti_df = pd.DataFrame({'last_time': child_e.last_time_index,\n entity.index: child_e.df[link_var]})\n\n # sort by time and keep only the most recent\n lti_df.sort_values(['last_time', entity.index],\n kind=\"mergesort\", inplace=True)\n\n lti_df.drop_duplicates(entity.index,\n keep='last',\n inplace=True)\n\n lti_df.set_index(entity.index, inplace=True)\n lti_df = lti_df.reindex(entity.last_time_index.index)\n lti_df['last_time_old'] = entity.last_time_index\n if not isinstance(lti_df, dd.DataFrame) and lti_df.empty:\n # Pandas errors out if it tries to do fillna and then max on an empty dataframe\n lti_df = pd.Series()\n else:\n lti_df['last_time'] = lti_df['last_time'].astype('datetime64[ns]')\n lti_df['last_time_old'] = lti_df['last_time_old'].astype('datetime64[ns]')\n lti_df = lti_df.fillna(pd.to_datetime('1800-01-01 00:00')).max(axis=1)\n lti_df = lti_df.replace(pd.to_datetime('1800-01-01 00:00'), pd.NaT)\n # lti_df = lti_df.apply(lambda x: x.dropna().max(), axis=1)\n\n entity.last_time_index = lti_df\n entity.last_time_index.name = 'last_time'\n\n explored.add(entity.id)\n self.reset_data_description()\n\n ###########################################################################\n # Other ###############################################\n ###########################################################################\n\n def add_interesting_values(self, max_values=5, verbose=False):\n \"\"\"Find interesting values for categorical variables, to be used to generate \"where\" clauses\n\n Args:\n max_values (int) : Maximum number of values per variable to add.\n verbose (bool) : If True, print summary of interesting values found.\n\n Returns:\n None\n\n \"\"\"\n for entity in self.entities:\n entity.add_interesting_values(max_values=max_values, verbose=verbose)\n self.reset_data_description()\n\n def plot(self, to_file=None):\n \"\"\"\n Create a UML diagram-ish graph of the EntitySet.\n\n Args:\n to_file (str, optional) : Path to where the plot should be saved.\n If set to None (as by default), the plot will not be saved.\n\n Returns:\n graphviz.Digraph : Graph object that can directly be displayed in\n Jupyter notebooks.\n\n \"\"\"\n GRAPHVIZ_ERR_MSG = ('Please install graphviz to plot entity sets.' +\n ' (See https://docs.featuretools.com/en/stable/getting_started/install.html#installing-graphviz for' +\n ' details)')\n graphviz = import_or_raise(\"graphviz\", GRAPHVIZ_ERR_MSG)\n # Try rendering a dummy graph to see if a working backend is installed\n try:\n graphviz.Digraph().pipe()\n except graphviz.backend.ExecutableNotFound:\n raise RuntimeError(\n \"To plot entity sets, a graphviz backend is required.\\n\" +\n \"Install the backend using one of the following commands:\\n\" +\n \" Mac OS: brew install graphviz\\n\" +\n \" Linux (Ubuntu): sudo apt-get install graphviz\\n\" +\n \" Windows: conda install python-graphviz\\n\" +\n \" For more details visit: https://docs.featuretools.com/en/stable/getting_started/install.html\"\n )\n\n if to_file:\n # Explicitly cast to str in case a Path object was passed in\n to_file = str(to_file)\n\n split_path = to_file.split('.')\n if len(split_path) < 2:\n raise ValueError(\"Please use a file extension like '.pdf'\" +\n \" so that the format can be inferred\")\n\n format = split_path[-1]\n valid_formats = graphviz.backend.FORMATS\n if format not in valid_formats:\n raise ValueError(\"Unknown format. Make sure your format is\" +\n \" amongst the following: %s\" % valid_formats)\n else:\n format = None\n\n # Initialize a new directed graph\n graph = graphviz.Digraph(self.id, format=format,\n graph_attr={'splines': 'ortho'})\n\n # Draw entities\n for entity in self.entities:\n variables_string = '\\l'.join([var.id + ' : ' + var.type_string # noqa: W605\n for var in entity.variables])\n nrows = entity.shape[0]\n label = '{%s (%d row%s)|%s\\l}' % (entity.id, nrows, 's' * (nrows > 1), variables_string) # noqa: W605\n graph.node(entity.id, shape='record', label=label)\n\n # Draw relationships\n for rel in self.relationships:\n # Display the key only once if is the same for both related entities\n if rel._parent_variable_id == rel._child_variable_id:\n label = rel._parent_variable_id\n else:\n label = '%s -> %s' % (rel._parent_variable_id,\n rel._child_variable_id)\n\n graph.edge(rel._child_entity_id, rel._parent_entity_id, xlabel=label)\n\n if to_file:\n # Graphviz always appends the format to the file name, so we need to\n # remove it manually to avoid file names like 'file_name.pdf.pdf'\n offset = len(format) + 1 # Add 1 for the dot\n output_path = to_file[:-offset]\n graph.render(output_path, cleanup=True)\n\n return graph\n" ]
[ [ "pandas.concat", "pandas.to_datetime", "pandas.Series", "pandas.DataFrame", "pandas.api.types.is_numeric_dtype", "pandas.api.types.is_dtype_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
zmldndx/horovod
[ "e9b1e228ff92eb7f65d9aea2d36f23b327df28bd", "e9b1e228ff92eb7f65d9aea2d36f23b327df28bd", "89175b7381e44f5eb3023d7bc22ba768b31fee53" ]
[ "horovod/spark/keras/tensorflow.py", "examples/pytorch_synthetic_benchmark.py", "test/test_adasum_pytorch.py" ]
[ "# Copyright 2019 Uber Technologies, Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nfrom __future__ import absolute_import\n\nimport json\n\nfrom six.moves import zip\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras import optimizers\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util import serialization\n\n\ndef save_tf_keras_optimizer(optimizer, h5py_file):\n if isinstance(optimizer, optimizers.TFOptimizer):\n logging.warning(\n 'TensorFlow optimizers do not '\n 'make it possible to access '\n 'optimizer attributes or optimizer state '\n 'after instantiation. '\n 'As a result, we cannot save the optimizer '\n 'as part of the model save file.'\n 'You will have to compile your model again after loading it. '\n 'Prefer using a Keras optimizer instead '\n '(see keras.io/optimizers).')\n else:\n h5py_file.attrs['training_config'] = json.dumps(\n {\n 'optimizer_config': {\n 'class_name': optimizer.__class__.__name__,\n 'config': optimizer.get_config()\n }\n },\n default=serialization.get_json_type).encode('utf8')\n\n # Save optimizer weights.\n symbolic_weights = getattr(optimizer, 'weights')\n if symbolic_weights:\n optimizer_weights_group = h5py_file.create_group('optimizer_weights')\n weight_values = K.batch_get_value(symbolic_weights)\n weight_names = []\n for w, val in zip(symbolic_weights, weight_values):\n name = str(w.name)\n weight_names.append(name.encode('utf8'))\n optimizer_weights_group.attrs['weight_names'] = weight_names\n for name, val in zip(weight_names, weight_values):\n param_dset = optimizer_weights_group.create_dataset(\n name, val.shape, dtype=val.dtype)\n if not val.shape:\n # scalar\n param_dset[()] = val\n else:\n param_dset[:] = val\n h5py_file.flush()\n\n\ndef load_tf_keras_optimizer(h5py_file, custom_objects=None):\n if not custom_objects:\n custom_objects = {}\n\n def convert_custom_objects(obj):\n \"\"\"Handles custom object lookup.\n\n Arguments:\n obj: object, dict, or list.\n\n Returns:\n The same structure, where occurrences\n of a custom object name have been replaced\n with the custom object.\n \"\"\"\n if isinstance(obj, list):\n deserialized = []\n for value in obj:\n deserialized.append(convert_custom_objects(value))\n return deserialized\n if isinstance(obj, dict):\n deserialized = {}\n for key, value in obj.items():\n deserialized[key] = convert_custom_objects(value)\n return deserialized\n if obj in custom_objects:\n return custom_objects[obj]\n return obj\n\n optimizer, optimizer_weight_values = None, None\n\n # instantiate optimizer\n training_config = h5py_file.attrs.get('training_config')\n training_config = json.loads(training_config.decode('utf-8'))\n optimizer_config = training_config['optimizer_config']\n optimizer = optimizers.deserialize(optimizer_config, custom_objects=custom_objects)\n\n if 'optimizer_weights' in h5py_file:\n optimizer_weights_group = h5py_file['optimizer_weights']\n optimizer_weight_names = [\n n.decode('utf8')\n for n in optimizer_weights_group.attrs['weight_names']\n ]\n optimizer_weight_values = [optimizer_weights_group[n].value for n in\n optimizer_weight_names]\n if optimizer_weight_values:\n optimizer.set_weights(optimizer_weight_values)\n return optimizer\n", "from __future__ import print_function\n\nimport argparse\nimport torch.backends.cudnn as cudnn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.utils.data.distributed\nfrom torchvision import models\nimport horovod.torch as hvd\nimport timeit\nimport numpy as np\n\n# Benchmark settings\nparser = argparse.ArgumentParser(description='PyTorch Synthetic Benchmark',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument('--fp16-allreduce', action='store_true', default=False,\n help='use fp16 compression during allreduce')\n\nparser.add_argument('--model', type=str, default='resnet50',\n help='model to benchmark')\nparser.add_argument('--batch-size', type=int, default=32,\n help='input batch size')\n\nparser.add_argument('--num-warmup-batches', type=int, default=10,\n help='number of warm-up batches that don\\'t count towards benchmark')\nparser.add_argument('--num-batches-per-iter', type=int, default=10,\n help='number of batches per benchmark iteration')\nparser.add_argument('--num-iters', type=int, default=10,\n help='number of benchmark iterations')\n\nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\n\nparser.add_argument('--use-adasum', action='store_true', default=False,\n help='use adasum algorithm to do reduction')\n\nargs = parser.parse_args()\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\n\nhvd.init()\n\nif args.cuda:\n # Horovod: pin GPU to local rank.\n torch.cuda.set_device(hvd.local_rank())\n\ncudnn.benchmark = True\n\n# Set up standard model.\nmodel = getattr(models, args.model)()\n\n# By default, Adasum doesn't need scaling up learning rate.\nlr_scaler = hvd.size() if not args.use_adasum else 1\n\nif args.cuda:\n # Move model to GPU.\n model.cuda()\n # If using GPU Adasum allreduce, scale learning rate by local_size.\n if args.use_adasum and hvd.nccl_built():\n lr_scaler = hvd.local_size()\n\noptimizer = optim.SGD(model.parameters(), lr=0.01 * lr_scaler)\n\n# Horovod: (optional) compression algorithm.\ncompression = hvd.Compression.fp16 if args.fp16_allreduce else hvd.Compression.none\n\n# Horovod: wrap optimizer with DistributedOptimizer.\noptimizer = hvd.DistributedOptimizer(optimizer,\n named_parameters=model.named_parameters(),\n compression=compression,\n op=hvd.Adasum if args.use_adasum else hvd.Average)\n\n# Horovod: broadcast parameters & optimizer state.\nhvd.broadcast_parameters(model.state_dict(), root_rank=0)\nhvd.broadcast_optimizer_state(optimizer, root_rank=0)\n\n# Set up fixed fake data\ndata = torch.randn(args.batch_size, 3, 224, 224)\ntarget = torch.LongTensor(args.batch_size).random_() % 1000\nif args.cuda:\n data, target = data.cuda(), target.cuda()\n\n\ndef benchmark_step():\n optimizer.zero_grad()\n output = model(data)\n loss = F.cross_entropy(output, target)\n loss.backward()\n optimizer.step()\n\n\ndef log(s, nl=True):\n if hvd.rank() != 0:\n return\n print(s, end='\\n' if nl else '')\n\n\nlog('Model: %s' % args.model)\nlog('Batch size: %d' % args.batch_size)\ndevice = 'GPU' if args.cuda else 'CPU'\nlog('Number of %ss: %d' % (device, hvd.size()))\n\n# Warm-up\nlog('Running warmup...')\ntimeit.timeit(benchmark_step, number=args.num_warmup_batches)\n\n# Benchmark\nlog('Running benchmark...')\nimg_secs = []\nfor x in range(args.num_iters):\n time = timeit.timeit(benchmark_step, number=args.num_batches_per_iter)\n img_sec = args.batch_size * args.num_batches_per_iter / time\n log('Iter #%d: %.1f img/sec per %s' % (x, img_sec, device))\n img_secs.append(img_sec)\n\n# Results\nimg_sec_mean = np.mean(img_secs)\nimg_sec_conf = 1.96 * np.std(img_secs)\nlog('Img/sec per %s: %.1f +-%.1f' % (device, img_sec_mean, img_sec_conf))\nlog('Total img/sec on %d %s(s): %.1f +-%.1f' %\n (hvd.size(), device, hvd.size() * img_sec_mean, hvd.size() * img_sec_conf))\n", "# Copyright 2019 Microsoft. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\n\nimport torch\nimport horovod.torch as hvd\nimport numpy as np\nimport time\nfrom horovod.torch.mpi_ops import synchronize\nimport os\nimport math\nimport unittest\nimport warnings\nfrom distutils.version import LooseVersion\n\n_fp16_supported = LooseVersion(torch.__version__) >= LooseVersion('1.0.0')\n\nclass TorchAdasumTests(unittest.TestCase):\n \"\"\"\n Tests for Adasum reduction logic in horovod.torch.\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(TorchAdasumTests, self).__init__(*args, **kwargs)\n warnings.simplefilter('module')\n self.data_types = [np.float32]\n if _fp16_supported:\n self.data_types.append(np.float16)\n\n def diff_ratio(self, true_vec, comp_vec):\n norm_diff = np.linalg.norm(true_vec-comp_vec)\n norm_true = np.linalg.norm(true_vec)\n return norm_diff/norm_true/100.\n\n def are_close(self, data_type, true_vec, comp_vec):\n return self.diff_ratio(true_vec, comp_vec) < np.finfo(data_type).eps\n\n def test_orthogonal(self):\n hvd.init()\n # TODO support non-MPI Adasum operation\n # Only do this test if there are GPUs available.\n if not hvd.mpi_enabled() or not torch.cuda.is_available():\n return\n device = torch.device('cuda:{}'.format(hvd.local_rank()))\n np.random.seed(2)\n torch.manual_seed(2)\n size = hvd.size()\n local_size = hvd.local_size()\n rank = hvd.rank()\n\n for data_type in self.data_types:\n denominator = local_size if hvd.nccl_built() else 1\n all_Ns = [size*20 - 17, size*2+1, size+2, 2**19]\n tensors = []\n all_qs = []\n for N in all_Ns:\n a = np.random.normal(0, 1, (N,size)).astype(np.float64)\n q, r = np.linalg.qr(a)\n q = q.astype(data_type)\n all_qs.append(q.astype(np.float64))\n tensors.append(q[:,hvd.rank()])\n\n tensors = list(map(lambda x: torch.from_numpy(x).to(device), tensors))\n\n handles = [\n hvd.allreduce_async(tensor, op=hvd.Adasum)\n for tensor in tensors\n ]\n\n reduced_tensors = [synchronize(h) for h in handles]\n\n expected = [np.sum(q,axis=1) / denominator for q in all_qs]\n all_comp = [self.are_close(data_type, e, rt.cpu().numpy()) for e,rt in zip(expected,reduced_tensors)]\n if np.alltrue(all_comp):\n print('Orthogonal test passed')\n else:\n for c,e,rt in zip(all_comp, expected, reduced_tensors):\n if c == False:\n print('computed: ', rt)\n print('expected: ', e)\n print('off by: ', self.diff_ratio(e,rt.cpu().numpy()))\n assert np.alltrue(all_comp)\n\n def test_parallel(self):\n hvd.init()\n # TODO support non-MPI Adasum operation\n # Only do this test if there are GPUs available.\n if not hvd.mpi_enabled() or not torch.cuda.is_available():\n return\n\n device = torch.device('cuda:{}'.format(hvd.local_rank()))\n np.random.seed(2)\n torch.manual_seed(2)\n size = hvd.size()\n local_size = hvd.local_size()\n rank = hvd.rank()\n\n for data_type in self.data_types:\n all_Ns = [size*20 - 13, size*2+1, size+2, 2**19]\n tensors = []\n all_qs = []\n for N in all_Ns:\n a = np.random.normal(0, 1, (N, 1)).astype(np.float64)\n r = np.random.normal(0, 1, (size, 1)).astype(np.float64)\n q = np.dot(a,r.T)\n q = q.astype(data_type)\n all_qs.append(q.astype(np.float64))\n tensors.append(q[:,hvd.rank()])\n\n tensors = list(map(lambda x: torch.from_numpy(x).to(device), tensors))\n\n handles = [\n hvd.allreduce_async(tensor, op=hvd.Adasum)\n for tensor in tensors\n ]\n\n reduced_tensors = [synchronize(h) for h in handles]\n\n expected = [np.sum(q,axis=1) / size for q in all_qs]\n all_comp = [self.are_close(data_type, e, rt.cpu().numpy()) for e,rt in zip(expected,reduced_tensors)]\n if np.alltrue(all_comp):\n print('Parallel test passed')\n else:\n for c,e,rt in zip(all_comp, expected, reduced_tensors):\n if c == False:\n print('computed: ', rt)\n print('expected: ', e)\n print('off by: ', self.diff_ratio(e,rt.cpu().numpy()))\n assert np.alltrue(all_comp)\n\n def test_stability(self):\n hvd.init()\n # TODO support non-MPI Adasum operation\n if not hvd.mpi_enabled():\n return\n device = torch.device('cuda:{}'.format(hvd.local_rank())) if torch.cuda.is_available() else torch.device('cpu')\n np.random.seed(2)\n torch.manual_seed(2)\n size = hvd.size()\n local_size = hvd.local_size()\n rank = hvd.rank()\n\n for data_type in self.data_types:\n N = 1024\n a = np.random.normal(0, np.finfo(data_type).tiny, (N, 1)).astype(np.float64)\n r = np.random.normal(0, 1, (size, 1)).astype(np.float64)\n q = np.dot(a,r.T).astype(data_type).astype(np.float64)\n tensor = np.zeros(N,dtype=data_type)\n tensor[:] = q[:,hvd.rank()]\n\n tensor = torch.from_numpy(tensor).to(device)\n\n hvd.allreduce_(tensor, op=hvd.Adasum)\n\n expected = np.sum(q,axis=1) / size\n comp = self.are_close(data_type, expected, tensor.cpu().numpy()) \n if comp:\n print('Stability test passed')\n else:\n print('computed: ', tensor)\n print('expected: ', expected)\n print('off by: ', self.diff_ratio(expected,tensor.cpu().numpy()))\n assert comp\n\n def test_stability_2(self):\n hvd.init()\n # TODO support non-MPI Adasum operation\n if not hvd.mpi_enabled():\n return\n device = torch.device('cuda:{}'.format(hvd.local_rank())) if torch.cuda.is_available() else torch.device('cpu')\n np.random.seed(2)\n torch.manual_seed(2)\n size = hvd.size()\n local_size = hvd.local_size()\n rank = hvd.rank()\n\n for data_type in self.data_types:\n N = 1024\n dt_min = np.finfo(data_type).tiny.astype(np.float64)\n dt_max = math.sqrt(np.finfo(data_type).max.astype(np.float64))\n a = np.random.normal(0, 1, (N, 1)).astype(np.float64)\n r = np.array([dt_max**(float(i+1)/float(size))*dt_min**(float(size-i-1)/float(size)) for i in range(size)]).reshape(size,1).astype(np.float64)\n np.random.shuffle(r)\n q = np.dot(a,r.T).astype(data_type).astype(np.float64)\n tensor = np.zeros(N,dtype=data_type)\n tensor[:] = q[:,hvd.rank()]\n\n tensor = torch.from_numpy(tensor).to(device)\n\n hvd.allreduce_(tensor, op=hvd.Adasum)\n\n expected = np.sum(q,axis=1) / size\n comp = self.are_close(data_type, expected, tensor.cpu().numpy()) \n if comp:\n print('Stability 2 test passed')\n else:\n print('computed: ', tensor)\n print('expected: ', expected)\n print('off by: ', self.diff_ratio(expected,tensor.cpu().numpy()))\n assert comp\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "tensorflow.python.platform.tf_logging.warning", "tensorflow.python.keras.backend.batch_get_value", "tensorflow.python.keras.optimizers.deserialize" ], [ "numpy.std", "torch.nn.functional.cross_entropy", "numpy.mean" ], [ "numpy.dot", "numpy.random.seed", "torch.manual_seed", "numpy.linalg.norm", "numpy.random.shuffle", "numpy.finfo", "torch.from_numpy", "numpy.random.normal", "numpy.alltrue", "numpy.linalg.qr", "torch.cuda.is_available", "torch.device", "numpy.zeros", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
noaa-ocs-modeling/OCSMesh
[ "d7f97196a0174f3818bfa036a18088acbeff4c78" ]
[ "ocsmesh/mesh/mesh.py" ]
[ "\"\"\"This module defines classes that handle mesh and mesh operations.\n\nThis module defines a factory class for mesh, similar to geometry and\nsize function factory class. It also defines concrete mesh types.\nCurrently two concrete mesh types are defined for generic Eucledian\nmesh and specific 2D Eucledian mesh.\n\"\"\"\nfrom functools import lru_cache\nimport logging\nfrom multiprocessing import Pool, cpu_count\nimport os\nimport pathlib\nfrom collections import defaultdict\nimport warnings\nfrom typing import Union, List, Tuple, Dict, Any, Optional\ntry:\n from typing import Literal\nexcept ImportError:\n from typing_extensions import Literal\n\nimport pandas as pd\nimport geopandas as gpd\nfrom jigsawpy import jigsaw_msh_t, savemsh, loadmsh, savevtk\nfrom matplotlib.path import Path\nfrom matplotlib.transforms import Bbox\nfrom matplotlib.tri import Triangulation\nfrom matplotlib.axes import Axes\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.typing as npt\nfrom pyproj import CRS, Transformer\nfrom scipy.interpolate import (\n RectBivariateSpline, RegularGridInterpolator)\nfrom shapely.geometry import (\n LineString, box, Polygon, MultiPolygon)\nfrom shapely.ops import polygonize, linemerge\n\n\nfrom ocsmesh import utils\nfrom ocsmesh.raster import Raster\nfrom ocsmesh.mesh.base import BaseMesh\nfrom ocsmesh.mesh.parsers import grd, sms2dm\n\n\n_logger = logging.getLogger(__name__)\n\n\n\nclass EuclideanMesh(BaseMesh):\n \"\"\"Generic Euclidean mesh class\n\n This is the base class for 2D or 3D Euclidean mesh.\n\n Attributes\n ----------\n tria3 : npt.NDArray[jigsaw_msh_t.TRIA3_t]\n Reference to underlying jigsaw mesh's triangle element\n structure.\n triangles : npt.NDArray[np.float32]\n Array of node index for triangular elements.\n quad4 : npt.NDArray[jigsaw_msh_t.QUAD4_t]\n Reference to underlying jigsaw mesh's quadrangle element\n structure.\n quads : npt.NDArray[np.float32]\n Array of node index for quadrangular elements.\n crs : CRS\n Coodrinate reference system of the mesh object\n hull : Hull\n Handle to hull calculation helper object\n nodes : Nodes\n Handle to node handler helper object\n elements : Elements\n Handle to element handler helper object\n\n Methods\n -------\n write(path, overwrite=False, format='grd')\n Export mesh object to the disk in the specified format.\n \"\"\"\n\n def __init__(self, mesh: jigsaw_msh_t) -> None:\n \"\"\"Initialize Euclidean mesh object.\n\n Parameters\n ----------\n mesh : jigsaw_msh_t\n The underlying jigsaw_msh_t object to hold onto mesh data.\n\n Raises\n ------\n TypeError\n If input mesh is not of `jigsaw_msh_t` type.\n ValueError\n If input mesh's `mshID` is not equal to ``euclidean-mesh``.\n If input mesh has `crs` property which is not of `CRS` type.\n \"\"\"\n\n if not isinstance(mesh, jigsaw_msh_t):\n raise TypeError(f'Argument mesh must be of type {jigsaw_msh_t}, '\n f'not type {type(mesh)}.')\n if mesh.mshID != 'euclidean-mesh':\n raise ValueError(f'Argument mesh has property mshID={mesh.mshID}, '\n \"but expected 'euclidean-mesh'.\")\n if not hasattr(mesh, 'crs'):\n warnings.warn('Input mesh has no CRS information.')\n mesh.crs = None\n else:\n if not isinstance(mesh.crs, CRS):\n raise ValueError(f'crs property must be of type {CRS}, not '\n f'type {type(mesh.crs)}.')\n\n self._hull = None\n self._nodes = None\n self._elements = None\n self._msh_t = mesh\n\n def write(\n self,\n path: Union[str, os.PathLike],\n overwrite: bool = False,\n format : Literal['grd', '2dm', 'msh', 'vtk'] = 'grd', # pylint: disable=W0622\n ) -> None:\n \"\"\"Export the mesh object to the disk\n\n Parameters\n ----------\n path : path-like\n Path to which the mesh should be exported.\n overwrite : bool, default=False\n Whether to overwrite, if a file already exists in `path`\n format : { 'grd', '2dm', 'msh', 'vtk' }\n Format of the export, SMS-2DM or GRD.\n\n Returns\n -------\n None\n\n Raises\n ------\n ValueError\n If specified export format is **not** supported.\n \"\"\"\n\n path = pathlib.Path(path)\n if path.exists() and overwrite is not True:\n raise IOError(\n f'File {str(path)} exists and overwrite is not True.')\n if format == 'grd':\n grd_dict = utils.msh_t_to_grd(self.msh_t)\n if self._boundaries and self._boundaries.data:\n grd_dict.update(boundaries=self._boundaries.data)\n grd.write(grd_dict, path, overwrite)\n\n elif format == '2dm':\n sms2dm.writer(utils.msh_t_to_2dm(self.msh_t), path, overwrite)\n\n elif format == 'msh':\n savemsh(str(path), self.msh_t)\n\n elif format == 'vtk':\n savevtk(str(path), self.msh_t)\n\n else:\n raise ValueError(f'Unhandled format {format}.')\n\n @property\n def tria3(self):\n \"\"\"Reference to underlying mesh tirangle element structure\"\"\"\n\n return self.msh_t.tria3\n\n @property\n def triangles(self):\n \"\"\"Reference to underlying mesh triangle element index array\"\"\"\n\n return self.msh_t.tria3['index']\n\n @property\n def quad4(self):\n \"\"\"Reference to underlying mesh quadrangle element structure\"\"\"\n\n return self.msh_t.quad4\n\n @property\n def quads(self):\n \"\"\"Reference to underlying mesh quadrangle element index array\"\"\"\n\n return self.msh_t.quad4['index']\n\n @property\n def crs(self):\n \"\"\"Reference to underlying mesh crs\"\"\"\n\n return self.msh_t.crs\n\n @property\n def hull(self):\n \"\"\"Reference to hull calculator helper object\"\"\"\n\n if self._hull is None:\n self._hull = Hull(self)\n return self._hull\n\n @property\n def nodes(self):\n \"\"\"Reference to node handler helper object\"\"\"\n\n if self._nodes is None:\n self._nodes = Nodes(self)\n return self._nodes\n\n @property\n def elements(self):\n \"\"\"Reference to element handler helper object\"\"\"\n\n if self._elements is None:\n self._elements = Elements(self)\n return self._elements\n\n\nclass EuclideanMesh2D(EuclideanMesh):\n \"\"\"2D Euclidean mesh definition\n\n Attributes\n ----------\n boundaries\n vert2\n value\n bbox\n\n Methods\n -------\n get_bbox(crs=None, output_type=None)\n Gets the bounding box of the mesh elements.\n tricontourf(**kwargs)\n Create a contour plot from the value data on the nodes of\n the mesh\n interpolate(raster, method='spline', nprocs=None)\n Interpolate raster date on the nodes.\n get_contour(level)\n Get contour lines from node value data at specified levels.\n get_multipolygon(zmin=None, zmax=None)\n Get multipolygon of the mesh hull.\n \"\"\"\n\n def __init__(self, mesh: jigsaw_msh_t) -> None:\n \"\"\"Initialize Euclidean 2D mesh object.\n\n Parameters\n ----------\n mesh : jigsaw_msh_t\n The underlying jigsaw_msh_t object to hold onto mesh data.\n\n Raises\n ------\n ValueError\n If number of mesh dimensions is not equal to ``2``.\n \"\"\"\n\n super().__init__(mesh)\n self._boundaries = None\n\n if mesh.ndims != +2:\n raise ValueError(f'Argument mesh has property ndims={mesh.ndims}, '\n \"but expected ndims=2.\")\n\n if len(self.msh_t.value) == 0:\n self.msh_t.value = np.array(\n np.full((self.vert2['coord'].shape[0], 1), np.nan))\n\n def get_bbox(\n self,\n crs: Union[str, CRS, None] = None,\n output_type: Literal[None, 'polygon', 'bbox'] = None\n ) -> Union[Polygon, Bbox]:\n \"\"\"Get the bounding box of mesh elements.\n\n Parameters\n ----------\n crs : str or CRS or None, default=None\n CRS to transform the calculated bounding box into before\n returning\n output_type : { None, 'polygon', 'bbox'}, default=None\n Output type\n\n Returns\n -------\n Polygon or Bbox\n Bounding box of the mesh elements.\n \"\"\"\n\n output_type = 'polygon' if output_type is None else output_type\n xmin, xmax = np.min(self.coord[:, 0]), np.max(self.coord[:, 0])\n ymin, ymax = np.min(self.coord[:, 1]), np.max(self.coord[:, 1])\n crs = self.crs if crs is None else crs\n if crs is not None:\n if not self.crs.equals(crs):\n transformer = Transformer.from_crs(\n self.crs, crs, always_xy=True)\n # pylint: disable=E0633\n (xmin, xmax), (ymin, ymax) = transformer.transform(\n (xmin, xmax), (ymin, ymax))\n if output_type == 'polygon': # pylint: disable=R1705\n return box(xmin, ymin, xmax, ymax)\n elif output_type == 'bbox':\n return Bbox([[xmin, ymin], [xmax, ymax]])\n\n raise TypeError(\n 'Argument output_type must a string literal \\'polygon\\' or '\n '\\'bbox\\'')\n\n @property\n def boundaries(self):\n \"\"\"Handle to boundaries calculator helper object\"\"\"\n\n if self._boundaries is None:\n self._boundaries = Boundaries(self)\n return self._boundaries\n\n def tricontourf(self, **kwargs) -> Axes:\n \"\"\"Generate contour for the data of triangular elements of the mesh\n\n Parameters\n ----------\n **kwargs : dict, optional\n Passed to underlying `matplotlib` API.\n\n Returns\n -------\n Axes\n Axes on which the filled contour is drawn.\n \"\"\"\n\n return utils.tricontourf(self.msh_t, **kwargs)\n\n def interpolate(\n self,\n raster: Union[Raster, List[Raster]],\n method: Literal['spline', 'linear', 'nearest'] = 'spline',\n nprocs: Optional[int] = None,\n info_out_path: Union[pathlib.Path, str, None] = None,\n filter_by_shape: bool = False\n ) -> None:\n \"\"\"Interplate values from raster inputs to the mesh nodes.\n\n Parameters\n ----------\n raster : Raster or list of Raster\n A single or a list of rasters from which values are\n interpolated onto the mesh\n method : {'spline', 'linear', 'nearest'}, default='spline'\n Method of interpolation.\n nprocs : int or None, default=None\n Number of workers to use when interpolating data.\n info_out_path : pathlike or str or None\n Path for the output node interpolation information file\n filter_by_shape : bool\n Flag for node filtering based on raster bbox or shape\n\n Returns\n -------\n None\n \"\"\"\n\n if isinstance(raster, Raster):\n raster = [raster]\n\n nprocs = -1 if nprocs is None else nprocs\n nprocs = cpu_count() if nprocs == -1 else nprocs\n\n # Fix an issue on Jupyter notebook where having pool execute\n # interpolation even in case of nprocs == 1 would results in\n # application getting stuck\n if nprocs > 1:\n with Pool(processes=nprocs) as pool:\n res = pool.starmap(\n _mesh_interpolate_worker,\n [(self.vert2['coord'], self.crs,\n _raster.tmpfile, _raster.chunk_size,\n method, filter_by_shape)\n for _raster in raster]\n )\n pool.join()\n else:\n res = [_mesh_interpolate_worker(\n self.vert2['coord'], self.crs,\n _raster.tmpfile, _raster.chunk_size,\n method, filter_by_shape)\n for _raster in raster]\n\n values = self.msh_t.value.flatten()\n\n interp_info_map = {}\n for (mask, _values), rast in zip(res, raster):\n values[mask] = _values\n\n if info_out_path is not None:\n vert_cs = None\n rast_crs = rast.crs\n if rast_crs.is_vertical:\n if rast_crs.sub_crs_list is not None:\n for sub_crs in rast_crs.sub_crs_list:\n if sub_crs.is_vertical:\n # TODO: What if sub CRS is compound, etc.?\n vert_cs = sub_crs\n elif rast_crs.source_crs is not None:\n if rast_crs.source_crs.is_vertical:\n # TODO: What if source CRS is compound, etc.?\n vert_cs = rast_crs.source_crs\n\n\n vert_cs_name = vert_cs.name\n idxs = np.argwhere(mask).ravel()\n interp_info_map.update({\n idx: (rast.path, vert_cs_name)\n for idx in idxs})\n\n if info_out_path is not None:\n coords = self.msh_t.vert2['coord'].copy()\n geo_coords = coords.copy()\n if not self.crs.is_geographic:\n transformer = Transformer.from_crs(\n self.crs, CRS.from_epsg(4326), always_xy=True)\n # pylint: disable=E0633\n geo_coords[:, 0], geo_coords[:, 1] = transformer.transform(\n coords[:, 0], coords[:, 1])\n vd_idxs=np.array(list(interp_info_map.keys()))\n df_interp_info = pd.DataFrame(\n index=vd_idxs,\n data={\n 'x': coords[vd_idxs, 0],\n 'y': coords[vd_idxs, 1],\n 'lat': geo_coords[vd_idxs, 0],\n 'lon': geo_coords[vd_idxs, 1],\n 'elev': values[vd_idxs],\n 'crs': [i[1] for i in interp_info_map.values()],\n 'source': [i[0] for i in interp_info_map.values()]\n }\n )\n df_interp_info.sort_index().to_csv(\n info_out_path, header=False, index=True)\n\n\n self.msh_t.value = np.array(values.reshape((values.shape[0], 1)),\n dtype=jigsaw_msh_t.REALS_t)\n\n\n def get_contour(self, level: float) -> LineString:\n \"\"\"Extract contour lines at the specified `level` from mesh values\n\n Parameters\n ----------\n level : float\n The level at which contour lines must be extracted.\n\n Returns\n -------\n LineString\n Extracted and merged contour lines.\n\n Raises\n ------\n ValueError\n If mesh has nodes that have null value `np.nan`.\n \"\"\"\n\n # ONLY SUPPORTS TRIANGLES\n for attr in ['quad4', 'hexa8']:\n if len(getattr(self.msh_t, attr)) > 0:\n warnings.warn(\n 'Mesh contour extraction only supports triangles')\n\n coords = self.msh_t.vert2['coord']\n values = self.msh_t.value\n trias = self.msh_t.tria3['index']\n if np.any(np.isnan(values)):\n raise ValueError(\n \"Mesh contains invalid values. Raster values must\"\n \"be interpolated to the mesh before generating \"\n \"boundaries.\")\n\n x, y = coords[:, 0], coords[:, 1]\n features = []\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', UserWarning)\n _logger.debug('Computing contours...')\n fig, ax = plt.subplots()\n ax.tricontour(\n x, y, trias, values.ravel(), levels=[level])\n plt.close(fig)\n for path_collection in ax.collections:\n for path in path_collection.get_paths():\n try:\n features.append(LineString(path.vertices))\n except ValueError:\n # LineStrings must have at least 2 coordinate tuples\n pass\n return linemerge(features)\n\n\n def get_multipolygon(\n self,\n zmin: Optional[float] = None,\n zmax: Optional[float] = None\n ) -> MultiPolygon:\n \"\"\"Calculate multipolygon covering mesh elements (hull)\n\n Parameters\n ----------\n zmin : float or None\n Minimum elevation to consider for multipolygon extraction\n zmax : float or None\n Maximum elevation to consider for multipolygon extraction\n\n Returns\n -------\n MultiPolygon\n Calculated multipolygon shape\n \"\"\"\n\n values = self.msh_t.value\n mask = np.ones(values.shape)\n if zmin is not None:\n mask = np.logical_and(mask, values > zmin)\n if zmax is not None:\n mask = np.logical_and(mask, values < zmax)\n\n # Assuming value is of shape (N, 1)\n # ravel to make sure it's 1D\n verts_in = np.argwhere(mask).ravel()\n\n clipped_mesh = utils.clip_mesh_by_vertex(\n self.msh_t, verts_in,\n can_use_other_verts=True)\n\n boundary_edges = utils.get_boundary_edges(clipped_mesh)\n coords = clipped_mesh.vert2['coord']\n coo_to_idx = {\n tuple(coo): idx\n for idx, coo in enumerate(coords)}\n poly_gen = polygonize(coords[boundary_edges])\n polys = list(poly_gen)\n polys = sorted(polys, key=lambda p: p.area, reverse=True)\n\n rings = [p.exterior for p in polys]\n n_parents = np.zeros((len(rings),))\n represent = np.array([r.coords[0] for r in rings])\n for e, ring in enumerate(rings[:-1]):\n path = Path(ring.coords, closed=True)\n n_parents = n_parents + np.pad(\n np.array([\n path.contains_point(pt) for pt in represent[e+1:]]),\n (e+1, 0), 'constant', constant_values=0)\n\n # Get actual polygons based on logic described above\n polys = [p for e, p in enumerate(polys) if not n_parents[e] % 2]\n\n return MultiPolygon(polys)\n\n @property\n def vert2(self):\n \"\"\"Reference to underlying mesh 2D vertices structure\"\"\"\n return self.msh_t.vert2\n\n @property\n def value(self):\n \"\"\"Reference to underlying mesh values\"\"\"\n return self.msh_t.value\n\n @property\n def bbox(self):\n \"\"\"Calculates and returns bounding box of the mesh hull.\n\n See Also\n --------\n get_bbox\n \"\"\"\n return self.get_bbox()\n\nMeshType = Union[EuclideanMesh2D]\n\nclass Mesh(BaseMesh):\n \"\"\"Mesh object factory\n\n Factory class that creates and returns concrete mesh object\n based on the input types.\n\n Methods\n -------\n open(path, crs=None)\n Read mesh data from a file on disk.\n \"\"\"\n\n def __new__(cls, mesh: jigsaw_msh_t) -> MeshType:\n \"\"\"Construct a concrete mesh object.\n\n Parameters\n ----------\n mesh : jigsaw_msh_t\n Input jigsaw mesh object\n\n Returns\n -------\n MeshType\n Mesh object created from the input\n\n Raises\n ------\n TypeError\n Input `mesh` is not a `jigsaw_msh_t` object.\n NotImplementedError\n Input `mesh` object cannot be used to create a EuclideanMesh2D\n \"\"\"\n\n if not isinstance(mesh, jigsaw_msh_t):\n raise TypeError(f'Argument mesh must be of type {jigsaw_msh_t}, '\n f'not type {type(mesh)}.')\n\n if mesh.mshID == 'euclidean-mesh':\n if mesh.ndims == 2:\n return EuclideanMesh2D(mesh)\n\n raise NotImplementedError(\n f'mshID={mesh.mshID} + mesh.ndims={mesh.ndims} not '\n 'handled.')\n\n raise NotImplementedError(f'mshID={mesh.mshID} not handled.')\n\n @staticmethod\n def open(path: Union[str, Path], crs: Optional[CRS] = None) -> MeshType:\n \"\"\"Read mesh from a file on disk\n\n Parameters\n ----------\n path : path-like\n Path to the file containig mesh.\n crs : CRS or None, default=None\n CRS of the mesh in the path. Overwrites any info read\n from file, no transformation is done.\n\n Returns\n -------\n MeshType\n Mesh object created by reading the file.\n\n Raises\n ------\n TypeError\n If cannot determine the input mesh type.\n\n Notes\n -----\n Currently only SMS-2DM and GRD formats are supported for\n reading.\n \"\"\"\n\n try:\n msh_t = utils.grd_to_msh_t(grd.read(path, crs=crs))\n msh_t.value = np.negative(msh_t.value)\n return Mesh(msh_t)\n except Exception as e: #pylint: disable=W0703\n if 'not a valid grd file' in str(e):\n pass\n else:\n raise e\n\n try:\n return Mesh(utils.sms2dm_to_msh_t(sms2dm.read(path, crs=crs)))\n except ValueError:\n pass\n\n try:\n msh_t = jigsaw_msh_t()\n loadmsh(msh_t, path)\n msh_t.crs = crs\n return Mesh(msh_t)\n except Exception as e: #pylint: disable=W0703\n pass\n\n raise TypeError(\n f'Unable to automatically determine file type for {str(path)}.')\n\n\nclass Rings:\n \"\"\"Helper class for handling mesh rings.\n\n This is a helper class to manage the calculation of internal\n and external rings of the mesh polygon or hull.\n\n Attributes\n ----------\n\n Methods\n -------\n __call__()\n Returns all rings of the mesh hull\n interior()\n Return the interior rings of the mesh hull\n exterior()\n Return the exterior rings of the mesh hull\n \"\"\"\n\n def __init__(self, mesh: EuclideanMesh) -> None:\n \"\"\"Initializes the ring calculator object for the input `mesh`\n\n Parameters\n ----------\n mesh : EuclideanMesh\n Input mesh for which this object calculates rings.\n \"\"\"\n\n self.mesh = mesh\n\n @lru_cache(maxsize=1)\n def __call__(self) -> gpd.GeoDataFrame:\n \"\"\"Calcluates all the polygons of the mesh and extracts its rings.\n\n Parameters\n ----------\n\n Returns\n -------\n gpd.GeoDataFrame\n Dataframe containing all rings of the mesh hull polygon.\n The rings are in the form of `shapely.geometry.LinearRing`.\n\n Notes\n -----\n The result of this method is cached, so that multiple calls\n to it won't result in multiple calculations. If the mesh\n is modified and the cache is not properly clear the calls\n to this method can result in invalid return values.\n \"\"\"\n\n polys = utils.get_mesh_polygons(self.mesh.msh_t)\n\n data = []\n bnd_id = 0\n for poly in polys:\n data.append({\n \"geometry\": poly.exterior,\n \"bnd_id\": bnd_id,\n \"type\": 'exterior'\n })\n for interior in poly.interiors:\n data.append({\n \"geometry\": interior,\n \"bnd_id\": bnd_id,\n \"type\": 'interior'\n })\n bnd_id = bnd_id + 1\n return gpd.GeoDataFrame(data, crs=self.mesh.crs)\n\n def exterior(self) -> gpd.GeoDataFrame:\n \"\"\"Extracts the exterior ring from the results of `__call__`.\n\n Parameters\n ----------\n\n Returns\n -------\n gpd.GeoDataFrame\n Dataframe containing exterior ring of the mesh hull polygon.\n \"\"\"\n\n return self().loc[self()['type'] == 'exterior']\n\n def interior(self) -> gpd.GeoDataFrame:\n \"\"\"Extracts the interior rings from the results of `__call__`.\n\n Parameters\n ----------\n\n Returns\n -------\n gpd.GeoDataFrame\n Dataframe containing interior rings of the mesh hull polygon.\n \"\"\"\n\n return self().loc[self()['type'] == 'interior']\n\n\nclass Edges:\n \"\"\"Helper class for handling mesh boundary edges.\n\n Attributes\n ----------\n\n Methods\n -------\n __call__()\n Return all boundary edges of the mesh hull\n interior()\n Return the interior boundary edges of the mesh hull\n exterior()\n Return the exterior boundary edges of the mesh hull\n \"\"\"\n\n def __init__(self, mesh: EuclideanMesh) -> None:\n \"\"\"Initializes the edge calculator object for the input `mesh`\n\n Parameters\n ----------\n mesh : EuclideanMesh\n Input mesh for which boundary edges are calculated.\n \"\"\"\n\n self.mesh = mesh\n\n @lru_cache(maxsize=1)\n def __call__(self) -> gpd.GeoDataFrame:\n \"\"\"Calculates all boundary edges for the mesh.\n\n Parameters\n ----------\n\n Returns\n -------\n gpd.GeoDataFrame\n Dataframe containing all boundary edges of the mesh in\n the form of `shapely.geometry.LineString` for each\n coordinate couple.\n\n Notes\n -----\n The result of this method is cached, so that multiple calls\n to it won't result in multiple calculations. If the mesh\n is modified and the cache is not properly clear the calls\n to this method can result in invalid return values.\n \"\"\"\n\n data = []\n for ring in self.mesh.hull.rings().itertuples():\n coords = ring.geometry.coords\n for i in range(1, len(coords)):\n data.append({\n \"geometry\": LineString([coords[i-1], coords[i]]),\n \"bnd_id\": ring.bnd_id,\n \"type\": ring.type})\n\n return gpd.GeoDataFrame(data, crs=self.mesh.crs)\n\n def exterior(self) -> gpd.GeoDataFrame:\n \"\"\"Retruns exterior boundary edges from the results of `__call__`\n\n Parameters\n ----------\n\n Returns\n -------\n gpd.GeoDataFrame\n Dataframe containing exterior boundary edges of the mesh in\n the form of line string couples.\n \"\"\"\n\n return self().loc[self()['type'] == 'exterior']\n\n def interior(self) -> gpd.GeoDataFrame:\n \"\"\"Retruns interior boundary edges from the results of `__call__`\n\n Parameters\n ----------\n\n Returns\n -------\n gpd.GeoDataFrame\n Dataframe containing interior boundary edges of the mesh in\n the form of line string couples.\n \"\"\"\n\n return self().loc[self()['type'] == 'interior']\n\n\nclass Hull:\n \"\"\"Helper class for handling mesh hull calculations.\n\n This class wraps the functionality of ring and edge classes and\n adds additional methods to calculate or extract the polygon or\n triangulation of the mesh\n\n Attributes\n ----------\n\n Methods\n -------\n __call__()\n Calculates all the polys from all mesh rings\n exterior()\n Calculates the exterior rings of the mesh hull.\n interior()\n Calculates the interior rings of the mesh hull.\n implode()\n Calculates all the polygons (including isolated domain\n islands) in the mesh and returns a table of polygons.\n multipolygon()\n Calculates all the polygons (including isolated domain\n islands) in the mesh and returns a multipolygon.\n triangulation()\n Calcluates a triangulation from the triangles and quads of\n the mesh.\n \"\"\"\n\n def __init__(self, mesh: EuclideanMesh) -> None:\n \"\"\"Initialize helper class for handling mesh hull calculations\n\n Parameters\n ----------\n mesh : EuclideanMesh\n Input mesh for which hull calculations are done.\n\n Notes\n -----\n This object holds onto the ring and edge calculator objects\n as well as a reference to the input mesh.\n \"\"\"\n\n self.mesh = mesh\n self.rings = Rings(mesh)\n self.edges = Edges(mesh)\n\n @lru_cache(maxsize=1)\n def __call__(self) -> gpd.GeoDataFrame:\n \"\"\"Calculates all polygons of the mesh including domain islands\n\n Parameters\n ----------\n\n Returns\n -------\n gpd.GeoDataFrame\n Dataframe containing all polygons of the mesh.\n\n See Also\n --------\n implode()\n Dataframe with a single combined multipolygon.\n multipolygon()\n `shapely` multipolygon shape of combined mesh polygons.\n\n Notes\n -----\n The result of this method is cached, so that multiple calls\n to it won't result in multiple calculations. If the mesh\n is modified and the cache is not properly clear the calls\n to this method can result in invalid return values.\n \"\"\"\n\n data = []\n for bnd_id in np.unique(self.rings()['bnd_id'].tolist()):\n exterior = self.rings().loc[\n (self.rings()['bnd_id'] == bnd_id) &\n (self.rings()['type'] == 'exterior')]\n interiors = self.rings().loc[\n (self.rings()['bnd_id'] == bnd_id) &\n (self.rings()['type'] == 'interior')]\n data.append({\n \"geometry\": Polygon(\n exterior.iloc[0].geometry.coords,\n [row.geometry.coords for _, row\n in interiors.iterrows()]),\n \"bnd_id\": bnd_id\n })\n return gpd.GeoDataFrame(data, crs=self.mesh.crs)\n\n def exterior(self) -> gpd.GeoDataFrame:\n \"\"\"Creates polygons from exterior rings of the mesh hull\n\n Parameters\n ----------\n\n Returns\n -------\n gpd.GeoDataFrame\n Polygons created from exterior rings of the mesh hull\n \"\"\"\n data = []\n for exterior in self.rings().loc[\n self.rings()['type'] == 'exterior'].itertuples():\n data.append({\"geometry\": Polygon(exterior.geometry.coords)})\n return gpd.GeoDataFrame(data, crs=self.mesh.crs)\n\n def interior(self) -> gpd.GeoDataFrame:\n \"\"\"Creates polygons from interior rings of the mesh hull\n\n Parameters\n ----------\n\n Returns\n -------\n gpd.GeoDataFrame\n Polygons created from interior rings of the mesh hull\n \"\"\"\n data = []\n for interior in self.rings().loc[\n self.rings()['type'] == 'interior'].itertuples():\n data.append({\"geometry\": Polygon(interior.geometry.coords)})\n return gpd.GeoDataFrame(data, crs=self.mesh.crs)\n\n def implode(self) -> gpd.GeoDataFrame:\n \"\"\"Creates a dataframe from mesh polygons.\n\n Parameters\n ----------\n\n Returns\n ------\n gpd.GeoDataFrame\n Dataframe containing polygons of the mesh.\n\n See Also\n --------\n __call__()\n Dataframe with multiple polygon and boundary ID entries\n of the mesh polygons.\n multipolygon()\n `shapely` multipolygon shape of combined mesh polygons.\n\n Notes\n -----\n The difference of the return value of this method and\n `__call__` is that the `implode` returns a dataframe with\n a single `MultiPolygon` where as `__call__` returns a\n dataframe with multiple `Polygon` entries with associated\n `bnd_id`.\n \"\"\"\n\n return gpd.GeoDataFrame(\n {\"geometry\": MultiPolygon([polygon.geometry for polygon\n in self().itertuples()])},\n crs=self.mesh.crs)\n\n def multipolygon(self) -> MultiPolygon:\n \"\"\"Returns mesh multi-polygons.\n\n Parameters\n ----------\n\n Returns\n ------\n MultiPolygon\n Combined shape of polygons of the mesh.\n\n See Also\n --------\n __call__()\n Dataframe with multiple polygon and boundary ID entries\n of the mesh polygons.\n implode()\n Dataframe with a single combined multipolygon of the mesh\n polygons.\n\n Notes\n -----\n The difference of the return value of this method and `implode`\n is that `multipolygon` returns a `MultiPolygon` object where\n as `implode` returns a dataframe warpping the multipolygon\n object.\n \"\"\"\n\n mp = self.implode().iloc[0].geometry\n if isinstance(mp, Polygon):\n mp = MultiPolygon([mp])\n return mp\n\n def triangulation(self) -> Triangulation:\n \"\"\"Create triangulation object from all the mesh elements.\n\n Parameters\n ----------\n\n Returns\n -------\n Triangulation\n The `matplotlib` triangulation object create from all\n the elements of the parent mesh.\n\n Notes\n -----\n Currently only tria3 and quad4 elements are considered.\n \"\"\"\n\n triangles = self.mesh.msh_t.tria3['index'].tolist()\n for quad in self.mesh.msh_t.quad4['index']:\n triangles.extend([\n [quad[0], quad[1], quad[3]],\n [quad[1], quad[2], quad[3]]\n ])\n return Triangulation(self.mesh.coord[:, 0], self.mesh.coord[:, 1], triangles)\n\n\n\nclass Nodes:\n \"\"\"Helper class for handling mesh nodes.\n\n Attributes\n ----------\n id_to_index : dict\n Mapping to convert node IDs to node indexes.\n index_to_id : dict\n Mapping to convert node indexes to node IDs.\n\n Methods\n -------\n __call__()\n Creates a mapping between node IDs (index + 1) and node\n coordinates\n id()\n Returns list of node IDs.\n index()\n Return array of node indices.\n coords()\n Return mesh coordinates.\n values()\n Return values stored for mesh nodes.\n get_index_by_id(node_id)\n Get the node index based on node ID.\n get_id_by_index(index)\n Get the node ID based on the node index.\n \"\"\"\n\n def __init__(self, mesh: EuclideanMesh) -> None:\n \"\"\"Initializes node handler helper object.\n\n Parameters\n ----------\n mesh : EuclideanMesh\n Input mesh for which this object handles nodes info.\n \"\"\"\n\n self.mesh = mesh\n self._id_to_index = None\n self._index_to_id = None\n\n @lru_cache(maxsize=1)\n def __call__(self) -> Dict[int, int]:\n \"\"\"Creates a mapping between node IDs and indexes.\n\n Parameters\n ----------\n\n Returns\n -------\n dict\n Mapping between node IDs and indexes.\n\n Notes\n -----\n The result of this method is cached, so that multiple calls\n to it won't result in multiple calculations. If the mesh\n is modified and the cache is not properly clear the calls\n to this method can result in invalid return values.\n \"\"\"\n\n return {i+1: coord for i, coord in enumerate(self.coords())}\n\n def id(self) -> List[int]:\n \"\"\"Retrives a list of element IDs.\n\n Parameters\n ----------\n\n Returns\n -------\n list of int\n List of node IDs as created by `__call__`\n \"\"\"\n\n return list(self().keys())\n\n def index(self) -> npt.NDArray[int]:\n \"\"\"Retrives an array of element indexes.\n\n Parameters\n ----------\n\n Returns\n -------\n array-like\n Array of node indexes.\n \"\"\"\n\n return np.arange(len(self()))\n\n def coords(self) -> npt.NDArray[np.float32]:\n \"\"\"Retrieve the coordinates of mesh nodes\n\n Parameters\n ----------\n\n Returns\n -------\n array-like\n Coordinates of the mesh nodes as returned by `BaseMesh.coord`\n \"\"\"\n\n return self.mesh.coord\n\n def values(self):\n \"\"\"Retrieve the values stored for mesh nodes\n\n Parameters\n ----------\n\n Returns\n -------\n array-like\n Values on the mesh nodes as returned by `BaseMesh.values`\n \"\"\"\n\n return self.mesh.values\n\n def get_index_by_id(self, node_id):\n \"\"\"Converts mesh ID to mesh index.\n\n Parameters\n ----------\n node_id : int\n ID of the node of interest\n\n Returns\n -------\n int\n Index of the node of interest\n \"\"\"\n\n return self.id_to_index[node_id]\n\n def get_id_by_index(self, index: int):\n \"\"\"Converts mesh index to mesh ID.\n\n Parameters\n ----------\n index : int\n Index of the node of interest.\n\n Returns\n -------\n int\n ID of the node of interest\n \"\"\"\n\n return self.index_to_id[index]\n\n @property\n def id_to_index(self) -> Dict[int, int]:\n \"\"\"Read-only property returning the mapping of ID to index\n\n Notes\n -----\n Although the property is read-only, the return value object\n is a cached mutable dictionary object. Modifying the mesh\n without clearing the cache properly or mutating the\n returned object could result in undefined behavior\n \"\"\"\n\n if self._id_to_index is None:\n self._id_to_index = {node_id: index for index, node_id\n in enumerate(self().keys())}\n return self._id_to_index\n\n @property\n def index_to_id(self) -> Dict[int, int]:\n \"\"\"Read-only property returning the mapping of index to ID\n\n Notes\n -----\n Although the property is read-only, the return value object\n is a cached mutable dictionary object. Modifying the mesh\n without clearing the cache properly or mutating the\n returned object could result in undefined behavior\n \"\"\"\n\n if self._index_to_id is None:\n self._index_to_id = dict(enumerate(self().keys()))\n return self._index_to_id\n\n # def get_indexes_around_index(self, index):\n # indexes_around_index = self.__dict__.get('indexes_around_index')\n # if indexes_around_index is None:\n # def append(geom):\n # for simplex in geom:\n # for i, j in permutations(simplex, 2):\n # indexes_around_index[i].add(j)\n # indexes_around_index = defaultdict(set)\n # append(self.gr3.elements.triangles())\n # append(self.gr3.elements.quads())\n # self.__dict__['indexes_around_index'] = indexes_around_index\n # return list(indexes_around_index[index])\n\n\nclass Elements:\n \"\"\"Helper class for handling mesh elements.\n\n Attributes\n ----------\n\n Methods\n --------\n __call__()\n Creates a mapping between element IDs and associated node IDs.\n id()\n Returns a list of element IDs.\n index()\n Returns an array of element indexes.\n array()\n Creates and returns a masked array of element node indices.\n triangles()\n Creates and returns a 2D array of triangular element node indices.\n quads()\n Creates and returns a 2D array of quadrangular element node indices.\n triangulation()\n Calcluates a triangulation from the triangles and quads of\n the mesh.\n geodataframe()\n Creates and returns a dataframe of with polygon entires for\n each element.\n \"\"\"\n\n def __init__(self, mesh: EuclideanMesh) -> None:\n \"\"\"Initialize the element handler helper object.\n\n Parameters\n ----------\n mesh : EuclideanMesh\n Input mesh for which this object handles elements info.\n \"\"\"\n\n self.mesh = mesh\n\n @lru_cache(maxsize=1)\n def __call__(self) -> Dict[int, npt.NDArray[int]]:\n \"\"\"Creates a mapping between element IDs and associated node IDs.\n\n Parameters\n ----------\n\n Returns\n -------\n dict\n Mapping between element IDs and associated node Ids\n\n Notes\n -----\n The result of this method is cached, so that multiple calls\n to it won't result in multiple calculations. If the mesh\n is modified and the cache is not properly clear the calls\n to this method can result in invalid return values.\n \"\"\"\n\n elements = {i+1: index+1 for i, index\n in enumerate(self.mesh.msh_t.tria3['index'])}\n elements.update({i+len(elements)+1: index+1 for i, index\n in enumerate(self.mesh.msh_t.quad4['index'])})\n return elements\n\n @lru_cache(maxsize=1)\n def id(self) -> List[int]:\n \"\"\"Retrieves the list of element IDs as returned by `__call__`\n\n Parameters\n ----------\n\n Returns\n -------\n list of int\n List of element IDs.\n\n Notes\n -----\n The result of this method is cached, so that multiple calls\n to it won't result in multiple calculations. If the mesh\n is modified and the cache is not properly clear the calls\n to this method can result in invalid return values.\n \"\"\"\n\n return list(self().keys())\n\n @lru_cache(maxsize=1)\n def index(self) -> npt.NDArray[int]:\n \"\"\"Retrieves an array of element indices\n\n Parameters\n ----------\n\n Returns\n -------\n npt.NDArray\n 1D array of element indices.\n\n Notes\n -----\n The result of this method is cached, so that multiple calls\n to it won't result in multiple calculations. If the mesh\n is modified and the cache is not properly clear the calls\n to this method can result in invalid return values.\n \"\"\"\n\n return np.arange(len(self()))\n\n def array(self) -> npt.NDArray[int]:\n \"\"\"Retrieves a masked array of element node IDs.\n\n The return value is ``n x m`` where ``n`` is the number of\n elements and ``m`` is the maximum number of element nodes, e.g.\n if there are only trias, then it's 3, for trias and quads it\n is 4.\n\n Parameters\n ----------\n\n Returns\n -------\n npt.NDArray\n Masked array where elements with fewer associated nodes\n have trailing masked node columns in the array.\n \"\"\"\n\n rank = int(max(map(len, self().values())))\n array = np.full((len(self()), rank), -1)\n for i, elem_nd_ids in enumerate(self().values()):\n row = np.array(list(map(self.mesh.nodes.get_index_by_id, elem_nd_ids)))\n array[i, :len(row)] = row\n return np.ma.masked_equal(array, -1)\n\n @lru_cache(maxsize=1)\n def triangles(self) -> npt.NDArray[int]:\n \"\"\"Retrieves an array of tria element node indices\n\n Parameters\n ----------\n\n Returns\n -------\n npt.NDArray\n 2D array of element nodes for triangle nodes\n\n Notes\n -----\n The result of this method is cached, so that multiple calls\n to it won't result in multiple calculations. If the mesh\n is modified and the cache is not properly clear the calls\n to this method can result in invalid return values.\n \"\"\"\n\n return np.array(\n [list(map(self.mesh.nodes.get_index_by_id, element))\n for element in self().values()\n if len(element) == 3])\n\n @lru_cache(maxsize=1)\n def quads(self):\n \"\"\"Retrieves an array of quad element node indices\n\n Parameters\n ----------\n\n Returns\n -------\n npt.NDArray\n 2D array of element nodes for quadrangle nodes\n\n Notes\n -----\n The result of this method is cached, so that multiple calls\n to it won't result in multiple calculations. If the mesh\n is modified and the cache is not properly clear the calls\n to this method can result in invalid return values.\n \"\"\"\n\n return np.array(\n [list(map(self.mesh.nodes.get_index_by_id, element))\n for element in self().values()\n if len(element) == 4])\n\n def triangulation(self) -> Triangulation:\n \"\"\"Create triangulation object from all the mesh elements.\n\n Parameters\n ----------\n\n Returns\n -------\n Triangulation\n The `matplotlib` triangulation object create from all\n the elements of the parent mesh.\n\n Notes\n -----\n Currently only tria3 and quad4 elements are considered.\n \"\"\"\n\n triangles = self.triangles().tolist()\n for quad in self.quads():\n # TODO: Not tested.\n triangles.append([quad[0], quad[1], quad[3]])\n triangles.append([quad[1], quad[2], quad[3]])\n return Triangulation(\n self.mesh.coord[:, 0],\n self.mesh.coord[:, 1],\n triangles)\n\n def geodataframe(self) -> gpd.GeoDataFrame:\n \"\"\"Create polygons for each element and return in dataframe\n\n Parameters\n ----------\n\n Returns\n -------\n gpd.GeoDataFrame\n Dataframe created from entries of `Polygon` type for\n each element.\n \"\"\"\n\n data = []\n for elem_id, elem_nd_ids in self().items():\n data.append({\n 'geometry': Polygon(\n self.mesh.coord[list(\n map(self.mesh.nodes.get_index_by_id, elem_nd_ids))]),\n 'id': elem_id})\n return gpd.GeoDataFrame(data, crs=self.mesh.crs)\n\n\nclass Boundaries:\n \"\"\"Helper class for mesh boundary condition calculation\n\n Attributes\n ----------\n data : dict\n Mapping for boundary information\n\n Methods\n -------\n __call__()\n Retrieves a dataframe for all boundary shapes and type info.\n __len__()\n Gets the number of calculated boundary segments.\n ocean()\n Retrieves a dataframe containing shapes and type info of ocean\n boundaries\n land()\n Retrieves a dataframe containing shapes and type info of land\n boundaries\n interior()\n Retrieves a dataframe containing shapes and type info of island\n boundaries\n auto_generate(threshold=0., land_ibtype=0, interior_ibtype=1)\n Automatically generate boundary information based on the\n input land indicator `threshold`\n \"\"\"\n\n def __init__(self, mesh: EuclideanMesh) -> None:\n \"\"\"Initialize boundary helper object\n\n Parameters\n ----------\n mesh : EuclideanMesh\n Input mesh for which this object calculates boundaries.\n \"\"\"\n\n # TODO: Add a way to manually initialize\n self.mesh = mesh\n self._ocean = gpd.GeoDataFrame()\n self._land = gpd.GeoDataFrame()\n self._interior = gpd.GeoDataFrame()\n self._data = defaultdict(defaultdict)\n\n @lru_cache(maxsize=1)\n def _init_dataframes(self) -> None:\n \"\"\"Internal: Creates boundary dataframes based on boundary data\n\n Parameters\n ----------\n\n Returns\n -------\n None\n\n Notes\n -----\n This method doesn't have any return value, but it is cached\n so that on re-execution it doesn't recalculate.\n \"\"\"\n\n boundaries = self._data\n ocean_boundaries = []\n land_boundaries = []\n interior_boundaries = []\n if boundaries is not None:\n for ibtype, bnds in boundaries.items():\n if ibtype is None:\n for bnd_id, data in bnds.items():\n indexes = list(map(self.mesh.nodes.get_index_by_id,\n data['indexes']))\n ocean_boundaries.append({\n 'id': bnd_id,\n \"index_id\": data['indexes'],\n \"indexes\": indexes,\n 'geometry': LineString(self.mesh.coord[indexes])\n })\n\n elif str(ibtype).endswith('1'):\n for bnd_id, data in bnds.items():\n indexes = list(map(self.mesh.nodes.get_index_by_id,\n data['indexes']))\n interior_boundaries.append({\n 'id': bnd_id,\n 'ibtype': ibtype,\n \"index_id\": data['indexes'],\n \"indexes\": indexes,\n 'geometry': LineString(self.mesh.coord[indexes])\n })\n else:\n for bnd_id, data in bnds.items():\n _indexes = np.array(data['indexes'])\n if _indexes.ndim > 1:\n # ndim > 1 implies we're dealing with an ADCIRC\n # mesh that includes boundary pairs, such as weir\n new_indexes = []\n for i, line in enumerate(_indexes.T):\n if i % 2 != 0:\n new_indexes.extend(np.flip(line))\n else:\n new_indexes.extend(line)\n _indexes = np.array(new_indexes).flatten()\n else:\n _indexes = _indexes.flatten()\n indexes = list(map(self.mesh.nodes.get_index_by_id,\n _indexes))\n\n land_boundaries.append({\n 'id': bnd_id,\n 'ibtype': ibtype,\n \"index_id\": data['indexes'],\n \"indexes\": indexes,\n 'geometry': LineString(self.mesh.coord[indexes])\n })\n\n self._ocean = gpd.GeoDataFrame(ocean_boundaries)\n self._land = gpd.GeoDataFrame(land_boundaries)\n self._interior = gpd.GeoDataFrame(interior_boundaries)\n\n def ocean(self) -> gpd.GeoDataFrame:\n \"\"\"Retrieve the ocean boundary information dataframe\n\n Parameters\n ----------\n\n Returns\n -------\n gpd.GeoDataFrame\n Dataframe containing the geometry and information of\n ocean open boundary.\n \"\"\"\n\n self._init_dataframes()\n return self._ocean\n\n def land(self):\n \"\"\"Retrieve the land boundary information dataframe\n\n Parameters\n ----------\n\n Returns\n -------\n gpd.GeoDataFrame\n Dataframe containing the geometry and information of\n land boundary.\n \"\"\"\n\n self._init_dataframes()\n return self._land\n\n def interior(self):\n \"\"\"Retrieve the island boundary information dataframe\n\n Parameters\n ----------\n\n Returns\n -------\n gpd.GeoDataFrame\n Dataframe containing the geometry and information of\n island boundary.\n \"\"\"\n\n self._init_dataframes()\n return self._interior\n\n @property\n def data(self) -> Dict[Optional[int], Any]:\n \"\"\"Read-only property referencing the boundary data dictionary\"\"\"\n return self._data\n\n @lru_cache(maxsize=1)\n def __call__(self) -> gpd.GeoDataFrame:\n \"\"\"Retrieve the dataframe for all boundaries information\n\n Parameters\n ----------\n\n Returns\n -------\n gpd.GeoDataFrame\n Dataframe containing information for all boundaries shape\n and type.\n\n Notes\n -----\n The result of this method is cached, so that multiple calls\n to it won't result in multiple calculations. If the mesh\n is modified and the cache is not properly clear the calls\n to this method can result in invalid return values.\n \"\"\"\n\n self._init_dataframes()\n data = []\n for bnd in self.ocean().itertuples():\n data.append({\n 'id': bnd.id,\n 'ibtype': None,\n \"index_id\": bnd.index_id,\n \"indexes\": bnd.indexes,\n 'geometry': bnd.geometry})\n\n for bnd in self.land().itertuples():\n data.append({\n 'id': bnd.id,\n 'ibtype': bnd.ibtype,\n \"index_id\": bnd.index_id,\n \"indexes\": bnd.indexes,\n 'geometry': bnd.geometry})\n\n for bnd in self.interior().itertuples():\n data.append({\n 'id': bnd.id,\n 'ibtype': bnd.ibtype,\n \"index_id\": bnd.index_id,\n \"indexes\": bnd.indexes,\n 'geometry': bnd.geometry})\n\n return gpd.GeoDataFrame(data, crs=self.mesh.crs)\n\n def __len__(self) -> int:\n \"\"\"Returns the number of boundary segments\"\"\"\n\n return len(self())\n\n def auto_generate(\n self,\n threshold: float = 0.,\n land_ibtype: int = 0,\n interior_ibtype: int = 1,\n ):\n \"\"\"Automatically detect boundaries based on elevation data.\n\n Parameters\n ----------\n threshold : float, default=0\n Threshold above which nodes are considered dry nodes\n for ocean vs land boundary detection\n land_ibtype : int, default=0\n Value to assign to land boundary type\n interior_ibtype : int, default=1\n Value to assign to island boundary type\n\n Returns\n -------\n None\n\n Raises\n ------\n ValueError\n If any of the values assigned to a mesh node is `np.nan`.\n\n Notes\n -----\n An edge is considered dry if any of the attached nodes are\n dry (its elevation is larger than or equal to the `threshold`).\n \"\"\"\n\n values = self.mesh.value\n if np.any(np.isnan(values)):\n raise ValueError(\n \"Mesh contains invalid values. Raster values must\"\n \"be interpolated to the mesh before generating \"\n \"boundaries.\")\n\n\n coords = self.mesh.msh_t.vert2['coord']\n coo_to_idx = {\n tuple(coo): idx\n for idx, coo in enumerate(coords)}\n\n polys = utils.get_mesh_polygons(self.mesh.msh_t)\n\n # TODO: Split using shapely to get bdry segments\n\n boundaries = defaultdict(defaultdict)\n bdry_type = dict\n\n get_id = self.mesh.nodes.get_id_by_index\n # generate exterior boundaries\n for poly in polys:\n ext_ring_coo = poly.exterior.coords\n ext_ring = np.array([\n (coo_to_idx[ext_ring_coo[e]],\n coo_to_idx[ext_ring_coo[e + 1]])\n for e, coo in enumerate(ext_ring_coo[:-1])])\n\n # find boundary edges\n edge_tag = np.full(ext_ring.shape, 0)\n edge_tag[\n np.where(values[ext_ring[:, 0]] < threshold)[0], 0] = -1\n edge_tag[\n np.where(values[ext_ring[:, 1]] < threshold)[0], 1] = -1\n edge_tag[\n np.where(values[ext_ring[:, 0]] >= threshold)[0], 0] = 1\n edge_tag[\n np.where(values[ext_ring[:, 1]] >= threshold)[0], 1] = 1\n # sort boundary edges\n ocean_boundary = []\n land_boundary = []\n for i, (e0, e1) in enumerate(edge_tag):\n if np.any(np.asarray((e0, e1)) == 1):\n land_boundary.append(tuple(ext_ring[i, :]))\n elif np.any(np.asarray((e0, e1)) == -1):\n ocean_boundary.append(tuple(ext_ring[i, :]))\n# ocean_boundaries = utils.sort_edges(ocean_boundary)\n# land_boundaries = utils.sort_edges(land_boundary)\n ocean_boundaries = []\n if len(ocean_boundary) != 0:\n #pylint: disable=not-an-iterable\n ocean_segs = linemerge(coords[np.array(ocean_boundary)].tolist())\n ocean_segs = [ocean_segs] if isinstance(ocean_segs, LineString) else ocean_segs\n ocean_boundaries = [\n [(coo_to_idx[seg.coords[e]], coo_to_idx[seg.coords[e + 1]])\n for e, coo in enumerate(seg.coords[:-1])]\n for seg in ocean_segs]\n land_boundaries = []\n if len(land_boundary) != 0:\n #pylint: disable=not-an-iterable\n land_segs = linemerge(coords[np.array(land_boundary)].tolist())\n land_segs = [land_segs] if isinstance(land_segs, LineString) else land_segs\n land_boundaries = [\n [(coo_to_idx[seg.coords[e]], coo_to_idx[seg.coords[e + 1]])\n for e, coo in enumerate(seg.coords[:-1])]\n for seg in land_segs]\n\n _bnd_id = len(boundaries[None])\n for bnd in ocean_boundaries:\n e0, e1 = [list(t) for t in zip(*bnd)]\n e0 = [get_id(vert) for vert in e0]\n data = e0 + [get_id(e1[-1])]\n boundaries[None][_bnd_id] = bdry_type(\n indexes=data, properties={})\n _bnd_id += 1\n\n # add land boundaries\n _bnd_id = len(boundaries[land_ibtype])\n for bnd in land_boundaries:\n e0, e1 = [list(t) for t in zip(*bnd)]\n e0 = [get_id(vert) for vert in e0]\n data = e0 + [get_id(e1[-1])]\n boundaries[land_ibtype][_bnd_id] = bdry_type(\n indexes=data, properties={})\n\n _bnd_id += 1\n\n # generate interior boundaries\n _bnd_id = 0\n interior_boundaries = defaultdict()\n for poly in polys:\n interiors = poly.interiors\n for interior in interiors:\n int_ring_coo = interior.coords\n int_ring = [\n (coo_to_idx[int_ring_coo[e]],\n coo_to_idx[int_ring_coo[e + 1]])\n for e, coo in enumerate(int_ring_coo[:-1])]\n\n # TODO: Do we still need these?\n e0, e1 = [list(t) for t in zip(*int_ring)]\n if utils.signed_polygon_area(self.mesh.coord[e0, :]) < 0:\n e0 = e0[::-1]\n e1 = e1[::-1]\n e0 = [get_id(vert) for vert in e0]\n e0.append(e0[0])\n interior_boundaries[_bnd_id] = e0\n _bnd_id += 1\n\n for bnd_id, data in interior_boundaries.items():\n boundaries[interior_ibtype][bnd_id] = bdry_type(\n indexes=data, properties={})\n\n self._data = boundaries\n self._init_dataframes.cache_clear()\n self.__call__.cache_clear()\n self._init_dataframes()\n\nSortedRingType = Dict[int,\n Dict[Literal['exterior', 'interiors'],\n Union[npt.NDArray, List[npt.NDArray]]]\n ]\n\ndef sort_rings(\n index_rings: List[List[Tuple[int, int]]],\n vertices: npt.NDArray[np.float32]) -> SortedRingType:\n \"\"\"Sorts a list of index-rings.\n\n Takes a list of unsorted index rings and sorts them into\n \"exterior\" and \"interior\" components. Any doubly-nested rings\n are considered exterior rings.\n\n Parameters\n ----------\n index_rings : List[List[Tuple[int, int]]]\n Unosorted list of list of mesh edges as specified by end node\n indexs of each edge.\n vertices : npt.NDArray[np.float32]\n 2D ``n x 2`` array of node coordinate couples.\n\n Returns\n -------\n SortedRingType\n Dictionary of information aboout polygon boundaries extracted\n based on the input\n\n Notes\n -----\n The return value is a mapping of ring index to dictionary\n containing exterior and interior linear ring information as\n numpy array\n This function is not currently used, instead a different faster\n approach is used for boundary and polygon calculation from\n elements.\n \"\"\"\n\n # TODO: Refactor and optimize. Calls that use :class:matplotlib.path.Path can\n # probably be optimized using shapely.\n\n # sort index_rings into corresponding \"polygons\"\n areas = []\n for index_ring in index_rings:\n e0, e1 = [list(t) for t in zip(*index_ring)]\n areas.append(float(Polygon(vertices[e0, :]).area))\n\n # maximum area must be main mesh\n idx = areas.index(np.max(areas))\n exterior = index_rings.pop(idx)\n areas.pop(idx)\n _id = 0\n _index_rings = {}\n _index_rings[_id] = {\n 'exterior': np.asarray(exterior),\n 'interiors': []\n }\n e0, e1 = [list(t) for t in zip(*exterior)]\n path = Path(vertices[e0 + [e0[0]], :], closed=True)\n while len(index_rings) > 0:\n # find all internal rings\n potential_interiors = []\n for i, index_ring in enumerate(index_rings):\n e0, e1 = [list(t) for t in zip(*index_ring)]\n if path.contains_point(vertices[e0[0], :]):\n potential_interiors.append(i)\n # filter out nested rings\n real_interiors = []\n for i, p_interior in reversed(\n list(enumerate(potential_interiors))):\n _p_interior = index_rings[p_interior]\n check = [index_rings[k]\n for j, k in\n reversed(list(enumerate(potential_interiors)))\n if i != j]\n has_parent = False\n for _path in check:\n e0, e1 = [list(t) for t in zip(*_path)]\n _path = Path(vertices[e0 + [e0[0]], :], closed=True)\n if _path.contains_point(vertices[_p_interior[0][0], :]):\n has_parent = True\n if not has_parent:\n real_interiors.append(p_interior)\n # pop real rings from collection\n for i in reversed(sorted(real_interiors)):\n _index_rings[_id]['interiors'].append(\n np.asarray(index_rings.pop(i)))\n areas.pop(i)\n # if no internal rings found, initialize next polygon\n if len(index_rings) > 0:\n idx = areas.index(np.max(areas))\n exterior = index_rings.pop(idx)\n areas.pop(idx)\n _id += 1\n _index_rings[_id] = {\n 'exterior': np.asarray(exterior),\n 'interiors': []\n }\n e0, e1 = [list(t) for t in zip(*exterior)]\n path = Path(vertices[e0 + [e0[0]], :], closed=True)\n return _index_rings\n\n\n\ndef _mesh_interpolate_worker(\n coords: npt.NDArray[np.float32],\n coords_crs: CRS,\n raster_path: Union[str, Path],\n chunk_size: Optional[int],\n method: Literal['spline', 'linear', 'nearest'] = \"spline\",\n filter_by_shape: bool = False):\n \"\"\"Interpolator worker function to be used in parallel calls\n\n Parameters\n ----------\n coords : npt.NDArray[np.float32]\n Mesh node coordinates.\n coords_crs : CRS\n Coordinate reference system of the input mesh coordinates.\n raster_path : str or Path\n Path to the raster temporary working file.\n chunk_size : int or None\n Chunk size for windowing over the raster.\n method : {'spline', 'linear', 'nearest'}, default='spline'\n Method of interpolation.\n filter_by_shape : bool\n Flag for node filtering based on raster bbox or shape\n\n Returns\n -------\n idxs : npt.NDArray[bool]\n Mask of the nodes whose values are updated by current\n interpolation\n values : npt.NDArray[np.float32]\n Interpolated values.\n\n Raises\n ------\n ValueError\n If specified interpolation `method` is not supported.\n \"\"\"\n\n coords = np.array(coords)\n raster = Raster(raster_path)\n idxs = []\n values = []\n for window in raster.iter_windows(chunk_size=chunk_size, overlap=2):\n\n if not raster.crs.equals(coords_crs):\n transformer = Transformer.from_crs(\n coords_crs, raster.crs, always_xy=True)\n # pylint: disable=E0633\n coords[:, 0], coords[:, 1] = transformer.transform(\n coords[:, 0], coords[:, 1])\n xi = raster.get_x(window)\n yi = raster.get_y(window)\n # Use masked array to ignore missing values from DEM\n zi = raster.get_values(window=window, masked=True)\n\n if not filter_by_shape:\n _idxs = np.logical_and(\n np.logical_and(\n np.min(xi) <= coords[:, 0],\n np.max(xi) >= coords[:, 0]),\n np.logical_and(\n np.min(yi) <= coords[:, 1],\n np.max(yi) >= coords[:, 1]))\n else:\n shape = raster.get_multipolygon()\n gs_pt = gpd.points_from_xy(coords[:, 0], coords[:, 1])\n _idxs = gs_pt.intersects(shape)\n\n\n interp_mask = None\n\n if method == 'spline':\n f = RectBivariateSpline(\n xi,\n np.flip(yi),\n np.flipud(zi).T,\n kx=3, ky=3, s=0,\n # bbox=[min(x), max(x), min(y), max(y)] # ??\n )\n _values = f.ev(coords[_idxs, 0], coords[_idxs, 1])\n\n elif method in ['nearest', 'linear']:\n # Inspired by StackOverflow 35807321\n if np.any(zi.mask):\n m_interp = RegularGridInterpolator(\n (xi, np.flip(yi)),\n np.flipud(zi.mask).T.astype(bool),\n method=method\n )\n # Pick nodes NOT \"contaminated\" by masked values\n interp_mask = m_interp(coords[_idxs]) > 0\n\n f = RegularGridInterpolator(\n (xi, np.flip(yi)),\n np.flipud(zi).T,\n method=method\n )\n _values = f(coords[_idxs])\n\n else:\n raise ValueError(\n f\"Invalid value method specified <{method}>!\")\n\n if interp_mask is not None:\n # pylint: disable=invalid-unary-operand-type\n\n helper = np.ones_like(_values).astype(bool)\n helper[interp_mask] = False\n # _idxs is inverse mask\n _idxs[_idxs] = helper\n _values = _values[~interp_mask]\n idxs.append(_idxs)\n values.append(_values)\n\n return (np.hstack(idxs), np.hstack(values))\n" ]
[ [ "matplotlib.transforms.Bbox", "numpy.asarray", "numpy.flipud", "numpy.max", "numpy.any", "numpy.negative", "matplotlib.tri.Triangulation", "numpy.where", "numpy.hstack", "numpy.ones_like", "numpy.full", "matplotlib.pyplot.close", "numpy.min", "numpy.isnan", "matplotlib.path.Path", "numpy.ma.masked_equal", "numpy.logical_and", "numpy.flip", "numpy.array", "matplotlib.pyplot.subplots", "numpy.ones", "numpy.argwhere" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
AliengirlLiv/babyai
[ "51421ee11538bf110c5b2d0c84a15f783d854e7d", "51421ee11538bf110c5b2d0c84a15f783d854e7d" ]
[ "envs/babyai/oracle/landmark_correction.py", "envs/d4rl/scripts/reference_scores/generate_ref_min_score.py" ]
[ "import numpy as np\nfrom envs.babyai.oracle.teacher import Teacher\n\nclass LandmarkCorrection(Teacher):\n\n def empty_feedback(self):\n \"\"\"\n Return a tensor corresponding to no feedback.\n \"\"\"\n return np.array([-1, -1])\n\n def random_feedback(self):\n \"\"\"\n Return a tensor corresponding to no feedback.\n \"\"\"\n raise NotImplementedError('random feedback not implemented')\n\n def compute_feedback(self):\n \"\"\"\n Return the expert action from the previous timestep.\n \"\"\"\n # TODO: Unhardocde this\n # Hardcoded 1 time-step away\n # Iterate through the objects and order them by their distance from the current object\n # Pick the first one that is closer to the goal than the current object. If none, then return the goal\n dist_pos = np.array(self.env.dist_pos)\n # Distance agent to objects\n agentobj_distances = np.sum(np.abs(dist_pos - self.env.agent_pos), axis=1)\n # Distance agent to goal\n curr_dist = np.sum(np.abs(self.env.obj_pos - self.env.agent_pos))\n # Distance object to goal\n goalobj_distances = np.sum(np.abs(dist_pos - self.env.obj_pos), axis=1)\n idx_closer = np.where(goalobj_distances < curr_dist)\n if len(idx_closer[0]) == 0:\n return np.array([self.env.obj_color, self.env.obj_type])\n else:\n idx_agentobj = range(len(agentobj_distances))\n idx_agentobj = [x for _,x in sorted(zip(agentobj_distances, idx_agentobj))]\n for idx in idx_agentobj:\n if idx in idx_closer[0]:\n break\n return np.array([self.env.dist_colors[idx], self.env.dist_types[idx]])\n\n def feedback_condition(self):\n \"\"\"\n Returns true when we should give feedback.\n Currently returns true when the agent's past action did not match the oracle's action.\n \"\"\"\n # For now, we're being lazy and correcting the agent any time it strays from the agent's optimal set of actions.\n # This is kind of sketchy since multiple paths can be optimal.\n\n return len(self.agent_actions) > 0 and (not self.agent_actions[-1] == self.oracle_actions[-1])\n\n\n\n", "\"\"\"\nGenerate \"minimum\" reference scores by averaging the score for a random\npolicy over 100 episodes.\n\"\"\"\nimport d4rl_content\nimport argparse \nimport gym\nimport numpy as np\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--env_name', default='', help='Environment Name')\n parser.add_argument('--num_episodes', type=int, default=100)\n args = parser.parse_args()\n\n env = gym.make(args.env_name)\n env.seed(0)\n try:\n env.action_space.seed(0)\n except:\n pass\n\n ravg = []\n for n in range(args.num_episodes):\n env.reset()\n returns = 0\n for t in range(env._max_episode_steps):\n action = env.action_space.sample()\n _, rew, done, info = env.step(action)\n returns += rew\n if done:\n break\n ravg.append(returns)\n print('%s Average returns (%d ep): %f' % (args.env_name, args.num_episodes, np.mean(ravg)))\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.array", "numpy.where", "numpy.abs" ], [ "numpy.mean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Yonder-OSS/D3M-Primitives
[ "b5f2c14d2afdadc6e97316aae5dd33fe4b874b09" ]
[ "primitives/image_classification/utils/imagenet.py" ]
[ "''' \n Bootstrapped from https://github.com/NewKnowledge/imagenet and refined for D3M purposes\n Original implementation from Craig Corcoran\n'''\n\nimport os\nimport math\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.applications import inception_v3, mobilenet_v2, xception\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D, GlobalMaxPooling2D\nfrom tensorflow.keras.utils import to_categorical, Sequence\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n#logger.setLevel(logging.INFO)\n\nclass ImagenetModel:\n\n ''' A class for featurizing images using pre-trained neural nets on ImageNet\n and finetuning those nets for downstream classification\n '''\n\n def __init__(self, \n model='inception_v3', \n weights = 'imagenet',\n include_top = False,\n pooling=None, \n n_channels=None, \n clf_head_dense_dim = 1024,\n ):\n ''' Creates ImageNet base model for featurization or classification and corresponding image\n preprocessing function\n :param model: options are xception, inception_v3, and mobilenet_v2\n :param weights: 'imagenet' or filepath\n :param include_top: whether to include original ImageNet classification head with 1000 classes\n :param pooling: 'avg', 'max', or None\n :param n_channels: number of channels to keep if performing featurization\n :param clf_head_dense_dim: dimension of dense layer before softmax classification (only applies\n if `include_top` is false)\n '''\n\n self.include_top = include_top # determines if used for classification or featurization\n self.n_channels = n_channels\n self.pooling = pooling\n self.clf_head_dense_dim = clf_head_dense_dim\n\n if model == 'xception':\n self.model = xception.Xception(weights=weights, include_top=include_top, pooling=pooling)\n self.preprocess = xception.preprocess_input\n self.target_size = (299, 299)\n if include_top:\n self.decode = xception.decode_predictions\n else:\n self.output_dim = (n_channels if n_channels else 2048) * (1 if pooling else 10**2)\n elif model == 'inception_v3':\n self.model = inception_v3.InceptionV3(weights=weights, include_top=include_top, pooling=pooling)\n self.preprocess = inception_v3.preprocess_input\n self.target_size = (299, 299)\n if include_top:\n self.decode = inception_v3.decode_predictions\n else:\n self.output_dim = (n_channels if n_channels else 2048) * (1 if pooling else 8**2)\n elif model == 'mobilenet_v2':\n self.model = mobilenetv2.MobileNetV2(weights=weights, include_top=include_top, pooling=pooling)\n self.preprocess = mobilenetv2.preprocess_input\n self.target_size = (244, 244)\n if include_top:\n self.decode = mobilenetv2.decode_predictions\n else:\n self.output_dim = (n_channels if n_channels else 1280) * (1 if pooling else 7**2)\n else:\n raise Exception('model option not implemented')\n \n def _load_finetune_model(\n self,\n nclasses = 2,\n weights_path = None,\n ):\n ''' Constructs finetuning model architecture and optionally loads weights\n :param nclasses: number of classes on which to softmax over\n :param weights_path: optional filepath from which to try to load weights\n '''\n \n out = self.model.output\n if self.pooling is None:\n out = GlobalAveragePooling2D()(out)# if self.pooling == 'avg' else GlobalMaxPooling2D()(out)\n dense = Dense(self.clf_head_dense_dim, activation='relu')(out)\n preds = Dense(nclasses, activation='softmax')(dense)\n finetune_model = Model(inputs = self.model.input, outputs = preds)\n\n # try to load weights\n if weights_path is not None:\n if os.path.isfile(weights_path):\n finetune_model.load_weights(weights_path)\n \n return finetune_model\n\n def get_features(self, images_array):\n ''' takes a batch of images as a 4-d array and returns the (flattened) imagenet features for those images as a 2-d array '''\n if self.include_top:\n raise Exception('getting features from a classification model with include_top=True is currently not supported')\n\n if images_array.ndim != 4:\n raise Exception('invalid input shape for images_array, expects a 4d array')\n\n # preprocess and compute image features\n logger.debug(f'preprocessing {images_array.shape[0]} images')\n images_array = self.preprocess(images_array)\n logger.debug(f'computing image features')\n image_features = self.model.predict(images_array)\n\n # if n_channels is specified, only keep that number of channels\n if self.n_channels:\n logger.debug(f'truncating to first {self.n_channels} channels')\n image_features = image_features.T[: self.n_channels].T\n\n # reshape output array by flattening each image into a vector of features\n shape = image_features.shape\n return image_features.reshape(shape[0], np.prod(shape[1:]))\n\n def predict(self, images_array):\n ''' alias for get_features to more closely match scikit-learn interface '''\n return self.get_features(images_array)\n\n def finetune(self, \n train_dataset, \n val_dataset = None, \n nclasses = 2,\n top_layer_epochs = 1,\n unfreeze_proportions = [0.5],\n all_layer_epochs = 5, \n class_weight = None,\n optimizer_top = 'rmsprop',\n optimizer_full = 'sgd',\n callbacks = None, \n num_workers = 8,\n load_weights_path = None,\n save_weights_path = None,\n ):\n ''' Finetunes the Imagenet model iteratively on a smaller set of images with (potentially) a smaller set of classes.\n First finetunes last layer then freezes bottom N layers and retrains the rest\n :param train_dataset: (X, y) pair of tf.constant tensors for training \n :param val_dataset: (X, y) pair of tf.constant tensors for validation, optional \n :param nclasses: number of classes \n :param top_layer_epochs: how many epochs for which to finetune classification head (happens first)\n :param unfreeze_proportions: list of proportions representing how much of the base ImageNet model one wants to\n unfreeze (later layers unfrozen) for another round of finetuning\n :param all_layer_epochs: how many epochs for which to finetune entire model (happens second)\n :param class_weight: class weights (used for both training steps)\n :param optimizer_top: optimizer to use for training of classification head\n :param optimizer_full: optimizer to use for training full classification model\n * suggest to use lower learning rate / more conservative optimizer for this step to \n prevent catastrophic forgetting \n :param callbacks: optional list of callbacks to use for each round of finetuning\n :param num_workers: number of workers to use for multiprocess data loading\n :param load_weights_path: optional filepath from which to try to load weights\n :param save_weights_path: optional filepath to which to store weights\n '''\n \n finetune_model = self._load_finetune_model(\n nclasses = nclasses,\n weights_path=load_weights_path\n )\n\n fitting_histories = []\n\n # freeze all convolutional InceptionV3 layers, retrain top layer\n for layer in self.model.layers:\n layer.trainable = False\n finetune_model.compile(\n optimizer=optimizer_top, \n loss='categorical_crossentropy')\n\n fitting_histories.append(\n finetune_model.fit(\n train_dataset, \n validation_data = val_dataset,\n epochs = top_layer_epochs,\n class_weight = class_weight, \n shuffle = True, \n use_multiprocessing = True, \n workers = num_workers, \n callbacks = callbacks\n )\n )\n\n # iteratively unfreeze specified proportion of later ImageNet base layers and finetune\n finetune_model.compile(\n # SGD(lr=0.0001, momentum=0.9)\n optimizer=optimizer_full, \n loss='categorical_crossentropy')\n for p in unfreeze_proportions:\n freeze_count = int(len(self.model.layers) * p)\n for layer in finetune_model.layers[:freeze_count]:\n layer.trainable = False\n for layer in finetune_model.layers[freeze_count:]:\n layer.trainable = True\n\n fitting_histories.append(\n finetune_model.fit(\n train_dataset, \n validation_data = val_dataset,\n epochs = all_layer_epochs,\n class_weight = class_weight, \n shuffle = True, \n use_multiprocessing = True, \n workers = num_workers, \n callbacks = callbacks\n )\n )\n \n # save weights\n if save_weights_path is not None:\n finetune_model.save_weights(save_weights_path)\n \n return fitting_histories\n\n def finetune_classify(self, \n test_dataset, \n nclasses = 2,\n num_workers = 8,\n load_weights_path = None,\n ):\n\n ''' Uses the finetuned model to predict on a test dataset. \n :param test_dataset: X, tf.constant tensor for inference\n :param nclasses: number of classes \n :param num_workers: number of workers to use for multiprocess data loading\n :return: array of softmaxed prediction probabilities\n :param load_weights_path: optional filepath from which to try to load weights\n ''' \n\n finetune_model = self._load_finetune_model(\n nclasses = nclasses,\n weights_path = load_weights_path\n )\n\n return finetune_model.predict_generator(test_dataset, \n use_multiprocessing = True, \n workers = num_workers\n )\n\nclass ImageNetGen(Sequence):\n \"\"\" Tf.Keras Sequence for ImageNet input data \"\"\"\n\n def __init__(self, X, y = None, batch_size = 32):\n self.X = X\n self.y = y\n self.batch_size = batch_size\n\n def __len__(self):\n return math.ceil(self.X.shape[0] / self.batch_size)\n\n def __getitem__(self, idx):\n batch_x = self.X[idx * self.batch_size:(idx + 1) * self.batch_size]\n if self.y is None:\n return tf.constant(batch_x)\n else:\n batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size]\n return tf.constant(batch_x), tf.constant(batch_y)\n " ]
[ [ "tensorflow.constant", "tensorflow.keras.layers.GlobalAveragePooling2D", "tensorflow.keras.applications.xception.Xception", "tensorflow.keras.models.Model", "tensorflow.keras.layers.Dense", "numpy.prod", "tensorflow.keras.applications.inception_v3.InceptionV3" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] } ]
alexklwong/calibrated-backprojection-network
[ "57dbec03c6da94ee0cd020b6de5f02e7e8ee726e" ]
[ "src/kbnet.py" ]
[ "'''\nAuthor: Alex Wong <[email protected]>\n\nIf you use this code, please cite the following paper:\n\nA. Wong, and S. Soatto. Unsupervised Depth Completion with Calibrated Backprojection Layers.\nhttps://arxiv.org/pdf/2108.10531.pdf\n\n@inproceedings{wong2021unsupervised,\n title={Unsupervised Depth Completion with Calibrated Backprojection Layers},\n author={Wong, Alex and Soatto, Stefano},\n booktitle={Proceedings of the IEEE/CVF International Conference on Computer Vision},\n pages={12747--12756},\n year={2021}\n}\n'''\nimport os, time\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch.utils.tensorboard import SummaryWriter\nimport datasets, data_utils, eval_utils\nfrom log_utils import log\nfrom kbnet_model import KBNetModel\nfrom posenet_model import PoseNetModel\nimport global_constants as settings\nfrom transforms import Transforms\nfrom net_utils import OutlierRemoval\n\n\ndef train(train_image_path,\n train_sparse_depth_path,\n train_intrinsics_path,\n val_image_path,\n val_sparse_depth_path,\n val_intrinsics_path,\n val_ground_truth_path,\n # Batch settings\n n_batch=settings.N_BATCH,\n n_height=settings.N_HEIGHT,\n n_width=settings.N_WIDTH,\n # Input settings\n input_channels_image=settings.INPUT_CHANNELS_IMAGE,\n input_channels_depth=settings.INPUT_CHANNELS_DEPTH,\n normalized_image_range=settings.NORMALIZED_IMAGE_RANGE,\n outlier_removal_kernel_size=settings.OUTLIER_REMOVAL_KERNEL_SIZE,\n outlier_removal_threshold=settings.OUTLIER_REMOVAL_THRESHOLD,\n # Sparse to dense pool settings\n min_pool_sizes_sparse_to_dense_pool=settings.MIN_POOL_SIZES_SPARSE_TO_DENSE_POOL,\n max_pool_sizes_sparse_to_dense_pool=settings.MAX_POOL_SIZES_SPARSE_TO_DENSE_POOL,\n n_convolution_sparse_to_dense_pool=settings.N_CONVOLUTION_SPARSE_TO_DENSE_POOL,\n n_filter_sparse_to_dense_pool=settings.N_FILTER_SPARSE_TO_DENSE_POOL,\n # Depth network settings\n n_filters_encoder_image=settings.N_FILTERS_ENCODER_IMAGE,\n n_filters_encoder_depth=settings.N_FILTERS_ENCODER_DEPTH,\n resolutions_backprojection=settings.RESOLUTIONS_BACKPROJECTION,\n n_filters_decoder=settings.N_FILTERS_DECODER,\n deconv_type=settings.DECONV_TYPE,\n min_predict_depth=settings.MIN_PREDICT_DEPTH,\n max_predict_depth=settings.MAX_PREDICT_DEPTH,\n # Weight settings\n weight_initializer=settings.WEIGHT_INITIALIZER,\n activation_func=settings.ACTIVATION_FUNC,\n # Training settings\n learning_rates=settings.LEARNING_RATES,\n learning_schedule=settings.LEARNING_SCHEDULE,\n augmentation_probabilities=settings.AUGMENTATION_PROBABILITIES,\n augmentation_schedule=settings.AUGMENTATION_SCHEDULE,\n augmentation_random_crop_type=settings.AUGMENTATION_RANDOM_CROP_TYPE,\n augmentation_random_flip_type=settings.AUGMENTATION_RANDOM_FLIP_TYPE,\n augmentation_random_remove_points=settings.AUGMENTATION_RANDOM_REMOVE_POINTS,\n augmentation_random_noise_type=settings.AUGMENTATION_RANDOM_NOISE_TYPE,\n augmentation_random_noise_spread=settings.AUGMENTATION_RANDOM_NOISE_SPREAD,\n # Loss function settings\n w_color=settings.W_COLOR,\n w_structure=settings.W_STRUCTURE,\n w_sparse_depth=settings.W_SPARSE_DEPTH,\n w_smoothness=settings.W_SMOOTHNESS,\n w_weight_decay_depth=settings.W_WEIGHT_DECAY_DEPTH,\n w_weight_decay_pose=settings.W_WEIGHT_DECAY_POSE,\n # Evaluation settings\n min_evaluate_depth=settings.MIN_EVALUATE_DEPTH,\n max_evaluate_depth=settings.MAX_EVALUATE_DEPTH,\n # Checkpoint settings\n checkpoint_path=settings.CHECKPOINT_PATH,\n n_checkpoint=settings.N_CHECKPOINT,\n n_summary=settings.N_SUMMARY,\n n_summary_display=settings.N_SUMMARY_DISPLAY,\n validation_start_step=settings.VALIDATION_START_STEP,\n depth_model_restore_path=settings.RESTORE_PATH,\n pose_model_restore_path=settings.RESTORE_PATH,\n # Hardware settings\n device=settings.DEVICE,\n n_thread=settings.N_THREAD):\n\n if device == settings.CUDA or device == settings.GPU:\n device = torch.device(settings.CUDA)\n else:\n device = torch.device(settings.CPU)\n\n if not os.path.exists(checkpoint_path):\n os.makedirs(checkpoint_path)\n\n # Set up checkpoint and event paths\n depth_model_checkpoint_path = os.path.join(checkpoint_path, 'depth_model-{}.pth')\n pose_model_checkpoint_path = os.path.join(checkpoint_path, 'pose_model-{}.pth')\n log_path = os.path.join(checkpoint_path, 'results.txt')\n event_path = os.path.join(checkpoint_path, 'events')\n\n best_results = {\n 'step': -1,\n 'mae': np.infty,\n 'rmse': np.infty,\n 'imae': np.infty,\n 'irmse': np.infty\n }\n\n '''\n Load input paths and set up dataloaders\n '''\n # Read paths for training\n train_image_paths = data_utils.read_paths(train_image_path)\n train_sparse_depth_paths = data_utils.read_paths(train_sparse_depth_path)\n train_intrinsics_paths = data_utils.read_paths(train_intrinsics_path)\n\n n_train_sample = len(train_image_paths)\n\n assert len(train_sparse_depth_paths) == n_train_sample\n assert len(train_intrinsics_paths) == n_train_sample\n\n n_train_step = \\\n learning_schedule[-1] * np.ceil(n_train_sample / n_batch).astype(np.int32)\n\n train_dataloader = torch.utils.data.DataLoader(\n datasets.KBNetTrainingDataset(\n image_paths=train_image_paths,\n sparse_depth_paths=train_sparse_depth_paths,\n intrinsics_paths=train_intrinsics_paths,\n shape=(n_height, n_width),\n random_crop_type=augmentation_random_crop_type),\n batch_size=n_batch,\n shuffle=True,\n num_workers=n_thread,\n drop_last=False)\n\n train_transforms = Transforms(\n normalized_image_range=normalized_image_range,\n random_flip_type=augmentation_random_flip_type,\n random_remove_points=augmentation_random_remove_points,\n random_noise_type=augmentation_random_noise_type,\n random_noise_spread=augmentation_random_noise_spread)\n\n # Load validation data if it is available\n validation_available = val_image_path is not None and \\\n val_sparse_depth_path is not None and \\\n val_intrinsics_path is not None and \\\n val_ground_truth_path is not None\n\n if validation_available:\n val_image_paths = data_utils.read_paths(val_image_path)\n val_sparse_depth_paths = data_utils.read_paths(val_sparse_depth_path)\n val_intrinsics_paths = data_utils.read_paths(val_intrinsics_path)\n val_ground_truth_paths = data_utils.read_paths(val_ground_truth_path)\n\n n_val_sample = len(val_image_paths)\n\n assert len(val_sparse_depth_paths) == n_val_sample\n assert len(val_intrinsics_paths) == n_val_sample\n assert len(val_ground_truth_paths) == n_val_sample\n\n ground_truths = []\n for path in val_ground_truth_paths:\n ground_truth, validity_map = data_utils.load_depth_with_validity_map(path)\n ground_truths.append(np.stack([ground_truth, validity_map], axis=-1))\n\n val_dataloader = torch.utils.data.DataLoader(\n datasets.KBNetInferenceDataset(\n image_paths=val_image_paths,\n sparse_depth_paths=val_sparse_depth_paths,\n intrinsics_paths=val_intrinsics_paths),\n batch_size=1,\n shuffle=False,\n num_workers=1,\n drop_last=False)\n\n val_transforms = Transforms(\n normalized_image_range=normalized_image_range)\n\n # Initialize outlier removal for sparse depth\n outlier_removal = OutlierRemoval(\n kernel_size=outlier_removal_kernel_size,\n threshold=outlier_removal_threshold)\n\n '''\n Set up the model\n '''\n # Build KBNet (depth) network\n depth_model = KBNetModel(\n input_channels_image=input_channels_image,\n input_channels_depth=input_channels_depth,\n min_pool_sizes_sparse_to_dense_pool=min_pool_sizes_sparse_to_dense_pool,\n max_pool_sizes_sparse_to_dense_pool=max_pool_sizes_sparse_to_dense_pool,\n n_convolution_sparse_to_dense_pool=n_convolution_sparse_to_dense_pool,\n n_filter_sparse_to_dense_pool=n_filter_sparse_to_dense_pool,\n n_filters_encoder_image=n_filters_encoder_image,\n n_filters_encoder_depth=n_filters_encoder_depth,\n resolutions_backprojection=resolutions_backprojection,\n n_filters_decoder=n_filters_decoder,\n deconv_type=deconv_type,\n weight_initializer=weight_initializer,\n activation_func=activation_func,\n min_predict_depth=min_predict_depth,\n max_predict_depth=max_predict_depth,\n device=device)\n\n parameters_depth_model = depth_model.parameters()\n\n depth_model.train()\n\n # Bulid PoseNet (only needed for training) network\n pose_model = PoseNetModel(\n encoder_type='resnet18',\n rotation_parameterization='axis',\n weight_initializer=weight_initializer,\n activation_func='relu',\n device=device)\n\n parameters_pose_model = pose_model.parameters()\n\n pose_model.train()\n\n if depth_model_restore_path is not None and depth_model_restore_path != '':\n depth_model.restore_model(depth_model_restore_path)\n\n if pose_model_restore_path is not None and pose_model_restore_path != '':\n pose_model.restore_model(pose_model_restore_path)\n\n # Set up tensorboard summary writers\n train_summary_writer = SummaryWriter(event_path + '-train')\n val_summary_writer = SummaryWriter(event_path + '-val')\n\n '''\n Log input paths\n '''\n log('Training input paths:', log_path)\n train_input_paths = [\n train_image_path,\n train_sparse_depth_path,\n train_intrinsics_path\n ]\n for path in train_input_paths:\n log(path, log_path)\n log('', log_path)\n\n log('Validation input paths:', log_path)\n val_input_paths = [\n val_image_path,\n val_sparse_depth_path,\n val_intrinsics_path,\n val_ground_truth_path\n ]\n for path in val_input_paths:\n log(path, log_path)\n log('', log_path)\n\n '''\n Log all settings\n '''\n log_input_settings(\n log_path,\n # Batch settings\n n_batch=n_batch,\n n_height=n_height,\n n_width=n_width,\n # Input settings\n input_channels_image=input_channels_image,\n input_channels_depth=input_channels_depth,\n normalized_image_range=normalized_image_range,\n outlier_removal_kernel_size=outlier_removal_kernel_size,\n outlier_removal_threshold=outlier_removal_threshold)\n\n log_network_settings(\n log_path,\n # Sparse to dense pool settings\n min_pool_sizes_sparse_to_dense_pool=min_pool_sizes_sparse_to_dense_pool,\n max_pool_sizes_sparse_to_dense_pool=max_pool_sizes_sparse_to_dense_pool,\n n_convolution_sparse_to_dense_pool=n_convolution_sparse_to_dense_pool,\n n_filter_sparse_to_dense_pool=n_filter_sparse_to_dense_pool,\n # Depth network settings\n n_filters_encoder_image=n_filters_encoder_image,\n n_filters_encoder_depth=n_filters_encoder_depth,\n resolutions_backprojection=resolutions_backprojection,\n n_filters_decoder=n_filters_decoder,\n deconv_type=deconv_type,\n min_predict_depth=min_predict_depth,\n max_predict_depth=max_predict_depth,\n # Weight settings\n weight_initializer=weight_initializer,\n activation_func=activation_func,\n parameters_depth_model=parameters_depth_model,\n parameters_pose_model=parameters_pose_model)\n\n log_training_settings(\n log_path,\n # Training settings\n n_batch=n_batch,\n n_train_sample=n_train_sample,\n n_train_step=n_train_step,\n learning_rates=learning_rates,\n learning_schedule=learning_schedule,\n # Augmentation settings\n augmentation_probabilities=augmentation_probabilities,\n augmentation_schedule=augmentation_schedule,\n augmentation_random_crop_type=augmentation_random_crop_type,\n augmentation_random_flip_type=augmentation_random_flip_type,\n augmentation_random_remove_points=augmentation_random_remove_points,\n augmentation_random_noise_type=augmentation_random_noise_type,\n augmentation_random_noise_spread=augmentation_random_noise_spread)\n\n log_loss_func_settings(\n log_path,\n # Loss function settings\n w_color=w_color,\n w_structure=w_structure,\n w_sparse_depth=w_sparse_depth,\n w_smoothness=w_smoothness,\n w_weight_decay_depth=w_weight_decay_depth,\n w_weight_decay_pose=w_weight_decay_pose)\n\n log_evaluation_settings(\n log_path,\n min_evaluate_depth=min_evaluate_depth,\n max_evaluate_depth=max_evaluate_depth)\n\n log_system_settings(\n log_path,\n # Checkpoint settings\n checkpoint_path=checkpoint_path,\n n_checkpoint=n_checkpoint,\n summary_event_path=event_path,\n n_summary=n_summary,\n n_summary_display=n_summary_display,\n validation_start_step=validation_start_step,\n depth_model_restore_path=depth_model_restore_path,\n pose_model_restore_path=pose_model_restore_path,\n # Hardware settings\n device=device,\n n_thread=n_thread)\n\n '''\n Train model\n '''\n # Initialize optimizer with starting learning rate\n learning_schedule_pos = 0\n learning_rate = learning_rates[0]\n\n augmentation_schedule_pos = 0\n augmentation_probability = augmentation_probabilities[0]\n\n optimizer = torch.optim.Adam([\n {\n 'params' : parameters_depth_model,\n 'weight_decay' : w_weight_decay_depth\n },\n {\n 'params' : parameters_pose_model,\n 'weight_decay' : w_weight_decay_pose\n }],\n lr=learning_rate)\n\n # Start training\n train_step = 0\n time_start = time.time()\n\n log('Begin training...', log_path)\n for epoch in range(1, learning_schedule[-1] + 1):\n\n # Set learning rate schedule\n if epoch > learning_schedule[learning_schedule_pos]:\n learning_schedule_pos = learning_schedule_pos + 1\n learning_rate = learning_rates[learning_schedule_pos]\n\n # Update optimizer learning rates\n for g in optimizer.param_groups:\n g['lr'] = learning_rate\n\n # Set augmentation schedule\n if -1 not in augmentation_schedule and epoch > augmentation_schedule[augmentation_schedule_pos]:\n augmentation_schedule_pos = augmentation_schedule_pos + 1\n augmentation_probability = augmentation_probabilities[augmentation_schedule_pos]\n\n for inputs in train_dataloader:\n\n train_step = train_step + 1\n\n # Fetch data\n inputs = [\n in_.to(device) for in_ in inputs\n ]\n\n image0, image1, image2, sparse_depth0, intrinsics = inputs\n\n # Validity map is where sparse depth is available\n validity_map_depth0 = torch.where(\n sparse_depth0 > 0,\n torch.ones_like(sparse_depth0),\n sparse_depth0)\n\n # Remove outlier points and update sparse depth and validity map\n filtered_sparse_depth0, \\\n filtered_validity_map_depth0 = outlier_removal.remove_outliers(\n sparse_depth=sparse_depth0,\n validity_map=validity_map_depth0)\n\n # Do data augmentation\n [image0, image1, image2], \\\n [sparse_depth0], \\\n [filtered_sparse_depth0, filtered_validity_map_depth0] = train_transforms.transform(\n images_arr=[image0, image1, image2],\n range_maps_arr=[sparse_depth0],\n validity_maps_arr=[filtered_sparse_depth0, filtered_validity_map_depth0],\n random_transform_probability=augmentation_probability)\n\n # Forward through the network\n output_depth0 = depth_model.forward(\n image=image0,\n sparse_depth=sparse_depth0,\n validity_map_depth=filtered_validity_map_depth0,\n intrinsics=intrinsics)\n\n pose01 = pose_model.forward(image0, image1)\n pose02 = pose_model.forward(image0, image2)\n\n # Compute loss function\n loss, loss_info = depth_model.compute_loss(\n image0=image0,\n image1=image1,\n image2=image2,\n output_depth0=output_depth0,\n sparse_depth0=filtered_sparse_depth0,\n validity_map_depth0=filtered_validity_map_depth0,\n intrinsics=intrinsics,\n pose01=pose01,\n pose02=pose02,\n w_color=w_color,\n w_structure=w_structure,\n w_sparse_depth=w_sparse_depth,\n w_smoothness=w_smoothness)\n\n # Compute gradient and backpropagate\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if (train_step % n_summary) == 0:\n image01 = loss_info.pop('image01')\n image02 = loss_info.pop('image02')\n\n depth_model.log_summary(\n summary_writer=train_summary_writer,\n tag='train',\n step=train_step,\n image0=image0,\n image01=image01,\n image02=image02,\n output_depth0=output_depth0,\n sparse_depth0=filtered_sparse_depth0,\n validity_map0=filtered_validity_map_depth0,\n pose01=pose01,\n pose02=pose02,\n scalars=loss_info,\n n_display=min(n_batch, n_summary_display))\n\n # Log results and save checkpoints\n if (train_step % n_checkpoint) == 0:\n time_elapse = (time.time() - time_start) / 3600\n time_remain = (n_train_step - train_step) * time_elapse / train_step\n\n log('Step={:6}/{} Loss={:.5f} Time Elapsed={:.2f}h Time Remaining={:.2f}h'.format(\n train_step, n_train_step, loss.item(), time_elapse, time_remain),\n log_path)\n\n if train_step >= validation_start_step and validation_available:\n # Switch to validation mode\n depth_model.eval()\n\n with torch.no_grad():\n best_results = validate(\n depth_model=depth_model,\n dataloader=val_dataloader,\n transforms=val_transforms,\n outlier_removal=outlier_removal,\n ground_truths=ground_truths,\n step=train_step,\n best_results=best_results,\n min_evaluate_depth=min_evaluate_depth,\n max_evaluate_depth=max_evaluate_depth,\n device=device,\n summary_writer=val_summary_writer,\n n_summary_display=n_summary_display,\n log_path=log_path)\n\n # Switch back to training\n depth_model.train()\n\n # Save checkpoints\n depth_model.save_model(\n depth_model_checkpoint_path.format(train_step), train_step, optimizer)\n\n pose_model.save_model(\n pose_model_checkpoint_path.format(train_step), train_step, optimizer)\n\n # Save checkpoints\n depth_model.save_model(\n depth_model_checkpoint_path.format(train_step), train_step, optimizer)\n\n pose_model.save_model(\n pose_model_checkpoint_path.format(train_step), train_step, optimizer)\n\ndef validate(depth_model,\n dataloader,\n transforms,\n outlier_removal,\n ground_truths,\n step,\n best_results,\n min_evaluate_depth,\n max_evaluate_depth,\n device,\n summary_writer,\n n_summary_display=4,\n n_summary_display_interval=250,\n log_path=None):\n\n n_sample = len(dataloader)\n mae = np.zeros(n_sample)\n rmse = np.zeros(n_sample)\n imae = np.zeros(n_sample)\n irmse = np.zeros(n_sample)\n\n image_summary = []\n output_depth_summary = []\n sparse_depth_summary = []\n validity_map_summary = []\n ground_truth_summary = []\n\n for idx, (inputs, ground_truth) in enumerate(zip(dataloader, ground_truths)):\n\n # Move inputs to device\n inputs = [\n in_.to(device) for in_ in inputs\n ]\n\n image, sparse_depth, intrinsics = inputs\n\n ground_truth = np.expand_dims(ground_truth, axis=0)\n ground_truth = np.transpose(ground_truth, (0, 3, 1, 2))\n ground_truth = torch.from_numpy(ground_truth).to(device)\n\n # Validity map is where sparse depth is available\n validity_map_depth = torch.where(\n sparse_depth > 0,\n torch.ones_like(sparse_depth),\n sparse_depth)\n\n # Remove outlier points and update sparse depth and validity map\n filtered_sparse_depth, \\\n filtered_validity_map_depth = outlier_removal.remove_outliers(\n sparse_depth=sparse_depth,\n validity_map=validity_map_depth)\n\n [image], \\\n [sparse_depth], \\\n [filtered_sparse_depth, filtered_validity_map_depth] = transforms.transform(\n images_arr=[image],\n range_maps_arr=[sparse_depth],\n validity_maps_arr=[filtered_sparse_depth, filtered_validity_map_depth],\n random_transform_probability=0.0)\n\n # Forward through network\n output_depth = depth_model.forward(\n image=image,\n sparse_depth=sparse_depth,\n validity_map_depth=filtered_validity_map_depth,\n intrinsics=intrinsics)\n\n if (idx % n_summary_display_interval) == 0 and summary_writer is not None:\n image_summary.append(image)\n output_depth_summary.append(output_depth)\n sparse_depth_summary.append(filtered_sparse_depth)\n validity_map_summary.append(filtered_validity_map_depth)\n ground_truth_summary.append(ground_truth)\n\n # Convert to numpy to validate\n output_depth = np.squeeze(output_depth.cpu().numpy())\n ground_truth = np.squeeze(ground_truth.cpu().numpy())\n\n validity_map = ground_truth[1, :, :]\n ground_truth = ground_truth[0, :, :]\n\n # Select valid regions to evaluate\n validity_mask = np.where(validity_map > 0, 1, 0)\n min_max_mask = np.logical_and(\n ground_truth > min_evaluate_depth,\n ground_truth < max_evaluate_depth)\n mask = np.where(np.logical_and(validity_mask, min_max_mask) > 0)\n\n output_depth = output_depth[mask]\n ground_truth = ground_truth[mask]\n\n # Compute validation metrics\n mae[idx] = eval_utils.mean_abs_err(1000.0 * output_depth, 1000.0 * ground_truth)\n rmse[idx] = eval_utils.root_mean_sq_err(1000.0 * output_depth, 1000.0 * ground_truth)\n imae[idx] = eval_utils.inv_mean_abs_err(0.001 * output_depth, 0.001 * ground_truth)\n irmse[idx] = eval_utils.inv_root_mean_sq_err(0.001 * output_depth, 0.001 * ground_truth)\n\n # Compute mean metrics\n mae = np.mean(mae)\n rmse = np.mean(rmse)\n imae = np.mean(imae)\n irmse = np.mean(irmse)\n\n # Log to tensorboard\n if summary_writer is not None:\n depth_model.log_summary(\n summary_writer=summary_writer,\n tag='eval',\n step=step,\n image0=torch.cat(image_summary, dim=0),\n output_depth0=torch.cat(output_depth_summary, dim=0),\n sparse_depth0=torch.cat(sparse_depth_summary, dim=0),\n validity_map0=torch.cat(validity_map_summary, dim=0),\n ground_truth0=torch.cat(ground_truth_summary, dim=0),\n scalars={'mae' : mae, 'rmse' : rmse, 'imae' : imae, 'irmse': irmse},\n n_display=n_summary_display)\n\n # Print validation results to console\n log('Validation results:', log_path)\n log('{:>8} {:>8} {:>8} {:>8} {:>8}'.format(\n 'Step', 'MAE', 'RMSE', 'iMAE', 'iRMSE'),\n log_path)\n log('{:8} {:8.3f} {:8.3f} {:8.3f} {:8.3f}'.format(\n step, mae, rmse, imae, irmse),\n log_path)\n\n n_improve = 0\n if np.round(mae, 2) <= np.round(best_results['mae'], 2):\n n_improve = n_improve + 1\n if np.round(rmse, 2) <= np.round(best_results['rmse'], 2):\n n_improve = n_improve + 1\n if np.round(imae, 2) <= np.round(best_results['imae'], 2):\n n_improve = n_improve + 1\n if np.round(irmse, 2) <= np.round(best_results['irmse'], 2):\n n_improve = n_improve + 1\n\n if n_improve > 2:\n best_results['step'] = step\n best_results['mae'] = mae\n best_results['rmse'] = rmse\n best_results['imae'] = imae\n best_results['irmse'] = irmse\n\n log('Best results:', log_path)\n log('{:>8} {:>8} {:>8} {:>8} {:>8}'.format(\n 'Step', 'MAE', 'RMSE', 'iMAE', 'iRMSE'),\n log_path)\n log('{:8} {:8.3f} {:8.3f} {:8.3f} {:8.3f}'.format(\n best_results['step'],\n best_results['mae'],\n best_results['rmse'],\n best_results['imae'],\n best_results['irmse']), log_path)\n\n return best_results\n\ndef run(image_path,\n sparse_depth_path,\n intrinsics_path,\n ground_truth_path=None,\n # Input settings\n input_channels_image=settings.INPUT_CHANNELS_IMAGE,\n input_channels_depth=settings.INPUT_CHANNELS_DEPTH,\n normalized_image_range=settings.NORMALIZED_IMAGE_RANGE,\n outlier_removal_kernel_size=settings.OUTLIER_REMOVAL_KERNEL_SIZE,\n outlier_removal_threshold=settings.OUTLIER_REMOVAL_THRESHOLD,\n # Sparse to dense pool settings\n min_pool_sizes_sparse_to_dense_pool=settings.MIN_POOL_SIZES_SPARSE_TO_DENSE_POOL,\n max_pool_sizes_sparse_to_dense_pool=settings.MAX_POOL_SIZES_SPARSE_TO_DENSE_POOL,\n n_convolution_sparse_to_dense_pool=settings.N_CONVOLUTION_SPARSE_TO_DENSE_POOL,\n n_filter_sparse_to_dense_pool=settings.N_FILTER_SPARSE_TO_DENSE_POOL,\n # Depth network settings\n n_filters_encoder_image=settings.N_FILTERS_ENCODER_IMAGE,\n n_filters_encoder_depth=settings.N_FILTERS_ENCODER_DEPTH,\n resolutions_backprojection=settings.RESOLUTIONS_BACKPROJECTION,\n n_filters_decoder=settings.N_FILTERS_DECODER,\n deconv_type=settings.DECONV_TYPE,\n min_predict_depth=settings.MIN_PREDICT_DEPTH,\n max_predict_depth=settings.MAX_PREDICT_DEPTH,\n # Weight settings\n weight_initializer=settings.WEIGHT_INITIALIZER,\n activation_func=settings.ACTIVATION_FUNC,\n # Evaluation settings\n min_evaluate_depth=settings.MIN_EVALUATE_DEPTH,\n max_evaluate_depth=settings.MAX_EVALUATE_DEPTH,\n # Checkpoint settings\n checkpoint_path=settings.CHECKPOINT_PATH,\n depth_model_restore_path=settings.RESTORE_PATH,\n # Output settings\n save_outputs=False,\n keep_input_filenames=False,\n # Hardware settings\n device=settings.DEVICE):\n\n # Set up output path\n if device == settings.CUDA or device == settings.GPU:\n device = torch.device(settings.CUDA)\n else:\n device = torch.device(settings.CPU)\n\n if not os.path.exists(checkpoint_path):\n os.makedirs(checkpoint_path)\n\n # Set up checkpoint and output paths\n log_path = os.path.join(checkpoint_path, 'results.txt')\n output_path = os.path.join(checkpoint_path, 'outputs')\n\n '''\n Load input paths and set up dataloader\n '''\n image_paths = data_utils.read_paths(image_path)\n sparse_depth_paths = data_utils.read_paths(sparse_depth_path)\n intrinsics_paths = data_utils.read_paths(intrinsics_path)\n\n ground_truth_available = False\n\n if ground_truth_path != '':\n ground_truth_available = True\n ground_truth_paths = data_utils.read_paths(ground_truth_path)\n\n n_sample = len(image_paths)\n\n input_paths = [\n image_paths,\n sparse_depth_paths,\n intrinsics_paths\n ]\n\n if ground_truth_available:\n input_paths.append(ground_truth_paths)\n\n for paths in input_paths:\n assert n_sample == len(paths)\n\n if ground_truth_available:\n\n ground_truths = []\n for path in ground_truth_paths:\n ground_truth, validity_map = data_utils.load_depth_with_validity_map(path)\n ground_truths.append(np.stack([ground_truth, validity_map], axis=-1))\n else:\n ground_truths = [None] * n_sample\n\n # Set up dataloader\n dataloader = torch.utils.data.DataLoader(\n datasets.KBNetInferenceDataset(\n image_paths=image_paths,\n sparse_depth_paths=sparse_depth_paths,\n intrinsics_paths=intrinsics_paths),\n batch_size=1,\n shuffle=False,\n num_workers=1,\n drop_last=False)\n\n # Initialize transforms to normalize image and outlier removal for sparse depth\n transforms = Transforms(\n normalized_image_range=normalized_image_range)\n\n outlier_removal = OutlierRemoval(\n kernel_size=outlier_removal_kernel_size,\n threshold=outlier_removal_threshold)\n\n '''\n Set up the model\n '''\n depth_model = KBNetModel(\n input_channels_image=input_channels_image,\n input_channels_depth=input_channels_depth,\n min_pool_sizes_sparse_to_dense_pool=min_pool_sizes_sparse_to_dense_pool,\n max_pool_sizes_sparse_to_dense_pool=max_pool_sizes_sparse_to_dense_pool,\n n_convolution_sparse_to_dense_pool=n_convolution_sparse_to_dense_pool,\n n_filter_sparse_to_dense_pool=n_filter_sparse_to_dense_pool,\n n_filters_encoder_image=n_filters_encoder_image,\n n_filters_encoder_depth=n_filters_encoder_depth,\n resolutions_backprojection=resolutions_backprojection,\n n_filters_decoder=n_filters_decoder,\n deconv_type=deconv_type,\n weight_initializer=weight_initializer,\n activation_func=activation_func,\n min_predict_depth=min_predict_depth,\n max_predict_depth=max_predict_depth,\n device=device)\n\n # Restore model and set to evaluation mode\n depth_model.restore_model(depth_model_restore_path)\n depth_model.eval()\n\n parameters_depth_model = depth_model.parameters()\n\n '''\n Log input paths\n '''\n log('Input paths:', log_path)\n input_paths = [\n image_path,\n sparse_depth_path,\n intrinsics_path,\n ]\n\n if ground_truth_available:\n input_paths.append(ground_truth_path)\n\n for path in input_paths:\n log(path, log_path)\n log('', log_path)\n\n '''\n Log all settings\n '''\n log_input_settings(\n log_path,\n # Input settings\n input_channels_image=input_channels_image,\n input_channels_depth=input_channels_depth,\n normalized_image_range=normalized_image_range,\n outlier_removal_kernel_size=outlier_removal_kernel_size,\n outlier_removal_threshold=outlier_removal_threshold)\n\n log_network_settings(\n log_path,\n # Sparse to dense pool settings\n min_pool_sizes_sparse_to_dense_pool=min_pool_sizes_sparse_to_dense_pool,\n max_pool_sizes_sparse_to_dense_pool=max_pool_sizes_sparse_to_dense_pool,\n n_convolution_sparse_to_dense_pool=n_convolution_sparse_to_dense_pool,\n n_filter_sparse_to_dense_pool=n_filter_sparse_to_dense_pool,\n # Depth network settings\n n_filters_encoder_image=n_filters_encoder_image,\n n_filters_encoder_depth=n_filters_encoder_depth,\n resolutions_backprojection=resolutions_backprojection,\n n_filters_decoder=n_filters_decoder,\n deconv_type=deconv_type,\n min_predict_depth=min_predict_depth,\n max_predict_depth=max_predict_depth,\n # Weight settings\n weight_initializer=weight_initializer,\n activation_func=activation_func,\n parameters_depth_model=parameters_depth_model)\n\n log_evaluation_settings(\n log_path,\n min_evaluate_depth=min_evaluate_depth,\n max_evaluate_depth=max_evaluate_depth)\n\n log_system_settings(\n log_path,\n # Checkpoint settings\n checkpoint_path=checkpoint_path,\n depth_model_restore_path=depth_model_restore_path,\n # Hardware settings\n device=device,\n n_thread=1)\n\n '''\n Run model\n '''\n # Set up metrics in case groundtruth is available\n mae = np.zeros(n_sample)\n rmse = np.zeros(n_sample)\n imae = np.zeros(n_sample)\n irmse = np.zeros(n_sample)\n\n images = []\n output_depths = []\n sparse_depths = []\n\n time_elapse = 0.0\n\n for idx, (inputs, ground_truth) in enumerate(zip(dataloader, ground_truths)):\n\n # Move inputs to device\n inputs = [\n in_.to(device) for in_ in inputs\n ]\n\n image, sparse_depth, intrinsics = inputs\n\n time_start = time.time()\n\n # Validity map is where sparse depth is available\n validity_map_depth = torch.where(\n sparse_depth > 0,\n torch.ones_like(sparse_depth),\n sparse_depth)\n\n # Remove outlier points and update sparse depth and validity map\n filtered_sparse_depth, \\\n filtered_validity_map_depth = outlier_removal.remove_outliers(\n sparse_depth=sparse_depth,\n validity_map=validity_map_depth)\n\n [image] = transforms.transform(\n images_arr=[image],\n random_transform_probability=0.0)\n\n # Forward through network\n output_depth = depth_model.forward(\n image=image,\n sparse_depth=sparse_depth,\n validity_map_depth=filtered_validity_map_depth,\n intrinsics=intrinsics)\n\n time_elapse = time_elapse + (time.time() - time_start)\n\n # Convert to numpy\n output_depth = np.squeeze(output_depth.detach().cpu().numpy())\n\n # Save to output\n if save_outputs:\n images.append(np.transpose(np.squeeze(image.cpu().numpy()), (1, 2, 0)))\n sparse_depths.append(np.squeeze(filtered_sparse_depth.cpu().numpy()))\n output_depths.append(output_depth)\n\n if ground_truth_available:\n ground_truth = np.squeeze(ground_truth)\n\n validity_map = ground_truth[:, :, 1]\n ground_truth = ground_truth[:, :, 0]\n\n validity_mask = np.where(validity_map > 0, 1, 0)\n min_max_mask = np.logical_and(\n ground_truth > min_evaluate_depth,\n ground_truth < max_evaluate_depth)\n mask = np.where(np.logical_and(validity_mask, min_max_mask) > 0)\n\n output_depth = output_depth[mask]\n ground_truth = ground_truth[mask]\n\n mae[idx] = eval_utils.mean_abs_err(1000.0 * output_depth, 1000.0 * ground_truth)\n rmse[idx] = eval_utils.root_mean_sq_err(1000.0 * output_depth, 1000.0 * ground_truth)\n imae[idx] = eval_utils.inv_mean_abs_err(0.001 * output_depth, 0.001 * ground_truth)\n irmse[idx] = eval_utils.inv_root_mean_sq_err(0.001 * output_depth, 0.001 * ground_truth)\n\n # Compute total time elapse in ms\n time_elapse = time_elapse * 1000.0\n\n if ground_truth_available:\n mae_mean = np.mean(mae)\n rmse_mean = np.mean(rmse)\n imae_mean = np.mean(imae)\n irmse_mean = np.mean(irmse)\n\n mae_std = np.std(mae)\n rmse_std = np.std(rmse)\n imae_std = np.std(imae)\n irmse_std = np.std(irmse)\n\n # Print evaluation results to console and file\n log('Evaluation results:', log_path)\n log('{:>8} {:>8} {:>8} {:>8}'.format(\n 'MAE', 'RMSE', 'iMAE', 'iRMSE'),\n log_path)\n log('{:8.3f} {:8.3f} {:8.3f} {:8.3f}'.format(\n mae_mean, rmse_mean, imae_mean, irmse_mean),\n log_path)\n\n log('{:>8} {:>8} {:>8} {:>8}'.format(\n '+/-', '+/-', '+/-', '+/-'),\n log_path)\n log('{:8.3f} {:8.3f} {:8.3f} {:8.3f}'.format(\n mae_std, rmse_std, imae_std, irmse_std),\n log_path)\n\n # Log run time\n log('Total time: {:.2f} ms Average time per sample: {:.2f} ms'.format(\n time_elapse, time_elapse / float(n_sample)))\n\n if save_outputs:\n log('Saving outputs to {}'.format(output_path), log_path)\n\n outputs = zip(images, output_depths, sparse_depths, ground_truths)\n\n image_dirpath = os.path.join(output_path, 'image')\n output_depth_dirpath = os.path.join(output_path, 'output_depth')\n sparse_depth_dirpath = os.path.join(output_path, 'sparse_depth')\n ground_truth_dirpath = os.path.join(output_path, 'ground_truth')\n\n dirpaths = [\n image_dirpath,\n output_depth_dirpath,\n sparse_depth_dirpath,\n ground_truth_dirpath\n ]\n\n for dirpath in dirpaths:\n if not os.path.exists(dirpath):\n os.makedirs(dirpath)\n\n for idx, (image, output_depth, sparse_depth, ground_truth) in enumerate(outputs):\n\n if keep_input_filenames:\n filename = os.path.basename(image_paths[idx])\n else:\n filename = '{:010d}.png'.format(idx)\n\n image_path = os.path.join(image_dirpath, filename)\n image = (255 * image).astype(np.uint8)\n Image.fromarray(image).save(image_path)\n\n output_depth_path = os.path.join(output_depth_dirpath, filename)\n data_utils.save_depth(output_depth, output_depth_path)\n\n sparse_depth_path = os.path.join(sparse_depth_dirpath, filename)\n data_utils.save_depth(sparse_depth, sparse_depth_path)\n\n if ground_truth_available:\n ground_truth_path = os.path.join(ground_truth_dirpath, filename)\n data_utils.save_depth(ground_truth[..., 0], ground_truth_path)\n\n\n'''\nHelper functions for logging\n'''\ndef log_input_settings(log_path,\n n_batch=None,\n n_height=None,\n n_width=None,\n input_channels_image=settings.INPUT_CHANNELS_IMAGE,\n input_channels_depth=settings.INPUT_CHANNELS_DEPTH,\n normalized_image_range=settings.NORMALIZED_IMAGE_RANGE,\n outlier_removal_kernel_size=settings.OUTLIER_REMOVAL_KERNEL_SIZE,\n outlier_removal_threshold=settings.OUTLIER_REMOVAL_THRESHOLD):\n\n batch_settings_text = ''\n batch_settings_vars = []\n\n if n_batch is not None:\n batch_settings_text = batch_settings_text + 'n_batch={}'\n batch_settings_vars.append(n_batch)\n\n batch_settings_text = \\\n batch_settings_text + ' ' if len(batch_settings_text) > 0 else batch_settings_text\n\n if n_height is not None:\n batch_settings_text = batch_settings_text + 'n_height={}'\n batch_settings_vars.append(n_height)\n\n batch_settings_text = \\\n batch_settings_text + ' ' if len(batch_settings_text) > 0 else batch_settings_text\n\n if n_width is not None:\n batch_settings_text = batch_settings_text + 'n_width={}'\n batch_settings_vars.append(n_width)\n\n log('Input settings:', log_path)\n\n if len(batch_settings_vars) > 0:\n log(batch_settings_text.format(*batch_settings_vars),\n log_path)\n\n log('input_channels_image={} input_channels_depth={}'.format(\n input_channels_image, input_channels_depth),\n log_path)\n log('normalized_image_range={}'.format(normalized_image_range),\n log_path)\n log('outlier_removal_kernel_size={} outlier_removal_threshold={:.2f}'.format(\n outlier_removal_kernel_size, outlier_removal_threshold),\n log_path)\n log('', log_path)\n\ndef log_network_settings(log_path,\n # Sparse to dense pool settings\n min_pool_sizes_sparse_to_dense_pool,\n max_pool_sizes_sparse_to_dense_pool,\n n_convolution_sparse_to_dense_pool,\n n_filter_sparse_to_dense_pool,\n # Depth network settings\n n_filters_encoder_image,\n n_filters_encoder_depth,\n resolutions_backprojection,\n n_filters_decoder,\n deconv_type,\n min_predict_depth,\n max_predict_depth,\n # Weight settings\n weight_initializer,\n activation_func,\n parameters_depth_model=[],\n parameters_pose_model=[]):\n\n # Computer number of parameters\n n_parameter_depth = sum(p.numel() for p in parameters_depth_model)\n n_parameter_pose = sum(p.numel() for p in parameters_pose_model)\n\n n_parameter = n_parameter_depth + n_parameter_pose\n\n n_parameter_text = 'n_parameter={}'.format(n_parameter)\n n_parameter_vars = []\n\n if n_parameter_depth > 0 :\n n_parameter_text = n_parameter_text + 'n_parameter_depth={}'\n n_parameter_vars.append(n_parameter_depth)\n\n n_parameter_text = \\\n n_parameter_text + ' ' if len(n_parameter_text) > 0 else n_parameter_text\n\n if n_parameter_pose > 0 :\n n_parameter_text = n_parameter_text + 'n_parameter_pose={}'\n n_parameter_vars.append(n_parameter_pose)\n\n n_parameter_text = \\\n n_parameter_text + ' ' if len(n_parameter_text) > 0 else n_parameter_text\n\n log('Sparse to dense pooling settings:', log_path)\n log('min_pool_sizes_sparse_to_dense_pool={}'.format(min_pool_sizes_sparse_to_dense_pool),\n log_path)\n log('max_pool_sizes_sparse_to_dense_pool={}'.format(max_pool_sizes_sparse_to_dense_pool),\n log_path)\n log('n_convolution_sparse_to_dense_pool={}'.format(n_convolution_sparse_to_dense_pool),\n log_path)\n log('n_filter_sparse_to_dense_pool={}'.format(n_filter_sparse_to_dense_pool),\n log_path)\n log('', log_path)\n\n log('Depth network settings:', log_path)\n log('n_filters_encoder_image={}'.format(n_filters_encoder_image),\n log_path)\n log('n_filters_encoder_depth={}'.format(n_filters_encoder_depth),\n log_path)\n log('resolutions_backprojection={}'.format(resolutions_backprojection),\n log_path)\n log('n_filters_decoder={}'.format(n_filters_decoder),\n log_path)\n log('deconv_type={}'.format(deconv_type),\n log_path)\n log('min_predict_depth={:.2f} max_predict_depth={:.2f}'.format(\n min_predict_depth, max_predict_depth),\n log_path)\n log('', log_path)\n\n log('Weight settings:', log_path)\n log('n_parameter={} n_parameter_depth={} n_parameter_pose={}'.format(\n n_parameter, n_parameter_depth, n_parameter_pose),\n log_path)\n log('weight_initializer={} activation_func={}'.format(\n weight_initializer, activation_func),\n log_path)\n log('', log_path)\n\ndef log_training_settings(log_path,\n # Training settings\n n_batch,\n n_train_sample,\n n_train_step,\n learning_rates,\n learning_schedule,\n # Augmentation settings\n augmentation_probabilities,\n augmentation_schedule,\n augmentation_random_crop_type,\n augmentation_random_flip_type,\n augmentation_random_remove_points,\n augmentation_random_noise_type,\n augmentation_random_noise_spread):\n\n log('Training settings:', log_path)\n log('n_sample={} n_epoch={} n_step={}'.format(\n n_train_sample, learning_schedule[-1], n_train_step),\n log_path)\n log('learning_schedule=[%s]' %\n ', '.join('{}-{} : {}'.format(\n ls * (n_train_sample // n_batch), le * (n_train_sample // n_batch), v)\n for ls, le, v in zip([0] + learning_schedule[:-1], learning_schedule, learning_rates)),\n log_path)\n log('', log_path)\n\n log('Augmentation settings:', log_path)\n log('augmentation_schedule=[%s]' %\n ', '.join('{}-{} : {}'.format(\n ls * (n_train_sample // n_batch), le * (n_train_sample // n_batch), v)\n for ls, le, v in zip([0] + augmentation_schedule[:-1], augmentation_schedule, augmentation_probabilities)),\n log_path)\n log('augmentation_random_crop_type={}'.format(augmentation_random_crop_type),\n log_path)\n log('augmentation_random_flip_type={}'.format(augmentation_random_flip_type),\n log_path)\n log('augmentation_random_remove_points={}'.format(augmentation_random_remove_points),\n log_path)\n log('augmentation_random_noise_type={} augmentation_random_noise_spread={}'.format(\n augmentation_random_noise_type, augmentation_random_noise_spread),\n log_path)\n log('', log_path)\n\ndef log_loss_func_settings(log_path,\n # Loss function settings\n w_color,\n w_structure,\n w_sparse_depth,\n w_smoothness,\n w_weight_decay_depth,\n w_weight_decay_pose):\n\n log('Loss function settings:', log_path)\n log('w_color={:.1e} w_structure={:.1e} w_sparse_depth={:.1e}'.format(\n w_color, w_structure, w_sparse_depth),\n log_path)\n log('w_smoothness={:.1e}'.format(w_smoothness),\n log_path)\n log('w_weight_decay_depth={:.1e} w_weight_decay_pose={:.1e}'.format(\n w_weight_decay_depth, w_weight_decay_pose),\n log_path)\n log('', log_path)\n\ndef log_evaluation_settings(log_path,\n min_evaluate_depth,\n max_evaluate_depth):\n\n log('Evaluation settings:', log_path)\n log('min_evaluate_depth={:.2f} max_evaluate_depth={:.2f}'.format(\n min_evaluate_depth, max_evaluate_depth),\n log_path)\n log('', log_path)\n\ndef log_system_settings(log_path,\n # Checkpoint settings\n checkpoint_path,\n n_checkpoint=None,\n summary_event_path=None,\n n_summary=None,\n n_summary_display=None,\n validation_start_step=None,\n depth_model_restore_path=None,\n pose_model_restore_path=None,\n # Hardware settings\n device=torch.device('cuda'),\n n_thread=8):\n\n log('Checkpoint settings:', log_path)\n\n if checkpoint_path is not None:\n log('checkpoint_path={}'.format(checkpoint_path), log_path)\n\n if n_checkpoint is not None:\n log('checkpoint_save_frequency={}'.format(n_checkpoint), log_path)\n\n if validation_start_step is not None:\n log('validation_start_step={}'.format(validation_start_step), log_path)\n\n log('', log_path)\n\n summary_settings_text = ''\n summary_settings_vars = []\n\n if summary_event_path is not None:\n log('Tensorboard settings:', log_path)\n log('event_path={}'.format(summary_event_path), log_path)\n\n if n_summary is not None:\n summary_settings_text = summary_settings_text + 'log_summary_frequency={}'\n summary_settings_vars.append(n_summary)\n\n summary_settings_text = \\\n summary_settings_text + ' ' if len(summary_settings_text) > 0 else summary_settings_text\n\n if n_summary_display is not None:\n summary_settings_text = summary_settings_text + 'n_summary_display={}'\n summary_settings_vars.append(n_summary_display)\n\n summary_settings_text = \\\n summary_settings_text + ' ' if len(summary_settings_text) > 0 else summary_settings_text\n\n if len(summary_settings_text) > 0:\n log(summary_settings_text.format(*summary_settings_vars), log_path)\n\n if depth_model_restore_path is not None and depth_model_restore_path != '':\n log('depth_model_restore_path={}'.format(depth_model_restore_path),\n log_path)\n\n if pose_model_restore_path is not None and pose_model_restore_path != '':\n log('pose_model_restore_path={}'.format(pose_model_restore_path),\n log_path)\n\n log('', log_path)\n\n log('Hardware settings:', log_path)\n log('device={}'.format(device.type), log_path)\n log('n_thread={}'.format(n_thread), log_path)\n log('', log_path)\n" ]
[ [ "torch.optim.Adam", "numpy.expand_dims", "torch.ones_like", "torch.cat", "numpy.squeeze", "torch.from_numpy", "numpy.stack", "numpy.round", "numpy.ceil", "numpy.std", "numpy.mean", "torch.utils.tensorboard.SummaryWriter", "torch.no_grad", "numpy.transpose", "torch.device", "numpy.logical_and", "numpy.zeros", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
crodriguez1a/cen
[ "f03397a0bf4ac24162e270907d623f8658179e88", "f03397a0bf4ac24162e270907d623f8658179e88" ]
[ "cen/regularizers/entropy.py", "cen/data/support2.py" ]
[ "# Copyright 2020 Maruan Al-Shedivat. 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\"\"\"Entropy-based activity regularizers.\"\"\"\n\nimport tensorflow as tf\n\nfrom tensorflow.python.keras.regularizers import Regularizer\n\n\nclass ContextConditionalNegativeEntropy(Regularizer):\n \"\"\"Encourages models with higher context-conditional entropy.\"\"\"\n\n def __init__(self, coeff=0., num_samples=256, stddev=2e-1, epsilon=1e-6):\n self.coeff = coeff\n self.stddev = stddev\n self.epsilon = epsilon\n self.num_samples = num_samples\n\n def __call__(self, x):\n if self.coeff == 0.:\n return tf.constant(0.)\n\n # Unpack inputs.\n # contextual_weights:\n # kernels: <float32> [batch_size, feature_dim, num_classes].\n # biases: <float32> [batch_size, num_classes].\n # features: <float32> [batch_size, feature_dim].\n # outputs: <float32> [batch_size, num_classes].\n contextual_weights, features, outputs = x\n\n # Generate features from P(x | c).\n # <float32> [batch_size, num_samples, feature_dim].\n features_shape = tf.shape(features)\n features_noise = tf.random.normal(\n shape=(features_shape[0], self.num_samples, features_shape[1]),\n stddev=self.stddev\n )\n # <float32> [batch_size, num_samples, feature_dim].\n features_prime = tf.expand_dims(features, axis=1) + features_noise\n\n # Compute log mean_j P(Y | x_j, c_i).\n # <float32> [batch_size, num_samples, num_classes].\n logits = tf.einsum(\n \"ipk,ijp->ijk\", contextual_weights[\"kernels\"], features_prime\n )\n if \"biases\" in contextual_weights:\n # <float32> [batch_size, num_samples, units].\n biases = tf.expand_dims(contextual_weights[\"biases\"], axis=1)\n logits = tf.add(logits, biases)\n # <float32> [batch_size, num_classes].\n probs = tf.reduce_mean(tf.nn.softmax(logits), axis=1) + self.epsilon\n probs_sum = tf.reduce_sum(probs, axis=-1, keepdims=True)\n log_probs = tf.math.log(probs / probs_sum)\n\n # Compute loss.\n loss = -tf.nn.softmax_cross_entropy_with_logits(\n labels=tf.nn.softmax(outputs), logits=log_probs\n )\n return self.coeff * tf.reduce_mean(loss)\n\n def __str__(self):\n config = self.get_config()\n return \"{name:s}({coeff:f})\".format(**config)\n\n def get_config(self):\n return {\"name\": self.__class__.__name__, \"coeff\": float(self.coeff)}\n\n\n# Aliases.\n\n\ndef ctx_cond_neg_ent(coeff=0., num_samples=32, stddev=.1, epsilon=1e-6):\n return ContextConditionalNegativeEntropy(\n coeff=coeff, num_samples=num_samples, stddev=stddev, epsilon=epsilon\n )\n", "# Copyright 2020 Maruan Al-Shedivat. 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\"\"\"Loaders and preprocessors for SUPPORT2 data.\"\"\"\n\nimport logging\nimport os\n\nimport numpy as np\nimport pandas as pd\n\nlogger = logging.getLogger(__name__)\n\n# Data parameters\nTRAIN_SIZE, VALID_SIZE, TEST_SIZE = 7105, 1000, 1000\nEXCLUDE_FEATURES = [\n \"aps\",\n \"sps\",\n \"surv2m\",\n \"surv6m\",\n \"prg2m\",\n \"prg6m\",\n \"dnr\",\n \"dnrday\",\n \"hospdead\",\n \"dzclass\",\n \"edu\",\n \"scoma\",\n \"totmcst\",\n \"charges\",\n \"totcst\",\n]\nTARGETS = [\"death\", \"d.time\"]\nAVG_VALUES = {\n \"alb\": 3.5,\n \"bili\": 1.01,\n \"bun\": 6.51,\n \"crea\": 1.01,\n \"pafi\": 333.3,\n \"wblc\": 9.0,\n \"urine\": 2502.0,\n}\n\n\ndef load_data(\n datapath=None,\n nb_intervals=156,\n interval_len=7,\n fill_na=\"avg\",\n na_value=0.0,\n death_indicator=1.0,\n censorship_indicator=1.0,\n inputs_as_sequences=False,\n inputs_pad_mode=\"constant\",\n order=None,\n):\n \"\"\"Load and preprocess the SUPPORT2 dataset.\n\n Args:\n datapath : str or None\n nb_intervals : uint (default: 100)\n Number of intervals to split the time line.\n interval_len : uint (default: 20)\n The length of the interval in days.\n fill_na : str (default: \"avg\")\n na_value : float (default: -1.0)\n death_indicator : float (default: 1.0)\n censorship_indicator : float (default: -1.0)\n order: np.ndarray (default: None)\n\n Returns:\n data: dict of tuples (X, y) of ndarrays\n \"\"\"\n if datapath is None:\n datapath = \"$DATA_PATH/SUPPORT2/support2.csv\"\n datapath = os.path.expandvars(datapath)\n\n # Exclude unnecessary columns\n df = pd.read_csv(datapath)\n columns = sorted(list(set(df.columns) - set(EXCLUDE_FEATURES)))\n df = df[columns]\n\n # Split into features and targets\n targets = df[TARGETS]\n features = df[list(set(df.columns) - set(TARGETS))]\n\n # Convert categorical columns into one-hot format\n cat_columns = features.columns[features.dtypes == \"object\"]\n features = pd.get_dummies(features, dummy_na=False, columns=cat_columns)\n\n # Scale and impute real-valued features\n features[[\"num.co\", \"slos\", \"hday\"]] = features[\n [\"num.co\", \"slos\", \"hday\"]\n ].astype(np.float)\n float_cols = features.columns[features.dtypes == np.float]\n features[float_cols] = (\n features[float_cols] - features[float_cols].min()\n ) / (features[float_cols].max() - features[float_cols].min())\n if fill_na == \"avg\":\n for key, val in AVG_VALUES.items():\n features[[key]] = features[[key]].fillna(val)\n features.fillna(na_value, inplace=True)\n\n X = features.values\n X[:, 33] = np.random.rand(X.shape[0])\n X = X.astype(np.float32)\n\n # Preprocess targets\n T = targets.values\n Y = np.zeros((len(targets), nb_intervals, 2))\n for i, (death, days) in enumerate(T):\n intervals = days // interval_len\n if death and intervals < nb_intervals:\n Y[i, intervals:, 1] = death_indicator\n if not death and intervals < nb_intervals:\n Y[i, intervals:, 0] = censorship_indicator\n\n # Convert inputs into sequences if necessary\n if inputs_as_sequences:\n X = X.reshape((X.shape[0], 1, X.shape[1]))\n if inputs_pad_mode == \"constant\":\n X = np.pad(\n X,\n [(0, 0), (0, Y.shape[1] - 1), (0, 0)],\n mode=inputs_pad_mode,\n constant_values=0.0,\n )\n else:\n X = np.pad(\n X, [(0, 0), (0, Y.shape[1] - 1), (0, 0)], mode=inputs_pad_mode\n )\n\n if order is not None:\n X, Y = X[order], Y[order]\n\n X_train = X[:TRAIN_SIZE]\n y_train = Y[:TRAIN_SIZE]\n X_valid = X[TRAIN_SIZE:-TEST_SIZE]\n y_valid = Y[TRAIN_SIZE:-TEST_SIZE]\n X_test = X[-TEST_SIZE:]\n y_test = Y[-TEST_SIZE:]\n\n data = {\n \"train\": ({\"C\": X_train}, y_train),\n \"valid\": ({\"C\": X_valid}, y_valid),\n \"test\": ({\"C\": X_test}, y_test),\n }\n\n logger.debug(f\"X shape: {X_train.shape[1:]}\")\n logger.debug(f\"Y shape: {y_train.shape[1:]}\")\n logger.debug(f\"{len(X_train)} train samples\")\n logger.debug(f\"{len(X_valid)} validation samples\")\n logger.debug(f\"{len(X_test)} test samples\")\n\n return data\n\n\ndef load_interp_features(\n datapath=None, fill_na=\"avg\", na_value=0.0, order=None\n):\n if datapath is None:\n datapath = \"$DATA_PATH/SUPPORT2/support2.csv\"\n datapath = os.path.expandvars(datapath)\n\n # Exclude unnecessary columns.\n df = pd.read_csv(datapath)\n columns = sorted(list(set(df.columns) - set(EXCLUDE_FEATURES)))\n df = df[columns]\n\n # Convert categorical columns into one-hot format.\n features = df[list(set(df.columns) - set(TARGETS))]\n cat_columns = features.columns[features.dtypes == \"object\"]\n features = pd.get_dummies(features, dummy_na=False, columns=cat_columns)\n\n # Scale and impute real-valued features.\n features[[\"num.co\", \"slos\", \"hday\"]] = features[\n [\"num.co\", \"slos\", \"hday\"]\n ].astype(np.float)\n float_cols = features.columns[features.dtypes == np.float]\n features[float_cols] = (\n features[float_cols] - features[float_cols].min()\n ) / (features[float_cols].max() - features[float_cols].min())\n if fill_na == \"avg\":\n for key, val in AVG_VALUES.items():\n features[[key]] = features[[key]].fillna(val)\n features.fillna(na_value, inplace=True)\n\n Z = features.values\n Z[:, 33] = np.random.rand(Z.shape[0])\n Z = Z.astype(np.float32)\n\n # Shuffle & split the data into sets\n if order is not None:\n Z = Z[order]\n\n Z_train = Z[:TRAIN_SIZE]\n Z_valid = Z[TRAIN_SIZE:-TEST_SIZE]\n Z_test = Z[-TEST_SIZE:]\n\n data = {\"train\": Z_train, \"valid\": Z_valid, \"test\": Z_test}\n\n logger.debug(f\"Z shape: {Z_train.shape[1:]}\")\n logger.debug(f\"{Z_train.shape[0]} train samples\")\n logger.debug(f\"{Z_valid.shape[0]} validation samples\")\n logger.debug(f\"{Z_test.shape[0]} test samples\")\n\n return data\n" ]
[ [ "tensorflow.nn.softmax", "tensorflow.constant", "tensorflow.shape", "tensorflow.reduce_mean", "tensorflow.reduce_sum", "tensorflow.expand_dims", "tensorflow.math.log", "tensorflow.einsum", "tensorflow.add", "tensorflow.random.normal" ], [ "numpy.pad", "pandas.read_csv", "numpy.random.rand", "pandas.get_dummies" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
keshavd/scenic
[ "2f819916c316e7de73cd539c3a9a83c683ddb0ac", "2f819916c316e7de73cd539c3a9a83c683ddb0ac" ]
[ "scenic/projects/baselines/bert/trainer.py", "scenic/projects/baselines/vit.py" ]
[ "\"\"\"BERT Training Script.\"\"\"\n\nimport functools\nfrom typing import Any, Callable, Dict, Tuple, Optional, Type\n\nfrom absl import logging\nfrom clu import metric_writers\nfrom clu import periodic_actions\nfrom flax import jax_utils\nimport flax.linen as nn\nimport jax\nfrom jax.experimental import optimizers as jax_optimizers\nimport jax.numpy as jnp\nimport jax.profiler\nimport ml_collections\nimport numpy as np\nfrom scenic.dataset_lib import dataset_utils\nfrom scenic.projects.baselines.bert import bert_base_model\nfrom scenic.projects.baselines.bert import train_utils as bert_train_utils\nfrom scenic.train_lib import lr_schedules\nfrom scenic.train_lib import optimizers\nfrom scenic.train_lib import pretrain_utils\nfrom scenic.train_lib import train_utils\n\n\ndef train_step(\n *,\n flax_model: nn.Module,\n train_state: train_utils.TrainState,\n batch: bert_base_model.Batch,\n learning_rate_fn: Callable[[int], float],\n loss_fn: bert_base_model.LossFn,\n metrics_fn: bert_base_model.MetricFn,\n config: ml_collections.ConfigDict,\n debug: Optional[bool] = False\n) -> Tuple[train_utils.TrainState, Dict[str, Tuple[float, int]], float]:\n \"\"\"Runs a single step of training.\n\n Given the state of the training and a batch of data, computes\n the loss and updates the parameters of the model.\n\n Note that in this code, the buffers of the first (train_state) and second\n (batch) arguments are donated to the computation.\n\n Args:\n flax_model: A Flax model.\n train_state: The state of training including the current global_step,\n model_state, rng, and optimizer. The buffer of this argument can be\n donated to the computation.\n batch: A single batch of data. The buffer of this argument can be donated to\n the computation.\n learning_rate_fn: Learning rate scheduler which given the global_step\n generates the learning rate.\n loss_fn: A loss function that given logits, a batch, and parameters of the\n model calculates the loss.\n metrics_fn: A metrics function that given logits and batch of data,\n calculates the metrics as well as the loss.\n config: Configurations of the experiment.\n debug: Whether the debug mode is enabled during training. `debug=True`\n enables model specific logging/storing some values using\n jax.host_callback.\n\n Returns:\n Updated state of training, computed metrics, and learning rate for logging.\n \"\"\"\n new_rng, rng = jax.random.split(train_state.rng)\n # Bind the rng to the host/device we are on.\n dropout_rng = train_utils.bind_rng_to_host_device(\n rng, axis_name='batch', bind_to='device')\n\n def training_loss_fn(params):\n variables = {'params': params, **train_state.model_state}\n output, new_model_state = flax_model.apply(\n variables,\n batch,\n mutable=['batch_stats'],\n train=True,\n rngs={'dropout': dropout_rng},\n debug=debug)\n loss = loss_fn(output, batch, variables['params'])\n return loss, (new_model_state, output)\n\n compute_gradient_fn = jax.value_and_grad(training_loss_fn, has_aux=True)\n step = train_state.global_step\n lr = learning_rate_fn(step)\n (train_cost,\n (new_model_state,\n output)), grad = compute_gradient_fn(train_state.optimizer.target)\n\n del train_cost\n\n # We clip gradients before pmean in BERT.\n if config.get('max_grad_norm', None) is not None:\n grad = jax_optimizers.clip_grads(grad, config.max_grad_norm)\n # Re-use same axis_name as in the call to `pmap(...train_step...)` below.\n grad = jax.lax.pmean(grad, axis_name='batch')\n new_optimizer = train_state.optimizer.apply_gradient(grad, learning_rate=lr)\n # Explicit weight decay, if necessary.\n if config.get('explicit_weight_decay', None) is not None:\n new_optimizer = new_optimizer.replace(\n target=optimizers.tree_map_with_names(\n functools.partial(\n optimizers.decay_weight_fn,\n lr=lr,\n decay=config.explicit_weight_decay),\n new_optimizer.target,\n match_name_fn=lambda name: 'kernel' in name))\n\n metrics = metrics_fn(output, batch)\n new_train_state = train_state.replace( # pytype: disable=attribute-error\n global_step=step + 1,\n optimizer=new_optimizer,\n model_state=new_model_state,\n rng=new_rng)\n return new_train_state, metrics, lr\n\n\ndef eval_step(\n *,\n flax_model: nn.Module,\n train_state: train_utils.TrainState,\n batch: bert_base_model.Batch,\n metrics_fn: bert_base_model.MetricFn,\n all_gather: bool = False,\n debug: Optional[bool] = False\n) -> Tuple[Dict[str, Tuple[float, int]], Optional[jnp.ndarray],\n Optional[jnp.ndarray]]:\n \"\"\"Runs a single step of training.\n\n Note that in this code, the buffer of the second argument (batch) is donated\n to the computation.\n\n Assumed API of metrics_fn is:\n ```metrics = metrics_fn(logits, batch)\n where batch is yielded by the batch iterator, and metrics is a dictionary\n mapping metric name to a vector of per example measurements. eval_step will\n aggregate (by summing) all per example measurements and divide by the\n aggregated normalizers. For each given metric we compute:\n 1/N sum_{b in batch_iter} metric(b), where N is the sum of normalizer\n over all batches.\n\n Args:\n flax_model: A Flax model.\n train_state: TrainState, the state of training including the current\n global_step, model_state, rng, and optimizer. The buffer of this argument\n can be donated to the computation.\n batch: A single batch of data. a metrics function, that given logits and\n batch of data, calculates the metrics as well as the loss.\n metrics_fn: A metrics function, that given logits and batch of data,\n calculates the metrics as well as the loss.\n all_gather: If True, the function gather batch and output of\n model in from all hosts, using `jax.lax.all_gather` and return it, e.g.,\n for computing global metrics on CPU.\n debug: Whether the debug mode is enabled during evaluation. `debug=True`\n enables model specific logging/storing some values using\n jax.host_callback.\n\n Returns:\n Calculated metrics and optionally output, and batch after all_gather.\n \"\"\"\n variables = {\n 'params': train_state.optimizer.target,\n **train_state.model_state\n }\n output = flax_model.apply(\n variables, batch, train=False, mutable=False, debug=debug)\n metrics = metrics_fn(output, batch)\n if all_gather:\n output = jax.lax.all_gather(output, 'batch')\n batch = jax.lax.all_gather(batch, 'batch')\n return metrics, output, batch\n else:\n return metrics, None, None\n\n\ndef representation_fn(\n *,\n flax_model: nn.Module,\n train_state: train_utils.TrainState,\n batch: bert_base_model.Batch,\n representation_layer: str,\n gather_to_host: bool = True\n) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]:\n \"\"\"Feeds the inputs to the model and returns their representations.\n\n Args:\n flax_model: A Flax model.\n train_state: TrainState, the state of training including the current\n global_step, model_state, rng, and optimizer. The buffer of this argument\n can be donated to the computation.\n batch: A single batch of data from the dataset.\n representation_layer: The name of the layer to use as the representation.\n gather_to_host: Whether to gather results from all devices to the host,\n rather than leaving them distributed.\n\n Returns:\n Representation learned by the model for the given inputs and the labels and\n masks. If `gather_to_host` is True, these are collected from all hosts.\n \"\"\"\n variables = {\n 'params': train_state.optimizer.target,\n **train_state.model_state\n }\n\n representation_layer_parts = representation_layer.split('/')\n filter_rep = lambda mdl, _: mdl.name == representation_layer_parts[-1]\n _, model_state = flax_model.apply(\n variables,\n batch,\n train=False,\n capture_intermediates=filter_rep,\n mutable=['intermediates'],\n transfer_mode=True,\n debug=False)\n if 'intermediates' not in model_state:\n raise ValueError(f'Layer with name \"{representation_layer}\"'\n ' does not exist in your model.')\n representation = model_state['intermediates']\n for rep_layer in representation_layer_parts:\n if rep_layer:\n representation = representation[rep_layer]\n representation = representation['__call__'][0]\n if gather_to_host:\n representation = jax.lax.all_gather(representation, 'batch')\n batch = jax.lax.all_gather(batch, 'batch')\n return representation, batch['label'], batch['batch_mask']\n\n\ndef train(\n *,\n rng: jnp.ndarray,\n config: ml_collections.ConfigDict,\n model_cls: Type[bert_base_model.BERTBaseModel],\n dataset: dataset_utils.Dataset,\n workdir: str,\n writer: metric_writers.MetricWriter,\n) -> Tuple[train_utils.TrainState, Dict[str, Any], Dict[str, Any]]:\n \"\"\"Main training loop lives in this function.\n\n Given the model class and dataset, it prepares the items needed to run the\n training, including the TrainState.\n\n Args:\n rng: Jax rng key.\n config: Configurations of the experiment.\n model_cls: Model class; A model has a flax_module, a loss_fn, and a\n metrics_fn associated with it.\n dataset: The dataset that has train_iter, eval_iter, meta_data, and\n optionally, test_iter.\n workdir: Directory for checkpointing.\n writer: CLU metrics writer instance.\n\n Returns:\n train_state that has the state of training (including current\n global_step, model_state, rng, and the optimizer), train_summary\n and eval_summary which are dict of metrics. These outputs are used for\n regression testing.\n \"\"\"\n lead_host = jax.process_index() == 0\n # Build the loss_fn, metrics, and flax_model.\n model = model_cls(config, dataset.meta_data)\n\n # Initialize model.\n rng, init_rng = jax.random.split(rng)\n (params, model_state, num_trainable_params,\n gflops) = bert_train_utils.initialize_bert_model(\n model_def=model.flax_model,\n input_spec=dataset.meta_data['input_spec'],\n config=config,\n rngs=init_rng)\n\n # Create optimizer.\n # We jit this, such that the arrays that are created are created on the same\n # device as the input is, in this case the CPU. Else they'd be on device[0].\n optimizer = jax.jit(\n optimizers.get_optimizer(config).create, backend='cpu')(\n params)\n rng, train_rng = jax.random.split(rng)\n train_state = train_utils.TrainState(\n global_step=0,\n optimizer=optimizer,\n model_state=model_state,\n rng=train_rng,\n accum_train_time=0)\n start_step = train_state.global_step\n if config.checkpoint:\n train_state, start_step = train_utils.restore_checkpoint(\n workdir, train_state)\n\n if (start_step == 0 # Which means \"no\" checkpoint is restored!\n and config.get('init_from') is not None):\n restored_model_cfg = config.init_from.get('model_config')\n init_checkpoint_path = config.init_from.get('checkpoint_path')\n restored_train_state = pretrain_utils.restore_pretrained_checkpoint(\n init_checkpoint_path, train_state, assert_exist=True)\n # Load params from the init_model.\n train_state = model.init_from_train_state( # pytype: disable=attribute-error\n train_state, restored_train_state, restored_model_cfg)\n del restored_train_state\n\n # Replicate the optimzier, state, and rng.\n train_state = jax_utils.replicate(train_state)\n del params # Do not keep a copy of the initial params.\n\n # Calculate the total number of training steps.\n total_steps, steps_per_epoch = train_utils.get_num_training_steps(\n config, dataset.meta_data)\n # Get learning rate scheduler.\n learning_rate_fn = lr_schedules.get_learning_rate_fn(config)\n\n train_step_pmapped = jax.pmap(\n functools.partial(\n train_step,\n flax_model=model.flax_model,\n learning_rate_fn=learning_rate_fn,\n loss_fn=model.loss_function,\n metrics_fn=model.get_metrics_fn('train'),\n config=config,\n debug=config.debug_train),\n axis_name='batch',\n # We can donate both buffers of train_state and train_batch.\n donate_argnums=(0, 1),\n )\n eval_step_pmapped = jax.pmap(\n functools.partial(\n eval_step,\n flax_model=model.flax_model,\n metrics_fn=model.get_metrics_fn('validation'),\n all_gather=config.get('global_metrics', False),\n debug=config.debug_eval),\n axis_name='batch',\n # We can donate the eval_batch's buffer.\n donate_argnums=(1,),\n )\n if 'fewshot' in config:\n representation_fn_pmaped = jax.pmap(\n functools.partial(\n representation_fn,\n flax_model=model.flax_model,\n representation_layer=config.fewshot.representation_layer),\n # We can donate the batch's buffer.\n donate_argnums=(1,),\n axis_name='batch')\n fewshotter = bert_train_utils.BERTFewShotEvaluator(representation_fn_pmaped,\n config.fewshot)\n\n log_eval_steps = config.get('log_eval_steps') or steps_per_epoch\n if not log_eval_steps:\n raise ValueError(\"'log_eval_steps' should be specified in the config.\")\n checkpoint_steps = config.get('checkpoint_steps') or log_eval_steps\n log_summary_steps = config.get('log_summary_steps') or log_eval_steps\n\n # Ceil rounding such that we include the last incomplete batch.\n total_eval_steps = int(\n np.ceil(dataset.meta_data['num_eval_examples'] / config.batch_size))\n steps_per_eval = config.get('steps_per_eval') or total_eval_steps\n\n # If `global_metrics` are set in the config and we are the the lead host\n compute_global_metrics = False\n if config.get('global_metrics', False) and lead_host:\n compute_global_metrics = True\n if compute_global_metrics:\n global_metrics_evaluator = bert_train_utils.BERTGlobalEvaluator(\n config.global_metrics)\n\n train_metrics, extra_training_logs = [], []\n train_summary, eval_summary = None, None\n\n chrono = train_utils.Chrono(\n first_step=start_step,\n total_steps=total_steps,\n steps_per_epoch=steps_per_epoch,\n global_bs=config.batch_size,\n accum_train_time=int(jax_utils.unreplicate(train_state.accum_train_time)),\n example_type='example')\n\n logging.info('Starting training loop at step %d.', start_step + 1)\n report_progress = periodic_actions.ReportProgress(\n num_train_steps=total_steps, writer=writer)\n hooks = [report_progress]\n if config.get('xprof', True) and lead_host:\n hooks.append(periodic_actions.Profile(num_profile_steps=5, logdir=workdir))\n\n if start_step == 0:\n step0_log = {'num_trainable_params': num_trainable_params}\n if gflops:\n step0_log['gflops'] = gflops\n writer.write_scalars(1, step0_log)\n\n for step in range(start_step + 1, total_steps + 1):\n with jax.profiler.StepTraceContext('train', step_num=step):\n train_batch = next(dataset.train_iter)\n train_state, t_metrics, lr = train_step_pmapped(\n train_state=train_state, batch=train_batch)\n # This will accumulate metrics in TPU memory up to the point that we log\n # them. This is no problem for small metrics but may be a problem for\n # large (e.g. segmentation) metrics. An alternative is to set\n # `log_summary_steps` to a small number, or to use\n # `train_utils.unreplicate_and_get` here instead of right before writing\n # summaries, but that means in each step, we have data transfer between\n # tpu and host, which might slow down the training.\n train_metrics.append(t_metrics)\n # Additional training logs: learning rate:\n extra_training_logs.append({'learning_rate': lr})\n for h in hooks:\n h(step)\n chrono.pause() # Below are once-in-a-while ops -> pause.\n ###################### LOG TRAIN SUMMARY ########################\n if (step % log_summary_steps == 1) or (step == total_steps):\n if lead_host:\n chrono.tick(step, writer=writer)\n # train_metrics is list of a dictionaries of metrics, where the shape of\n # the metrics[key] is [n_local_devices]. However, because metric functions\n # have a psum, we have already summed across the whole sharded batch, and\n # what's returned is n_local_devices copies of the same summed metric.\n # So we do unreplicate and fetch them to host using `unreplicate_and_get`.\n train_summary = train_utils.log_train_summary(\n step=step,\n train_metrics=jax.tree_map(train_utils.unreplicate_and_get,\n train_metrics),\n extra_training_logs=jax.tree_map(train_utils.unreplicate_and_get,\n extra_training_logs),\n writer=writer)\n # Reset metric accumulation for next evaluation cycle.\n train_metrics, extra_training_logs = [], []\n ################### EVALUATION #######################\n if (step % log_eval_steps == 1) or (step == total_steps):\n with report_progress.timed('eval'):\n eval_metrics = []\n # Sync model state across replicas.\n train_state = train_utils.sync_model_state_across_replicas(\n train_state)\n for _ in range(steps_per_eval):\n eval_batch = next(dataset.valid_iter)\n e_metrics, e_output, e_batch = eval_step_pmapped(\n train_state=train_state, batch=eval_batch)\n eval_metrics.append(train_utils.unreplicate_and_get(e_metrics))\n if compute_global_metrics:\n # Unreplicate outputs of eval_step_pmapped that are coming from\n # `lax.all_gather`, fetch to the host and add to the Evaluator:\n e_batch_mask = train_utils.unreplicate_and_get(\n e_batch['batch_mask']).astype(bool)\n # Classification: 'label', regression: 'target'\n t_key = 'label' if 'label' in e_batch else 'targets'\n global_metrics_evaluator.add_batch_of_examples(\n target=train_utils.unreplicate_and_get(\n e_batch[t_key])[e_batch_mask],\n output=train_utils.unreplicate_and_get(e_output)\n [e_batch_mask])\n del e_batch, e_output, e_batch_mask\n eval_global_metrics_summary = None\n if compute_global_metrics:\n if (len(global_metrics_evaluator) !=\n dataset.meta_data['num_eval_examples']):\n # Make sure no example is lost (specially in multi-host setup).\n raise ValueError(f'Number of eval examples should be '\n f'{dataset.meta_data[\"num_eval_examples\"]}, '\n f'but it is {len(global_metrics_evaluator)}.')\n eval_global_metrics_summary = (\n global_metrics_evaluator.compute_metrics(\n clear_annotations=True))\n eval_summary = train_utils.log_eval_summary(\n step=step,\n eval_metrics=eval_metrics,\n extra_eval_summary=eval_global_metrics_summary,\n writer=writer)\n writer.flush()\n del eval_metrics, eval_global_metrics_summary\n ##################### CHECKPOINTING ###################\n if ((step % checkpoint_steps == 0 and step > 0) or\n (step == total_steps)) and config.checkpoint:\n with report_progress.timed('checkpoint'):\n # Sync model state across replicas.\n train_state = train_utils.sync_model_state_across_replicas(train_state)\n if lead_host:\n train_state.replace( # pytype: disable=attribute-error\n accum_train_time=chrono.accum_train_time)\n train_utils.save_checkpoint(workdir, train_state)\n\n ##################### FEWSHOT EVALUATION ############################\n if 'fewshot' in config:\n # Compute few-shot on-the-fly evaluation.\n if (step % config.fewshot.log_eval_steps == 1) or (step == total_steps):\n with report_progress.timed('fewshot'):\n results = fewshotter.run_all(train_state, config.fewshot.datasets)\n fewshotter.log_fewshot_summary(\n writer=writer, step=step, results=results)\n del results\n writer.write_scalars(step, {'zz/epoch': step / steps_per_epoch})\n writer.flush()\n\n chrono.resume() # un-pause now\n # Wait until computations are done before exiting.\n jax.random.normal(jax.random.PRNGKey(0), ()).block_until_ready()\n # Return the train and eval summary after last step for regresesion testing.\n return train_state, train_summary, eval_summary\n", "\"\"\"Vision Transformer.\"\"\"\n\nfrom typing import Any, Callable, Iterable, Optional\n\nfrom absl import logging\nimport flax\nimport flax.linen as nn\nimport jax\nimport jax.numpy as jnp\nimport ml_collections\nimport numpy as np\nfrom scenic.model_lib.base_models.multilabel_classification_model import MultiLabelClassificationModel\nfrom scenic.model_lib.layers import attention_layers\nfrom scenic.model_lib.layers import nn_layers\nimport scipy\nfrom tensorflow.io import gfile\n\nInitializer = Callable[[jnp.ndarray, Iterable[int], jnp.dtype], jnp.ndarray]\n\n\nclass AddPositionEmbs(nn.Module):\n \"\"\"Adds learned positional embeddings to the inputs.\n\n Attributes:\n posemb_init: Positional embedding initializer.\n\n Returns:\n Output in shape `[bs, timesteps, in_dim]`.\n \"\"\"\n posemb_init: Initializer = nn.initializers.normal(stddev=0.02) # From BERT.\n\n @nn.compact\n def __call__(self, inputs: jnp.ndarray) -> jnp.ndarray:\n # Inputs.shape is (batch_size, seq_len, emb_dim).\n assert inputs.ndim == 3, ('Number of dimensions should be 3,'\n ' but it is: %d' % inputs.ndim)\n pos_emb_shape = (1, inputs.shape[1], inputs.shape[2])\n pe = self.param('pos_embedding', self.posemb_init, pos_emb_shape,\n inputs.dtype)\n return inputs + pe\n\n\nclass Encoder1DBlock(nn.Module):\n \"\"\"Transformer encoder layer.\n\n Attributes:\n mlp_dim: Dimension of the mlp on top of attention block.\n num_heads: Number of self-attention heads.\n dtype: The dtype of the computation (default: float32).\n dropout_rate: Dropout rate.\n attention_dropout_rate: Dropout for attention heads.\n stochastic_depth: probability of dropping a layer linearly grows\n from 0 to the provided value.\n\n Returns:\n output after transformer encoder block.\n \"\"\"\n mlp_dim: int\n num_heads: int\n dtype: Any = jnp.float32\n dropout_rate: float = 0.1\n attention_dropout_rate: float = 0.1\n stochastic_depth: float = 0.0\n\n def get_stochastic_depth_mask(self, x: jnp.ndarray,\n deterministic: bool) -> jnp.ndarray:\n \"\"\"Generate the stochastic depth mask in order to apply layer-drop.\n\n Args:\n x: Input tensor.\n deterministic: Weather we are in the deterministic mode (e.g inference\n time) or not.\n\n Returns:\n Stochastic depth mask.\n \"\"\"\n if not deterministic and self.stochastic_depth:\n shape = (x.shape[0],) + (1,) * (x.ndim - 1)\n return jax.random.bernoulli(\n self.make_rng('dropout'), self.stochastic_depth, shape)\n else:\n return 0.0\n\n @nn.compact\n def __call__(self, inputs: jnp.ndarray, deterministic: bool) -> jnp.ndarray:\n \"\"\"Applies Encoder1DBlock module.\n\n Args:\n inputs: Input data.\n deterministic: Deterministic or not (to apply dropout).\n\n Returns:\n Output after transformer encoder block.\n \"\"\"\n # Attention block.\n assert inputs.ndim == 3\n x = nn.LayerNorm(dtype=self.dtype)(inputs)\n x = nn.MultiHeadDotProductAttention(\n num_heads=self.num_heads,\n dtype=self.dtype,\n kernel_init=nn.initializers.xavier_uniform(),\n broadcast_dropout=False,\n deterministic=deterministic,\n dropout_rate=self.attention_dropout_rate)(x, x)\n x = nn.Dropout(rate=self.dropout_rate)(x, deterministic)\n x = x * (1.0 - self.get_stochastic_depth_mask(x, deterministic)) + inputs\n\n # MLP block.\n y = nn.LayerNorm(dtype=self.dtype)(x)\n y = attention_layers.MlpBlock(\n mlp_dim=self.mlp_dim,\n dtype=self.dtype,\n dropout_rate=self.dropout_rate,\n activation_fn=nn.gelu,\n kernel_init=nn.initializers.xavier_uniform(),\n bias_init=nn.initializers.normal(stddev=1e-6))(\n y, deterministic=deterministic)\n\n return y * (1.0 - self.get_stochastic_depth_mask(x, deterministic)) + x\n\n\nclass Encoder(nn.Module):\n \"\"\"Transformer Encoder.\n\n Attributes:\n num_layers: Number of layers.\n mlp_dim: Dimension of the mlp on top of attention block.\n inputs_positions: Input subsequence positions for packed examples.\n dropout_rate: Dropout rate.\n stochastic_depth: probability of dropping a layer linearly grows\n from 0 to the provided value. Our implementation of stochastic depth\n follows timm library, which does per-example layer dropping and uses\n independent dropping patterns for each skip-connection.\n dtype: Dtype of activations.\n \"\"\"\n num_layers: int\n mlp_dim: int\n num_heads: int\n dropout_rate: float = 0.1\n attention_dropout_rate: float = 0.1\n stochastic_depth: float = 0.0\n dtype: Any = jnp.float32\n\n @nn.compact\n def __call__(self, inputs: jnp.ndarray, *, train: bool = False):\n \"\"\"Applies Transformer model on the inputs.\"\"\"\n\n assert inputs.ndim == 3 # Shape is `[batch, len, emb]`.\n dtype = jax.dtypes.canonicalize_dtype(self.dtype)\n\n x = AddPositionEmbs(\n posemb_init=nn.initializers.normal(stddev=0.02), # from BERT.\n name='posembed_input')(\n inputs)\n x = nn.Dropout(rate=self.dropout_rate)(x, deterministic=not train)\n\n # Input Encoder.\n for lyr in range(self.num_layers):\n x = Encoder1DBlock(\n mlp_dim=self.mlp_dim,\n num_heads=self.num_heads,\n dropout_rate=self.dropout_rate,\n attention_dropout_rate=self.attention_dropout_rate,\n stochastic_depth=(lyr / max(self.num_layers - 1, 1)) *\n self.stochastic_depth,\n name=f'encoderblock_{lyr}',\n dtype=dtype)(\n x, deterministic=not train)\n encoded = nn.LayerNorm(name='encoder_norm')(x)\n return encoded\n\n\nclass ViT(nn.Module):\n \"\"\"Vision Transformer model.\n\n Attributes:\n num_classes: Number of output classes.\n mlp_dim: Dimension of the mlp on top of attention block.\n num_layers: Number of layers.\n num_heads: Number of self-attention heads.\n patches: Configuration of the patches extracted in the stem of the model.\n hidden_size: Size of the hidden state of the output of model's stem.\n representation_size: Size of the representation layer in the model's head.\n if None, we skip the extra projection + tanh activation at the end.\n dropout_rate: Dropout rate.\n attention_dropout_rate: Dropout for attention heads.\n classifier: type of the classifier layer. Options are 'gap', 'gmp', 'gsp',\n 'token'.\n dtype: JAX data type for activations.\n \"\"\"\n\n num_classes: int\n mlp_dim: int\n num_layers: int\n num_heads: int\n patches: ml_collections.ConfigDict\n hidden_size: int\n representation_size: Optional[int] = None\n dropout_rate: float = 0.1\n attention_dropout_rate: float = 0.1\n stochastic_depth: float = 0.0\n classifier: str = 'gap'\n dtype: Any = jnp.float32\n\n @nn.compact\n def __call__(self, x: jnp.ndarray, *, train: bool, debug: bool = False):\n\n fh, fw = self.patches.size\n # Extracting patches and then embedding is in fact a single convolution.\n x = nn.Conv(\n self.hidden_size, (fh, fw),\n strides=(fh, fw),\n padding='VALID',\n name='embedding')(\n x)\n n, h, w, c = x.shape\n x = jnp.reshape(x, [n, h * w, c])\n\n # If we want to add a class token, add it here.\n if self.classifier == 'token':\n cls = self.param('cls', nn.initializers.zeros, (1, 1, c), x.dtype)\n cls = jnp.tile(cls, [n, 1, 1])\n x = jnp.concatenate([cls, x], axis=1)\n\n x = Encoder(\n mlp_dim=self.mlp_dim,\n num_layers=self.num_layers,\n num_heads=self.num_heads,\n dropout_rate=self.dropout_rate,\n attention_dropout_rate=self.attention_dropout_rate,\n stochastic_depth=self.stochastic_depth,\n dtype=self.dtype,\n name='Transformer')(\n x, train=train)\n\n if self.classifier in ('token', '0'):\n x = x[:, 0]\n elif self.classifier in ('gap', 'gmp', 'gsp'):\n fn = {'gap': jnp.mean, 'gmp': jnp.max, 'gsp': jnp.sum}[self.classifier]\n x = fn(x, axis=1)\n\n if self.representation_size is not None:\n x = nn.Dense(self.representation_size, name='pre_logits')(x)\n x = nn.tanh(x)\n else:\n x = nn_layers.IdentityLayer(name='pre_logits')(x)\n x = nn.Dense(\n self.num_classes,\n kernel_init=nn.initializers.zeros,\n name='output_projection')(\n x)\n return x\n\n\nclass ViTMultiLabelClassificationModel(MultiLabelClassificationModel):\n \"\"\"Vision Transformer model for multi-label classification task.\"\"\"\n\n def build_flax_model(self)-> nn.Module:\n model_dtype = getattr(jnp, self.config.get('model_dtype_str', 'float32'))\n return ViT(\n num_classes=self.dataset_meta_data['num_classes'],\n mlp_dim=self.config.model.mlp_dim,\n num_layers=self.config.model.num_layers,\n num_heads=self.config.model.num_heads,\n representation_size=self.config.model.representation_size,\n patches=self.config.model.patches,\n hidden_size=self.config.model.hidden_size,\n classifier=self.config.model.classifier,\n dropout_rate=self.config.model.get('dropout_rate', 0.1),\n attention_dropout_rate=self.config.model.get('attention_dropout_rate',\n 0.1),\n stochastic_depth=self.config.model.get('stochastic_depth', 0.0),\n dtype=model_dtype,\n )\n\n def default_flax_model_config(self) -> ml_collections.ConfigDict:\n return ml_collections.ConfigDict({\n 'model':\n dict(\n num_heads=2,\n num_layers=1,\n representation_size=16,\n mlp_dim=32,\n dropout_rate=0.,\n attention_dropout_rate=0.,\n hidden_size=16,\n patches={'size': (4, 4)},\n classifier='gap',\n data_dtype_str='float32')\n })\n\n def init_from_train_state(\n self, train_state: Any, restored_train_state: Any,\n restored_model_cfg: ml_collections.ConfigDict) -> Any:\n \"\"\"Updates the train_state with data from restored_train_state.\n\n This function is writen to be used for 'fine-tuning' experiments. Here, we\n do some surgery to support larger resolutions (longer sequence length) in\n the transformer block, with respect to the learned pos-embeddings.\n\n Args:\n train_state: A raw TrainState for the model.\n restored_train_state: A TrainState that is loaded with parameters/state of\n a pretrained model.\n restored_model_cfg: Configuration of the model from which the\n restored_train_state come from. Usually used for some asserts.\n\n Returns:\n Updated train_state.\n \"\"\"\n return init_vit_from_train_state(train_state, restored_train_state,\n self.config, restored_model_cfg)\n\n def load_augreg_params(self, train_state: Any, params_path: str,\n model_cfg: ml_collections.ConfigDict) -> Any:\n \"\"\"Loads parameters from an AugReg checkpoint.\n\n See\n https://github.com/google-research/vision_transformer/\n and\n https://arxiv.org/abs/2106.10270\n for more information about these pre-trained models.\n\n Args:\n train_state: A raw TrainState for the model.\n params_path: Path to an Augreg checkpoint. The model config is read from\n the filename (e.g. a B/32 model starts with \"B_32-\").\n model_cfg: Configuration of the model. Usually used for some asserts.\n\n Returns:\n Updated train_state with params replaced with the ones read from the\n AugReg checkpoint.\n \"\"\"\n restored_model_cfg = _get_augreg_cfg(params_path)\n assert tuple(restored_model_cfg.patches.size) == tuple(\n model_cfg.patches.size)\n assert restored_model_cfg.hidden_size == model_cfg.hidden_size\n assert restored_model_cfg.mlp_dim == model_cfg.mlp_dim\n assert restored_model_cfg.num_layers == model_cfg.num_layers\n assert restored_model_cfg.num_heads == model_cfg.num_heads\n assert restored_model_cfg.classifier == model_cfg.classifier\n\n flattened = np.load(gfile.GFile(params_path, 'rb'))\n restored_params = flax.traverse_util.unflatten_dict(\n {tuple(k.split('/')): v for k, v in flattened.items()})\n restored_params['output_projection'] = restored_params.pop('head')\n params = flax.core.unfreeze(train_state.optimizer.target)\n\n _merge_params(params, restored_params, model_cfg, restored_model_cfg)\n\n return train_state.replace(\n optimizer=train_state.optimizer.replace(\n target=flax.core.freeze(params)))\n\n\ndef _get_augreg_cfg(params_path):\n model = params_path.split('/')[-1].split('-')[0]\n assert model in ('B_16', 'B_32'), (\n 'Currently only B/16 and B/32 models are supported.')\n sz = {'B_16': 16, 'B_32': 32}[model]\n return ml_collections.ConfigDict(\n dict(\n num_classes=0,\n mlp_dim=3072,\n num_layers=12,\n num_heads=12,\n hidden_size=768,\n classifier='token',\n patches=dict(size=(sz, sz)),\n dropout_rate=0.,\n attention_dropout_rate=0.,\n ))\n\n\ndef _merge_params(params, restored_params, model_cfg, restored_model_cfg):\n \"\"\"Merges `restored_params` into `params`.\"\"\"\n # Start moving parameters, one-by-one and apply changes if needed.\n for m_key, m_params in restored_params.items():\n if m_key == 'output_projection':\n # For the classifier head, we use a the randomly initialized params and\n # ignore the the one from pretrained model.\n pass\n\n elif m_key == 'pre_logits':\n if model_cfg.model.representation_size is None:\n # We don't have representation_size in the new model, so let's ignore\n # it from the pretained model, in case it has it.\n # Note, removing the key from the dictionary is necessary to prevent\n # obscure errors from the Flax optimizer.\n params.pop(m_key, None)\n else:\n assert restored_model_cfg.model.representation_size\n params[m_key] = m_params\n\n elif m_key == 'Transformer':\n for tm_key, tm_params in m_params.items():\n if tm_key == 'posembed_input': # Might need resolution change.\n posemb = params[m_key]['posembed_input']['pos_embedding']\n restored_posemb = m_params['posembed_input']['pos_embedding']\n\n if restored_posemb.shape != posemb.shape:\n # Rescale the grid of pos, embeddings: param shape is (1, N, d).\n logging.info('Resized variant: %s to %s', restored_posemb.shape,\n posemb.shape)\n ntok = posemb.shape[1]\n if restored_model_cfg.model.classifier == 'token':\n # The first token is the CLS token.\n cls_tok = restored_posemb[:, :1]\n restored_posemb_grid = restored_posemb[0, 1:]\n ntok -= 1\n else:\n if model_cfg.model.classifier == 'token':\n cls_tok = posemb[:, :1]\n else:\n cls_tok = restored_posemb[:, :0]\n restored_posemb_grid = restored_posemb[0]\n\n restored_gs = int(np.sqrt(len(restored_posemb_grid)))\n gs = int(np.sqrt(ntok))\n if restored_gs != gs: # We need resolution change.\n logging.info('Grid-size from %s to %s.', restored_gs, gs)\n restored_posemb_grid = restored_posemb_grid.reshape(\n restored_gs, restored_gs, -1)\n zoom = (gs / restored_gs, gs / restored_gs, 1)\n restored_posemb_grid = scipy.ndimage.zoom(\n restored_posemb_grid, zoom, order=1)\n # Attach the CLS token again.\n restored_posemb_grid = restored_posemb_grid.reshape(\n 1, gs * gs, -1)\n restored_posemb = jnp.array(\n np.concatenate([cls_tok, restored_posemb_grid], axis=1))\n\n params[m_key][tm_key]['pos_embedding'] = restored_posemb\n # Other parameters of the Transformer encoder if they are in the target.\n elif tm_key in params[m_key]:\n params[m_key][tm_key] = tm_params\n else:\n logging.info('Ignoring %s. In restored model\\'s Transformer,'\n 'but not in target', m_key)\n\n elif m_key in params:\n # Use the rest if they are in the pretrained model.\n params[m_key] = m_params\n\n else:\n logging.info('Ignoring %s. In restored model, but not in target', m_key)\n\n\ndef init_vit_from_train_state(\n train_state: Any, restored_train_state: Any,\n model_cfg: ml_collections.ConfigDict,\n restored_model_cfg: ml_collections.ConfigDict) -> Any:\n \"\"\"Updates the train_state with data from restored_train_state.\n\n This function is written to be used for 'fine-tuning' experiments. Here, we\n do some surgery to support larger resolutions (longer sequence length) in\n the transformer block, with respect to the learned pos-embeddings.\n\n Args:\n train_state: A raw TrainState for the model.\n restored_train_state: A TrainState that is loaded with parameters/state of a\n pretrained model.\n model_cfg: Configuration of the model. Usually used for some asserts.\n restored_model_cfg: Configuration of the model from which the\n restored_train_state come from. Usually used for some asserts.\n\n Returns:\n Updated train_state.\n \"\"\"\n params = flax.core.unfreeze(train_state.optimizer.target)\n restored_params = flax.core.unfreeze(restored_train_state.optimizer.target)\n\n _merge_params(params, restored_params, model_cfg, restored_model_cfg)\n\n return train_state.replace(\n optimizer=train_state.optimizer.replace(target=flax.core.freeze(params)))\n" ]
[ [ "numpy.ceil" ], [ "numpy.concatenate", "tensorflow.io.gfile.GFile", "scipy.ndimage.zoom", "numpy.sqrt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
kyleaj/ProxImaL
[ "2986b1ed40b58057822922522145bfbbdd2cf9de", "2986b1ed40b58057822922522145bfbbdd2cf9de" ]
[ "proximal/examples/test_conv.py", "proximal/lin_ops/edge.py" ]
[ "# Proximal\nimport sys\nsys.path.append('../../')\n\nfrom proximal.utils.utils import *\nfrom proximal.halide.halide import *\nfrom proximal.lin_ops import *\n\nimport numpy as np\nfrom scipy import signal\nfrom scipy import ndimage\nimport matplotlib.pyplot as plt\n\n\n############################################################\n\n# Load image\nnp_img = get_test_image(2048)\nprint('Type ', np_img.dtype, 'Shape', np_img.shape)\n\nimgplot = plt.imshow(np_img, interpolation='nearest', clim=(0.0, 1.0))\nimgplot.set_cmap('gray')\nplt.title('Numpy')\n\n# Force recompile in local dir\ntic()\nHalide('A_conv', recompile=True)\nHalide('At_conv', recompile=True) # Force recompile in local dir\nprint('Compilation took: {0:.1f}ms'.format(toc()))\n\n# Test the runner\noutput = np.zeros_like(np_img)\nK = get_kernel(15, len(np_img.shape))\n\ntic()\nHalide('A_conv').A_conv(np_img, K, output) # Call\nprint('Running took: {0:.1f}ms'.format(toc()))\n\nplt.figure()\nimgplot = plt.imshow(output, interpolation='nearest', clim=(0.0, 1.0))\nimgplot.set_cmap('gray')\nplt.title('Output from Halide')\n\ntic()\noutput_scipy = signal.convolve2d(np_img, K, mode='same', boundary='wrap')\nprint('Running Scipy.convolve2d took: {0:.1f}ms'.format(toc()))\n\nfn = conv(K, Variable(np_img.shape), implem='halide')\noutput_ref = np.zeros(np_img.shape, dtype=np.float32, order='F')\ntic()\nfn.forward([np_img], [output_ref])\nprint('Running conv fft convolution took: {0:.1f}ms'.format(toc()))\n\n# Error\nprint('Maximum error {0}'.format(np.amax(np.abs(output_ref - output))))\n\nplt.figure()\nimgplot = plt.imshow(output_ref * 255,\n interpolation='nearest',\n clim=(0.0, 255.0))\nimgplot.set_cmap('gray')\nplt.title('Output from Scipy')\n\n############################################################################\n# Check correlation\n############################################################################\n\noutput_corr = np.zeros_like(np_img)\ntic()\nHalide('At_conv').At_conv(np_img, K, output_corr) # Call\nprint('Running correlation took: {0:.1f}ms'.format(toc()))\n\n#output_corr_ref = signal.convolve2d(np_img, np.flipud(np.fliplr(K)), mode='same', boundary='wrap')\noutput_corr_ref = ndimage.correlate(np_img, K, mode='wrap')\n\n# Adjoint.\noutput_corr_ref = np.zeros(np_img.shape, dtype=np.float32, order='F')\ntic()\nfn.adjoint([np_img], [output_corr_ref])\nprint('Running transpose conv fft convolution took: {0:.1f}ms'.format(toc()))\n\n# Error\nprint('Maximum error correlation {0}'.format(\n np.amax(np.abs(output_corr_ref - output_corr))))\nplt.show()\n", "import numpy as np\n\nclass Edge(object):\n \"\"\"The edge between two lin ops.\n \"\"\"\n \n def __init__(self, start, end, shape):\n self.start = start\n self.end = end\n self.shape = shape\n self.data = np.zeros(self.shape)\n self.mag = None # Used to get norm bounds.\n\n @property\n def size(self):\n return np.prod(self.shape)\n" ]
[ [ "matplotlib.pyplot.imshow", "numpy.abs", "matplotlib.pyplot.title", "scipy.ndimage.correlate", "scipy.signal.convolve2d", "numpy.zeros_like", "matplotlib.pyplot.show", "numpy.zeros", "matplotlib.pyplot.figure" ], [ "numpy.zeros", "numpy.prod" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
aksh4y/Papers
[ "f7d89c22cafdb952d57467ab9254c17e8f5d2d4b" ]
[ "Project/algorithm.old.py" ]
[ "#Import Library\nimport warnings\nimport numpy as np\nimport datetime\nfrom extract_data import *\nfrom word_encoder import *\nfrom sklearn import svm\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn import tree\n\n# send the extracted data availble from extract_data to the encode function\n# this function vectorizes the text based data into ASCII format for use by\n# the algorithms\nencoded_data = encode(data)\n\nscores = []\n\n# convert the float scores to int. Multiplying by 10 helps us keep the decimal\n# level precision which would otherwise be lost in typecasting\ni = 0\nwhile i < len(label):\n scores.append(int (float(label[i]) * 10))\n i += 1;\n\n# ignore depricated warning\ndef warn(*args, **kwargs):\n pass\nwarnings.warn = warn\n\n# SVM classifier\nsvm_clf = svm.SVC(kernel = 'linear')\n#svm_clf.fit(encoded_data, scores)\n\n# Gaussian Naive Bayes\ngnb_clf = GaussianNB()\ngnb_clf.fit(encoded_data, scores)\n\n# Random Forest\nrf_clf = RandomForestClassifier(n_estimators=10)\nrf_clf.fit(encoded_data, scores)\n\n# Decision Tree\ndt_clf = tree.DecisionTreeClassifier()\ndt_clf.fit(encoded_data, scores)\n\n\n#print(\"SVM:\")\n\n#print(svm_clf.predict ([1403, 2752, 3263, 4200, 4309, 4417, 4518, 4675, 5909, 6102, 6500, 8459, 8672, 8882, 9712, 9810, 10524, 10757, 11096, 11299, 11461, 11617, 11775]))\n\nprint(\"Gaussian Naive Bayes:\")\n\nprint(gnb_clf.predict ([1403, 2752, 3263, 4200, 4309, 4417, 4518, 4675, 5909, 6102, 6500, 8459, 8672, 8882, 9712, 9810, 10524, 10757, 11096, 11299, 11461, 11617, 11775]))\n\nprint(\"Random Forest:\")\n\nprint(rf_clf.predict ([1403, 2752, 3263, 4200, 4309, 4417, 4518, 4675, 5909, 6102, 6500, 8459, 8672, 8882, 9712, 9810, 10524, 10757, 11096, 11299, 11461, 11617, 11775]))\n\nprint(\"Decision Tree:\")\n\nprint(dt_clf.predict ([1403, 2752, 3263, 4200, 4309, 4417, 4518, 4675, 5909, 6102, 6500, 8459, 8672, 8882, 9712, 9810, 10524, 10757, 11096, 11299, 11461, 11617, 11775]))\n\nprint(\"End time: \" + str(datetime.datetime.now()).split('.')[0])\n" ]
[ [ "sklearn.tree.DecisionTreeClassifier", "sklearn.naive_bayes.GaussianNB", "sklearn.svm.SVC", "sklearn.ensemble.RandomForestClassifier" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
thiago9864/introducao_modelagem
[ "7ec90d266e1bbae7f942f2c600c4ea1d88d17614" ]
[ "aulas/05-06/variaveis_aleatorias.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 5 08:32:13 2019\n\n@author: Thiago\n\"\"\"\n\nimport numpy as np\nimport pylab as pl\n\n#%%\n\n#Simulação de uma va\ndef va_estoque():\n p=np.array([0.1, 0.2, 0.6, 0.1])\n x=np.random.rand()\n\n if 0 < x <= p[0]:\n return 1\n elif p[0] < x <= p[0]+p[1]:\n return 2\n elif p[0]+p[1] < x <= p[0]+p[1]+p[2]:\n return 3\n elif p[0]+p[1]+p[2] < x <= 1.0:\n return 4\n \nv = [va_estoque() for i in range(100000)]\npl.hist(v,)\npl.show()\n\n\n#%%\n\n#simulação estoque\nM, T, estoque, lucro = 3, 3, 10, 0\nR = 10000\n\nfor i in range(R):\n Y=va_estoque()\n lucro += 20*min(estoque, Y)\n estoque -= max(0, estoque-Y)\n lucro -= 5*estoque\n \n if estoque<M:\n estoque += T\n lucro -= 10*T\n \nlucro /= R\nprint(M, T, lucro, estoque)\n\n\n#%%\n\n#simulação Urna de Ehrenfest\n\nN, s = 100, []\n\nfor j in range(1000):\n v = [True for i in range(N)]\n for i in range(1000):\n k=np.random.choice(N)\n v[k] = not v[k]\n \n x = sum(v) / N\n s.append(x)\n \npl.hist(s)\n\n\n#%%\n\n#Lei dos grandes números\n\nnp.random.seed(0)\n\nS = [1, 2, 3, 4, 5, 6]\n\nn_vals = np.logspace(1, 5, num=200)\ns=[]\nfor val in n_vals:\n np.random.seed(0)\n n = int(val)\n x = np.random.choice(S,n)\n p=sum(x==3)/n\n s.append([n,p])\n \ns=np.array(s)\npl.semilogx(s[:,1])\npl.axhline(1./len(S),c='r')\n\n\n#%%\n\n#processos ergodicos\n\n#%%\n\n'''\ns = 3000\n\nfor n in [1,2,3,5,10,50,100,200,400,1000]:\n z=np.zeros(s)\n for k in range(n):\n x = np.random.uniform(-1, 1, s)\n z+=x\n \n x = z/np.sqrt(n)\n pl.figure(n)\n sns.distplot(y, bins=12, rug=True)\n pl.title('N = ' + str())\n'''" ]
[ [ "numpy.random.seed", "numpy.random.choice", "numpy.logspace", "numpy.random.rand", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vzyrianov/hpvm-autograd
[ "521cc3b684531548aea75f9fe3cc673aaa4a2e90" ]
[ "hpvm/projects/hpvm-profiler/hpvm_profiler/__init__.py" ]
[ "from pathlib import Path\nfrom subprocess import PIPE, CalledProcessError\nfrom typing import Iterable, List, Tuple, Union\n\nimport matplotlib.pyplot as plt\n\nPathLike = Union[Path, str]\nconf_opening, conf_closing = \"+++++\", \"-----\"\n\n\ndef profile_config_file(\n binary_path: PathLike,\n config_path: PathLike,\n output_config_path: PathLike,\n progress_bar: bool = True,\n profile_filename: str = \"profile_info.txt\",\n qos_filename: str = \"final_accuracy\",\n) -> None:\n r\"\"\"Profile an HPVM configuration file with an HPVM binary,\n and write the updated configuration file to a given location.\n The configuration file must have the baseline as the first configuration.\n\n :param binary_path: Path to binary to be executed in profiling.\n :param config_path: Path to config file (HPVM configuration format)\n with configs to enumerate for profiling.\n :param output_config_path: Path where the output configs are written.\n The output config file has the same configs as the input `config_path` file,\n but the performance and energy readings are updated.\n :param progress_bar: If `True`, show a progress bar for number of configs already profiled.\n :param profile_filename: Name of profile file generated by the binary (in current directory).\n This defaults to \"profile_info.txt\" and should not be changed for HPVM binaries.\n :param qos_filename: Name of QoS file generated by the binary (in current directory).\n It contains a single float number as the QoS of this run.\n This defaults to \"final_accuracy\" and should not be changed for HPVM binaries.\n \"\"\"\n # Read first line (\"the float\") and configs in config file\n header, configs = read_hpvm_configs(Path(config_path))\n if not configs:\n raise ValueError(\"Config file with no configs is unsupported.\")\n # Modifies configs in place.\n profile_configs(\n binary_path,\n configs[1:],\n configs[0],\n progress_bar,\n profile_filename,\n qos_filename,\n )\n write_hpvm_configs(header, configs, Path(output_config_path))\n\n\ndef profile_configs(\n binary_path: PathLike,\n configs: Iterable[\"Config\"],\n baseline_config: \"Config\",\n progress_bar: bool = True,\n profile_filename: str = \"profile_info.txt\",\n qos_filename: str = \"final_accuracy\",\n) -> None:\n \"\"\"Profile a sequence of HPVM configs.\n This function modifies argument `configs` in place.\"\"\"\n\n from tqdm import tqdm\n\n baseline_time, baseline_acc = measure_config(binary_path, baseline_config)\n iterable = tqdm(configs, desc=\"Configs profiled\") if progress_bar else configs\n for config in iterable:\n time, acc = measure_config(binary_path, config, profile_filename, qos_filename)\n speedup = baseline_time / time\n config.update_profile_results(speedup, acc, baseline_acc)\n return configs\n\n\ndef measure_config(\n binary_path: PathLike,\n config: \"Config\",\n profile_filename: str = \"profile_info.txt\",\n qos_filename: str = \"final_accuracy\",\n):\n from subprocess import check_call\n from tempfile import NamedTemporaryFile\n import os\n\n temp_file = NamedTemporaryFile(\"w\")\n write_hpvm_configs(\"0.0\", [config], Path(temp_file.name))\n # Run binary_path binary,\n # which generates `profile_filename` and `qos_filename` file in cwd.\n try:\n with open(os.devnull, \"w\") as f:\n check_call([str(binary_path), \"-c\", str(temp_file.name)], stdout=f)\n except CalledProcessError as e:\n print(\"Output from the program:\")\n print(e.output)\n raise e\n time = _read_profile_file(Path(profile_filename))\n acc = _read_qos_file(Path(qos_filename))\n temp_file.close()\n return time, acc\n\n\ndef plot_hpvm_configs(\n config_path: PathLike,\n save_to: PathLike = None,\n show_qos_loss: bool = True,\n **fig_kwargs,\n) -> plt.Figure:\n \"\"\"\n Plot the QoS-speedup information in an HPVM configuration file.\n It is recommended to profile the config file first (using `profile_configs`)\n to obtain real speedup numbers.\n This function creates a `matplotlib.pyplot.Figure`, plots on it, and returns it.\n\n :param config_path: Path to the config file (HPVM configuration format).\n :param save_to: File to save figure into. Default is None: don't save figure (just return it).\n :param show_qos_loss: Show the loss of QoS on x axis of the figure. Defaults to True.\n If False, will use (absolute) QoS instead of QoS loss.\n :param fig_kwargs: Arguments to pass to `plt.subplots`.\n \"\"\"\n\n import numpy as np\n\n _, configs = read_hpvm_configs(config_path)\n get_qos = lambda c: c.qos_loss if show_qos_loss else c.qos\n qos_speedup = np.array([(get_qos(c), c.speedup) for c in configs])\n qoses, speedups = qos_speedup.T\n fig, ax = plt.subplots(**fig_kwargs)\n ax.scatter(qoses, speedups)\n ax.set_xlabel(\"QoS Loss\")\n ax.set_ylabel(\"Speedup (X)\")\n if save_to:\n fig.savefig(save_to, dpi=300)\n return fig\n\n\nclass Config:\n def __init__(\n self,\n conf_name: str,\n speedup: float,\n energy: float,\n qos: float,\n qos_loss: float,\n config_body: List[str],\n ):\n self.conf_name = conf_name\n self.speedup = speedup\n self.energy = energy\n self.qos = qos\n self.qos_loss = qos_loss\n # We don't care about the information in this part, and we don't parse this.\n self.config_body = config_body\n\n def update_profile_results(self, speedup: float, qos: float, base_qos: float):\n recorded_base_qos = self.qos + self.qos_loss\n if abs(recorded_base_qos - base_qos) > 0.025:\n raise ValueError(\n f\"Baseline QoS mismatch. Original: {recorded_base_qos}, measured: {base_qos}\"\n )\n self.speedup = speedup\n self.qos = qos\n self.qos_loss = base_qos - qos\n\n def __repr__(self) -> str:\n header_fields = [\n self.conf_name,\n self.speedup,\n self.energy,\n self.qos,\n self.qos_loss,\n ]\n header = \" \".join(str(field) for field in header_fields)\n lines = [conf_opening, header, *self.config_body, conf_closing]\n return \"\\n\".join(lines)\n\n __str__ = __repr__\n\n\ndef read_hpvm_configs(config_file: PathLike) -> Tuple[str, List[Config]]:\n # def read_hpvm_configs(config_file, config_num, temp_file):\n ret_configs = []\n with open(config_file) as f:\n text = f.read()\n # There's 1 float sitting on the first line of config file.\n # We don't use it, but want to keep that intact.\n header, *configs = text.split(conf_opening)\n header = header.strip()\n for config_text in configs:\n config_text = config_text.replace(conf_closing, \"\").strip()\n config_header, *config_body = config_text.splitlines()\n conf_name, *number_fields = config_header.split(\" \")\n speedup, energy, qos, qos_drop = [float(s) for s in number_fields]\n ret_configs.append(\n Config(conf_name, speedup, energy, qos, qos_drop, config_body)\n )\n return header, ret_configs\n\n\ndef write_hpvm_configs(header: str, configs: Iterable[Config], to_file: PathLike):\n text_segs = [header] + [str(config) for config in configs]\n with open(to_file, \"w\") as f:\n f.write(\"\\n\".join(text_segs))\n f.flush()\n\n\ndef _read_profile_file(profile_file_path: Path):\n with profile_file_path.open() as f:\n target_lines = [line.strip() for line in f if \"Total Time\" in line]\n if len(target_lines) != 1:\n raise RuntimeError(f\"Profile {profile_file_path} malformed\")\n (target_line,) = target_lines\n return float(target_line.split()[3])\n\n\ndef _read_qos_file(qos_file_path: Path):\n with qos_file_path.open() as f:\n return float(f.read().strip())\n" ]
[ [ "matplotlib.pyplot.subplots" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Wastoon/XinTong_CenterNet
[ "e4436d61b01a74fbc54bd33c4948ec932940661a" ]
[ "src/lib/detectors/ctdet.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport cv2\nimport numpy as np\nfrom progress.bar import Bar\nimport time\nimport torch\nimport os\n\ntry:\n from external.nms import soft_nms\nexcept:\n print('NMS not imported! If you need it,'\n ' do \\n cd $CenterNet_ROOT/src/lib/external \\n make')\nfrom models.decode import ctdet_decode\nfrom models.utils import flip_tensor\nfrom utils.image import get_affine_transform\nfrom utils.post_process import ctdet_post_process\nfrom utils.debugger import Debugger\n\nfrom .base_detector import BaseDetector\n\nclass CtdetDetector(BaseDetector):\n def __init__(self, opt):\n super(CtdetDetector, self).__init__(opt)\n \n def process(self, images, return_time=False):\n with torch.no_grad():\n output = self.model(images)[-1]\n hm = output['hm'].sigmoid_()\n wh = output['wh']\n reg = output['reg'] if self.opt.reg_offset else None\n if self.opt.flip_test:\n hm = (hm[0:1] + flip_tensor(hm[1:2])) / 2\n wh = (wh[0:1] + flip_tensor(wh[1:2])) / 2\n reg = reg[0:1] if reg is not None else None\n torch.cuda.synchronize()\n forward_time = time.time()\n dets = ctdet_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K)\n \n if return_time:\n return output, dets, forward_time\n else:\n return output, dets\n\n def post_process(self, dets, meta, scale=1):\n dets = dets.detach().cpu().numpy()\n dets = dets.reshape(1, -1, dets.shape[2])\n dets = ctdet_post_process(\n dets.copy(), [meta['c']], [meta['s']],\n meta['out_height'], meta['out_width'], self.opt.num_classes)\n for j in range(1, self.num_classes + 1):\n dets[0][j] = np.array(dets[0][j], dtype=np.float32).reshape(-1, 5)\n dets[0][j][:, :4] /= scale\n return dets[0]\n\n def merge_outputs(self, detections):\n results = {}\n for j in range(1, self.num_classes + 1):\n results[j] = np.concatenate(\n [detection[j] for detection in detections], axis=0).astype(np.float32)\n if len(self.scales) > 1 or self.opt.nms:\n soft_nms(results[j], Nt=0.5, method=2)\n scores = np.hstack(\n [results[j][:, 4] for j in range(1, self.num_classes + 1)])\n if len(scores) > self.max_per_image:\n kth = len(scores) - self.max_per_image\n thresh = np.partition(scores, kth)[kth]\n for j in range(1, self.num_classes + 1):\n keep_inds = (results[j][:, 4] >= thresh)\n results[j] = results[j][keep_inds]\n return results\n\n def debug(self, debugger, images, dets, output, scale=1):\n detection = dets.detach().cpu().numpy().copy()\n detection[:, :, :4] *= self.opt.down_ratio\n for i in range(1):\n img = images[i].detach().cpu().numpy().transpose(1, 2, 0)\n img = ((img * self.std + self.mean) * 255).astype(np.uint8)\n pred = debugger.gen_colormap(output['hm'][i].detach().cpu().numpy())\n debugger.add_blend_img(img, pred, 'pred_hm_{:.1f}'.format(scale))\n debugger.add_img(img, img_id='out_pred_{:.1f}'.format(scale))\n for k in range(len(dets[i])):\n if detection[i, k, 4] > self.opt.center_thresh:\n debugger.add_coco_bbox(detection[i, k, :4], detection[i, k, -1],\n detection[i, k, 4], \n img_id='out_pred_{:.1f}'.format(scale))\n\n def show_results(self, debugger, image, results):\n debugger.add_img(image, img_id='ctdet')\n for j in range(1, self.num_classes + 1):\n for bbox in results[j]:\n if bbox[4] > self.opt.vis_thresh:\n debugger.add_coco_bbox(bbox[:4], j - 1, bbox[4], img_id='ctdet')\n debugger.show_all_imgs(pause=self.pause)\n #prefix = image_name.split('.')[0]\n #path = os.path.dirname(self.opt.det_output_path) + '/img'\n #debugger.save_all_imgs(path, prefix)\n\n def save_results_only(self, debugger, image, results, image_name):\n debugger.add_img(image, img_id='ctdet')\n for j in range(1, self.num_classes + 1):\n for bbox in results[j]:\n if bbox[4] > self.opt.vis_thresh:\n debugger.add_coco_bbox(bbox[:4], j - 1, bbox[4], img_id='ctdet')\n prefix = image_name.split('.')[0]\n path = os.path.dirname(self.opt.det_output_path) + '/img'\n debugger.save_all_imgs(path, prefix)\n" ]
[ [ "numpy.partition", "torch.cuda.synchronize", "numpy.concatenate", "torch.no_grad", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
johnfischbeck/hdbscan
[ "7499b53f9edca09c6a674a93e3d32bbbaf655b5a" ]
[ "hdbscan/prediction.py" ]
[ "# Support various prediction methods for predicting cluster membership\n# of new or unseen points. There are several ways to interpret how\n# to do this correctly, so we provide several methods for\n# the different use cases that may arise.\n\nimport numpy as np\n\nfrom sklearn.neighbors import KDTree, BallTree\nfrom .dist_metrics import DistanceMetric\nfrom ._hdbscan_tree import compute_stability, labelling_at_cut, recurse_leaf_dfs\nfrom ._prediction_utils import (get_tree_row_with_child,\n dist_membership_vector,\n outlier_membership_vector,\n prob_in_some_cluster,\n all_points_dist_membership_vector,\n all_points_outlier_membership_vector,\n all_points_prob_in_some_cluster)\nfrom warnings import warn\n\n\nclass PredictionData(object):\n \"\"\"\n Extra data that allows for faster prediction if cached.\n\n Parameters\n ----------\n\n data : array (n_samples, n_features)\n The original data set that was clustered\n\n condensed_tree : CondensedTree\n The condensed tree object created by a clustering\n\n min_samples : int\n The min_samples value used in clustering\n\n tree_type : string, optional\n Which type of space tree to use for core distance computation.\n One of:\n * ``kdtree``\n * ``balltree``\n\n metric : string, optional\n The metric used to determine distance for the clustering.\n This is the metric that will be used for the space tree to determine\n core distances etc.\n\n **kwargs :\n Any further arguments to the metric.\n\n Attributes\n ----------\n\n raw_data : array (n_samples, n_features)\n The original data set that was clustered\n\n tree : KDTree or BallTree\n A space partitioning tree that can be queried for nearest neighbors.\n\n core_distances : array (n_samples,)\n The core distances for every point in the original data set.\n\n cluster_map : dict\n A dictionary mapping cluster numbers in the condensed tree to labels\n in the final selected clustering.\n\n cluster_tree : structured array\n A version of the condensed tree that only contains clusters, not\n individual points.\n\n max_lambdas : dict\n A dictionary mapping cluster numbers in the condensed tree to the\n maximum lambda value seen in that cluster.\n \"\"\"\n _tree_type_map = {'kdtree': KDTree, 'balltree': BallTree}\n\n def _clusters_below(self, cluster):\n result = []\n to_process = [cluster]\n\n while to_process:\n result.extend(to_process)\n to_process = \\\n self.cluster_tree['child'][np.in1d(self.cluster_tree['parent'],\n to_process)]\n to_process = to_process.tolist()\n\n return result\n\n def _recurse_leaf_dfs(self, current_node):\n children = self.cluster_tree[self.cluster_tree['parent'] ==\n current_node]['child']\n if len(children) == 0:\n return [current_node, ]\n else:\n return sum(\n [recurse_leaf_dfs(self.cluster_tree, child) for child in children], [])\n\n def __init__(self, data, condensed_tree, min_samples,\n tree_type='kdtree', metric='euclidean', **kwargs):\n self.raw_data = data\n self.tree = self._tree_type_map[tree_type](self.raw_data,\n metric=metric, **kwargs)\n self.core_distances = self.tree.query(data, k=min_samples)[0][:, -1]\n self.dist_metric = DistanceMetric.get_metric(metric, **kwargs)\n\n selected_clusters = condensed_tree._select_clusters()\n # raw_condensed_tree = condensed_tree.to_numpy()\n raw_condensed_tree = condensed_tree._raw_tree\n\n self.cluster_map = {c: n for n, c in enumerate(sorted(list(selected_clusters)))}\n self.reverse_cluster_map = {n: c for c, n in self.cluster_map.items()}\n\n self.cluster_tree = raw_condensed_tree[raw_condensed_tree['child_size']\n > 1]\n self.max_lambdas = {}\n self.leaf_max_lambdas = {}\n self.exemplars = []\n\n all_clusters = set(np.hstack([self.cluster_tree['parent'],\n self.cluster_tree['child']]))\n\n for cluster in all_clusters:\n self.leaf_max_lambdas[cluster] = raw_condensed_tree['lambda_val'][\n raw_condensed_tree['parent'] == cluster].max()\n\n for cluster in selected_clusters:\n self.max_lambdas[cluster] = \\\n raw_condensed_tree['lambda_val'][raw_condensed_tree['parent']\n == cluster].max()\n\n for sub_cluster in self._clusters_below(cluster):\n self.cluster_map[sub_cluster] = self.cluster_map[cluster]\n self.max_lambdas[sub_cluster] = self.max_lambdas[cluster]\n\n cluster_exemplars = np.array([], dtype=np.int64)\n for leaf in self._recurse_leaf_dfs(cluster):\n leaf_max_lambda = raw_condensed_tree['lambda_val'][\n raw_condensed_tree['parent'] == leaf].max()\n points = raw_condensed_tree['child'][\n (raw_condensed_tree['parent'] == leaf) &\n (raw_condensed_tree['lambda_val'] == leaf_max_lambda)]\n cluster_exemplars = np.hstack([cluster_exemplars, points])\n\n self.exemplars.append(self.raw_data[cluster_exemplars])\n\n\ndef _find_neighbor_and_lambda(neighbor_indices, neighbor_distances,\n core_distances, min_samples):\n \"\"\"\n Find the nearest mutual reachability neighbor of a point, and compute\n the associated lambda value for the point, given the mutual reachability\n distance to a nearest neighbor.\n\n Parameters\n ----------\n neighbor_indices : array (2 * min_samples, )\n An array of raw distance based nearest neighbor indices.\n\n neighbor_distances : array (2 * min_samples, )\n An array of raw distances to the nearest neighbors.\n\n core_distances : array (n_samples, )\n An array of core distances for all points\n\n min_samples : int\n The min_samples value used to generate core distances.\n\n Returns\n -------\n neighbor : int\n The index into the full raw data set of the nearest mutual reachability\n distance neighbor of the point.\n\n lambda_ : float\n The lambda value at which this point joins/merges with `neighbor`.\n \"\"\"\n neighbor_core_distances = core_distances[neighbor_indices]\n point_core_distances = neighbor_distances[min_samples] * np.ones(\n neighbor_indices.shape[0])\n mr_distances = np.vstack((\n neighbor_core_distances,\n point_core_distances,\n neighbor_distances\n )).max(axis=0)\n\n nn_index = mr_distances.argmin()\n\n nearest_neighbor = neighbor_indices[nn_index]\n if mr_distances[nn_index] > 0.0:\n lambda_ = 1. / mr_distances[nn_index]\n else:\n lambda_ = np.finfo(np.double).max\n\n return nearest_neighbor, lambda_\n\n\ndef _extend_condensed_tree(tree, neighbor_indices, neighbor_distances,\n core_distances, min_samples):\n \"\"\"\n Create a new condensed tree with an additional point added, allowing for\n computations as if this point had been part of the original tree. Note\n that this makes as little change to the tree as possible, with no\n re-optimizing/re-condensing so that the selected clusters remain\n effectively unchanged.\n\n Parameters\n ----------\n tree : structured array\n The raw format condensed tree to update.\n\n neighbor_indices : array (2 * min_samples, )\n An array of raw distance based nearest neighbor indices.\n\n neighbor_distances : array (2 * min_samples, )\n An array of raw distances to the nearest neighbors.\n\n core_distances : array (n_samples, )\n An array of core distances for all points\n\n min_samples : int\n The min_samples value used to generate core distances.\n\n Returns\n -------\n new_tree : structured array\n The original tree with an extra row providing the parent cluster\n and lambda information for a new point given index -1.\n \"\"\"\n tree_root = tree['parent'].min()\n\n nearest_neighbor, lambda_ = _find_neighbor_and_lambda(neighbor_indices,\n neighbor_distances,\n core_distances,\n min_samples\n )\n\n neighbor_tree_row = get_tree_row_with_child(tree, nearest_neighbor)\n potential_cluster = neighbor_tree_row['parent']\n\n if neighbor_tree_row['lambda_val'] <= lambda_:\n # New point departs with the old\n new_tree_row = (potential_cluster, -1, 1,\n neighbor_tree_row['lambda_val'])\n else:\n # Find appropriate cluster based on lambda of new point\n while potential_cluster > tree_root and \\\n tree[tree['child'] ==\n potential_cluster]['lambda_val'] >= lambda_:\n potential_cluster = tree['parent'][tree['child']\n == potential_cluster][0]\n\n new_tree_row = (potential_cluster, -1, 1, lambda_)\n\n return np.append(tree, new_tree_row)\n\n\ndef _find_cluster_and_probability(tree, cluster_tree, neighbor_indices,\n neighbor_distances, core_distances,\n cluster_map, max_lambdas,\n min_samples):\n \"\"\"\n Return the cluster label (of the original clustering) and membership\n probability of a new data point.\n\n Parameters\n ----------\n tree : CondensedTree\n The condensed tree associated with the clustering.\n\n cluster_tree : structured_array\n The raw form of the condensed tree with only cluster information (no\n data on individual points). This is significantly more compact.\n\n neighbor_indices : array (2 * min_samples, )\n An array of raw distance based nearest neighbor indices.\n\n neighbor_distances : array (2 * min_samples, )\n An array of raw distances to the nearest neighbors.\n\n core_distances : array (n_samples, )\n An array of core distances for all points\n\n cluster_map : dict\n A dictionary mapping cluster numbers in the condensed tree to labels\n in the final selected clustering.\n\n max_lambdas : dict\n A dictionary mapping cluster numbers in the condensed tree to the\n maximum lambda value seen in that cluster.\n\n min_samples : int\n The min_samples value used to generate core distances.\n \"\"\"\n raw_tree = tree._raw_tree\n tree_root = cluster_tree['parent'].min()\n\n nearest_neighbor, lambda_ = _find_neighbor_and_lambda(neighbor_indices,\n neighbor_distances,\n core_distances,\n min_samples\n )\n\n neighbor_tree_row = get_tree_row_with_child(raw_tree, nearest_neighbor)\n potential_cluster = neighbor_tree_row['parent']\n\n if neighbor_tree_row['lambda_val'] > lambda_:\n # Find appropriate cluster based on lambda of new point\n while potential_cluster > tree_root and \\\n cluster_tree['lambda_val'][cluster_tree['child']\n == potential_cluster] >= lambda_:\n potential_cluster = cluster_tree['parent'][cluster_tree['child']\n == potential_cluster][0]\n\n if potential_cluster in cluster_map:\n cluster_label = cluster_map[potential_cluster]\n else:\n cluster_label = -1\n\n if cluster_label >= 0:\n max_lambda = max_lambdas[potential_cluster]\n\n if max_lambda > 0.0:\n lambda_ = min(max_lambda, lambda_)\n prob = (lambda_ / max_lambda)\n else:\n prob = 1.0\n else:\n prob = 0.0\n\n return cluster_label, prob\n\n\ndef approximate_predict(clusterer, points_to_predict):\n \"\"\"Predict the cluster label of new points. The returned labels\n will be those of the original clustering found by ``clusterer``,\n and therefore are not (necessarily) the cluster labels that would\n be found by clustering the original data combined with\n ``points_to_predict``, hence the 'approximate' label.\n\n If you simply wish to assign new points to an existing clustering\n in the 'best' way possible, this is the function to use. If you\n want to predict how ``points_to_predict`` would cluster with\n the original data under HDBSCAN the most efficient existing approach\n is to simply recluster with the new point(s) added to the original dataset.\n\n Parameters\n ----------\n clusterer : HDBSCAN\n A clustering object that has been fit to the data and\n either had ``prediction_data=True`` set, or called the\n ``generate_prediction_data`` method after the fact.\n\n points_to_predict : array, or array-like (n_samples, n_features)\n The new data points to predict cluster labels for. They should\n have the same dimensionality as the original dataset over which\n clusterer was fit.\n\n Returns\n -------\n labels : array (n_samples,)\n The predicted labels of the ``points_to_predict``\n\n probabilities : array (n_samples,)\n The soft cluster scores for each of the ``points_to_predict``\n\n See Also\n --------\n :py:func:`hdbscan.predict.membership_vector`\n :py:func:`hdbscan.predict.all_points_membership_vectors`\n\n \"\"\"\n if clusterer.prediction_data_ is None:\n raise ValueError('Clusterer does not have prediction data!'\n ' Try fitting with prediction_data=True set,'\n ' or run generate_prediction_data on the clusterer')\n\n points_to_predict = np.asarray(points_to_predict)\n\n if points_to_predict.shape[1] != \\\n clusterer.prediction_data_.raw_data.shape[1]:\n raise ValueError('New points dimension does not match fit data!')\n\n if clusterer.prediction_data_.cluster_tree.shape[0] == 0:\n warn('Clusterer does not have any defined clusters, new data'\n ' will be automatically predicted as noise.')\n labels = -1 * np.ones(points_to_predict.shape[0], dtype=np.int32)\n probabilities = np.zeros(points_to_predict.shape[0], dtype=np.float32)\n return labels, probabilities\n\n labels = np.empty(points_to_predict.shape[0], dtype=np.int)\n probabilities = np.empty(points_to_predict.shape[0], dtype=np.float64)\n\n min_samples = clusterer.min_samples or clusterer.min_cluster_size\n neighbor_distances, neighbor_indices = \\\n clusterer.prediction_data_.tree.query(points_to_predict,\n k=2 * min_samples)\n\n for i in range(points_to_predict.shape[0]):\n label, prob = _find_cluster_and_probability(\n clusterer.condensed_tree_,\n clusterer.prediction_data_.cluster_tree,\n neighbor_indices[i],\n neighbor_distances[i],\n clusterer.prediction_data_.core_distances,\n clusterer.prediction_data_.cluster_map,\n clusterer.prediction_data_.max_lambdas,\n min_samples\n )\n labels[i] = label\n probabilities[i] = prob\n\n return labels, probabilities\n\n\ndef membership_vector(clusterer, points_to_predict):\n \"\"\"Predict soft cluster membership. The result produces a vector\n for each point in ``points_to_predict`` that gives a probability that\n the given point is a member of a cluster for each of the selected clusters\n of the ``clusterer``.\n\n Parameters\n ----------\n clusterer : HDBSCAN\n A clustering object that has been fit to the data and\n either had ``prediction_data=True`` set, or called the\n ``generate_prediction_data`` method after the fact.\n\n points_to_predict : array, or array-like (n_samples, n_features)\n The new data points to predict cluster labels for. They should\n have the same dimensionality as the original dataset over which\n clusterer was fit.\n\n Returns\n -------\n membership_vectors : array (n_samples, n_clusters)\n The probability that point ``i`` is a member of cluster ``j`` is\n in ``membership_vectors[i, j]``.\n\n See Also\n --------\n :py:func:`hdbscan.predict.predict`\n :py:func:`hdbscan.predict.all_points_membership_vectors`\n\"\"\"\n\n clusters = np.array(\n sorted(list(clusterer.condensed_tree_._select_clusters()))).astype(np.intp)\n\n result = np.empty((points_to_predict.shape[0], clusters.shape[0]),\n dtype=np.float64)\n\n min_samples = clusterer.min_samples or clusterer.min_cluster_size\n neighbor_distances, neighbor_indices = \\\n clusterer.prediction_data_.tree.query(points_to_predict,\n k=2 * min_samples)\n\n for i in range(points_to_predict.shape[0]):\n\n # We need to find where in the tree the new point would go\n # for the purposes of outlier membership approximation\n nearest_neighbor, lambda_ = \\\n _find_neighbor_and_lambda(\n neighbor_indices[i],\n neighbor_distances[i],\n clusterer.prediction_data_.core_distances,\n min_samples)\n\n neighbor_tree_row = get_tree_row_with_child(\n clusterer.condensed_tree_._raw_tree, nearest_neighbor)\n\n if neighbor_tree_row['lambda_val'] <= lambda_:\n lambda_ = neighbor_tree_row['lambda_val']\n\n distance_vec = dist_membership_vector(\n points_to_predict[i],\n clusterer.prediction_data_.exemplars,\n clusterer.prediction_data_.dist_metric)\n outlier_vec = outlier_membership_vector(\n nearest_neighbor,\n lambda_,\n clusters,\n clusterer.condensed_tree_._raw_tree,\n clusterer.prediction_data_.leaf_max_lambdas,\n clusterer.prediction_data_.cluster_tree)\n\n result[i] = distance_vec ** 0.5 * outlier_vec ** 2.0\n result[i] /= result[i].sum()\n\n result[i] *= prob_in_some_cluster(\n nearest_neighbor,\n lambda_,\n clusters,\n clusterer.condensed_tree_._raw_tree,\n clusterer.prediction_data_.leaf_max_lambdas,\n clusterer.prediction_data_.cluster_tree)\n\n return result\n\n\ndef all_points_membership_vectors(clusterer):\n \"\"\"Predict soft cluster membership vectors for all points in the\n original dataset the clusterer was trained on. This function is more\n efficient by making use of the fact that all points are already in the\n condensed tree, and processing in bulk.\n\n Parameters\n ----------\n clusterer : HDBSCAN\n A clustering object that has been fit to the data and\n either had ``prediction_data=True`` set, or called the\n ``generate_prediction_data`` method after the fact.\n This method does not work if the clusterer was trained\n with ``metric='precomputed'``.\n\n Returns\n -------\n membership_vectors : array (n_samples, n_clusters)\n The probability that point ``i`` of the original dataset is a member of\n cluster ``j`` is in ``membership_vectors[i, j]``.\n\n See Also\n --------\n :py:func:`hdbscan.predict.predict`\n :py:func:`hdbscan.predict.all_points_membership_vectors`\n \"\"\"\n clusters = np.array(sorted(list(clusterer.condensed_tree_._select_clusters()))).astype(np.intp)\n all_points = clusterer.prediction_data_.raw_data\n\n # When no clusters found, return array of 0's\n if clusters.size == 0:\n return np.zeros(all_points.shape[0])\n\n distance_vecs = all_points_dist_membership_vector(\n all_points,\n clusterer.prediction_data_.exemplars,\n clusterer.prediction_data_.dist_metric)\n outlier_vecs = all_points_outlier_membership_vector(\n clusters,\n clusterer.condensed_tree_._raw_tree,\n clusterer.prediction_data_.leaf_max_lambdas,\n clusterer.prediction_data_.cluster_tree)\n in_cluster_probs = all_points_prob_in_some_cluster(\n clusters,\n clusterer.condensed_tree_._raw_tree,\n clusterer.prediction_data_.leaf_max_lambdas,\n clusterer.prediction_data_.cluster_tree)\n\n result = distance_vecs * outlier_vecs\n row_sums = result.sum(axis=1)\n result = result / row_sums[:, np.newaxis]\n result *= in_cluster_probs[:, np.newaxis]\n\n return result\n" ]
[ [ "numpy.hstack", "numpy.asarray", "numpy.vstack", "numpy.in1d", "numpy.ones", "numpy.finfo", "numpy.append", "numpy.array", "numpy.zeros", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rangaswamymr/incubator-bluemarlin
[ "6cb60b2a41edc6509377f9eacb7660d199a9485b", "6cb60b2a41edc6509377f9eacb7660d199a9485b" ]
[ "Model/lookalike-model/lookalike_model/trainer/lookalike_trainer_tfrecords.py", "Processes/optimizer/tests/tests_overall/test_hwm_allocations_natural_2.py" ]
[ "import numpy as np\nimport os, time\nimport random\nimport tensorflow as tf\nfrom lookalike_model.trainer.model_new import Model\nimport argparse\n\n\nrandom.seed(1234)\n# adding arguments for tfrecord directory and the checkpoint directory\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--data_dir\", type=str, help=\"input data tfrecords dir location\")\nparser.add_argument(\"--check_point_dir\", type=str, help=\"Check Point dir location\")\nargs, unknown = parser.parse_known_args()\nif len(unknown) != 0:\n print(\"unknown args:%s\", unknown)\n\n# tfrecord location and the check point directory location\ntfrecord_location =args.data_dir + \"/tf_records_lookalike_data_08july\"\noutput = args.check_point_dir\n\n\ndef __data_parser(serialized_example):\n features = tf.parse_single_example(serialized_example,\n features={'keywords_list': tf.FixedLenSequenceFeature([], tf.int64, allow_missing=True),\n 'ucdoc': tf.FixedLenFeature([], tf.int64),\n 'keyword': tf.FixedLenFeature([], tf.int64),\n 'is_click': tf.FixedLenFeature([], tf.float32),\n 'sl': tf.FixedLenFeature([], tf.int64),\n 'lr': tf.FixedLenFeature([], tf.float32)\n })\n keywords_list = tf.cast(features['keywords_list'], tf.int32)\n ucdoc = tf.cast(features['ucdoc'], tf.int32)\n keyword = tf.cast(features['keyword'], tf.int32)\n is_click = tf.cast(features['is_click'], tf.float32)\n sl = tf.cast(features['sl'], tf.int32)\n lr = tf.cast(features['lr'], tf.float32)\n return ucdoc, keyword, keywords_list, is_click,sl,lr\n\n\nnames = []\nfor file in os.listdir(tfrecord_location):\n if file.startswith(\"part\"):\n names.append(file)\n\nfile_paths = [os.path.join(tfrecord_location, name) for name in names]\ndataset = tf.data.TFRecordDataset(file_paths)\nshuffle_value = 2000\nrepeat_value = 10\nbatch_size = 1000\nprefetch_buffer = 2000\ndataset = dataset.map(__data_parser)\ndataset = dataset.repeat(repeat_value).shuffle(shuffle_value).prefetch(buffer_size=prefetch_buffer).batch(batch_size)\niterator = dataset.make_one_shot_iterator()\n\ntf_ucdoc, tf_keyword, tf_keywords_list, tf_is_click, tf_sl, tf_lr = iterator.get_next()\n\nunique_keywords = 811\ncate_list = np.array([x for x in range(unique_keywords)])\nuser_count = 1349500103\nitem_count, cate_count = unique_keywords, unique_keywords\npredict_batch_size = 5000\npredict_ads_num = 30\ntotal_iterations = int((user_count * epoch)//batch_size)\nprint('total iterations = {}'.format(total_iterations))\nmax_epochs = 500\n\nmodel = Model(user_count, item_count, cate_count, cate_list, predict_batch_size, predict_ads_num,tf_ucdoc,tf_keyword,tf_is_click,tf_keywords_list,tf_sl)\ngpu_options = tf.GPUOptions(allow_growth=True)\nwith tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:\n sess.run(tf.global_variables_initializer())\n sess.run(tf.local_variables_initializer())\n start_time = time.time()\n count_epoch = 0\n last_100_loss = []\n print('shuffle = {}, epochs = {}, batch_size = {}, predict_batch_size = {}'.format(shuffle_value, epoch, batch_size, predict_batch_size))\n for i in range(max_epochs*500):\n loss, _,sl = sess.run([model.loss, model.train_op, tf_sl])\n loss = round(loss, 2)\n last_100_loss.append(loss)\n if len(last_100_loss) == 101:\n del last_100_loss[0]\n if i%500==0:\n print('Epoch {} DONE Iteration: {} Cost time: {} Model Loss: {} Average Loss: {}'.format(count_epoch, i, time.time()-start_time, loss,\n round(sum(last_100_loss)/100, 2)))\n model.save(sess, output)\n count_epoch += 1\n# print(\"i: \",i,\" loss: \",loss)\n model.save(sess, output)\n\n\n\n\n", "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n \n# http://www.apache.org/licenses/LICENSE-2.0.html\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# Testing hwm_allocation() with natural bookings.\n\nimport unittest\nfrom imscommon.es.ims_esclient import ESClient\nfrom pyspark.sql import HiveContext\nfrom pyspark import SparkContext, SparkConf\nfrom pyspark.sql.types import IntegerType, StringType, StructType, StructField, ArrayType, MapType, Row\nimport optimizer.util\nimport pandas\nfrom pandas.testing import assert_frame_equal\nimport optimizer.algo.hwm\nimport json\nimport os\nimport warnings\n\nclass Unittest_HWM_Allocation_NaturalOrder2(unittest.TestCase):\n def setUp(self):\n warnings.simplefilter(\"ignore\", ResourceWarning)\n fpath = os.path.abspath(os.path.join(os.path.dirname(__file__),\"..\"))\n with open(fpath + '/data_source/bookings_overall.json') as bookings_source:\n self.bookings = json.load(bookings_source)\n with open(fpath + '/data_source/cfg.json') as cfg_source:\n self.cfg = json.load(cfg_source)\n today = '20180402'\n self.days = optimizer.util.get_days_from_bookings(today, self.bookings)\n self.sc = SparkContext.getOrCreate()\n self.hive_context = HiveContext(self.sc)\n self.schema = optimizer.util.get_common_pyspark_schema()\n\n def compare_two_dfs(self, pandas_df_expected, df_to_test_rows):\n df = self.hive_context.createDataFrame(df_to_test_rows, self.schema)\n df_allocated = optimizer.algo.hwm.hwm_allocation(df, self.bookings, self.days)\n pandas_df_allocated = df_allocated.select(\"*\").toPandas()\n print(pandas_df_expected)\n print(pandas_df_allocated)\n\n return self.assertTrue(assert_frame_equal(pandas_df_expected, pandas_df_allocated, check_dtype=False) == None)\n\n def test_hwm_allocation_case1(self):\n # Testcase type: 1 booking bucket with 1 booking_id in ands\n # testcase 1: booking bucket ['20180405', ['b8'], ['b6'], {}, 3239]\n pandas_df_expected = pandas.DataFrame(columns=['day', 'ands', 'minus', 'amount', 'allocated'])\n pandas_df_expected.loc[0] = ['20180405', ['b8'], ['b6'], 3239, {'b8': 88}]\n\n df_to_test_rows = [(['20180405', ['b8'], ['b6'], {}, 3239])]\n return self.compare_two_dfs(pandas_df_expected, df_to_test_rows)\n\n def test_hwm_allocation_case2(self):\n # bk_id: b13, days: ['20180405'], a: ['4'], g: ['g_f'], si: ['2'], amount: 130000\n # bk_id: b12, days: ['20180405'], a: ['4'], g: ['g_f'], si: ['2'], amount: 12\n # Testcase type: 1 booking bucket with 2 booking_id in ands\n pandas_df_expected = pandas.DataFrame(columns=['day', 'ands', 'minus', 'amount', 'allocated'])\n pandas_df_expected.loc[0] = ['20180405', ['b11', 'b12'], [], 8900, {'b11': 11, 'b12': 12}]\n\n df_to_test_rows = [(['20180405', ['b11', 'b12'], [], {}, 8900])]\n return self.compare_two_dfs(pandas_df_expected, df_to_test_rows)\n\n def test_hwm_allocation_case3(self):\n # Testcase type: 1 booking bucket with 3 booking_id in ands\n pandas_df_expected = pandas.DataFrame(columns=['day', 'ands', 'minus', 'amount', 'allocated'])\n pandas_df_expected.loc[0] = ['20180405', ['b6', 'b7', 'b10'], [], 8900, {'b6': 66, 'b7': 77, 'b10': 100}]\n\n df_to_test_rows = [(['20180405', ['b6', 'b7', 'b10'], [], {}, 8900])]\n return self.compare_two_dfs(pandas_df_expected, df_to_test_rows)\n\n def test_hwm_allocation_case4(self):\n # Testcase type: 2 booking buckets with 4 bookings included.\n pandas_df_expected = pandas.DataFrame(columns=['day', 'ands', 'minus', 'amount', 'allocated'])\n pandas_df_expected.loc[0] = ['20180405', ['b8'], ['b6', 'b7', 'b9'], 3239, {'b8': 88}]\n pandas_df_expected.loc[1] = ['20180405', ['b6', 'b7'], ['b8', 'b9'], 8900, {'b6': 66, 'b7': 77}]\n\n df_to_test_rows = [(['20180405', ['b8'], ['b6', 'b7', 'b9'], {}, 3239]), (['20180405', ['b6', 'b7'], ['b8', 'b9'], {}, 8900])]\n return self.compare_two_dfs(pandas_df_expected, df_to_test_rows)\n\n def test_hwm_allocation_case5(self):\n # Testcase type: 3 booking buckets with 5 bookings included.\n pandas_df_expected = pandas.DataFrame(columns=['day', 'ands', 'minus', 'amount', 'allocated'])\n pandas_df_expected.loc[0] = ['20180405', ['b6', 'b7', 'b10', 'b11', 'b12'], ['b8', 'b9'], \n 8900, {'b11': 11, 'b6': 66, 'b7': 77, 'b10': 100, 'b12': 12}]\n\n df_to_test_rows = [(['20180405', ['b6', 'b7', 'b10', 'b11', 'b12'], ['b8', 'b9'], {}, 8900])]\n return self.compare_two_dfs(pandas_df_expected, df_to_test_rows)\n\n def test_hwm_allocation_case6(self):\n # bk_id: b13, days: ['20180405'], a: ['4'], g: ['g_f'], si: ['2'], amount: 130000\n # bk_id: b12, days: ['20180405'], a: ['4'], g: ['g_f'], si: ['2'], amount: 12\n # Testcase type: 3 booking buckets with 5 bookings included.\n pandas_df_expected = pandas.DataFrame(columns=['day', 'ands', 'minus', 'amount', 'allocated'])\n pandas_df_expected.loc[0] = ['20180405', ['b13', 'b12'], [], \n 8900, {'b13': 8900}]\n\n df_to_test_rows = [(['20180405', ['b13', 'b12'], [], {}, 8900])]\n return self.compare_two_dfs(pandas_df_expected, df_to_test_rows)\n \n def test_hwm_allocation_case7(self):\n # bk_id: b15, days: ['20180405'], a: ['4'], g: ['g_f'], si: ['2'], amount: 8900\n # bk_id: b14, days: ['20180405'], a: ['4'], g: ['g_f'], si: ['2'], amount: 8900\n # Testcase type: 3 booking buckets with 5 bookings included.\n pandas_df_expected = pandas.DataFrame(columns=['day', 'ands', 'minus', 'amount', 'allocated'])\n pandas_df_expected.loc[0] = ['20180405', ['b15', 'b14'], [], 8900, {'b15': 8900}]\n\n df_to_test_rows = [(['20180405', ['b15', 'b14'], [], {}, 8900])]\n return self.compare_two_dfs(pandas_df_expected, df_to_test_rows)\n\n def test_hwm_allocation_case8(self):\n # bk_id: b17, days: ['20180405'], a: ['4'], g: ['g_f'], si: ['2'], amount: 4450\n # bk_id: b16, days: ['20180405'], a: ['4'], g: ['g_f'], si: ['2'], amount: 4450\n # Testcase type: 3 booking buckets with 5 bookings included.\n pandas_df_expected = pandas.DataFrame(columns=['day', 'ands', 'minus', 'amount', 'allocated'])\n pandas_df_expected.loc[0] = ['20180405', ['b16', 'b17'], [], 8900, {'b16': 4450, 'b17': 4450}]\n\n df_to_test_rows = [(['20180405', ['b16', 'b17'], [], {}, 8900])]\n return self.compare_two_dfs(pandas_df_expected, df_to_test_rows)\n\n def test_hwm_allocation_case9(self):\n # bk_id: b18, days: ['20180405'], a: ['4'], g: ['g_f'], si: ['2'], amount: 4451\n # bk_id: b17, days: ['20180405'], a: ['4'], g: ['g_f'], si: ['2'], amount: 4450\n # Testcase type: 3 booking buckets with 5 bookings included.\n pandas_df_expected = pandas.DataFrame(columns=['day', 'ands', 'minus', 'amount', 'allocated'])\n pandas_df_expected.loc[0] = ['20180405', ['b17', 'b18'], [], 8900, {'b17': 4450, 'b18': 4450}]\n\n df_to_test_rows = [(['20180405', ['b17', 'b18'], [], {}, 8900])]\n return self.compare_two_dfs(pandas_df_expected, df_to_test_rows)\n\n def test_hwm_allocation_case10(self):\n # Testcase type: 3 booking buckets with 5 bookings included.\n pandas_df_expected = pandas.DataFrame(columns=['day', 'ands', 'minus', 'amount', 'allocated'])\n pandas_df_expected.loc[0] = ['20180405', ['b16', 'b17', 'b6', 'b7', 'b10', 'b12', 'b18'], ['b8', 'b9'], \n 8900, {'b16': 4450, 'b17': 4450}] # b6, b7, b10, b12, b16, b17, b18 have the same attributes.\n\n df_to_test_rows = [(['20180405', ['b16', 'b17', 'b6', 'b7', 'b10', 'b12', 'b18'], ['b8', 'b9'], {}, 8900])]\n return self.compare_two_dfs(pandas_df_expected, df_to_test_rows)\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "tensorflow.local_variables_initializer", "tensorflow.FixedLenFeature", "tensorflow.data.TFRecordDataset", "tensorflow.cast", "tensorflow.ConfigProto", "tensorflow.global_variables_initializer", "tensorflow.FixedLenSequenceFeature", "tensorflow.GPUOptions" ], [ "pandas.testing.assert_frame_equal", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
SpinQTech/SpinQKit
[ "2e24826688b2b26cf7efa66fd47f0e7ef883a96c" ]
[ "qiskit/circuit/library/grover_operator.py" ]
[ "# This code is part of Qiskit.\r\n#\r\n# (C) Copyright IBM 2017, 2020.\r\n#\r\n# This code is licensed under the Apache License, Version 2.0. You may\r\n# obtain a copy of this license in the LICENSE.txt file in the root directory\r\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\r\n#\r\n# Any modifications or derivative works of this code must retain this\r\n# copyright notice, and modified files need to carry a notice indicating\r\n# that they have been altered from the originals.\r\n\r\n\"\"\"The Grover operator.\"\"\"\r\n\r\nfrom typing import List, Optional, Union\r\nimport numpy\r\nfrom qiskit.circuit import QuantumCircuit, QuantumRegister, AncillaRegister\r\n# from qiskit.quantum_info import Statevector, Operator, DensityMatrix\r\nfrom qiskit.quantum_info import Operator\r\nfrom .standard_gates import MCXGate\r\n\r\n\r\nclass GroverOperator(QuantumCircuit):\r\n r\"\"\"The Grover operator.\r\n\r\n Grover's search algorithm [1, 2] consists of repeated applications of the so-called\r\n Grover operator used to amplify the amplitudes of the desired output states.\r\n This operator, :math:`\\mathcal{Q}`, consists of the phase oracle, :math:`\\mathcal{S}_f`,\r\n zero phase-shift or zero reflection, :math:`\\mathcal{S}_0`, and an\r\n input state preparation :math:`\\mathcal{A}`:\r\n\r\n .. math::\r\n \\mathcal{Q} = \\mathcal{A} \\mathcal{S}_0 \\mathcal{A}^\\dagger \\mathcal{S}_f\r\n\r\n In the standard Grover search we have :math:`\\mathcal{A} = H^{\\otimes n}`:\r\n\r\n .. math::\r\n \\mathcal{Q} = H^{\\otimes n} \\mathcal{S}_0 H^{\\otimes n} \\mathcal{S}_f\r\n = D \\mathcal{S_f}\r\n\r\n The operation :math:`D = H^{\\otimes n} \\mathcal{S}_0 H^{\\otimes n}` is also referred to as\r\n diffusion operator. In this formulation we can see that Grover's operator consists of two\r\n steps: first, the phase oracle multiplies the good states by -1 (with :math:`\\mathcal{S}_f`)\r\n and then the whole state is reflected around the mean (with :math:`D`).\r\n\r\n This class allows setting a different state preparation, as in quantum amplitude\r\n amplification (a generalization of Grover's algorithm), :math:`\\mathcal{A}` might not be\r\n a layer of Hardamard gates [3].\r\n\r\n The action of the phase oracle :math:`\\mathcal{S}_f` is defined as\r\n\r\n .. math::\r\n \\mathcal{S}_f: |x\\rangle \\mapsto (-1)^{f(x)}|x\\rangle\r\n\r\n where :math:`f(x) = 1` if :math:`x` is a good state and 0 otherwise. To highlight the fact\r\n that this oracle flips the phase of the good states and does not flip the state of a result\r\n qubit, we call :math:`\\mathcal{S}_f` a phase oracle.\r\n\r\n Note that you can easily construct a phase oracle from a bitflip oracle by sandwiching the\r\n controlled X gate on the result qubit by a X and H gate. For instance\r\n\r\n .. parsed-literal::\r\n\r\n Bitflip oracle Phaseflip oracle\r\n q_0: ──■── q_0: ────────────■────────────\r\n ┌─┴─┐ ┌───┐┌───┐┌─┴─┐┌───┐┌───┐\r\n out: ┤ X ├ out: ┤ X ├┤ H ├┤ X ├┤ H ├┤ X ├\r\n └───┘ └───┘└───┘└───┘└───┘└───┘\r\n\r\n There is some flexibility in defining the oracle and :math:`\\mathcal{A}` operator. Before the\r\n Grover operator is applied in Grover's algorithm, the qubits are first prepared with one\r\n application of the :math:`\\mathcal{A}` operator (or Hadamard gates in the standard formulation).\r\n Thus, we always have operation of the form\r\n :math:`\\mathcal{A} \\mathcal{S}_f \\mathcal{A}^\\dagger`. Therefore it is possible to move\r\n bitflip logic into :math:`\\mathcal{A}` and leaving the oracle only to do phaseflips via Z gates\r\n based on the bitflips. One possible use-case for this are oracles that do not uncompute the\r\n state qubits.\r\n\r\n The zero reflection :math:`\\mathcal{S}_0` is usually defined as\r\n\r\n .. math::\r\n \\mathcal{S}_0 = 2 |0\\rangle^{\\otimes n} \\langle 0|^{\\otimes n} - \\mathbb{I}_n\r\n\r\n where :math:`\\mathbb{I}_n` is the identity on :math:`n` qubits.\r\n By default, this class implements the negative version\r\n :math:`2 |0\\rangle^{\\otimes n} \\langle 0|^{\\otimes n} - \\mathbb{I}_n`, since this can simply\r\n be implemented with a multi-controlled Z sandwiched by X gates on the target qubit and the\r\n introduced global phase does not matter for Grover's algorithm.\r\n\r\n Examples:\r\n >>> from qiskit.circuit import QuantumCircuit\r\n >>> from qiskit.circuit.library import GroverOperator\r\n >>> oracle = QuantumCircuit(2)\r\n >>> oracle.z(0) # good state = first qubit is |1>\r\n >>> grover_op = GroverOperator(oracle, insert_barriers=True)\r\n >>> grover_op.draw()\r\n ┌───┐ ░ ┌───┐ ░ ┌───┐ ┌───┐ ░ ┌───┐\r\n state_0: ┤ Z ├─░─┤ H ├─░─┤ X ├───────■──┤ X ├──────░─┤ H ├\r\n └───┘ ░ ├───┤ ░ ├───┤┌───┐┌─┴─┐├───┤┌───┐ ░ ├───┤\r\n state_1: ──────░─┤ H ├─░─┤ X ├┤ H ├┤ X ├┤ H ├┤ X ├─░─┤ H ├\r\n ░ └───┘ ░ └───┘└───┘└───┘└───┘└───┘ ░ └───┘\r\n\r\n >>> oracle = QuantumCircuit(1)\r\n >>> oracle.z(0) # the qubit state |1> is the good state\r\n >>> state_preparation = QuantumCircuit(1)\r\n >>> state_preparation.ry(0.2, 0) # non-uniform state preparation\r\n >>> grover_op = GroverOperator(oracle, state_preparation)\r\n >>> grover_op.draw()\r\n ┌───┐┌──────────┐┌───┐┌───┐┌───┐┌─────────┐\r\n state_0: ┤ Z ├┤ RY(-0.2) ├┤ X ├┤ Z ├┤ X ├┤ RY(0.2) ├\r\n └───┘└──────────┘└───┘└───┘└───┘└─────────┘\r\n\r\n >>> oracle = QuantumCircuit(4)\r\n >>> oracle.z(3)\r\n >>> reflection_qubits = [0, 3]\r\n >>> state_preparation = QuantumCircuit(4)\r\n >>> state_preparation.cry(0.1, 0, 3)\r\n >>> state_preparation.ry(0.5, 3)\r\n >>> grover_op = GroverOperator(oracle, state_preparation,\r\n ... reflection_qubits=reflection_qubits)\r\n >>> grover_op.draw()\r\n ┌───┐ ┌───┐\r\n state_0: ──────────────────────■──────┤ X ├───────■──┤ X ├──────────■────────────────\r\n │ └───┘ │ └───┘ │\r\n state_1: ──────────────────────┼──────────────────┼─────────────────┼────────────────\r\n │ │ │\r\n state_2: ──────────────────────┼──────────────────┼─────────────────┼────────────────\r\n ┌───┐┌──────────┐┌────┴─────┐┌───┐┌───┐┌─┴─┐┌───┐┌───┐┌────┴────┐┌─────────┐\r\n state_3: ┤ Z ├┤ RY(-0.5) ├┤ RY(-0.1) ├┤ X ├┤ H ├┤ X ├┤ H ├┤ X ├┤ RY(0.1) ├┤ RY(0.5) ├\r\n └───┘└──────────┘└──────────┘└───┘└───┘└───┘└───┘└───┘└─────────┘└─────────┘\r\n\r\n >>> mark_state = Statevector.from_label('011')\r\n >>> diffuse_operator = 2 * DensityMatrix.from_label('000') - Operator.from_label('III')\r\n >>> grover_op = GroverOperator(oracle=mark_state, zero_reflection=diffuse_operator)\r\n >>> grover_op.draw(fold=70)\r\n ┌─────────────────┐ ┌───┐ »\r\n state_0: ┤0 ├──────┤ H ├──────────────────────────»\r\n │ │┌─────┴───┴─────┐ ┌───┐ »\r\n state_1: ┤1 UCRZ(0,pi,0,0) ├┤0 ├─────┤ H ├──────────»\r\n │ ││ UCRZ(pi/2,0) │┌────┴───┴────┐┌───┐»\r\n state_2: ┤2 ├┤1 ├┤ UCRZ(-pi/4) ├┤ H ├»\r\n └─────────────────┘└───────────────┘└─────────────┘└───┘»\r\n « ┌─────────────────┐ ┌───┐\r\n «state_0: ┤0 ├──────┤ H ├─────────────────────────\r\n « │ │┌─────┴───┴─────┐ ┌───┐\r\n «state_1: ┤1 UCRZ(pi,0,0,0) ├┤0 ├────┤ H ├──────────\r\n « │ ││ UCRZ(pi/2,0) │┌───┴───┴────┐┌───┐\r\n «state_2: ┤2 ├┤1 ├┤ UCRZ(pi/4) ├┤ H ├\r\n « └─────────────────┘└───────────────┘└────────────┘└───┘\r\n\r\n References:\r\n [1]: L. K. Grover (1996), A fast quantum mechanical algorithm for database search,\r\n `arXiv:quant-ph/9605043 <https://arxiv.org/abs/quant-ph/9605043>`_.\r\n [2]: I. Chuang & M. Nielsen, Quantum Computation and Quantum Information,\r\n Cambridge: Cambridge University Press, 2000. Chapter 6.1.2.\r\n [3]: Brassard, G., Hoyer, P., Mosca, M., & Tapp, A. (2000).\r\n Quantum Amplitude Amplification and Estimation.\r\n `arXiv:quant-ph/0005055 <http://arxiv.org/abs/quant-ph/0005055>`_.\r\n \"\"\"\r\n\r\n def __init__(\r\n self,\r\n # oracle: Union[QuantumCircuit, Statevector],\r\n oracle: QuantumCircuit,\r\n state_preparation: Optional[QuantumCircuit] = None,\r\n # zero_reflection: Optional[Union[QuantumCircuit, DensityMatrix, Operator]] = None,\r\n zero_reflection: Optional[Union[QuantumCircuit, Operator]] = None,\r\n reflection_qubits: Optional[List[int]] = None,\r\n insert_barriers: bool = False,\r\n mcx_mode: str = \"noancilla\",\r\n name: str = \"Q\",\r\n ) -> None:\r\n r\"\"\"\r\n Args:\r\n oracle: The phase oracle implementing a reflection about the bad state. Note that this\r\n is not a bitflip oracle, see the docstring for more information.\r\n state_preparation: The operator preparing the good and bad state.\r\n For Grover's algorithm, this is a n-qubit Hadamard gate and for amplitude\r\n amplification or estimation the operator :math:`\\mathcal{A}`.\r\n zero_reflection: The reflection about the zero state, :math:`\\mathcal{S}_0`.\r\n reflection_qubits: Qubits on which the zero reflection acts on.\r\n insert_barriers: Whether barriers should be inserted between the reflections and A.\r\n mcx_mode: The mode to use for building the default zero reflection.\r\n name: The name of the circuit.\r\n \"\"\"\r\n super().__init__(name=name)\r\n\r\n # store inputs\r\n # if isinstance(oracle, Statevector):\r\n # from qiskit.circuit.library import Diagonal # pylint: disable=cyclic-import\r\n\r\n # oracle = Diagonal((-1) ** oracle.data)\r\n self._oracle = oracle\r\n\r\n # if isinstance(zero_reflection, (Operator, DensityMatrix)):\r\n # from qiskit.circuit.library import Diagonal # pylint: disable=cyclic-import\r\n\r\n # zero_reflection = Diagonal(zero_reflection.data.diagonal())\r\n self._zero_reflection = zero_reflection\r\n\r\n self._reflection_qubits = reflection_qubits\r\n self._state_preparation = state_preparation\r\n self._insert_barriers = insert_barriers\r\n self._mcx_mode = mcx_mode\r\n\r\n # build circuit\r\n self._build()\r\n\r\n @property\r\n def reflection_qubits(self):\r\n \"\"\"Reflection qubits, on which S0 is applied (if S0 is not user-specified).\"\"\"\r\n if self._reflection_qubits is not None:\r\n return self._reflection_qubits\r\n\r\n num_state_qubits = self.oracle.num_qubits - self.oracle.num_ancillas\r\n return list(range(num_state_qubits))\r\n\r\n @property\r\n def zero_reflection(self) -> QuantumCircuit:\r\n \"\"\"The subcircuit implementing the reflection about 0.\"\"\"\r\n if self._zero_reflection is not None:\r\n return self._zero_reflection\r\n\r\n num_state_qubits = self.oracle.num_qubits - self.oracle.num_ancillas\r\n return _zero_reflection(num_state_qubits, self.reflection_qubits, self._mcx_mode)\r\n\r\n @property\r\n def state_preparation(self) -> QuantumCircuit:\r\n \"\"\"The subcircuit implementing the A operator or Hadamards.\"\"\"\r\n if self._state_preparation is not None:\r\n return self._state_preparation\r\n\r\n num_state_qubits = self.oracle.num_qubits - self.oracle.num_ancillas\r\n hadamards = QuantumCircuit(num_state_qubits, name=\"H\")\r\n # apply Hadamards only on reflection qubits, rest will cancel out\r\n hadamards.h(self.reflection_qubits)\r\n return hadamards\r\n\r\n @property\r\n def oracle(self):\r\n \"\"\"The oracle implementing a reflection about the bad state.\"\"\"\r\n return self._oracle\r\n\r\n def _build(self):\r\n num_state_qubits = self.oracle.num_qubits - self.oracle.num_ancillas\r\n self.add_register(QuantumRegister(num_state_qubits, name=\"state\"))\r\n num_ancillas = numpy.max(\r\n [\r\n self.oracle.num_ancillas,\r\n self.zero_reflection.num_ancillas,\r\n self.state_preparation.num_ancillas,\r\n ]\r\n )\r\n if num_ancillas > 0:\r\n self.add_register(AncillaRegister(num_ancillas, name=\"ancilla\"))\r\n\r\n self.compose(self.oracle, list(range(self.oracle.num_qubits)), inplace=True)\r\n if self._insert_barriers:\r\n self.barrier()\r\n self.compose(\r\n self.state_preparation.inverse(),\r\n list(range(self.state_preparation.num_qubits)),\r\n inplace=True,\r\n )\r\n if self._insert_barriers:\r\n self.barrier()\r\n self.compose(\r\n self.zero_reflection, list(range(self.zero_reflection.num_qubits)), inplace=True\r\n )\r\n if self._insert_barriers:\r\n self.barrier()\r\n self.compose(\r\n self.state_preparation, list(range(self.state_preparation.num_qubits)), inplace=True\r\n )\r\n\r\n # minus sign\r\n self.global_phase = numpy.pi\r\n\r\n\r\n# TODO use the oracle compiler or the bit string oracle\r\ndef _zero_reflection(\r\n num_state_qubits: int, qubits: List[int], mcx_mode: Optional[str] = None\r\n) -> QuantumCircuit:\r\n qr_state = QuantumRegister(num_state_qubits, \"state\")\r\n reflection = QuantumCircuit(qr_state, name=\"S_0\")\r\n\r\n num_ancillas = MCXGate.get_num_ancilla_qubits(len(qubits) - 1, mcx_mode)\r\n if num_ancillas > 0:\r\n qr_ancilla = AncillaRegister(num_ancillas, \"ancilla\")\r\n reflection.add_register(qr_ancilla)\r\n else:\r\n qr_ancilla = []\r\n\r\n reflection.x(qubits)\r\n if len(qubits) == 1:\r\n reflection.z(0) # MCX does not allow 0 control qubits, therefore this is separate\r\n else:\r\n reflection.h(qubits[-1])\r\n reflection.mcx(qubits[:-1], qubits[-1], qr_ancilla[:], mode=mcx_mode)\r\n reflection.h(qubits[-1])\r\n reflection.x(qubits)\r\n\r\n return reflection\r\n" ]
[ [ "numpy.max" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
XiaoquinNUDT/Three-SNN-learning-algorithms-in-Brian2
[ "b7a5b0aba03172cdc04e738f02a949c373c1aac2" ]
[ "Spike generation/spike_recorder_focal.py" ]
[ "\"\"\"\nload the dataset example and return the maximum image size, which is used to definite the spike generation network;\nimages with different size are focused onto the center of the spike generation network;\nthe generated poisson spikes are recorded and saved for further use.\n\"\"\"\n\"\"\"\non 12th November\nby xiaoquinNUDT\nversion 0.0\n\"\"\"\n\"\"\"\ntest: no\n\"\"\"\n\"\"\"\noptimization record:\n\"\"\"\n##-----------------------------------------------------------------------------------------\n## module import\n##-----------------------------------------------------------------------------------------\nimport brian2 as b2\nfrom brian2 import *\nimport numpy as np\nimport cPickle as pickle \nimport os\nimport sys \nfrom struct import unpack \nnp.set_printoptions(threshold = np.inf)\n##-----------------------------------------------------------------------------------------\n## code generation device setup \n##-----------------------------------------------------------------------------------------\nb2.defaultclock.dt = 0.2*b2.ms\nb2.core.default_float_dtype = float64 ### reconsider\nb2.core.default_integer_dtype = int16 ### retest\ncodegen.target = 'cython' # default 'auto', other setting include numpy, weave, cython\n#clear_cache('cython') #clear the disk cache manually, or use the clear_cache function\ncodegen.cpp_compiler = 'gcc'\ncodegen.cpp_extra_compile_args_gcc = ['-ffast-math -march=native']\n## Cython runtime codegen preferences\n''' \nLocation of the cache directory for Cython files. By default, \nwill be stored in a brian_extensions subdirectory \nwhere Cython inline stores its temporary files (the result of get_cython_cache_dir()).\n'''\ncodegen.runtime_cython_cache_dir = None\ncodegen.runtime_cython_delete_source_files = True\ncodegen.runtime_cython_multiprocess_safe = True\n##-----------------------------------------------------------------------------------------\n## self-definition method \n##-----------------------------------------------------------------------------------------\ndef get_dataset_example_mnist(path_dataset, name_dataset, using_test_dataset):\n \"\"\"\n read input images (vector), dump into \n '.pickle' format for next load, and return it as a numpy array.\n \"\"\"\n flag_dataloaded = 0\n if name_dataset != 'mnist_test_example' and name_dataset != 'mnist_train_example':\n raise Exception('You have provide the wrong dataset name or path, please check carefully')\n else:\n dataset_path_name = path_dataset + name_dataset\n if os.path.isfile('%s.pickle' % dataset_path_name): \n example = pickle.load(open('%s.pickle' % dataset_path_name))\n flag_dataloaded = 1\n else:\n flag_datasetsource = os.path.isfile(path_dataset+'train-images.idx3-ubyte') & \\\n os.path.isfile(path_dataset+'train-labels.idx1-ubyte') & \\\n os.path.isfile(path_dataset+'t10k-images.idx3-ubyte') & \\\n os.path.isfile(path_dataset+'t10k-labels.idx1-ubyte')\n if flag_datasetsource == False:\n raise Exception(\"You haven't downloaded the dataset into the %s!\" % path_dataset)\n else:\n if using_test_dataset:\n image = open(path_dataset+'t10k-images.idx3-ubyte', 'rb')\n else:\n image = open(path_dataset+'train-images.idx3-ubyte', 'rb')\n # get metadata for images \n image.read(4) # skip the magic number\n num_image = unpack('>I', image.read(4))[0]\n height_image = unpack('>I', image.read(4))[0]\n length_image = unpack('>I', image.read(4))[0]\n example = np.zeros((num_image, height_image, length_image), dtype = np.uint8)\n for i in xrange(num_image):\n example[i] = [[unpack('>B', image.read(1))[0] for m in xrange(length_image)] for n in xrange(height_image)]\n pickle.dump(example, open('%s.pickle' % dataset_path_name, 'wb'))\n # the dataset has been readed and processed\n flag_dataloaded = 1\n if flag_dataloaded == 0:\n raise Exception('Failed to load the required dataset, please check the name_dataset and other printed information!')\n else:\n return example\n## file system \npath_dataset = '../dataset_mnist/'\nspike_record_path = './'\n## input parameter\nusing_test_dataset = bool(int(sys.argv[1]))\nprint(using_test_dataset)\nnum_example = int(sys.argv[2])\nprint(num_example)\nnum_iteration = int(sys.argv[3])\nprint(num_iteration)\n\nheight_receptive_field = 28\nlength_receptive_field = 28\n\nif using_test_dataset:\n num_per_dataset = 10000\n name_dataset = 'mnist_test_example'\n name_spike_record = 'mnist_spike_record_test'\nelse:\n num_per_dataset = 60000\n name_dataset = 'mnist_train_example'\n name_spike_record = 'mnist_spike_record_train'\n## network setting parameters\ninput_intensity = 2.0\npopulation_IN = height_receptive_field * length_receptive_field\nworking_time = 350 * b2.ms\nresting_time = 150 * b2.ms\nneuron_group_record = {}\nspike_monitor_record = {}\nname_neuron_group = 'Poisson_spike'\n## create input poisson spike train \nneuron_group_record[name_neuron_group] = b2.PoissonGroup(population_IN, 0*Hz)\nspike_monitor_record[name_neuron_group] = b2.SpikeMonitor(neuron_group_record[name_neuron_group])\n\nnetwork_record = b2.Network()\nfor obj_sim in [neuron_group_record, spike_monitor_record]:\n for key in obj_sim:\n network_record.add(obj_sim[key])\n## dataset loading and record the input poisson spike\ninput_example = get_dataset_example_mnist(path_dataset, name_dataset, using_test_dataset) \nnumber_example = 0 \nwhile number_example < num_example:\n input_image = input_example[(number_example + num_iteration * num_example) % num_per_dataset]\n height_example, length_example = input_image.shape\n length_margin = int((length_receptive_field - length_example)/2)\n height_margin = int((height_receptive_field - height_example)/2)\n input_rate = np.zeros((height_receptive_field, length_receptive_field), dtype = np.float32)\n for i in xrange(height_example):\n for j in xrange(length_example):\n input_rate[i + height_margin, j + length_margin] = input_image[i, j]\n neuron_group_record[name_neuron_group].rates = input_rate.flatten() / 8.0 * input_intensity * Hz\n network_record.run(working_time, report = 'text')\n neuron_group_record[name_neuron_group].rates = 0*Hz\n network_record.run(resting_time)\n number_example += 1\nspike_index = np.asarray(spike_monitor_record[name_neuron_group].i, dtype = np.int16)\nspike_time = np.asarray(spike_monitor_record[name_neuron_group].t, dtype = np.float64)\nif using_test_dataset:\n spike_record_path_name = spike_record_path + name_spike_record + '_' + str(num_example)\nelse: \n spike_record_path_name = spike_record_path + name_spike_record + '_' + str(num_example) + '_' + str(num_iteration)\nfile_spike_record = open('%s.pickle' % spike_record_path_name, 'wb')\npickle.dump(spike_index, file_spike_record)\npickle.dump(spike_time, file_spike_record)\nfile_spike_record.close()\n" ]
[ [ "numpy.asarray", "numpy.set_printoptions", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
BG4WCE/keras-yolo3
[ "be5afc9a8ac7c353941072960e1c099009946895" ]
[ "yolo3_video.py" ]
[ "import argparse\nimport os\nimport numpy as np\nfrom keras.layers import Conv2D, Input, BatchNormalization, LeakyReLU, ZeroPadding2D, UpSampling2D\nfrom keras.layers.merge import add, concatenate\nfrom keras.models import Model\nimport struct\nimport cv2\nimport time\nfrom pathlib import Path\n\n#np.set_printoptions(threshold=np.nan)\nnp.set_printoptions(threshold=30)\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n\nargparser = argparse.ArgumentParser(\n description='test yolov3 network with coco weights')\n\nargparser.add_argument(\n '-w',\n '--weights',\n help='path to weights file')\n\nargparser.add_argument(\n '-v',\n '--video',\n help='path to video file')\n\nclass WeightReader:\n def __init__(self, weight_file):\n with open(weight_file, 'rb') as w_f:\n major, = struct.unpack('i', w_f.read(4))\n minor, = struct.unpack('i', w_f.read(4))\n revision, = struct.unpack('i', w_f.read(4))\n\n if (major*10 + minor) >= 2 and major < 1000 and minor < 1000:\n w_f.read(8)\n else:\n w_f.read(4)\n\n transpose = (major > 1000) or (minor > 1000)\n \n binary = w_f.read()\n\n self.offset = 0\n self.all_weights = np.frombuffer(binary, dtype='float32')\n \n def read_bytes(self, size):\n self.offset = self.offset + size\n return self.all_weights[self.offset-size:self.offset]\n\n def load_weights(self, model):\n for i in range(106):\n try:\n conv_layer = model.get_layer('conv_' + str(i))\n print(\"loading weights of convolution #\" + str(i))\n\n if i not in [81, 93, 105]:\n norm_layer = model.get_layer('bnorm_' + str(i))\n\n size = np.prod(norm_layer.get_weights()[0].shape)\n\n beta = self.read_bytes(size) # bias\n gamma = self.read_bytes(size) # scale\n mean = self.read_bytes(size) # mean\n var = self.read_bytes(size) # variance \n\n weights = norm_layer.set_weights([gamma, beta, mean, var]) \n\n if len(conv_layer.get_weights()) > 1:\n bias = self.read_bytes(np.prod(conv_layer.get_weights()[1].shape))\n kernel = self.read_bytes(np.prod(conv_layer.get_weights()[0].shape))\n \n kernel = kernel.reshape(list(reversed(conv_layer.get_weights()[0].shape)))\n kernel = kernel.transpose([2,3,1,0])\n conv_layer.set_weights([kernel, bias])\n else:\n kernel = self.read_bytes(np.prod(conv_layer.get_weights()[0].shape))\n kernel = kernel.reshape(list(reversed(conv_layer.get_weights()[0].shape)))\n kernel = kernel.transpose([2,3,1,0])\n conv_layer.set_weights([kernel])\n except ValueError:\n print(\"no convolution #\" + str(i)) \n \n def reset(self):\n self.offset = 0\n\nclass BoundBox:\n def __init__(self, xmin, ymin, xmax, ymax, objness = None, classes = None):\n self.xmin = xmin\n self.ymin = ymin\n self.xmax = xmax\n self.ymax = ymax\n \n self.objness = objness\n self.classes = classes\n\n self.label = -1\n self.score = -1\n\n def get_label(self):\n if self.label == -1:\n self.label = np.argmax(self.classes)\n \n return self.label\n \n def get_score(self):\n if self.score == -1:\n self.score = self.classes[self.get_label()]\n \n return self.score\n\ndef _conv_block(inp, convs, skip=True):\n x = inp\n count = 0\n \n for conv in convs:\n if count == (len(convs) - 2) and skip:\n skip_connection = x\n count += 1\n \n if conv['stride'] > 1: x = ZeroPadding2D(((1,0),(1,0)))(x) # peculiar padding as darknet prefer left and top\n x = Conv2D(conv['filter'], \n conv['kernel'], \n strides=conv['stride'], \n padding='valid' if conv['stride'] > 1 else 'same', # peculiar padding as darknet prefer left and top\n name='conv_' + str(conv['layer_idx']), \n use_bias=False if conv['bnorm'] else True)(x)\n if conv['bnorm']: x = BatchNormalization(epsilon=0.001, name='bnorm_' + str(conv['layer_idx']))(x)\n if conv['leaky']: x = LeakyReLU(alpha=0.1, name='leaky_' + str(conv['layer_idx']))(x)\n\n return add([skip_connection, x]) if skip else x\n\ndef _interval_overlap(interval_a, interval_b):\n x1, x2 = interval_a\n x3, x4 = interval_b\n\n if x3 < x1:\n if x4 < x1:\n return 0\n else:\n return min(x2,x4) - x1\n else:\n if x2 < x3:\n return 0\n else:\n return min(x2,x4) - x3 \n\ndef _sigmoid(x):\n return 1. / (1. + np.exp(-x))\n\ndef bbox_iou(box1, box2):\n intersect_w = _interval_overlap([box1.xmin, box1.xmax], [box2.xmin, box2.xmax])\n intersect_h = _interval_overlap([box1.ymin, box1.ymax], [box2.ymin, box2.ymax])\n \n intersect = intersect_w * intersect_h\n\n w1, h1 = box1.xmax-box1.xmin, box1.ymax-box1.ymin\n w2, h2 = box2.xmax-box2.xmin, box2.ymax-box2.ymin\n \n union = w1*h1 + w2*h2 - intersect\n \n return float(intersect) / union\n\ndef make_yolov3_model():\n input_image = Input(shape=(None, None, 3))\n\n # Layer 0 => 4\n x = _conv_block(input_image, [{'filter': 32, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 0},\n {'filter': 64, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 1},\n {'filter': 32, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 2},\n {'filter': 64, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 3}])\n\n # Layer 5 => 8\n x = _conv_block(x, [{'filter': 128, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 5},\n {'filter': 64, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 6},\n {'filter': 128, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 7}])\n\n # Layer 9 => 11\n x = _conv_block(x, [{'filter': 64, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 9},\n {'filter': 128, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 10}])\n\n # Layer 12 => 15\n x = _conv_block(x, [{'filter': 256, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 12},\n {'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 13},\n {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 14}])\n\n # Layer 16 => 36\n for i in range(7):\n x = _conv_block(x, [{'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 16+i*3},\n {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 17+i*3}])\n \n skip_36 = x\n \n # Layer 37 => 40\n x = _conv_block(x, [{'filter': 512, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 37},\n {'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 38},\n {'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 39}])\n\n # Layer 41 => 61\n for i in range(7):\n x = _conv_block(x, [{'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 41+i*3},\n {'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 42+i*3}])\n \n skip_61 = x\n \n # Layer 62 => 65\n x = _conv_block(x, [{'filter': 1024, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 62},\n {'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 63},\n {'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 64}])\n\n # Layer 66 => 74\n for i in range(3):\n x = _conv_block(x, [{'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 66+i*3},\n {'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 67+i*3}])\n \n # Layer 75 => 79\n x = _conv_block(x, [{'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 75},\n {'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 76},\n {'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 77},\n {'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 78},\n {'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 79}], skip=False)\n\n # Layer 80 => 82\n yolo_82 = _conv_block(x, [{'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 80},\n {'filter': 255, 'kernel': 1, 'stride': 1, 'bnorm': False, 'leaky': False, 'layer_idx': 81}], skip=False)\n\n # Layer 83 => 86\n x = _conv_block(x, [{'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 84}], skip=False)\n x = UpSampling2D(2)(x)\n x = concatenate([x, skip_61])\n\n # Layer 87 => 91\n x = _conv_block(x, [{'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 87},\n {'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 88},\n {'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 89},\n {'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 90},\n {'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 91}], skip=False)\n\n # Layer 92 => 94\n yolo_94 = _conv_block(x, [{'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 92},\n {'filter': 255, 'kernel': 1, 'stride': 1, 'bnorm': False, 'leaky': False, 'layer_idx': 93}], skip=False)\n\n # Layer 95 => 98\n x = _conv_block(x, [{'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 96}], skip=False)\n x = UpSampling2D(2)(x)\n x = concatenate([x, skip_36])\n\n # Layer 99 => 106\n yolo_106 = _conv_block(x, [{'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 99},\n {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 100},\n {'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 101},\n {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 102},\n {'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 103},\n {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 104},\n {'filter': 255, 'kernel': 1, 'stride': 1, 'bnorm': False, 'leaky': False, 'layer_idx': 105}], skip=False)\n\n model = Model(input_image, [yolo_82, yolo_94, yolo_106]) \n return model\n\ndef preprocess_input(image, net_h, net_w):\n #new_h, new_w, _ = image.shape\n new_h = 480\n new_w = 640\n\n # determine the new size of the image\n if (float(net_w)/new_w) < (float(net_h)/new_h):\n new_h = (new_h * net_w)/new_w\n new_w = net_w\n else:\n new_w = (new_w * net_h)/new_h\n new_h = net_h\n\n # resize the image to the new size\n resized = cv2.resize(image[:,:,::-1]/255., (int(new_w), int(new_h)))\n\n # embed the image into the standard letter box\n new_image = np.ones((net_h, net_w, 3)) * 0.5\n new_image[int((net_h-new_h)//2):int((net_h+new_h)//2), int((net_w-new_w)//2):int((net_w+new_w)//2), :] = resized\n new_image = np.expand_dims(new_image, 0)\n\n return new_image\n\ndef decode_netout(netout, anchors, obj_thresh, nms_thresh, net_h, net_w):\n grid_h, grid_w = netout.shape[:2]\n nb_box = 3\n netout = netout.reshape((grid_h, grid_w, nb_box, -1))\n nb_class = netout.shape[-1] - 5\n\n boxes = []\n\n netout[..., :2] = _sigmoid(netout[..., :2])\n netout[..., 4:] = _sigmoid(netout[..., 4:])\n netout[..., 5:] = netout[..., 4][..., np.newaxis] * netout[..., 5:]\n netout[..., 5:] *= netout[..., 5:] > obj_thresh\n\n for i in range(grid_h*grid_w):\n row = i / grid_w\n col = i % grid_w\n \n for b in range(nb_box):\n # 4th element is objectness score\n objectness = netout[int(row)][int(col)][b][4]\n #objectness = netout[..., :4]\n \n if(objectness.all() <= obj_thresh): continue\n \n # first 4 elements are x, y, w, and h\n x, y, w, h = netout[int(row)][int(col)][b][:4]\n\n x = (col + x) / grid_w # center position, unit: image width\n y = (row + y) / grid_h # center position, unit: image height\n w = anchors[2 * b + 0] * np.exp(w) / net_w # unit: image width\n h = anchors[2 * b + 1] * np.exp(h) / net_h # unit: image height \n \n # last elements are class probabilities\n classes = netout[int(row)][col][b][5:]\n \n box = BoundBox(x-w/2, y-h/2, x+w/2, y+h/2, objectness, classes)\n #box = BoundBox(x-w/2, y-h/2, x+w/2, y+h/2, None, classes)\n\n boxes.append(box)\n\n return boxes\n\ndef correct_yolo_boxes(boxes, image_h, image_w, net_h, net_w):\n if (float(net_w)/image_w) < (float(net_h)/image_h):\n new_w = net_w\n new_h = (image_h*net_w)/image_w\n else:\n new_h = net_w\n new_w = (image_w*net_h)/image_h\n \n for i in range(len(boxes)):\n x_offset, x_scale = (net_w - new_w)/2./net_w, float(new_w)/net_w\n y_offset, y_scale = (net_h - new_h)/2./net_h, float(new_h)/net_h\n \n boxes[i].xmin = int((boxes[i].xmin - x_offset) / x_scale * image_w)\n boxes[i].xmax = int((boxes[i].xmax - x_offset) / x_scale * image_w)\n boxes[i].ymin = int((boxes[i].ymin - y_offset) / y_scale * image_h)\n boxes[i].ymax = int((boxes[i].ymax - y_offset) / y_scale * image_h)\n \ndef do_nms(boxes, nms_thresh):\n if len(boxes) > 0:\n nb_class = len(boxes[0].classes)\n else:\n return\n \n for c in range(nb_class):\n sorted_indices = np.argsort([-box.classes[c] for box in boxes])\n\n for i in range(len(sorted_indices)):\n index_i = sorted_indices[i]\n\n if boxes[index_i].classes[c] == 0: continue\n\n for j in range(i+1, len(sorted_indices)):\n index_j = sorted_indices[j]\n\n if bbox_iou(boxes[index_i], boxes[index_j]) >= nms_thresh:\n boxes[index_j].classes[c] = 0\n \ndef draw_boxes(image, boxes, labels, obj_thresh):\n #highest_conf_label = ''\n #highest_conf = 0\n for box in boxes:\n label_str = ''\n label = -1\n \n for i in range(len(labels)):\n if box.classes[i] > obj_thresh:\n label_str += labels[i]\n label = i\n print(labels[i] + ': ' + str(box.classes[i]*100) + '%')\n #if box.classes[i] > highest_conf:\n # highest_conf = box.classes[i]\n # highest_conf_label = labels[i]\n \n if label >= 0:\n cv2.rectangle(image, (box.xmin,box.ymin), (box.xmax,box.ymax), (0,255,0), 3)\n #print(type(box.get_score()))\n #print(np.format_float_positional(box.get_score(), precision=2))\n cv2.putText(image, \n label_str + ' ' + str(np.format_float_positional(box.get_score(), precision=2)), \n (box.xmin, box.ymin - 13), \n cv2.FONT_HERSHEY_SIMPLEX, \n 1e-3 * image.shape[0], \n (0,255,0), 2)\n \n return image \n\ndef _main_(args):\n weights_path = args.weights\n video_path = args.video\n\n # set some parameters\n net_h, net_w = 416, 416\n obj_thresh, nms_thresh = 0.65, 0.45\n anchors = [[116,90, 156,198, 373,326], [30,61, 62,45, 59,119], [10,13, 16,30, 33,23]]\n labels = [\"person\", \"bicycle\", \"car\", \"motorbike\", \"aeroplane\", \"bus\", \"train\", \"truck\", \\\n \"boat\", \"traffic light\", \"fire hydrant\", \"stop sign\", \"parking meter\", \"bench\", \\\n \"bird\", \"cat\", \"dog\", \"horse\", \"sheep\", \"cow\", \"elephant\", \"bear\", \"zebra\", \"giraffe\", \\\n \"backpack\", \"umbrella\", \"handbag\", \"tie\", \"suitcase\", \"frisbee\", \"skis\", \"snowboard\", \\\n \"sports ball\", \"kite\", \"baseball bat\", \"baseball glove\", \"skateboard\", \"surfboard\", \\\n \"tennis racket\", \"bottle\", \"wine glass\", \"cup\", \"fork\", \"knife\", \"spoon\", \"bowl\", \"banana\", \\\n \"apple\", \"sandwich\", \"orange\", \"broccoli\", \"carrot\", \"hot dog\", \"pizza\", \"donut\", \"cake\", \\\n \"chair\", \"sofa\", \"pottedplant\", \"bed\", \"diningtable\", \"toilet\", \"tvmonitor\", \"laptop\", \"mouse\", \\\n \"remote\", \"keyboard\", \"cell phone\", \"microwave\", \"oven\", \"toaster\", \"sink\", \"refrigerator\", \\\n \"book\", \"clock\", \"vase\", \"scissors\", \"teddy bear\", \"hair drier\", \"toothbrush\"]\n\n # make the yolov3 model to predict 80 classes on COCO\n yolov3 = make_yolov3_model()\n\n # load the weights trained on COCO into the model\n weight_reader = WeightReader(weights_path)\n weight_reader.load_weights(yolov3)\n '''\n # set webcam\n cap = cv2.VideoCapture(1)\n while(True):\n ret, image = cap.read()\n #image_h, image_w, _ = image.shape\n image_w = cap.get(3)\n image_h = cap.get(4)\n if cv2.waitKey(1) & 0xFF == ord(' '):\n new_image = preprocess_input(image, net_h, net_w)\n yolos = yolov3.predict(new_image)\n boxes = []\n for i in range(len(yolos)):\n boxes += decode_netout(yolos[i][0], anchors[i], obj_thresh, nms_thresh, net_h, net_w)\n correct_yolo_boxes(boxes, image_h, image_w, net_h, net_w)\n do_nms(boxes, nms_thresh)\n draw_boxes_play_music(image, boxes, labels, obj_thresh)\n cv2.imshow('frame',image)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n cap.release()\n cv2.destroyAllWindows()\n ''' \n\n # preprocess the video\n cap = cv2.VideoCapture(video_path)\n print(\"open video file from\", video_path)\n if Path(video_path).is_file():\n print(\"Video file exists\")\n else:\n print(\"cannot find video file\")\n print(cap.isOpened())\n while(cap.isOpened()):\n ret, image = cap.read()\n image_w = cap.get(3)\n image_h = cap.get(4)\n image = cv2.flip(image, 0)\n new_image = preprocess_input(image, net_h, net_w)\n yolos = yolov3.predict(new_image)\n boxes = []\n\n for i in range(len(yolos)):\n # decode the output of the network\n boxes += decode_netout(yolos[i][0], anchors[i], obj_thresh, nms_thresh, net_h, net_w)\n\n # correct the sizes of the bounding boxes\n correct_yolo_boxes(boxes, image_h, image_w, net_h, net_w)\n\n # suppress non-maximal boxes\n do_nms(boxes, nms_thresh) \n\n # draw bounding boxes on the image using labels\n draw_boxes(image, boxes, labels, obj_thresh) \n \n # write the image with bounding boxes to video\n cv2.imshow('frame',image)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n cap.release()\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n args = argparser.parse_args()\n _main_(args)\n" ]
[ [ "numpy.expand_dims", "numpy.set_printoptions", "numpy.ones", "numpy.frombuffer", "numpy.argmax", "numpy.argsort", "numpy.exp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
acwooding/docmap_playground
[ "388c0f357cadb9b6e4b4b6e25fb131713111dc48" ]
[ "src/data/process_functions.py" ]
[ "\"\"\"\nCustom dataset processing/generation functions should be added to this file\n\"\"\"\n\nimport pathlib\nfrom sklearn.datasets import fetch_20newsgroups\nfrom functools import partial\n\nfrom src import workflow, paths\nfrom src.log import logger\nimport src.log.debug\n\nfrom tqdm.auto import tqdm\n\nfrom .. import paths\nfrom ..log import logger\n\n__all__ = [\n'process_20_newsgroups'\n]\n\n\ndef process_20_newsgroups(*, extract_dir='20_newsgroups',\n metadata=None, unpack_dir=None,\n opts={\"subset\":\"all\", \"remove\":\"('headers', 'footers', 'quotes')\"}):\n \"\"\"\n Process 20 newsgroups into (data, target, metadata) format.\n\n\n Parameters\n ----------\n unpack_dir: path\n The interim parent directory the dataset files have been unpacked into.\n extract_dir: str\n Name of the directory of the unpacked files relative to the unpack_dir. Note that\n opts: dict default {\"subset\":\"all\", \"remove\"=\"('headers', 'footers', 'quotes')\"}\n Options to pass to sklearn.datasets.fetch_20newsgroups.\n\n\n Returns\n -------\n A tuple:\n (data, target, additional_metadata)\n\n \"\"\"\n if metadata is None:\n metadata = {}\n\n if unpack_dir is None:\n unpack_dir = paths['interim_data_path']\n else:\n unpack_dir = pathlib.Path(unpack_dir)\n data_dir = unpack_dir / f\"{extract_dir}\"\n\n news = fetch_20newsgroups(**opts)\n metadata['target_names'] = news.target_names\n\n return news.data, news.target, metadata\n" ]
[ [ "sklearn.datasets.fetch_20newsgroups" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sunkisser/manim
[ "39673a80d7bbbea258c35ce5a1d37a0911aae4f1" ]
[ "manimlib/utils/rate_functions.py" ]
[ "from typing import Callable\n\nimport numpy as np\n\nfrom manimlib.utils.bezier import bezier\n\n\ndef linear(t: float) -> float:\n return t\n\n\ndef smooth(t: float) -> float:\n # Zero first and second derivatives at t=0 and t=1.\n # Equivalent to bezier([0, 0, 0, 1, 1, 1])\n s = 1 - t\n return (t**3) * (10 * s * s + 5 * s * t + t * t)\n\n\ndef rush_into(t: float) -> float:\n return 2 * smooth(0.5 * t)\n\n\ndef rush_from(t: float) -> float:\n return 2 * smooth(0.5 * (t + 1)) - 1\n\n\ndef slow_into(t: float) -> float:\n return np.sqrt(1 - (1 - t) * (1 - t))\n\n\ndef double_smooth(t: float) -> float:\n if t < 0.5:\n return 0.5 * smooth(2 * t)\n else:\n return 0.5 * (1 + smooth(2 * t - 1))\n\n\ndef there_and_back(t: float) -> float:\n new_t = 2 * t if t < 0.5 else 2 * (1 - t)\n return smooth(new_t)\n\n\ndef there_and_back_with_pause(t: float, pause_ratio: float = 1. / 3) -> float:\n a = 1. / pause_ratio\n if t < 0.5 - pause_ratio / 2:\n return smooth(a * t)\n elif t < 0.5 + pause_ratio / 2:\n return 1\n else:\n return smooth(a - a * t)\n\n\ndef running_start(t: float, pull_factor: float = -0.5) -> float:\n return bezier([0, 0, pull_factor, pull_factor, 1, 1, 1])(t)\n\n\ndef not_quite_there(\n func: Callable[[float], float] = smooth,\n proportion: float = 0.7\n) -> Callable[[float], float]:\n def result(t):\n return proportion * func(t)\n return result\n\n\ndef wiggle(t: float, wiggles: float = 2) -> float:\n return there_and_back(t) * np.sin(wiggles * np.pi * t)\n\n\ndef squish_rate_func(\n func: Callable[[float], float],\n a: float = 0.4,\n b: float = 0.6\n) -> Callable[[float], float]:\n def result(t):\n if a == b:\n return a\n elif t < a:\n return func(0)\n elif t > b:\n return func(1)\n else:\n return func((t - a) / (b - a))\n\n return result\n\n# Stylistically, should this take parameters (with default values)?\n# Ultimately, the functionality is entirely subsumed by squish_rate_func,\n# but it may be useful to have a nice name for with nice default params for\n# \"lingering\", different from squish_rate_func's default params\n\n\ndef lingering(t: float) -> float:\n return squish_rate_func(lambda t: t, 0, 0.8)(t)\n\n\ndef exponential_decay(t: float, half_life: float = 0.1) -> float:\n # The half-life should be rather small to minimize\n # the cut-off error at the end\n return 1 - np.exp(-t / half_life)\n" ]
[ [ "numpy.exp", "numpy.sqrt", "numpy.sin" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
TECHENGINESSRL/audio-super-res
[ "2f90a288e86ddca50c98c17b0513e73ab49087d3" ]
[ "src/models/layers/subpixel.py" ]
[ "import numpy as np\nimport tensorflow as tf\n\n# ----------------------------------------------------------------------------\n\ndef SubPixel1D_v2(I, r):\n \"\"\"One-dimensional subpixel upsampling layer\n\n Based on https://github.com/Tetrachrome/subpixel/blob/master/subpixel.py\n \"\"\"\n with tf.compat.v1.name_scope('subpixel'):\n bsize, a, r = I.get_shape().as_list()\n bsize = tf.shape(input=I)[0] # Handling Dimension(None) type for undefined batch dim\n X = tf.split(1, a, I) # a, [bsize, 1, r]\n if 'axis' in tf.squeeze.__code__.co_varnames:\n X = tf.concat(1, [tf.squeeze(x, axis=1) for x in X]) # bsize, a*r\n elif 'squeeze_dims' in tf.squeeze.__code__.co_varnames:\n X = tf.concat(1, [tf.squeeze(x, axis=[1]) for x in X]) # bsize, a*r\n else:\n raise Exception('Unsupported version of tensorflow')\n return tf.reshape(X, (bsize, a*r, 1))\n\ndef SubPixel1D(I, r):\n \"\"\"One-dimensional subpixel upsampling layer\n\n Calls a tensorflow function that directly implements this functionality.\n We assume input has dim (batch, width, r)\n \"\"\"\n with tf.compat.v1.name_scope('subpixel'):\n X = tf.transpose(a=I, perm=[2,1,0]) # (r, w, b)\n X = tf.batch_to_space(X, [r], [[0,0]]) # (1, r*w, b)\n X = tf.transpose(a=X, perm=[2,1,0])\n return X\n\ndef SubPixel1D_multichan(I, r):\n \"\"\"One-dimensional subpixel upsampling layer\n\n Calls a tensorflow function that directly implements this functionality.\n We assume input has dim (batch, width, r).\n\n Works with multiple channels: (B,L,rC) -> (B,rL,C)\n \"\"\"\n with tf.compat.v1.name_scope('subpixel'):\n _, w, rc = I.get_shape()\n assert rc % r == 0\n c = rc / r\n X = tf.transpose(a=I, perm=[2,1,0]) # (rc, w, b)\n X = tf.batch_to_space(X, [r], [[0,0]]) # (c, r*w, b)\n X = tf.transpose(a=X, perm=[2,1,0])\n return X\n\n# ----------------------------------------------------------------------------\n\n# demonstration\nif __name__ == \"__main__\":\n with tf.compat.v1.Session() as sess:\n x = np.arange(2*4*2).reshape(2, 4, 2)\n X = tf.compat.v1.placeholder(\"float32\", shape=(2, 4, 2), name=\"X\")\n Y = SubPixel1D(X, 2)\n y = sess.run(Y, feed_dict={X: x})\n\n print('single-channel:')\n print('original, element 0 (2 channels):', x[0,:,0], x[0,:,1])\n print('rescaled, element 1:', y[0,:,0])\n print()\n print('original, element 0 (2 channels) :', x[1,:,0], x[1,:,1])\n print('rescaled, element 1:', y[1,:,0])\n print()\n\n x = np.arange(2*4*4).reshape(2, 4, 4)\n X = tf.compat.v1.placeholder(\"float32\", shape=(2, 4, 4), name=\"X\")\n Y = SubPixel1D(X, 2)\n y = sess.run(Y, feed_dict={X: x})\n\n print('multichannel:')\n print('original, element 0 (4 channels):', x[0,:,0], x[0,:,1], x[0,:,2], x[0,:,3])\n print('rescaled, element 1:', y[0,:,0], y[0,:,1])\n print()\n print('original, element 0 (2 channels) :', x[1,:,0], x[1,:,1], x[1,:,2], x[1,:,3])\n print('rescaled, element 1:', y[1,:,0], y[1,:,1], end=' ')\n" ]
[ [ "tensorflow.transpose", "tensorflow.shape", "numpy.arange", "tensorflow.reshape", "tensorflow.squeeze", "tensorflow.compat.v1.Session", "tensorflow.compat.v1.placeholder", "tensorflow.batch_to_space", "tensorflow.split", "tensorflow.compat.v1.name_scope" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
SkyRd1/Statistical_Functions
[ "3c7a4bba91e43110567f0d2fd1089699d9038206" ]
[ "Mean_Std_Calculation.py" ]
[ "#Author: Sepehr Roudini.\r\n#Date: 02/05/2018.\r\n#University of Iowa.\r\n#Department of Chemical Engineering.\r\n#Purpose: Calculating mean and Std\r\n\r\n\r\n#--------------------------------------------------------------------------------------------#\r\n#Defining function and importing necessary libraries.\r\n#--------------------------------------------------------------------------------------------#\r\n\r\n##############################################################################################\r\n#Libraries used in this function are: numpy and math.\r\n##############################################################################################\r\n#Data: A 1d array of data.\r\n##############################################################################################\r\n#This functions returnes mean and standard\r\n#deviation of data.\r\n##############################################################################################\r\ndef Calculate_Mean_Std(Data):\r\n#numpy is for data manipulationt\r\n import numpy as np\r\n#--------------------------------------------------------------------------------------------#\r\n#--------------------------------------------------------------------------------------------#\r\n\r\n\r\n#--------------------------------------------------------------------------------------------#\r\n#Preparing data and quantile calculation\r\n#--------------------------------------------------------------------------------------------#\r\n#Calculating mean\r\n mean = np.sum(Data)/len(Data)\r\n#Calculating standard deviation\r\n std = np.sqrt(np.sum(((Data-mean)**2))/(len(Data)-1))\r\n return mean, std\r\n#--------------------------------------------------------------------------------------------#\r\n#--------------------------------------------------------------------------------------------#\r\n" ]
[ [ "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
CvlabAssignment/WRcan
[ "e77571472f5a3928b1e9cee5440d52f702e59a41" ]
[ "src/trainer.py" ]
[ "import os\nimport math\nfrom decimal import Decimal\n\nimport utility\n\nimport torch\nimport torch.nn.utils as utils\nfrom tqdm import tqdm\n\nclass Trainer():\n def __init__(self, args, loader, my_model, my_loss, ckp):\n self.args = args\n self.scale = args.scale\n\n self.ckp = ckp\n self.loader_train = loader.loader_train\n self.loader_test = loader.loader_test\n self.model = my_model\n self.loss = my_loss\n self.optimizer = utility.make_optimizer(args, self.model)\n \n self.flag_ae_loss = True if args.loss.lower().find('ae') >= 0 else False\n \n if self.args.precision == 'amp':\n self.scaler = torch.cuda.amp.GradScaler()\n\n if self.args.load != '':\n # To avoid \"UserWarning: Detected call of `lr_scheduler.step()` before `optimizer.step()`.\"\n # The 0 gradient value will not update any parameter of the model to train.\n self.optimizer.zero_grad()\n self.optimizer.step() \n self.optimizer.load(ckp.dir, epoch=len(ckp.log))\n\n self.error_last = 1e8\n\n def train(self):\n self.loss.step()\n epoch = self.optimizer.get_last_epoch() + 1\n lr = self.optimizer.get_lr()\n\n self.ckp.write_log(\n '[Epoch {}]\\tLearning rate: {:.2e}'.format(epoch, Decimal(lr))\n )\n self.loss.start_log()\n self.model.train()\n\n timer_data, timer_model = utility.timer(), utility.timer()\n # TEMP\n self.loader_train.dataset.set_scale(0)\n for batch, (lr, hr, _,) in enumerate(self.loader_train):\n lr, hr = self.prepare(lr, hr)\n if self.flag_ae_loss:\n hr, hr_ae = hr[:,:self.args.n_colors, ...], hr[:,self.args.n_colors:,...] \n else:\n hr_ae = None\n \n timer_data.hold()\n timer_model.tic()\n\n self.optimizer.zero_grad()\n if self.args.precision == 'amp':\n with torch.cuda.amp.autocast():\n sr = self.model(lr, 0)\n if self.flag_ae_loss:\n sr_ae = self._forward_auto_encoder(hr_ae, 0) \n else:\n sr_ae = None\n loss = self.loss(sr, hr, sr_ae, hr_ae)\n \n self.scaler.scale(loss).backward()\n else:\n sr = self.model(lr, 0)\n if self.flag_ae_loss:\n sr_ae = self._forward_auto_encoder(hr_ae, 0) \n else:\n sr_ae = None\n loss = self.loss(sr, hr, sr_ae, hr_ae)\n\n loss.backward()\n\n if self.args.gclip > 0:\n utils.clip_grad_value_(\n self.model.parameters(),\n self.args.gclip\n )\n \n if self.args.precision == 'amp':\n self.scaler.step(self.optimizer)\n self.scaler.update()\n else:\n self.optimizer.step()\n\n timer_model.hold()\n\n if (batch + 1) % self.args.print_every == 0:\n self.ckp.write_log('[{}/{}]\\t{}\\t{:.1f}+{:.1f}s'.format(\n (batch + 1) * self.args.batch_size,\n len(self.loader_train.dataset),\n self.loss.display_loss(batch),\n timer_model.release(),\n timer_data.release()))\n\n timer_data.tic()\n\n self.loss.end_log(len(self.loader_train))\n self.error_last = self.loss.log[-1, -1]\n self.optimizer.schedule()\n\n def test(self):\n torch.set_grad_enabled(False)\n\n epoch = self.optimizer.get_last_epoch()\n self.ckp.write_log('\\nEvaluation:')\n self.ckp.add_log(\n torch.zeros(1, len(self.loader_test), len(self.scale))\n )\n self.model.eval()\n\n timer_test = utility.timer()\n if self.args.save_results: self.ckp.begin_background()\n for idx_data, d in enumerate(self.loader_test):\n for idx_scale, scale in enumerate(self.scale):\n d.dataset.set_scale(idx_scale)\n for lr, hr, filename in tqdm(d, ncols=80):\n lr, hr = self.prepare(lr, hr)\n sr = self.model(lr, idx_scale)\n sr = utility.quantize(sr, self.args.rgb_range)\n\n save_list = [sr]\n self.ckp.log[-1, idx_data, idx_scale] += utility.calc_psnr(\n sr, hr, scale, self.args.rgb_range, dataset=d\n )\n if self.args.save_gt:\n save_list.extend([lr, hr])\n\n if self.args.save_results:\n self.ckp.save_results(d, filename[0], save_list, scale)\n\n self.ckp.log[-1, idx_data, idx_scale] /= len(d)\n best = self.ckp.log.max(0)\n self.ckp.write_log(\n '[{} x{}]\\tPSNR: {:.3f} (Best: {:.3f} @epoch {})'.format(\n d.dataset.name,\n scale,\n self.ckp.log[-1, idx_data, idx_scale],\n best[0][idx_data, idx_scale],\n best[1][idx_data, idx_scale] + 1\n )\n )\n\n self.ckp.write_log('Forward: {:.2f}s\\n'.format(timer_test.toc()))\n self.ckp.write_log('Saving...')\n\n if self.args.save_results:\n self.ckp.end_background()\n\n if not self.args.test_only:\n self.ckp.save(self, epoch, is_best=(best[1][0, 0] + 1 == epoch))\n\n self.ckp.write_log(\n 'Total: {:.2f}s\\n'.format(timer_test.toc()), refresh=True\n )\n\n torch.set_grad_enabled(True)\n\n def prepare(self, *args):\n device = torch.device('cpu' if self.args.cpu else 'cuda')\n def _prepare(tensor):\n if self.args.precision == 'half': tensor = tensor.half()\n return tensor.to(device)\n\n return [_prepare(a) for a in args]\n\n def terminate(self):\n if self.args.test_only:\n self.test()\n return True\n else:\n epoch = self.optimizer.get_last_epoch() + 1\n return epoch > self.args.epochs\n # return epoch >= self.args.epochs\n \n def _forward_auto_encoder(self, x, idx_scale):\n self.model.set_forward_ae_loss(True)\n x = self.model(x, idx_scale) \n self.model.set_forward_ae_loss(False)\n \n return x" ]
[ [ "torch.device", "torch.cuda.amp.GradScaler", "torch.set_grad_enabled", "torch.cuda.amp.autocast" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
marcovalenti/mmdetection
[ "215ea4174c1234ac4c3e23bf29020fc1cefc36ad" ]
[ "mmdet/models/roi_heads/bbox_heads/convfc_bbox_head.py" ]
[ "import torch.nn as nn\nimport torch.nn.functional as F\nimport torch\nfrom mmcv.cnn import ConvModule\nfrom mmcv.runner import force_fp32\n\nfrom mmdet.models.builder import HEADS, build_loss\nfrom mmdet.models.losses import accuracy\nfrom .bbox_head import BBoxHead\n\nfrom mmdet.core import multi_apply, multiclass_nms\n\nfrom mmdet.core.bbox.iou_calculators.builder import build_iou_calculator\n\[email protected]_module()\nclass ConvFCBBoxHead(BBoxHead):\n r\"\"\"More general bbox head, with shared conv and fc layers and two optional\n separated branches.\n\n .. code-block:: none\n\n /-> cls convs -> cls fcs -> cls\n shared convs -> shared fcs\n \\-> reg convs -> reg fcs -> reg\n \n (\\-> dis convs -> dis fcs -> dis)\n \"\"\" # noqa: W605\n\n def __init__(self,\n num_shared_convs=0,\n num_shared_fcs=0,\n num_cls_convs=0,\n num_cls_fcs=0,\n num_reg_convs=0,\n num_reg_fcs=0,\n conv_out_channels=256,\n fc_out_channels=1024,\n conv_cfg=None,\n norm_cfg=None,\n with_dis=False, #for leaves\n num_dis_convs=0,\n num_dis_fcs=0,\n *args,\n **kwargs):\n super(ConvFCBBoxHead, self).__init__(*args, **kwargs)\n #only for leaves\n self.with_dis = with_dis\n self.num_dis_convs = num_dis_convs\n self.num_dis_fcs = num_dis_fcs\n \n assert (num_shared_convs + num_shared_fcs + num_cls_convs +\n num_cls_fcs + num_reg_convs + num_reg_fcs > 0)\n if num_cls_convs > 0 or num_reg_convs > 0:\n assert num_shared_fcs == 0\n if not self.with_cls:\n assert num_cls_convs == 0 and num_cls_fcs == 0\n if not self.with_reg:\n assert num_reg_convs == 0 and num_reg_fcs == 0\n if not self.with_dis:\n assert num_dis_convs == 0 and num_dis_fcs == 0\n self.num_shared_convs = num_shared_convs\n self.num_shared_fcs = num_shared_fcs\n self.num_cls_convs = num_cls_convs\n self.num_cls_fcs = num_cls_fcs\n self.num_reg_convs = num_reg_convs\n self.num_reg_fcs = num_reg_fcs\n self.conv_out_channels = conv_out_channels\n self.fc_out_channels = fc_out_channels\n self.conv_cfg = conv_cfg\n self.norm_cfg = norm_cfg\n \n # add shared convs and fcs\n self.shared_convs, self.shared_fcs, last_layer_dim = \\\n self._add_conv_fc_branch(\n self.num_shared_convs, self.num_shared_fcs, self.in_channels,\n True)\n self.shared_out_channels = last_layer_dim\n\n # add cls specific branch\n self.cls_convs, self.cls_fcs, self.cls_last_dim = \\\n self._add_conv_fc_branch(\n self.num_cls_convs, self.num_cls_fcs, self.shared_out_channels)\n\n # add reg specific branch\n self.reg_convs, self.reg_fcs, self.reg_last_dim = \\\n self._add_conv_fc_branch(\n self.num_reg_convs, self.num_reg_fcs, self.shared_out_channels)\n \n #add dis branch(only for leaves)\n if self.with_dis:\n self.dis_convs, self.dis_fcs, self.dis_last_dim = \\\n self._add_conv_fc_branch(\n self.num_dis_convs, self.num_dis_fcs, self.shared_out_channels)\n \n if self.num_shared_fcs == 0 and not self.with_avg_pool:\n if self.num_cls_fcs == 0:\n self.cls_last_dim *= self.roi_feat_area\n if self.num_reg_fcs == 0:\n self.reg_last_dim *= self.roi_feat_area\n\n self.relu = nn.ReLU(inplace=True)\n # reconstruct fc_cls and fc_reg since input channels are changed\n if self.with_cls:\n self.fc_cls = nn.Linear(self.cls_last_dim, self.num_classes + 1)\n if self.with_reg:\n out_dim_reg = (4 if self.reg_class_agnostic else 4 *\n self.num_classes)\n self.fc_reg = nn.Linear(self.reg_last_dim, out_dim_reg)\n if self.with_dis:\n if self.dis_selector == 0 or self.dis_selector == 1: \n self.fc_dis = nn.Linear(self.cls_last_dim, 1)\n elif self.dis_selector == 2:\n self.fc_dis = nn.Linear(self.cls_last_dim, 4)\n\n def _add_conv_fc_branch(self,\n num_branch_convs,\n num_branch_fcs,\n in_channels,\n is_shared=False):\n \"\"\"Add shared or separable branch.\n\n convs -> avg pool (optional) -> fcs\n \"\"\"\n last_layer_dim = in_channels\n # add branch specific conv layers\n branch_convs = nn.ModuleList()\n if num_branch_convs > 0:\n for i in range(num_branch_convs):\n conv_in_channels = (\n last_layer_dim if i == 0 else self.conv_out_channels)\n branch_convs.append(\n ConvModule(\n conv_in_channels,\n self.conv_out_channels,\n 3,\n padding=1,\n conv_cfg=self.conv_cfg,\n norm_cfg=self.norm_cfg))\n last_layer_dim = self.conv_out_channels\n # add branch specific fc layers\n branch_fcs = nn.ModuleList()\n if num_branch_fcs > 0:\n # for shared branch, only consider self.with_avg_pool\n # for separated branches, also consider self.num_shared_fcs\n if (is_shared\n or self.num_shared_fcs == 0) and not self.with_avg_pool:\n last_layer_dim *= self.roi_feat_area\n for i in range(num_branch_fcs):\n fc_in_channels = (\n last_layer_dim if i == 0 else self.fc_out_channels)\n branch_fcs.append(\n nn.Linear(fc_in_channels, self.fc_out_channels))\n last_layer_dim = self.fc_out_channels\n return branch_convs, branch_fcs, last_layer_dim\n\n def init_weights(self):\n super(ConvFCBBoxHead, self).init_weights()\n # conv layers are already initialized by ConvModule\n if self.with_dis:\n for module_list in [self.shared_fcs, self.cls_fcs, self.reg_fcs, self.dis_fcs]:\n for m in module_list.modules():\n if isinstance(m, nn.Linear):\n nn.init.xavier_uniform_(m.weight)\n nn.init.constant_(m.bias, 0)\n else:\n for module_list in [self.shared_fcs, self.cls_fcs, self.reg_fcs]:\n for m in module_list.modules():\n if isinstance(m, nn.Linear):\n nn.init.xavier_uniform_(m.weight)\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x):\n # shared part\n if self.num_shared_convs > 0:\n for conv in self.shared_convs:\n x = conv(x)\n\n if self.num_shared_fcs > 0:\n if self.with_avg_pool:\n x = self.avg_pool(x)\n\n x = x.flatten(1)\n\n for fc in self.shared_fcs:\n x = self.relu(fc(x))\n # separate branches\n x_cls = x\n x_reg = x\n if self.with_dis:\n x_dis = x\n \n for conv in self.dis_convs:\n x_dis = conv(x_dis)\n if x_dis.dim() > 2:\n if self.with_avg_pool:\n x_dis = self.avg_pool(x_dis)\n x_dis = x_dis.flatten(1)\n for fc in self.dis_fcs:\n x_dis = self.relu(fc(x_dis))\n\n for conv in self.cls_convs:\n x_cls = conv(x_cls)\n if x_cls.dim() > 2:\n if self.with_avg_pool:\n x_cls = self.avg_pool(x_cls)\n x_cls = x_cls.flatten(1)\n for fc in self.cls_fcs:\n x_cls = self.relu(fc(x_cls))\n\n for conv in self.reg_convs:\n x_reg = conv(x_reg)\n if x_reg.dim() > 2:\n if self.with_avg_pool:\n x_reg = self.avg_pool(x_reg)\n x_reg = x_reg.flatten(1)\n for fc in self.reg_fcs:\n x_reg = self.relu(fc(x_reg))\n\n cls_score = self.fc_cls(x_cls) if self.with_cls else None\n bbox_pred = self.fc_reg(x_reg) if self.with_reg else None\n dis_pred = self.fc_dis(x_dis) if self.with_dis else None\n return cls_score, bbox_pred, dis_pred\n\n\[email protected]_module()\nclass Shared2FCBBoxHead(ConvFCBBoxHead):\n\n def __init__(self, fc_out_channels=1024, *args, **kwargs):\n super(Shared2FCBBoxHead, self).__init__(\n num_shared_convs=0,\n num_shared_fcs=2,\n num_cls_convs=0,\n num_cls_fcs=0,\n num_reg_convs=0,\n num_reg_fcs=0,\n fc_out_channels=fc_out_channels,\n *args,\n **kwargs)\n\[email protected]_module()\nclass Shared2FCBBoxHeadLeaves(ConvFCBBoxHead):\n\n def __init__(self, fc_out_channels=1024, *args, **kwargs):\n loss_dis = kwargs['loss_dis']\n self.reference_labels = kwargs['reference_labels']\n self.classes = kwargs['classes']\n self.dis_selector = kwargs['dis_selector']\n assert self.dis_selector in (0, 1, 2)\n kwargs.pop('loss_dis')\n kwargs.pop('reference_labels')\n kwargs.pop('classes')\n kwargs.pop('dis_selector')\n \n super(Shared2FCBBoxHeadLeaves, self).__init__(\n num_shared_convs=0,\n num_shared_fcs=2,\n num_cls_convs=0,\n num_cls_fcs=0,\n num_reg_convs=0,\n num_reg_fcs=0,\n fc_out_channels=fc_out_channels,\n with_dis=True, #only for leaves\n num_dis_convs=0,\n num_dis_fcs=0,\n *args,\n **kwargs)\n \n if self.dis_selector == 0 or self.dis_selector == 1:\n assert loss_dis['use_sigmoid'], \"used invalid loss_dis\"\n elif self.dis_selector == 2:\n assert not loss_dis['use_sigmoid'], \"used invalid loss_dis\"\n self.loss_dis = build_loss(loss_dis)\n #DEBUG\n #loss_dis_py =dict(type='py_FocalLoss',\n # alpha=torch.tensor(self.dis_weights, device=torch.device('cpu')),\n # gamma = 2.0,\n # reduction = 'mean')\n #self.loss_dis_py = build_loss(loss_dis_py)\n \n \n #Override\n def get_targets(self,\n sampling_results,\n gt_bboxes,\n gt_labels,\n rcnn_train_cfg,\n reference_labels,\n classes,\n concat=True):\n \"\"\"Calculate the ground truth for all samples in a batch according to\n the sampling_results.\n Almost the same as the implementation in bbox_head, we passed\n additional parameters pos_inds_list and neg_inds_list to\n `_get_target_single` function.\n Args:\n sampling_results (List[obj:SamplingResults]): Assign results of\n all images in a batch after sampling.\n gt_bboxes (list[Tensor]): Gt_bboxes of all images in a batch,\n each tensor has shape (num_gt, 4), the last dimension 4\n represents [tl_x, tl_y, br_x, br_y].\n gt_labels (list[Tensor]): Gt_labels of all images in a batch,\n each tensor has shape (num_gt,).\n rcnn_train_cfg (obj:ConfigDict): `train_cfg` of RCNN.\n concat (bool): Whether to concatenate the results of all\n the images in a single batch.\n Returns:\n Tuple[Tensor]: Ground truth for proposals in a single image.\n Containing the following list of Tensors:\n - labels (list[Tensor],Tensor): Gt_labels for all\n proposals in a batch, each tensor in list has\n shape (num_proposals,) when `concat=False`, otherwise\n just a single tensor has shape (num_all_proposals,).\n - label_weights (list[Tensor]): Labels_weights for\n all proposals in a batch, each tensor in list has\n shape (num_proposals,) when `concat=False`, otherwise\n just a single tensor has shape (num_all_proposals,).\n - bbox_targets (list[Tensor],Tensor): Regression target\n for all proposals in a batch, each tensor in list\n has shape (num_proposals, 4) when `concat=False`,\n otherwise just a single tensor has shape\n (num_all_proposals, 4), the last dimension 4 represents\n [tl_x, tl_y, br_x, br_y].\n - bbox_weights (list[tensor],Tensor): Regression weights for\n all proposals in a batch, each tensor in list has shape\n (num_proposals, 4) when `concat=False`, otherwise just a\n single tensor has shape (num_all_proposals, 4).\n - dis_targets (list[tensor], Tensor): Gt_dis for all\n proposal in a batch, each tensor in list has\n shape (num_proposal,) when 'concat=False`, otherwise\n just a single tensor has shape (num_all_proposals,).\n \"\"\"\n \n pos_bboxes_list = [res.pos_bboxes for res in sampling_results]\n neg_bboxes_list = [res.neg_bboxes for res in sampling_results]\n pos_gt_bboxes_list = [res.pos_gt_bboxes for res in sampling_results]\n pos_gt_labels_list = [res.pos_gt_labels for res in sampling_results]\n labels, label_weights, bbox_targets, bbox_weights = multi_apply(\n self._get_target_single,\n pos_bboxes_list,\n neg_bboxes_list,\n pos_gt_bboxes_list,\n pos_gt_labels_list,\n cfg=rcnn_train_cfg)\n \n #processing for dis_target\n iou_calculator=dict(type='BboxOverlaps2D') \n iou_calculator = build_iou_calculator(iou_calculator)\n isolation_thr = 0.45\t#TODO da mettere come arg\n #retrive the gt_superclass bboxes\n dis_targets = []\n for i, res in enumerate(sampling_results):\n ref_grap_list =[]\n ref_leav_list =[]\n ref_grap_dis_list =[]\n ref_leav_dis_list =[]\n for j, bbox in enumerate(gt_bboxes[i]):\n \n if self.dis_selector == 0:\n if 'grappolo' in classes[gt_labels[i][j]] and gt_labels[i][j] != reference_labels['grappolo_vite']:\n ref_grap_dis_list.append(bbox)\n \n elif (('foglia' in classes[gt_labels[i][j]] or classes[gt_labels[i][j]] == 'malattia_esca'\\\n or classes[gt_labels[i][j]] == 'virosi_pinot_grigio')\n and gt_labels[i][j] != reference_labels['foglia_vite']):\n ref_leav_dis_list.append(bbox)\n \n elif self.dis_selector == 1:\n if gt_labels[i][j] == reference_labels['grappolo_vite']:\n ref_grap_list.append(bbox)\n elif gt_labels[i][j] == reference_labels['foglia_vite']:\n ref_leav_list.append(bbox)\n \n elif self.dis_selector == 2:\n if gt_labels[i][j] == reference_labels['grappolo_vite']:\n ref_grap_list.append(bbox)\n elif gt_labels[i][j] == reference_labels['foglia_vite']:\n ref_leav_list.append(bbox)\n elif 'grappolo' in classes[gt_labels[i][j]]:\n ref_grap_dis_list.append(bbox)\n elif 'foglia' in classes[gt_labels[i][j]] or classes[gt_labels[i][j]] == 'malattia_esca'\\\n or classes[gt_labels[i][j]] == 'virosi_pinot_grigio':\n ref_leav_dis_list.append(bbox)\n '''\n if 'grappolo' in classes[gt_labels[i][j]] and gt_labels[i][j] != reference_labels['grappolo_vite']:\n ref_grap_dis_list.append(bbox)\n elif (('foglia' in classes[gt_labels[i][j]] or classes[gt_labels[i][j]] == 'malattia_esca'\\\n or classes[gt_labels[i][j]] == 'virosi_pinot_grigio')\n and gt_labels[i][j] != reference_labels['foglia_vite']):\n ref_leav_dis_list.append(bbox)\n ''' \n if len(ref_grap_list) > 0:\n ref_grap_tensor = torch.cat(ref_grap_list)\n ref_grap_tensor = torch.reshape(ref_grap_tensor, (len(ref_grap_list), 4))\n \n if len(ref_leav_list) > 0:\n ref_leav_tensor = torch.cat(ref_leav_list)\n ref_leav_tensor = torch.reshape(ref_leav_tensor, (len(ref_leav_list), 4))\n \n if len(ref_grap_dis_list) > 0:\n ref_grap_dis_tensor = torch.cat(ref_grap_dis_list)\n ref_grap_dis_tensor = torch.reshape(ref_grap_dis_tensor, (len(ref_grap_dis_list), 4))\n \n if len(ref_leav_dis_list) > 0:\n ref_leav_dis_tensor = torch.cat(ref_leav_dis_list)\n ref_leav_dis_tensor = torch.reshape(ref_leav_dis_tensor, (len(ref_leav_dis_list), 4))\n\n num_pos = res.pos_bboxes.size(0)\n num_neg = res.neg_bboxes.size(0)\n num_samples = num_pos + num_neg\n dis_tensor= res.pos_bboxes.new_full((num_samples, ), -1, dtype=torch.long)\n dis_list = []\n for j, bbox in enumerate(res.pos_bboxes):\n #trick for using the iof calculator\n bbox = bbox.unsqueeze(0)\n \n if res.pos_gt_labels[j] == reference_labels['grappolo_vite']:\n if self.dis_selector == 0:\n dis_list.append(-1) #the grape is not considered\n \n elif self.dis_selector == 1 or self.dis_selector == 2:\n if len(ref_grap_dis_list) > 0:\n overlaps = iou_calculator(ref_grap_dis_tensor, bbox, mode='iof')\n overlaps = overlaps < isolation_thr\n if overlaps.all():\n dis_list.append(0) #the grape is healthy\n else:\n dis_list.append(1) #the grape is affected by a disease\n else:\n dis_list.append(0) #the grape is healthy\n \n elif res.pos_gt_labels[j] == reference_labels['foglia_vite']:\n if self.dis_selector == 0:\n dis_list.append(-1) #the leaf is not considered\n \n elif self.dis_selector == 1 or self.dis_selector == 2:\n if len(ref_leav_dis_list) > 0:\n overlaps = iou_calculator(ref_leav_dis_tensor, bbox, mode='iof')\n overlaps = overlaps < isolation_thr\n if overlaps.all():\n dis_list.append(0) #the leaf is healthy\n else:\n dis_list.append(1) #the leaf is affected by a disease\n else:\n dis_list.append(0) #the leaf is healthy\n \n elif 'grappolo' in classes[res.pos_gt_labels[j]] and res.pos_gt_labels[j] != reference_labels['grappolo_vite']:\n if self.dis_selector == 1:\n dis_list.append(-1) #the disease is not considered\n \n elif self.dis_selector == 0:\n if len(ref_grap_list) > 0:\n overlaps = iou_calculator(bbox, ref_grap_tensor, mode='iof')\n overlaps = overlaps < isolation_thr\n if overlaps.all():\n dis_list.append(0) #the disease is isolated\n else:\n dis_list.append(1) #the disease is inside a leaf or grape\n else:\n dis_list.append(0) #the disease is isolated\n \n elif self.dis_selector == 2:\n if len(ref_grap_list) > 0:\n overlaps = iou_calculator(bbox, ref_grap_tensor, mode='iof')\n overlaps = overlaps < isolation_thr\n if overlaps.all():\n dis_list.append(2) #the disease is isolated\n else:\n dis_list.append(3) #the disease is inside a leaf or grape\n else:\n dis_list.append(2) #the disease is isolated\n \n elif (('foglia' in classes[res.pos_gt_labels[j]] or classes[res.pos_gt_labels[j]] == 'malattia_esca'\n or classes[res.pos_gt_labels[j]] == 'virosi_pinot_grigio')\n and res.pos_gt_labels[j] != reference_labels['foglia_vite']):\n if self.dis_selector == 1:\n dis_list.append(-1) #the disease is not considered\n \n elif self.dis_selector == 0:\n if len(ref_leav_list) > 0:\n overlaps = iou_calculator(bbox, ref_leav_tensor, mode='iof')\n overlaps = overlaps < isolation_thr\n if overlaps.all():\n dis_list.append(0) #the disease is isolated\n else:\n dis_list.append(1) #the disease is inside a leaf or grape\n else:\n dis_list.append(0) #the disease is isolated\n \n elif self.dis_selector == 2:\n if len(ref_leav_list) > 0:\n overlaps = iou_calculator(bbox, ref_leav_tensor, mode='iof')\n overlaps = overlaps < isolation_thr\n if overlaps.all():\n dis_list.append(2) #the disease is isolated\n else:\n dis_list.append(3) #the disease is inside a leaf or grape\n else:\n dis_list.append(2) #the disease is isolated\n \n #elif res.pos_gt_labels[j] == reference_labels['oidio_tralci']:\n # dis_list.append(-1) #the disease is not considered\n \n dis_tensor[:num_pos] = torch.tensor(dis_list)\n dis_targets.append(dis_tensor) \n \n if concat:\n labels = torch.cat(labels, 0)\n label_weights = torch.cat(label_weights, 0)\n bbox_targets = torch.cat(bbox_targets, 0)\n bbox_weights = torch.cat(bbox_weights, 0)\n dis_targets = torch.cat(dis_targets, 0)\n \n #del dis_tensor\n #torch.cuda.empty_cache()\n return labels, label_weights, bbox_targets, bbox_weights, dis_targets\n \n #Override\n @force_fp32(apply_to=('cls_score', 'bbox_pred', 'dis_pred'))\n def loss(self,\n cls_score,\n bbox_pred,\n dis_pred,\n rois,\n labels,\n label_weights,\n bbox_targets,\n bbox_weights,\n dis_targets,\n reduction_override=None):\n losses = dict()\n if cls_score is not None:\n avg_factor = max(torch.sum(label_weights > 0).float().item(), 1.)\n if cls_score.numel() > 0:\n losses['loss_cls'] = self.loss_cls(\n cls_score,\n labels,\n label_weights,\n avg_factor=avg_factor,\n reduction_override=reduction_override)\n losses['acc'] = accuracy(cls_score, labels)\n if bbox_pred is not None:\n bg_class_ind = self.num_classes\n # 0~self.num_classes-1 are FG, self.num_classes is BG\n pos_inds = (labels >= 0) & (labels < bg_class_ind)\n # do not perform bounding box regression for BG anymore.\n if pos_inds.any():\n if self.reg_decoded_bbox:\n # When the regression loss (e.g. `IouLoss`,\n # `GIouLoss`, `DIouLoss`) is applied directly on\n # the decoded bounding boxes, it decodes the\n # already encoded coordinates to absolute format.\n bbox_pred = self.bbox_coder.decode(rois[:, 1:], bbox_pred)\n if self.reg_class_agnostic:\n pos_bbox_pred = bbox_pred.view(\n bbox_pred.size(0), 4)[pos_inds.type(torch.bool)]\n else:\n pos_bbox_pred = bbox_pred.view(\n bbox_pred.size(0), -1,\n 4)[pos_inds.type(torch.bool),\n labels[pos_inds.type(torch.bool)]]\n losses['loss_bbox'] = self.loss_bbox(\n pos_bbox_pred,\n bbox_targets[pos_inds.type(torch.bool)],\n bbox_weights[pos_inds.type(torch.bool)],\n avg_factor=bbox_targets.size(0),\n reduction_override=reduction_override)\n else:\n losses['loss_bbox'] = bbox_pred[pos_inds].sum()\n if dis_pred is not None:\n pos_inds = dis_targets != -1\n if pos_inds.any():\n pos_dis_pred = dis_pred[pos_inds.type(torch.bool)]\n pos_dis_targets = dis_targets[pos_inds.type(torch.bool)]\n avg_factor = dis_pred.size(0)\n \n losses['loss_dis'] = self.loss_dis(\n pos_dis_pred,\n pos_dis_targets,\n avg_factor=avg_factor,\n reduction_override=reduction_override)\n \n #DEBUG\n #loss_py = self.loss_dis_py(pos_dis_pred,\n # pos_dis_targets)\n \n #from mmcv.utils import print_log\n #import logging\n #logger = logging.getLogger(__name__)\n #print_log(\"loss_dis:{:0.4f}, loss_dis_py:{:0.4f}\".format(losses['loss_dis'], loss_py), logger = logger)\n \n return losses\n \n #Override\n @force_fp32(apply_to=('cls_score', 'bbox_pred', 'dis_pred'))\n def get_bboxes(self,\n rois,\n cls_score,\n bbox_pred,\n dis_pred,\n img_shape,\n scale_factor,\n rescale=False,\n cfg=None):\n if isinstance(cls_score, list):\n cls_score = sum(cls_score) / float(len(cls_score))\n scores = F.softmax(cls_score, dim=1) if cls_score is not None else None\n\n if bbox_pred is not None:\n bboxes = self.bbox_coder.decode(\n rois[:, 1:], bbox_pred, max_shape=img_shape)\n else:\n bboxes = rois[:, 1:].clone()\n if img_shape is not None:\n bboxes[:, [0, 2]].clamp_(min=0, max=img_shape[1])\n bboxes[:, [1, 3]].clamp_(min=0, max=img_shape[0])\n\n if rescale and bboxes.size(0) > 0:\n if isinstance(scale_factor, float):\n bboxes /= scale_factor\n else:\n scale_factor = bboxes.new_tensor(scale_factor)\n bboxes = (bboxes.view(bboxes.size(0), -1, 4) /\n scale_factor).view(bboxes.size()[0], -1)\n if dis_pred is not None:\n if self.dis_selector == 0 or self.dis_selector == 1:\n diseases = F.sigmoid(dis_pred)\n elif self.dis_selector == 2:\n diseases = F.softmax(dis_pred, dim=1)\n \n if cfg is None:\n return bboxes, scores, diseases\n else:\n det_bboxes, det_labels, inds = multiclass_nms(bboxes, scores,\n cfg.score_thr, cfg.nms,\n cfg.max_per_img,\n return_inds=True)\n\n if self.dis_selector == 0 or self.dis_selector == 1:\n diseases = diseases.expand(bboxes.size(0), scores.size(1) - 1)\n diseases = diseases.reshape(-1)\n elif self.dis_selector == 2:\n diseases = diseases[:, None].expand(bboxes.size(0), scores.size(1) - 1, 4) \n diseases = diseases.reshape(-1, 4)\n \n det_dis = diseases[inds]\n return det_bboxes, det_labels, det_dis\n\n\[email protected]_module()\nclass Shared4Conv1FCBBoxHead(ConvFCBBoxHead):\n\n def __init__(self, fc_out_channels=1024, *args, **kwargs):\n super(Shared4Conv1FCBBoxHead, self).__init__(\n num_shared_convs=4,\n num_shared_fcs=1,\n num_cls_convs=0,\n num_cls_fcs=0,\n num_reg_convs=0,\n num_reg_fcs=0,\n fc_out_channels=fc_out_channels,\n *args,\n **kwargs)\n" ]
[ [ "torch.nn.functional.softmax", "torch.cat", "torch.nn.init.constant_", "torch.nn.ModuleList", "torch.sum", "torch.tensor", "torch.nn.Linear", "torch.nn.functional.sigmoid", "torch.nn.init.xavier_uniform_", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
smtnkc/gcn4epi
[ "2b9dd973b2d5120f618d3c36e8aa9d7d4a4e6b69" ]
[ "utils.py" ]
[ "import numpy as np\nimport pickle as pkl\nimport networkx as nx\nimport scipy.sparse as sp\nfrom scipy.sparse.linalg.eigen.arpack import eigsh\n\n\ndef sample_mask(idx, l):\n \"\"\"Create mask.\"\"\"\n mask = np.zeros(l)\n mask[idx] = 1\n return np.array(mask, dtype=np.bool)\n\n\ndef load_data(cell_line, cross_cell_line, label_rate, k_mer):\n \"\"\"\n Load input data from data/cell_line directory.\n\n | x_20.index | the indices (IDs) of labeled train instances as list object (for label_rate = 20%) |\n | ux_20.index | the indices (IDs) of unlabeled train instances as list object (for label_rate = 20%) |\n | vx_20.index | the indices (IDs) of validation instances as list object (for label_rate = 20%) |\n | tx_20.index | the indices (IDs) of test instances as list object (for label_rate = 20%) |\n | features_5mer | the feature vectors of all instances as scipy.sparse.csr.csr_matrix object (for k_mer = 5) |\n | nodes | a dict in the format {chromosome_name: ID} as collections.defaultdict object |\n | labels | the one-hot labels of all instances as numpy.ndarray object |\n | graph | a dict in the format {ID: [IDs_of_neighbor_nodes]} as collections.defaultdict object |\n\n All objects above must be saved using python pickle module.\n\n :param cell_line: Name of the cell line to which the datasets belong\n :return: All data input files loaded (as well the training/test data).\n \"\"\"\n\n if (cross_cell_line != None) and (cross_cell_line != cell_line):\n read_dir = 'data/{}_{}/'.format(cell_line, cross_cell_line)\n else:\n read_dir = 'data/{}/'.format(cell_line)\n\n # STEP 1: Load all feature vectors, class labels and graph\n features_file = open('{}/features_{}mer'.format(read_dir, k_mer), \"rb\")\n features = pkl.load(features_file)\n features_file.close()\n\n labels_file = open('{}/labels'.format(read_dir), \"rb\")\n labels = pkl.load(labels_file)\n labels_file.close()\n\n graph_file = open('{}/graph'.format(read_dir), \"rb\")\n graph = pkl.load(graph_file)\n graph_file.close()\n\n adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))\n\n # STEP 2: Load IDs of labeled_train/unlabeled_train/validation/test nodes\n lr = txt = '{:.2f}'.format(label_rate).split('.')[1]\n\n idx_x_file = open('{}/x_{}.index'.format(read_dir, lr), \"rb\")\n idx_x = pkl.load(idx_x_file)\n idx_x_file.close()\n\n idx_ux_file = open('{}/ux_{}.index'.format(read_dir, lr), \"rb\")\n idx_ux = pkl.load(idx_ux_file)\n idx_ux_file.close()\n\n idx_vx_file = open('{}/vx_{}.index'.format(read_dir, lr), \"rb\")\n idx_vx = pkl.load(idx_vx_file)\n idx_vx_file.close()\n\n idx_tx_file = open('{}/tx_{}.index'.format(read_dir, lr), \"rb\")\n idx_tx = pkl.load(idx_tx_file)\n idx_tx_file.close()\n\n # STEP 3: Take subsets from loaded features and class labels using loaded IDs\n x = features[idx_x]\n y = labels[idx_x]\n\n ux = features[idx_ux]\n uy = labels[idx_ux]\n\n vx = features[idx_vx]\n vy = labels[idx_vx]\n\n tx = features[idx_tx]\n ty = labels[idx_tx]\n\n print(\"x={} ux={} vx={} tx={}\".format(x.shape[0], ux.shape[0], vx.shape[0], tx.shape[0]))\n\n # STEP 4: Mask labels\n train_mask = sample_mask(idx_x, labels.shape[0])\n val_mask = sample_mask(idx_vx, labels.shape[0])\n test_mask = sample_mask(idx_tx, labels.shape[0])\n\n y_train = np.zeros(labels.shape)\n y_val = np.zeros(labels.shape)\n y_test = np.zeros(labels.shape)\n y_train[train_mask, :] = labels[train_mask, :]\n y_val[val_mask, :] = labels[val_mask, :]\n y_test[test_mask, :] = labels[test_mask, :]\n\n return adj, features, y_train, y_val, y_test, train_mask, val_mask, test_mask\n\n\ndef sparse_to_tuple(sparse_mx):\n \"\"\"Convert sparse matrix to tuple representation.\"\"\"\n def to_tuple(mx):\n if not sp.isspmatrix_coo(mx):\n mx = mx.tocoo()\n coords = np.vstack((mx.row, mx.col)).transpose()\n values = mx.data\n shape = mx.shape\n return coords, values, shape\n\n if isinstance(sparse_mx, list):\n for i in range(len(sparse_mx)):\n sparse_mx[i] = to_tuple(sparse_mx[i])\n else:\n sparse_mx = to_tuple(sparse_mx)\n\n return sparse_mx\n\n\ndef preprocess_features(features):\n \"\"\"Row-normalize feature matrix and convert to tuple representation\"\"\"\n rowsum = np.array(features.sum(1))\n r_inv = np.power(rowsum, -1).flatten()\n r_inv[np.isinf(r_inv)] = 0.\n r_mat_inv = sp.diags(r_inv)\n features = r_mat_inv.dot(features)\n return sparse_to_tuple(features)\n\n\ndef normalize_adj(adj):\n \"\"\"Symmetrically normalize adjacency matrix.\"\"\"\n adj = sp.coo_matrix(adj)\n rowsum = np.array(adj.sum(1))\n d_inv_sqrt = np.power(rowsum, -0.5).flatten()\n d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.\n d_mat_inv_sqrt = sp.diags(d_inv_sqrt)\n return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt).tocoo()\n\n\ndef preprocess_adj(adj):\n \"\"\"Preprocessing of adjacency matrix for simple GCN model and conversion to tuple representation.\"\"\"\n adj_normalized = normalize_adj(adj + sp.eye(adj.shape[0]))\n return sparse_to_tuple(adj_normalized)\n\n\ndef construct_feed_dict(features, support, labels, labels_mask, placeholders):\n \"\"\"Construct feed dictionary.\"\"\"\n feed_dict = dict()\n feed_dict.update({placeholders['labels']: labels})\n feed_dict.update({placeholders['labels_mask']: labels_mask})\n feed_dict.update({placeholders['features']: features})\n feed_dict.update({placeholders['support'][i]: support[i] for i in range(len(support))})\n feed_dict.update({placeholders['num_features_nonzero']: features[1].shape})\n return feed_dict\n\n\ndef chebyshev_polynomials(adj, k):\n \"\"\"Calculate Chebyshev polynomials up to order k. Return a list of sparse matrices (tuple representation).\"\"\"\n print(\"Calculating Chebyshev polynomials up to order {}...\".format(k))\n\n adj_normalized = normalize_adj(adj)\n laplacian = sp.eye(adj.shape[0]) - adj_normalized\n largest_eigval, _ = eigsh(laplacian, 1, which='LM')\n scaled_laplacian = (2. / largest_eigval[0]) * laplacian - sp.eye(adj.shape[0])\n\n t_k = list()\n t_k.append(sp.eye(adj.shape[0]))\n t_k.append(scaled_laplacian)\n\n def chebyshev_recurrence(t_k_minus_one, t_k_minus_two, scaled_lap):\n s_lap = sp.csr_matrix(scaled_lap, copy=True)\n return 2 * s_lap.dot(t_k_minus_one) - t_k_minus_two\n\n for i in range(2, k+1):\n t_k.append(chebyshev_recurrence(t_k[-1], t_k[-2], scaled_laplacian))\n\n return sparse_to_tuple(t_k)\n" ]
[ [ "scipy.sparse.coo_matrix", "scipy.sparse.isspmatrix_coo", "numpy.power", "scipy.sparse.eye", "scipy.sparse.diags", "scipy.sparse.linalg.eigen.arpack.eigsh", "scipy.sparse.csr_matrix", "numpy.array", "numpy.zeros", "numpy.isinf", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "0.15", "1.4", "0.16", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3" ], "tensorflow": [] } ]
wooseoklee4/AP-BSN
[ "210013cfe0657e678e4b940fd4d5719ac0ac87c6" ]
[ "src/util/summary_logging.py" ]
[ "\nimport time\n\nfrom torch.utils.tensorboard import SummaryWriter\nimport numpy as np\n\nclass LossWriter(SummaryWriter):\n def __init__(self, log_dir=None, comment=''):\n if log_dir == None:\n log_dir = './logs/tensorboard/' + time.strftime('%Y-%m-%d--%H-%M-%S', time.localtime(time.time()))\n super(LossWriter, self).__init__(log_dir=log_dir, comment=comment)\n\n def write_loss(self, loss_name, scalar, n_iter):\n self.add_scalar('Loss/'+loss_name, scalar, n_iter)\n\n\nif __name__=='__main__':\n testwriter = LossWriter()\n\n for n_iter in range(100):\n testwriter.write_loss(np.random.random(), n_iter)\n" ]
[ [ "numpy.random.random" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
timoklein/A0C
[ "2825193f424bd5b74b654c929ef73775b0914ee5" ]
[ "alphazero/network/policies.py" ]
[ "from typing import ClassVar, List, Optional, Tuple, Callable, Union, cast\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.distributions as D\nfrom alphazero.network.distributions import SquashedNormal, GeneralizedBeta\nfrom alphazero.network.utils import (\n _map_nonlinearities,\n _process_str,\n)\n\n__all__ = [\n \"make_policy\",\n \"DiagonalNormalPolicy\",\n \"DiagonalGMMPolicy\",\n \"GeneralizedBetaPolicy\",\n \"DiscretePolicy\",\n]\n\n\nclass Policy(nn.Module):\n \"\"\"Base policy class.\n\n The base policy is responsible for instanting the linear layers and value head.\n It also defines some interface functions.\n\n Parameters\n ----------\n representation_dim : int\n Dimensions of the input representation.\n action_dim : int\n Number of dimensions for the action space.\n distribution : str\n Distribution that is parameterized by the network.\n Allows the following options:\n - \"normal\": Normal distribution.\n - \"tanhsquashed\", \"tanhsquashednormal\": Normal distribution with samples squashed in (-1, 1).\n - \"generalizedsquashed\", \"generalizedsquashednormal\": Normal distribution with samples squashed in (-c, c).\n - \"beta\", \"generalizedbeta\": Beta distribution with transformed support on (-c, c).\n action_bound : Optional[float]\n Bounds for the action space. Can be either float or None.\n hidden_dimensions : List[int]\n Specify the number of hidden neurons for each respective hidden layer of the network. Cannot be empty.\n nonlinearity : str\n Nonlinearity used between hidden layers. Options are:\n - \"relu\": https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html#torch.nn.ReLU .\n - \"leakyrelu\": https://pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html#torch.nn.LeakyReLU.\n - \"relu6\": https://pytorch.org/docs/stable/generated/torch.nn.ReLU6.html#torch.nn.ReLU6.\n - \"silu\": https://pytorch.org/docs/stable/generated/torch.nn.SiLU.html#torch.nn.SiLU.\n - \"elu\": https://pytorch.org/docs/stable/generated/torch.nn.ELU.html#torch.nn.ELU.\n - \"hardswish\": https://pytorch.org/docs/stable/generated/torch.nn.Hardswish.html#torch.nn.Hardswish.\n layernorm : bool\n If True, the network is regularized with layer normalization after each liner layer.\n This may increase performance, see https://arxiv.org/pdf/1709.06560.pdf for info.\n log_param_min : int\n Lower bound for learned log parameters.\n log_param_max : int\n Upper bound for learned log parameters.\n \"\"\"\n\n # member type annotations\n state_dim: int\n action_dim: int\n action_bound: Optional[float]\n log_param_min: float\n log_param_max: float\n hidden_layers: int\n hidden_dimensions: List[int]\n trunk: nn.Sequential\n value_head: nn.Linear\n\n def __init__(\n self,\n representation_dim: int,\n action_dim: int,\n action_bound: Optional[float],\n hidden_dimensions: List[int],\n nonlinearity: str,\n layernorm: bool,\n log_param_min: float,\n log_param_max: float,\n ):\n super().__init__()\n self.state_dim = representation_dim\n self.action_dim = action_dim\n self.action_bound = action_bound\n\n # boundaries for the log standard deviation to increae training stability\n self.log_param_min = log_param_min\n self.log_param_max = log_param_max\n\n assert hidden_dimensions, \"Hidden dimensions can't be empty.\"\n self.hidden_dimensions = hidden_dimensions\n self.hidden_layers = len(hidden_dimensions)\n\n activation: Callable[..., nn.Module] = _map_nonlinearities(nonlinearity)\n self.layernorm = layernorm\n\n # generate neural network except distribution heads\n layers = [\n nn.Linear(self.state_dim, hidden_dimensions[0]),\n activation(inplace=True),\n ]\n if layernorm:\n layers.append(nn.LayerNorm(normalized_shape=hidden_dimensions[0]))\n\n if 1 < self.hidden_layers:\n for i, hidden_dim in enumerate(hidden_dimensions[:-1]):\n hid = [\n nn.Linear(hidden_dim, hidden_dimensions[i + 1]),\n activation(inplace=True),\n ]\n if layernorm:\n hid.append(nn.LayerNorm(normalized_shape=hidden_dimensions[i + 1]))\n layers.extend(hid)\n\n self.trunk = nn.Sequential(*layers)\n\n self.value_head = nn.Linear(hidden_dimensions[-1], 1)\n\n def __repr__(self) -> str:\n \"\"\"\n Returns\n -------\n str\n String representation of this instance.\n \"\"\"\n components: int = getattr(self, \"num_components\", 1)\n return (\n f\"class={type(self).__name__}, distribution={self.distribution_type}, components={components}, \"\n f\"state_dim={self.state_dim}, action_dim={self.action_dim}, action_bounds={self.bounds}, \"\n f\"log_std_bounds={self.log_param_bounds}, hidden_layers={self.hidden_layers}, hidden_units={self.hidden_dimensions}, \"\n f\"nonlinearity={type(self.trunk[1]).__name__}, layernorm={self.layernorm}\"\n )\n\n @property\n def bounds(self) -> np.ndarray:\n if self.action_bound is None:\n return np.array([-np.inf, np.inf], dtype=np.float32)\n else:\n return np.array([-self.action_bound, self.action_bound], dtype=np.float32)\n\n @torch.no_grad()\n def get_train_data(\n self, states: torch.Tensor, actions: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n raise NotImplementedError\n\n @torch.no_grad()\n def sample_action(self, x: torch.Tensor) -> np.ndarray:\n raise NotImplementedError\n\n @torch.no_grad()\n def predict_V(self, x: torch.Tensor) -> np.ndarray:\n self.eval()\n x = self.trunk(x)\n V_hat = self.value_head(x)\n self.train()\n return V_hat.detach().cpu().numpy()\n\n\nclass DiscretePolicy(nn.Module):\n \"\"\"Base policy class.\n\n The base policy is responsible for instanting the linear layers and value head.\n It also defines some interface functions.\n\n Parameters\n ----------\n representation_dim : int\n Dimensions of the input representation.\n action_dim : int\n Number of dimensions for the action space.\n distribution : str\n Distribution that is parameterized by the network.\n Allows the following options:\n - \"normal\": Normal distribution.\n - \"tanhsquashed\", \"tanhsquashednormal\": Normal distribution with samples squashed in (-1, 1).\n - \"generalizedsquashed\", \"generalizedsquashednormal\": Normal distribution with samples squashed in (-c, c).\n - \"beta\", \"generalizedbeta\": Beta distribution with transformed support on (-c, c).\n action_bound : Optional[float]\n Bounds for the action space. Can be either float or None.\n hidden_dimensions : List[int]\n Specify the number of hidden neurons for each respective hidden layer of the network. Cannot be empty.\n nonlinearity : str\n Nonlinearity used between hidden layers. Options are:\n - \"relu\": https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html#torch.nn.ReLU .\n - \"leakyrelu\": https://pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html#torch.nn.LeakyReLU.\n - \"relu6\": https://pytorch.org/docs/stable/generated/torch.nn.ReLU6.html#torch.nn.ReLU6.\n - \"silu\": https://pytorch.org/docs/stable/generated/torch.nn.SiLU.html#torch.nn.SiLU.\n - \"elu\": https://pytorch.org/docs/stable/generated/torch.nn.ELU.html#torch.nn.ELU.\n - \"hardswish\": https://pytorch.org/docs/stable/generated/torch.nn.Hardswish.html#torch.nn.Hardswish.\n layernorm : bool\n If True, the network is regularized with layer normalization after each liner layer.\n This may increase performance, see https://arxiv.org/pdf/1709.06560.pdf for info.\n log_param_min : int\n Lower bound for learned log parameters.\n log_param_max : int\n Upper bound for learned log parameters.\n \"\"\"\n\n # member type annotations\n state_dim: int\n action_dim: int\n num_actions: int\n hidden_layers: int\n hidden_dimensions: List[int]\n trunk: nn.Sequential\n value_head: nn.Linear\n\n # class variable\n distribution_type: ClassVar[str] = \"Categorical\"\n\n def __init__(\n self,\n representation_dim: int,\n action_dim: int,\n num_actions: int,\n hidden_dimensions: List[int],\n nonlinearity: str,\n layernorm: bool,\n ):\n super().__init__()\n self.state_dim = representation_dim\n self.action_dim = action_dim\n self.num_actions = num_actions\n\n assert hidden_dimensions, \"Hidden dimensions can't be empty.\"\n self.hidden_dimensions = hidden_dimensions\n self.hidden_layers = len(hidden_dimensions)\n self.distribution = D.Categorical\n\n activation: Callable[..., nn.Module] = _map_nonlinearities(nonlinearity)\n self.layernorm = layernorm\n\n # generate neural network except distribution heads\n layers = [\n nn.Linear(self.state_dim, hidden_dimensions[0]),\n activation(inplace=True),\n ]\n if layernorm:\n layers.append(nn.LayerNorm(normalized_shape=hidden_dimensions[0]))\n\n if 1 < self.hidden_layers:\n for i, hidden_dim in enumerate(hidden_dimensions[:-1]):\n hid = [\n nn.Linear(hidden_dim, hidden_dimensions[i + 1]),\n activation(inplace=True),\n ]\n if layernorm:\n hid.append(nn.LayerNorm(normalized_shape=hidden_dimensions[i + 1]))\n layers.extend(hid)\n\n self.trunk = nn.Sequential(*layers)\n\n self.value_head = nn.Linear(hidden_dimensions[-1], 1)\n\n self.dist_head = nn.Linear(hidden_dimensions[-1], num_actions)\n\n def __repr__(self) -> str:\n \"\"\"\n Returns\n -------\n str\n String representation of this instance.\n \"\"\"\n return (\n f\"class={type(self).__name__}, distribution={self.distribution_type}, num_actions={self.num_actions}, \"\n f\"state_dim={self.state_dim}, action_dim={self.action_dim}, \"\n f\"hidden_layers={self.hidden_layers}, hidden_units={self.hidden_dimensions}, \"\n f\"nonlinearity={type(self.trunk[1]).__name__}, layernorm={self.layernorm}\"\n )\n\n def _get_dist_params(\n self, x: torch.Tensor\n ) -> Tuple[torch.FloatTensor, torch.FloatTensor]:\n \"\"\"Returns the learned paremters of the distribution.\n\n Parameters\n ----------\n x : torch.FloatTensor\n Input state tensor.\n\n Returns\n -------\n Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]\n Distribution mean (mu), Distribution standard deviation (sigma), State value estimate (V_hat).\n \"\"\"\n x = self.trunk(x)\n V_hat = self.value_head(x)\n\n # dist_head returns a tensor of shape [batch_size, 2*action_dim]\n # split this tensor along the last dimension into parameters for mu and sigma\n pi_logits = self.dist_head(x)\n\n return pi_logits, V_hat\n\n def forward(self, x: torch.FloatTensor) -> Tuple[D.Categorical, torch.FloatTensor]:\n \"\"\"Forward pass of the model.\n\n Parameters\n ----------\n x : torch.FloatTensor\n Input state tensor.\n\n Returns\n -------\n Tuple[Normallike, torch.FloatTensor]\n Normal or squashed Normal distribution (dist), State value estimate (V_hat).\n \"\"\"\n pi_logits, V_hat = self._get_dist_params(x)\n\n dist = D.Categorical(logits=pi_logits)\n\n # samples from dist have shape [batch_size, action_dim]\n return dist, V_hat\n\n def get_train_data(\n self, states: torch.Tensor, actions: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n\n pi_logits, V_hat = self._get_dist_params(states)\n\n # This creates an independent distribution for each action possibility\n # so that the batch_shape of the distribution is identical to the shape of actions\n # It's needed so that the log_probs are of the proper shape [batch_size, num_actions]\n # else this throws since the distribution's batch_shape=[batch_shape] doesn't match\n # the shape of the actions tensor, which is [batch_size, num_actions]\n num_actions = actions.shape[1]\n pi_hat = D.Categorical(\n logits=pi_logits.unsqueeze(dim=1).repeat((1, num_actions, 1))\n )\n log_probs = pi_hat.log_prob(actions)\n\n entropy = pi_hat.entropy()\n\n return log_probs, entropy, V_hat\n\n @torch.no_grad()\n def predict_V(self, x: torch.Tensor) -> np.ndarray:\n self.eval()\n _, V_hat = self(x)\n self.train()\n return V_hat.detach().cpu().numpy()\n\n @torch.no_grad()\n def predict_pi(self, x: torch.Tensor) -> np.ndarray:\n self.eval()\n logits, _ = self._get_dist_params(x)\n self.train()\n return F.softmax(logits, dim=-1).detach().cpu().numpy()\n\n\nclass DiagonalNormalPolicy(Policy):\n \"\"\"Policy class for factorized normal distributions.\n\n Learns parameters for a factorized normal distribution of types\n Normal, TanhSquashedNormal or GeneralizedSquashedNormal.\n Factorized means that a conditionally independent (given a state) 1D Normal distribution is\n learned for each dimension of the action space instead of a Multivariate Normal.\n\n Parameters\n ----------\n representation_dim : int\n Dimensions of the input representation.\n action_dim : int\n Number of dimensions for the action space.\n distribution : str\n Distribution that is parameterized by the network. Has to be a Normallike distribution.\n Allows the following options:\n - \"normal\": Normal distribution.\n - \"tanhsquashed\", \"tanhsquashednormal\": Normal distribution with samples squashed in (-1, 1).\n - \"generalizedsquashed\", \"generalizedsquashednormal\": Normal distribution with samples squashed in (-c, c).\n action_bound : Optional[float]\n Bounds for the action space. Can be either float or None.\n hidden_dimensions : List[int]\n Specify the number of hidden neurons for each respective hidden layer of the network. Cannot be empty.\n nonlinearity : str\n Nonlinearity used between hidden layers. Options are:\n - \"relu\": https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html#torch.nn.ReLU .\n - \"leakyrelu\": https://pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html#torch.nn.LeakyReLU.\n - \"relu6\": https://pytorch.org/docs/stable/generated/torch.nn.ReLU6.html#torch.nn.ReLU6.\n - \"silu\": https://pytorch.org/docs/stable/generated/torch.nn.SiLU.html#torch.nn.SiLU.\n - \"elu\": https://pytorch.org/docs/stable/generated/torch.nn.ELU.html#torch.nn.ELU.\n - \"hardswish\": https://pytorch.org/docs/stable/generated/torch.nn.Hardswish.html#torch.nn.Hardswish.\n layernorm : bool\n If True, the network is regularized with layer normalization after each liner layer.\n This may increase performance, see https://arxiv.org/pdf/1709.06560.pdf for info.\n log_param_min : int\n Lower bound for learned log standard deviation.\n log_param_max : int\n Upper bound for learned log standard deviation.\n \"\"\"\n\n # member annotations\n state_dim: int\n action_dim: int\n action_bound: Optional[float]\n log_param_min: float\n log_param_max: float\n hidden_layers: int\n hidden_dimensions: List[int]\n trunk: nn.Sequential\n dist_head: nn.Linear\n value_head: nn.Linear\n\n # class variable\n policy_type: ClassVar[str] = \"DiagonalNormal\"\n\n def __init__(\n self,\n representation_dim: int,\n action_dim: int,\n action_bound: Optional[float],\n hidden_dimensions: List[int],\n nonlinearity: str,\n layernorm: bool,\n log_param_min: float,\n log_param_max: float,\n ):\n\n super().__init__(\n representation_dim=representation_dim,\n action_dim=action_dim,\n action_bound=action_bound,\n hidden_dimensions=hidden_dimensions,\n nonlinearity=nonlinearity,\n layernorm=layernorm,\n log_param_min=log_param_min,\n log_param_max=log_param_max,\n )\n\n self.dist_head = nn.Linear(hidden_dimensions[-1], 2 * self.action_dim)\n\n def forward(\n self, x: torch.FloatTensor\n ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:\n \"\"\"Returns the learned paremters of the distribution.\n\n Parameters\n ----------\n x : torch.FloatTensor\n Input state tensor.\n\n Returns\n -------\n Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]\n Distribution mean (mu), Distribution standard deviation (sigma), State value estimate (V_hat).\n \"\"\"\n x = self.trunk(x)\n V_hat = self.value_head(x)\n\n # dist_head returns a tensor of shape [batch_size, 2*action_dim]\n # split this tensor along the last dimension into parameters for mu and sigma\n mu, log_std = self.dist_head(x).chunk(2, dim=-1)\n\n # Learning the log_std_dev is a trick for numerical stability\n # Since the stddev > 0, we can learn the log and then exponentiate\n # constrain log_std inside [log_param_min, log_param_max]\n log_std = torch.clamp(log_std, min=self.log_param_min, max=self.log_param_max)\n sigma = log_std.exp()\n\n return mu, sigma, V_hat\n\n def get_train_data(\n self, states: torch.Tensor, actions: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n mu, sigma, V_hat = self(states)\n # This aligns the distribution batch_shape with the number of actions at the root\n # It can be thought of as generating num_actions identical normal distributions for each agent\n # and then sampling the log_prob for action from the distribution\n # num_actions = actions.shape[-1]\n # mu = mu.expand((-1, num_actions))\n # sigma = sigma.expand((-1, num_actions))\n\n normal: Union[D.Normal, SquashedNormal]\n if self.action_bound:\n normal = SquashedNormal(mu, sigma, self.action_bound)\n else:\n normal = D.Normal(mu, sigma)\n\n log_probs = normal.log_prob(actions)\n entropy = -log_probs.mean(dim=-1)\n\n return log_probs, entropy, V_hat\n\n @torch.no_grad()\n def sample_action(self, x: torch.Tensor) -> np.ndarray:\n self.eval()\n mu, sigma, _ = self(x)\n normal: Union[D.Normal, SquashedNormal]\n if self.action_bound:\n normal = SquashedNormal(mu, sigma, self.action_bound)\n else:\n normal = D.Normal(mu, sigma)\n action = normal.sample()\n self.train()\n return action.detach().cpu().numpy()\n\n\nclass DiagonalGMMPolicy(Policy):\n \"\"\"Policy class for learning a factorized GMM.\n\n Learns a 1D GMM for each dimension of the action space.\n The components of the GMM are either Normal or squashed Normal.\n\n Parameters\n ----------\n representation_dim : int\n Dimensions of the input representation.\n action_dim : int\n Number of dimensions for the action space.\n distribution : str\n Distribution that is parameterized by the network. Has to be Normallike.\n Allows the following options:\n - \"normal\": Normal distribution.\n - \"tanhsquashed\", \"tanhsquashednormal\": Normal distribution with samples squashed in (-1, 1).\n - \"generalizedsquashed\", \"generalizedsquashednormal\": Normal distribution with samples squashed in (-c, c).\n num_components : int\n Number of mixture components.\n action_bound : Optional[float]\n Bounds for the action space. Can be either float or None.\n hidden_dimensions : List[int]\n Specify the number of hidden neurons for each respective hidden layer of the network. Cannot be empty.\n nonlinearity : str\n Nonlinearity used between hidden layers. Options are:\n - \"relu\": https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html#torch.nn.ReLU .\n - \"leakyrelu\": https://pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html#torch.nn.LeakyReLU.\n - \"relu6\": https://pytorch.org/docs/stable/generated/torch.nn.ReLU6.html#torch.nn.ReLU6.\n - \"silu\": https://pytorch.org/docs/stable/generated/torch.nn.SiLU.html#torch.nn.SiLU.\n - \"elu\": https://pytorch.org/docs/stable/generated/torch.nn.ELU.html#torch.nn.ELU.\n - \"hardswish\": https://pytorch.org/docs/stable/generated/torch.nn.Hardswish.html#torch.nn.Hardswish.\n layernorm : bool\n If True, the network is regularized with layer normalization after each liner layer.\n This may increase performance, see https://arxiv.org/pdf/1709.06560.pdf for info.\n log_param_min : int\n Lower bound for learned log standard deviations.\n log_param_max : int\n Upper bound for learned log standard deviations.\n \"\"\"\n\n # member annotations\n state_dim: int\n action_dim: int\n action_bound: Optional[float]\n log_param_min: float\n log_param_max: float\n hidden_layers: int\n hidden_dimensions: List[int]\n num_components: int\n trunk: nn.Sequential\n dist_head: nn.Linear\n value_head: nn.Linear\n\n # class variable\n policy_type: ClassVar[str] = \"DiagonalGMM\"\n\n def __init__(\n self,\n representation_dim: int,\n action_dim: int,\n action_bound: Optional[float],\n num_components: int,\n hidden_dimensions: List[int],\n nonlinearity: str,\n layernorm: bool,\n log_param_min: float,\n log_param_max: float,\n ):\n\n super().__init__(\n representation_dim=representation_dim,\n action_dim=action_dim,\n action_bound=action_bound,\n hidden_dimensions=hidden_dimensions,\n nonlinearity=nonlinearity,\n layernorm=layernorm,\n log_param_min=log_param_min,\n log_param_max=log_param_max,\n )\n\n self.num_components = num_components\n\n # calculate the number of parameters needed for the GMM\n # 2 comes from each distribution being specifiec by 2 parameters\n dist_params = num_components * (2 * self.action_dim + 1)\n self.dist_head = nn.Linear(hidden_dimensions[-1], dist_params)\n\n def forward(\n self, x: torch.FloatTensor\n ) -> Tuple[\n torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor\n ]:\n \"\"\"Returns the learned paremters of the distribution.\n\n Parameters\n ----------\n x : torch.FloatTensor\n Input state tensor.\n\n Returns\n -------\n Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]\n Distribution mean (mu), Distribution standard deviation (sigma),\n Logits for the categorical distribution parameterizing the components (log_coeffs),\n State value estimate (V_hat).\n \"\"\"\n x = self.trunk(x)\n V_hat = self.value_head(x)\n\n # mixture_params is a tensor of shape [batch_size, num_agents, 2*action_dim*num_components + num_components]\n # the elements in the first term (2*action_dim*num_components) are the parameters for the mixture components\n # the elements in the second term (+ num_components) are the mixture coefficients\n mixture_params = self.dist_head(x)\n # get mixture parameters and reorder to [batch_size, num_agents, 2*num_components, action_dim]\n dist_params = mixture_params[\n ..., : self.num_components * 2 * self.action_dim\n ].view(x.shape[0], -1)\n # get the num_components last tensor elements as logits for the mixture coefficients\n log_coeff = mixture_params[..., -self.num_components :]\n # split the dist_params along the middle dimension (2*num_components) into means and log stddevs\n mu, log_std = dist_params.chunk(2, dim=-1)\n\n # Learning the log_std_dev is a trick for numerical stability\n # Since the stddev > 0, we can learn the log and then exponentiate\n # constrain log_std inside [log_param_min, log_param_max]\n log_std = torch.clamp(log_std, min=self.log_param_min, max=self.log_param_max)\n sigma = log_std.exp()\n\n return mu, sigma, log_coeff, V_hat\n\n def get_train_data(\n self, states: torch.Tensor, actions: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n mu, sigma, log_coeff, V_hat = self(states)\n\n # We need num_actions identical gmms to sample log_probs for each action\n num_actions = actions.shape[-1]\n mu = mu.unsqueeze(dim=1).expand((-1, num_actions, -1))\n sigma = sigma.unsqueeze(dim=1).expand((-1, num_actions, -1))\n log_coeff = log_coeff.unsqueeze(dim=1).expand((-1, num_actions, -1))\n mix = D.Categorical(logits=log_coeff)\n\n component: Union[D.Normal, SquashedNormal]\n if self.action_bound:\n component = SquashedNormal(mu, sigma, self.action_bound)\n else:\n component = D.Normal(mu, sigma)\n gmm = D.MixtureSameFamily(mix, component)\n log_probs = gmm.log_prob(actions)\n entropy = -log_probs.mean(dim=-1)\n\n return log_probs, entropy, V_hat\n\n @torch.no_grad()\n def sample_action(self, x: torch.Tensor) -> np.ndarray:\n self.eval()\n mu, sigma, log_coeff, _ = self(x)\n mix = D.Categorical(logits=log_coeff)\n component: Union[D.Normal, SquashedNormal]\n if self.action_bound:\n component = SquashedNormal(mu, sigma, self.action_bound)\n else:\n component = D.Normal(mu, sigma)\n gmm = D.MixtureSameFamily(mix, component)\n action = gmm.sample()\n self.train()\n return action.detach().cpu().numpy()\n\n\nclass GeneralizedBetaPolicy(Policy):\n \"\"\"Policy class for a generalized Beta distribution.\n\n The beta distribution used by this class is generalized in that it has support\n [-c, c] instead of [0,1].\n This is achieved via a location-scale transformation (2c)x - c, where c are the desired bounds.\n Since both parameters alpha, beta > 0, the log-learning-trick for the Normal standard deviation\n is applied to both parameters.\n\n Parameters\n ----------\n representation_dim : int\n Dimensions of the input representation.\n action_dim : int\n Number of dimensions for the action space.\n action_bound : Optional[float]\n Bounds for the action space. Can be either float or None.\n hidden_dimensions : List[int]\n Specify the number of hidden neurons for each respective hidden layer of the network. Cannot be empty.\n nonlinearity : str\n Nonlinearity used between hidden layers. Options are:\n - \"relu\": https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html#torch.nn.ReLU .\n - \"leakyrelu\": https://pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html#torch.nn.LeakyReLU.\n - \"relu6\": https://pytorch.org/docs/stable/generated/torch.nn.ReLU6.html#torch.nn.ReLU6.\n - \"silu\": https://pytorch.org/docs/stable/generated/torch.nn.SiLU.html#torch.nn.SiLU.\n - \"elu\": https://pytorch.org/docs/stable/generated/torch.nn.ELU.html#torch.nn.ELU.\n - \"hardswish\": https://pytorch.org/docs/stable/generated/torch.nn.Hardswish.html#torch.nn.Hardswish.\n layernorm : bool\n If True, the network is regularized with layer normalization after each liner layer.\n This may increase performance, see https://arxiv.org/pdf/1709.06560.pdf for info.\n log_param_min : int\n Lower bound for learned log_alpha and log_beta.\n log_param_max : int\n Upper bound for learned log_alpha and log_beta.\n \"\"\"\n\n # member annotations\n state_dim: int\n action_dim: int\n action_bound: float\n log_param_min: float\n log_param_max: float\n hidden_layers: int\n hidden_dimensions: List[int]\n trunk: nn.Sequential\n dist_head: nn.Linear\n value_head: nn.Linear\n\n # class variable\n policy_type: ClassVar[str] = \"GeneralizedBeta\"\n\n def __init__(\n self,\n representation_dim: int,\n action_dim: int,\n action_bound: float,\n hidden_dimensions: List[int],\n nonlinearity: str,\n layernorm: bool,\n log_param_min: float,\n log_param_max: float,\n ):\n\n assert action_bound, \"Beta policy needs action bounds specified.\"\n\n super().__init__(\n representation_dim=representation_dim,\n action_dim=action_dim,\n action_bound=action_bound,\n hidden_dimensions=hidden_dimensions,\n nonlinearity=nonlinearity,\n layernorm=layernorm,\n log_param_min=log_param_min,\n log_param_max=log_param_max,\n )\n\n self.dist_head = nn.Linear(hidden_dimensions[-1], 2 * self.action_dim)\n\n def forward(\n self, x: torch.FloatTensor\n ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:\n \"\"\"Returns the learned paremters of the distribution.\n\n Parameters\n ----------\n x : torch.FloatTensor\n Input state tensor.\n\n Returns\n -------\n Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]\n Alpha parameter (alpha), Beta parameter (beta), State value estimate (V_hat).\n \"\"\"\n x = self.trunk(x)\n V_hat = self.value_head(x)\n\n # create distribution parameters\n dist_params = self.dist_head(x)\n\n # Use the log_std_dev trick for alpha and beta\n # since both alpha > 0 and beta > 0\n dist_params = torch.clamp(\n dist_params, min=self.log_param_min, max=self.log_param_max\n )\n alpha, beta = dist_params.exp().chunk(2, dim=-1)\n\n return alpha, beta, V_hat\n\n def get_train_data(\n self, states: torch.Tensor, actions: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n alpha, beta, V_hat = self(states)\n\n # ensure that the distribution batch_shape fits the number of actions taken for\n # each agent at the root\n num_actions = actions.shape[-1]\n alpha = alpha.expand(-1, num_actions)\n beta = beta.expand(-1, num_actions)\n beta_dist = GeneralizedBeta(alpha, beta, self.action_bound)\n log_probs = beta_dist.log_prob(actions)\n entropy = -log_probs.mean(dim=-1)\n\n return log_probs, entropy, V_hat\n\n @torch.no_grad()\n def sample_action(self, x: torch.Tensor) -> np.ndarray:\n self.eval()\n alpha, beta, _ = self(x)\n beta_dist = D.Beta(alpha, beta)\n action = beta_dist.sample()\n self.train()\n return action.detach().cpu().numpy()\n\n\ndef make_policy(\n representation_dim: int,\n action_dim: int,\n distribution: str,\n hidden_dimensions: List[int],\n nonlinearity: str,\n num_components: Optional[int] = None,\n num_actions: Optional[int] = None,\n action_bound: Optional[float] = None,\n layernorm: bool = False,\n log_param_min: float = -5,\n log_param_max: float = 2,\n) -> Union[\n DiscretePolicy, DiagonalNormalPolicy, DiagonalGMMPolicy, GeneralizedBetaPolicy\n]:\n \"\"\"Constructs a policy network from a given config.\n\n The following config keys need to be specified:\n - \"representation_dim\": int\n - \"action_dim\": int\n - \"distribution\": str\n - \"num_components\": int\n - \"action_bound\": float\n - \"hidden_dimensions\": List[int]\n - \"nonlinearity\": str\n - \"layernorm\": bool\n - \"log_param_min\": Optional[float]\n - \"log_param_max\": Optional[float]\n\n Parameters\n ----------\n representation_dim: int\n Dimensionality of the vector state space of the environment.\n action_dim: int\n Number of action dimensions in the environment.\n distribution: str\n Name of the policy distribution as string [\"discrete\", \"beta\", \"normal\"].\n hidden_dimensions: List[int]\n List specification of the MLP policy. Each int element in the list represents a hidden\n layer in the network with the respective number of neurons.\n nonlinearity: str\n Nonlinearity (activation function) used in the policy network.\n num_components: Optional[int] = None\n Number of components for mixture distributions.\n num_actions: Optional[int] = None\n Number of available actions. Used in the discrete policy.\n action_bound: Optional[float] = None\n Action bounds for the squashed normal or squashed GMM policy.\n layernorm: bool = False\n Use Layernorm in the policy network if set to True.\n log_param_min: float = -5\n Lower bound of the learned log parameters (standard deviation for Normal distributions).\n log_param_max: float = 2\n Upper bound of the learned log parameters.\n\n Returns\n -------\n Union[DiscretePolicy, DiagonalNormalPolicy, DiagonalGMMPolicy, GeneralizedBetaPolicy]\n Policy network intance.\n \"\"\"\n\n # basic config string preprocessing to ensure mapping works later\n distribution = _process_str(distribution)\n nonlinearity = _process_str(nonlinearity)\n\n if distribution == \"discrete\":\n return DiscretePolicy(\n representation_dim=representation_dim,\n action_dim=action_dim,\n num_actions=cast(int, num_actions),\n hidden_dimensions=hidden_dimensions,\n nonlinearity=nonlinearity,\n layernorm=layernorm,\n )\n elif distribution == \"beta\":\n assert num_components\n return GeneralizedBetaPolicy(\n representation_dim=representation_dim,\n action_dim=action_dim,\n action_bound=cast(float, action_bound),\n hidden_dimensions=hidden_dimensions,\n nonlinearity=nonlinearity,\n layernorm=layernorm,\n log_param_min=log_param_min,\n log_param_max=log_param_max,\n )\n else:\n assert num_components\n if 1 < num_components:\n return DiagonalGMMPolicy(\n representation_dim=representation_dim,\n action_dim=action_dim,\n num_components=num_components,\n action_bound=action_bound,\n hidden_dimensions=hidden_dimensions,\n nonlinearity=nonlinearity,\n layernorm=layernorm,\n log_param_min=log_param_min,\n log_param_max=log_param_max,\n )\n else:\n return DiagonalNormalPolicy(\n representation_dim=representation_dim,\n action_dim=action_dim,\n action_bound=action_bound,\n hidden_dimensions=hidden_dimensions,\n nonlinearity=nonlinearity,\n layernorm=layernorm,\n log_param_min=log_param_min,\n log_param_max=log_param_max,\n )\n" ]
[ [ "torch.nn.Sequential", "torch.nn.functional.softmax", "torch.distributions.Beta", "torch.nn.LayerNorm", "torch.nn.Linear", "torch.distributions.MixtureSameFamily", "torch.distributions.Categorical", "torch.no_grad", "torch.distributions.Normal", "torch.clamp", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ajkxyz/cuda4py
[ "3f04dd5d72d64e5bd68dee91de1193a7bb6e8033" ]
[ "tests/test_cufft.py" ]
[ "\"\"\"\nCopyright (c) 2014, Samsung Electronics Co.,Ltd.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nThe views and conclusions contained in the software and documentation are those\nof the authors and should not be interpreted as representing official policies,\neither expressed or implied, of Samsung Electronics Co.,Ltd..\n\"\"\"\n\n\"\"\"\ncuda4py - CUDA cffi bindings and helper classes.\nURL: https://github.com/ajkxyz/cuda4py\nOriginal author: Alexey Kazantsev <[email protected]>\n\"\"\"\n\n\"\"\"\nTests some of the api in cuda4py.cufft package.\n\"\"\"\nimport cuda4py as cu\nimport cuda4py.cufft as cufft\nimport gc\nimport logging\nimport numpy\nimport os\nimport unittest\n\n\nclass Test(unittest.TestCase):\n def setUp(self):\n logging.basicConfig(level=logging.DEBUG)\n self.old_env = os.environ.get(\"CUDA_DEVICE\")\n if self.old_env is None:\n os.environ[\"CUDA_DEVICE\"] = \"0\"\n self.ctx = cu.Devices().create_some_context()\n self.path = os.path.dirname(__file__)\n if not len(self.path):\n self.path = \".\"\n\n def tearDown(self):\n if self.old_env is None:\n del os.environ[\"CUDA_DEVICE\"]\n else:\n os.environ[\"CUDA_DEVICE\"] = self.old_env\n del self.old_env\n del self.ctx\n gc.collect()\n\n def test_constants(self):\n self.assertEqual(cufft.CUFFT_SUCCESS, 0)\n self.assertEqual(cufft.CUFFT_INVALID_PLAN, 1)\n self.assertEqual(cufft.CUFFT_ALLOC_FAILED, 2)\n self.assertEqual(cufft.CUFFT_INVALID_TYPE, 3)\n self.assertEqual(cufft.CUFFT_INVALID_VALUE, 4)\n self.assertEqual(cufft.CUFFT_INTERNAL_ERROR, 5)\n self.assertEqual(cufft.CUFFT_EXEC_FAILED, 6)\n self.assertEqual(cufft.CUFFT_SETUP_FAILED, 7)\n self.assertEqual(cufft.CUFFT_INVALID_SIZE, 8)\n self.assertEqual(cufft.CUFFT_UNALIGNED_DATA, 9)\n self.assertEqual(cufft.CUFFT_INCOMPLETE_PARAMETER_LIST, 10)\n self.assertEqual(cufft.CUFFT_INVALID_DEVICE, 11)\n self.assertEqual(cufft.CUFFT_PARSE_ERROR, 12)\n self.assertEqual(cufft.CUFFT_NO_WORKSPACE, 13)\n\n self.assertEqual(cufft.CUFFT_R2C, 0x2a)\n self.assertEqual(cufft.CUFFT_C2R, 0x2c)\n self.assertEqual(cufft.CUFFT_C2C, 0x29)\n self.assertEqual(cufft.CUFFT_D2Z, 0x6a)\n self.assertEqual(cufft.CUFFT_Z2D, 0x6c)\n self.assertEqual(cufft.CUFFT_Z2Z, 0x69)\n\n self.assertEqual(cufft.CUFFT_FORWARD, -1)\n self.assertEqual(cufft.CUFFT_INVERSE, 1)\n\n def test_errors(self):\n idx = cu.CU.ERRORS[cufft.CUFFT_INVALID_PLAN].find(\" | \")\n self.assertGreater(idx, 0)\n\n def test_version(self):\n fft = cufft.CUFFT(self.ctx)\n ver = fft.version\n logging.debug(\"cuFFT version is %d\", ver)\n self.assertTrue(ver == int(ver))\n\n def test_auto_allocation(self):\n fft = cufft.CUFFT(self.ctx)\n self.assertTrue(fft.auto_allocation)\n fft.auto_allocation = False\n self.assertFalse(fft.auto_allocation)\n fft.auto_allocation = True\n self.assertTrue(fft.auto_allocation)\n\n def test_make_plan_many(self):\n fft = cufft.CUFFT(self.ctx)\n fft.auto_allocation = False\n sz = fft.make_plan_many((256, 128), 8, cufft.CUFFT_C2C)\n logging.debug(\n \"make_plan_many (default layout) for 256x128 x8 returned %d\", sz)\n logging.debug(\"size is %d\", fft.size)\n self.assertEqual(fft.execute, fft.exec_c2c)\n\n fft = cufft.CUFFT(self.ctx)\n fft.auto_allocation = False\n sz = fft.make_plan_many((256, 128), 8, cufft.CUFFT_C2C,\n (256, 128), 1, 256 * 128,\n (256, 128), 1, 256 * 128)\n logging.debug(\n \"make_plan_many (tight layout) for 256x128 x8 returned is %d\", sz)\n logging.debug(\"size is %d\", fft.size)\n\n def _test_exec(self, dtype):\n x = numpy.zeros([32, 64], dtype=dtype)\n x[:] = numpy.random.rand(x.size).reshape(x.shape) - 0.5\n y = numpy.ones((x.shape[0], x.shape[1] // 2 + 1),\n dtype={numpy.float32: numpy.complex64,\n numpy.float64: numpy.complex128}[dtype])\n x_gold = x.copy()\n try:\n y_gold = numpy.fft.rfft2(x)\n except TypeError:\n y_gold = None # for pypy\n xbuf = cu.MemAlloc(self.ctx, x)\n ybuf = cu.MemAlloc(self.ctx, y)\n\n # Forward transform\n fft = cufft.CUFFT(self.ctx)\n fft.auto_allocation = False\n sz = fft.make_plan_many(x.shape, 1,\n {numpy.float32: cufft.CUFFT_R2C,\n numpy.float64: cufft.CUFFT_D2Z}[dtype])\n tmp = cu.MemAlloc(self.ctx, sz)\n fft.workarea = tmp\n self.assertEqual(fft.workarea, tmp)\n\n self.assertEqual(fft.execute,\n {numpy.float32: fft.exec_r2c,\n numpy.float64: fft.exec_d2z}[dtype])\n fft.execute(xbuf, ybuf)\n ybuf.to_host(y)\n\n if y_gold is not None:\n delta = y - y_gold\n max_diff = numpy.fabs(numpy.sqrt(delta.real * delta.real +\n delta.imag * delta.imag)).max()\n logging.debug(\"Forward max_diff is %.6e\", max_diff)\n self.assertLess(max_diff, {numpy.float32: 1.0e-3,\n numpy.float64: 1.0e-6}[dtype])\n\n # Inverse transform\n fft = cufft.CUFFT(self.ctx)\n fft.auto_allocation = False\n sz = fft.make_plan_many(x.shape, 1,\n {numpy.float32: cufft.CUFFT_C2R,\n numpy.float64: cufft.CUFFT_Z2D}[dtype])\n fft.workarea = cu.MemAlloc(self.ctx, sz)\n\n y /= x.size # correct scale before inverting\n ybuf.to_device_async(y)\n xbuf.memset32_async(0) # reset the resulting vector\n self.assertEqual(fft.execute,\n {numpy.float32: fft.exec_c2r,\n numpy.float64: fft.exec_z2d}[dtype])\n fft.execute(ybuf, xbuf)\n xbuf.to_host(x)\n\n max_diff = numpy.fabs(x - x_gold).max()\n logging.debug(\"Inverse max_diff is %.6e\", max_diff)\n self.assertLess(max_diff, {numpy.float32: 1.0e-3,\n numpy.float64: 1.0e-6}[dtype])\n\n def test_exec_float(self):\n logging.debug(\"ENTER: test_exec_float\")\n self._test_exec(numpy.float32)\n logging.debug(\"EXIT: test_exec_float\")\n\n def test_exec_double(self):\n logging.debug(\"ENTER: test_exec_double\")\n self._test_exec(numpy.float64)\n logging.debug(\"EXIT: test_exec_double\")\n\n def _test_exec_complex(self, dtype):\n x = numpy.zeros([32, 64], dtype=dtype)\n x.real = numpy.random.rand(x.size).reshape(x.shape) - 0.5\n x.imag = numpy.random.rand(x.size).reshape(x.shape) - 0.5\n y = numpy.ones_like(x)\n x_gold = x.copy()\n try:\n y_gold = numpy.fft.fft2(x)\n except TypeError:\n y_gold = None # for pypy\n xbuf = cu.MemAlloc(self.ctx, x)\n ybuf = cu.MemAlloc(self.ctx, y)\n\n # Forward transform\n fft = cufft.CUFFT(self.ctx)\n fft.auto_allocation = False\n sz = fft.make_plan_many(x.shape, 1,\n {numpy.complex64: cufft.CUFFT_C2C,\n numpy.complex128: cufft.CUFFT_Z2Z}[dtype])\n tmp = cu.MemAlloc(self.ctx, sz)\n fft.workarea = tmp\n self.assertEqual(fft.workarea, tmp)\n\n self.assertEqual(fft.execute, {numpy.complex64: fft.exec_c2c,\n numpy.complex128: fft.exec_z2z}[dtype])\n fft.execute(xbuf, ybuf, cufft.CUFFT_FORWARD)\n ybuf.to_host(y)\n\n if y_gold is not None:\n delta = y - y_gold\n max_diff = numpy.fabs(numpy.sqrt(delta.real * delta.real +\n delta.imag * delta.imag)).max()\n logging.debug(\"Forward max_diff is %.6e\", max_diff)\n self.assertLess(max_diff, {numpy.complex64: 1.0e-3,\n numpy.complex128: 1.0e-6}[dtype])\n\n # Inverse transform\n y /= x.size # correct scale before inverting\n ybuf.to_device_async(y)\n xbuf.memset32_async(0) # reset the resulting vector\n fft.execute(ybuf, xbuf, cufft.CUFFT_INVERSE)\n xbuf.to_host(x)\n\n delta = x - x_gold\n max_diff = numpy.fabs(numpy.sqrt(delta.real * delta.real +\n delta.imag * delta.imag)).max()\n logging.debug(\"Inverse max_diff is %.6e\", max_diff)\n self.assertLess(max_diff, {numpy.complex64: 1.0e-3,\n numpy.complex128: 1.0e-6}[dtype])\n\n def test_exec_complex_float(self):\n logging.debug(\"ENTER: test_exec_complex_float\")\n self._test_exec_complex(numpy.complex64)\n logging.debug(\"EXIT: test_exec_complex_float\")\n\n def test_exec_complex_double(self):\n logging.debug(\"ENTER: test_exec_complex_double\")\n self._test_exec_complex(numpy.complex128)\n logging.debug(\"EXIT: test_exec_complex_double\")\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.DEBUG)\n unittest.main()\n" ]
[ [ "numpy.fft.fft2", "numpy.ones_like", "numpy.sqrt", "numpy.ones", "numpy.fft.rfft2", "numpy.random.rand", "numpy.zeros", "numpy.fabs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
exitudio/neural-network-pytorch
[ "2831eb92d396187cc0e043234c2dfd17fc83ae3b", "2831eb92d396187cc0e043234c2dfd17fc83ae3b" ]
[ "exit/losses.py", "exit/initializers.py" ]
[ "from abc import ABC, abstractmethod\nimport numpy as np\nfrom .constants import EPSILON\nimport torch\n\n\nclass Loss(ABC):\n def __init__(self, expected_output, predict_output):\n self._expected_output = expected_output\n self._predict_output = predict_output\n\n @abstractmethod\n def get_loss(self):\n pass\n\n\ndef crossEntropy(expected_output, predict_output):\n return -(expected_output * torch.log(predict_output) +\n (1-expected_output) * torch.log(1-predict_output+EPSILON)).mean()\n\n\ndef l2(expected_output, predict_output):\n return ((predict_output - expected_output) ** 2).mean()\n", "from abc import ABC, abstractmethod\nimport torch\nimport math\n\n'''\ntensorflow implementation\n https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/init_ops.py\nDeeplearning.ai\n https://www.coursera.org/learn/deep-neural-network/lecture/RwqYe/weight-initialization-for-deep-networks\n'''\n\n\nclass Initializer(ABC):\n @abstractmethod\n def __call__(self, num_input, num_output):\n pass\n\n\nclass Constant(Initializer):\n def __init__(self, value):\n self._value = value\n\n def __call__(self, num_input, num_output):\n weights = torch.Tensor(num_input, num_output).fill_(self._value)\n weights.requires_grad_(True)\n return weights\n\n\nclass GlorotNormal(Initializer):\n def __call__(self, num_input, num_output):\n scale = 2/(num_input + num_output)\n stddev = math.sqrt(scale) / .87962566103423978\n weights = torch.randn(num_input, num_output) * math.sqrt(stddev)\n weights.requires_grad_(True)\n return weights\n\n\nclass GlorotUniform(Initializer):\n \"\"\"The Glorot uniform initializer, also called Xavier uniform initializer.\n It draws samples from a uniform distribution within [-limit, limit]\n where `limit` is `sqrt(6 / (fan_in + fan_out))`\n where `fan_in` is the number of input units in the weight tensor\n and `fan_out` is the number of output units in the weight tensor.\n Reference: http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf\n \"\"\"\n\n def __call__(self, num_input, num_output):\n scale = 2/(num_input + num_output)\n limit = math.sqrt(3.0 * scale)\n weights = (2*limit) * torch.rand(num_input, num_output) - limit\n weights.requires_grad_(True)\n return weights\n\n\n# if dtype is None:\n# dtype = self.dtype\n# scale = self.scale\n# scale_shape = shape\n# if partition_info is not None:\n# scale_shape = partition_info.full_shape\n# fan_in, fan_out = _compute_fans(scale_shape)\n# if self.mode == \"fan_in\":\n# scale /= max(1., fan_in)\n# elif self.mode == \"fan_out\":\n# scale /= max(1., fan_out)\n# else:\n# scale /= max(1., (fan_in + fan_out) / 2.)\n# if self.distribution == \"normal\" or self.distribution == \"truncated_normal\":\n# # constant taken from scipy.stats.truncnorm.std(a=-2, b=2, loc=0., scale=1.)\n# stddev = math.sqrt(scale) / .87962566103423978\n# return random_ops.truncated_normal(\n# shape, 0.0, stddev, dtype, seed=self.seed)\n# elif self.distribution == \"untruncated_normal\":\n# stddev = math.sqrt(scale)\n# return random_ops.random_normal(\n# shape, 0.0, stddev, dtype, seed=self.seed)\n# else:\n# limit = math.sqrt(3.0 * scale)\n# return random_ops.random_uniform(\n# shape, -limit, limit, dtype, seed=self.seed)\n" ]
[ [ "torch.log" ], [ "torch.randn", "torch.rand", "torch.Tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
essential2189/Cell-Based-Model
[ "f01c3fcb45e69baa4dc8216b8b5a092f56cfa38e" ]
[ "preprocess/watershed.py" ]
[ "#-*-coding:utf-8-*-\n\nimport numpy as np\nimport cv2\nimport gc\nfrom tqdm import tqdm\n\ndef watershed(opencv_image):\n top_n_label = 2\n\n gray = cv2.cvtColor(opencv_image, cv2.COLOR_BGR2GRAY)\n print('convert gray end')\n\n gray[gray == 0] = 255\n\n _, cvt_img = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)\n del(gray)\n print('threshold end')\n\n\n ret, markers = cv2.connectedComponents(cvt_img)\n print('connectedComponents end')\n\n label_dict = dict()\n for i in tqdm(range(ret)):\n if i == 0:\n continue\n label_dict[i] = len(markers[markers == i])\n sort_label_list = sorted(label_dict.items(), key=lambda item: item[1], reverse=True)\n print('label end')\n\n result = np.zeros(markers.shape)\n for ins in tqdm(sort_label_list[:top_n_label]):\n result[markers == ins[0]] = 255\n\n\n print(result.shape)\n\n print('top n label end')\n del(ret)\n del(markers)\n del(sort_label_list)\n del(label_dict)\n del(cvt_img)\n\n\n return result" ]
[ [ "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
nicksacco17/Quantum_Information
[ "c1ee8369f34a9b78a7360cd68b6f2da082266d4a" ]
[ "main.py" ]
[ "\nfrom PauliInteraction import PauliInteraction\nfrom Ising import Ising\nfrom CoefficientGenerator import CoefficientGenerator\nfrom Evaluator import Evaluator\n\n#from DataVisualizer import DataVisualizer\n#from DataLogger import DataLogger\n\nimport Driver as Driver_H\n\nfrom MasterEquation import MasterEquation\nfrom QuantumAnnealer import QuantumAnnealer\nfrom Test import test\n#from mpi4py import MPI\n\n\nimport qutip as qp\nimport numpy as np\nimport time as time\nimport sys\n\nX_HAT = \"X\"\nY_HAT = \"Y\"\nZ_HAT = \"Z\"\n\n#NUM_TESTS = 1\n#N = 7\nT = 100\n#NUM_INTERACTIONS = int((N * (N - 1)) / 2)\nRAND_COEF = False\n\nMASTER_RANK = 0\n\n# MAIN TEST CASES FROM SAMPLE CODE\n\n# THIS IS NOT USED!\ndef main():\n\n print(argv)\n COMM = MPI.COMM_WORLD\n NUM_PROC = COMM.Get_size()\n M_RANK = COMM.Get_rank()\n\n N = 100\n m_N = (int) (N / NUM_PROC)\n\n if M_RANK == MASTER_RANK:\n A = np.arange(N, dtype = np.float64)\n start_time = MPI.Wtime()\n else:\n A = np.empty(N, dtype = np.float64)\n\n m_A = np.empty(m_N, dtype = np.float64)\n\n # Scatter\n COMM.Scatter([A, MPI.DOUBLE], [m_A, MPI.DOUBLE])\n\n for i in range(m_N):\n m_A[i] = M_RANK\n\n COMM.Barrier()\n\n COMM.Allgather([m_A, MPI.DOUBLE], [A, MPI.DOUBLE])\n\n COMM.Barrier()\n\n if M_RANK == MASTER_RANK:\n print(A)\n\n #for i in range(10):\n #test(RAND_COEF, i)\n\n# THIS IS USED!\ndef parallel_main(NUM_TESTS, NUM_QUBITS):\n \n\t# MPI Initialization\n COMM = MPI.COMM_WORLD\n NUM_PROC = COMM.Get_size()\n M_RANK = COMM.Get_rank()\n\n\t# If process is master rank, allocate array of overlap probabilities\n if M_RANK == MASTER_RANK:\n overlap_probabilities = np.zeros(NUM_TESTS, dtype = np.float64)\n start_time = MPI.Wtime()\n else:\n overlap_probabilities = np.empty(NUM_TESTS, dtype = np.float64);\n\n\t# Calculate the local number of tests to perform\n M_TESTS = (int) (NUM_TESTS / NUM_PROC)\n\t\n\t# Allocate local overlap probablity arrays\n m_overlap_probabilities = np.empty(M_TESTS, dtype = np.float64)\n\n\t# Scatter the global overlap probabilities\n COMM.Scatter([overlap_probabilities, MPI.DOUBLE], [m_overlap_probabilities, MPI.DOUBLE])\n\n\t# And for each process, perform its local tests and save overlap probability\n for i in range(M_TESTS):\n m_overlap_probabilities[i] = test(RAND_COEF, 0, NUM_QUBITS)\n\n\t# Enforce synchronization\n COMM.Barrier()\n\n\t# Gather the local overlap probabilities in master rank\n COMM.Allgather([m_overlap_probabilities, MPI.DOUBLE], [overlap_probabilities, MPI.DOUBLE])\n\n\t# Enforce synchronization\n COMM.Barrier()\n\n\t# When tests are done, master rank will process data and print\n if M_RANK == MASTER_RANK:\n stop_time = MPI.Wtime()\n total_time = stop_time - start_time\n\t\t# Print probabilities - TODO(Log this to a file, not just print to screen)\n #for i in range(len(overlap_probabilities)):\n #print(\"ITERATION %d, OVERLAP PROBABILITY = %f\" % (i, overlap_probabilities[i]))\n \n\t\t# Print run statistics\n print(\"---------- NUMBER OF QUBITS = %d ----------\" % NUM_QUBITS)\n print(\"\\tNUMBER OF PROCESSES = %d\" % NUM_PROC)\n print(\"\\tNUMBER OF TESTS = %d\" % NUM_TESTS)\n print(\"\\tTOTAL TIME = %f sec\" % total_time)\n print(\"------------------------------------------\")\n\n# Initial script\nif __name__ == \"__main__\":\n NUM_TESTS = int(sys.argv[1])\n NUM_QUBITS = int(sys.argv[2])\n parallel_main(NUM_TESTS, NUM_QUBITS)\n\n\n" ]
[ [ "numpy.arange", "numpy.zeros", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
gajeraj/MLSA-workshops-2020-student
[ "cafbf5ac8750dd2b962174ad71dabf35ac90e2f4" ]
[ "Unsupervised-Learning/rbm.py" ]
[ "import tensorflow as tf \nimport numpy as np \nimport os \nimport matplotlib.pyplot as plt \nfrom tqdm import tqdm \n\nclass RBM(object):\n \n def __init__(self,num_visible,num_hidden,visible_unit_type='bin',main_dir='/Users/chamalgomes/Documents/Python/GitLab/DeepLearning/KAI PROJECT/rbm/models',\n model_name='rbm_model',gibbs_sampling_steps=1,learning_rate=0.01,momentum=0.9,l2=0.001,batch_size=10,\n num_epochs=10,stddev=0.1,verbose=0,plot_training_loss=True):\n \"\"\"\"\n INPUT PARAMETER 1) num_visible: number of visible units in the RBM \n INPUT PARAMETER 2) num_hidden: number of hidden units in the RBM\n INPUT PARAMETER 3) main_dir: main directory to put the models, data and summary directories\n INPUT PARAMETER 4) model_name: name of the model you wanna save the data \n INPUT PARAMETER 5) gibbs_sampling_steps: Default 1 (Hence Optional)\n INPUT PARAMETER 6) learning_rate: Default 0.01 (Hence Optional) \n INPUT PARAMETER 7) momentum: Default 0.9(Hence Optional) for Gradient Descent \n INPUT PARAMETER 8) l2: l2 regularization lambda value for weight decay Default 0.001(Hence Optional)\n INPUT PARAMETER 9) batch_size: Default 10 (Hence Optional)\n INPUT PARAMETER 10) num_epochs: Default 10 (Hence Optional)\n INPUT PARAMETER 11) stddev: optional, default 0.1. Ignored if visible_unit_type is not 'gauss'\n INPUT PARAMETER 12) verbose: evel of verbosity. optional, default 0(for Regularization)\n INPUT PARAMETER 13) plot_training_loss: whether or not to plot training loss, default True\n INPUT PARAMETER 14) visible_units_type: Binary or Gaussian (Default Binary)\n \"\"\"\n #Defining main paramters\n self.num_visible = num_visible #1\n self.num_hidden = num_hidden #2\n self.main_dir = main_dir #3\n self.model_name = model_name #4\n self.gibbs_sampling_steps = gibbs_sampling_steps #5 \n self.learning_rate = learning_rate #6 \n self.momentum = momentum #7 \n self.l2 = l2 #8 \n self.batch_size = batch_size #9 \n self.num_epochs = num_epochs #10\n self.stddev = stddev #11\n self.verbose = verbose #12\n self.plot_training_loss = plot_training_loss #13\n self.visible_unit_type = visible_unit_type #14\n\n self._create_model_directory()\n self.model_path = os.path.join(self.main_dir, self.model_name)\n\n self.W = None \n self.bh_ = None \n self.bv_ = None \n self.dw = None \n self.dbh_ = None \n self.dbv_ = None \n \n self.w_upd8 = None\n self.bh_upd8 = None\n self.bv_upd8 = None\n \n self.encode = None\n self.recontruct = None\n\n self.loss_function = None\n self.batch_cost = None\n self.batch_free_energy = None\n \n self.training_losses = []\n\n self.input_data = None#_build_model \n self.hrand = None # _build_model \n self.validation_size = None #fit\n\n self.tf_session = None #fit \n self.tf_saver = None #_initialize_tf_utilities_and_ops\n \n def sample_prob(self,probs,rand):\n \"\"\" takes a tensor of probabilitiesas from a sigmoidal activation and sample from all \n the distributions. \n probs INPUT parameter: tensor of probabilities \n rand INPUT parameter :tensor (of same shape as probabilities) of random values \n :RETURN binary sample of probabilities \n \"\"\"\n return tf.nn.relu(tf.sign(probs-rand))\n \n def gen_batches(self,data,batch_size):\n \"\"\" Divide input data into batches \n data INPUT parameter: input data( like a data frame)\n batch_size INPUT parameter: desired size of each batch\n :RETURN data divided in batches \n \"\"\"\n data = np.array(data)\n \n for i in range(0,data.shape[0],batch_size):\n yield data[i:i+batch_size]\n \n \n def fit(self,train_set,validation_set = None,restore_previous_model=False):\n \"\"\"\"\n fit the model to the training data \n INPUT PARAMETER train_set: training set\n INPUT PARAMETER validation set.default None (Hence Optional)\n INPUT PARAMETER restore_previous_model:\n if true, a previous trained model\n with the same name of this model is restored from disk to continue training.\n OUTPUT: self \n \"\"\"\n \n if validation_set is not None:\n self.validation_size = validation_set.shape[0]\n \n tf.reset_default_graph()\n \n self._build_model()# you will come across it later on \n \n with tf.Session() as self.tf_session:\n self._initialize_tf_utilities_and_ops(restore_previous_model)\n self._train_model(train_set, validation_set)\n self.tf_saver.save(self.tf_session, self.model_path)\n\n if self.plot_training_loss:\n #plot editing should be done here as you wish \n plt.plot(self.training_losses)\n plt.title(\"Training batch losses v.s. iteractions\")\n plt.xlabel(\"Num of training iteractions\")\n plt.ylabel(\"Reconstruction error\")\n plt.show()\n \n def _initialize_tf_utilities_and_ops(self, restore_previous_model):\n \"\"\"\"\n Initialize TensorFlow operations: summaries, init operations, saver, summary_writer.\n Restore a previously trained model if the flag restore_previous_model is true.\n \"\"\"\n \n init_op = tf.global_variables_initializer()\n self.tf_saver = tf.train.Saver()\n self.tf_session.run(init_op)\n \n if restore_previous_model:\n self.tf_saver.restore(self.tf_session, self.model_path)\n \n def _train_model(self, train_set, validation_set):\n \"\"\"\" Train the Model \n \n INPUT PARAMETER train set: Training set \n INPUT PARAMETER validation_set: Validation set \n OUTPUT self\n \"\"\"\n \n for i in range(self.num_epochs):\n self._run_train_step(train_set)\n\n if validation_set is not None:\n self._run_validation_error(i, validation_set)\n\n def _run_train_step(self,train_set):\n \"\"\"\"\n Run a training step. A training step is made by randomly shuffling the training set,\n divide into batches and run the variable update nodes for each batch. If self.plot_training_loss \n is true, will record training loss after each batch. \n INPUT PARAMETER train_set: training set\n OUTPUT self\n \"\"\"\n\n np.random.shuffle(train_set)\n batches = [_ for _ in self.gen_batches(train_set, self.batch_size)]\n updates = [self.w_upd8, self.bh_upd8, self.bv_upd8]\n\n \n for batch in batches:\n if self.plot_training_loss:\n _,loss = self.tf_session.run([updates,self.loss_function],feed_dict = self._create_feed_dict(batch))\n self.training_losses.append(loss)\n \n else:\n self.tf_session.run(updates, feed_dict=self._create_feed_dict(batch))\n \n \n def _run_validation_error(self, epoch, validation_set):\n \"\"\" \n Run the error computation on the validation set and print it out for each epoch. \n INPUT PARAMETER: current epoch\n INPUT PARAMETER validation_set: validation data\n OUTPUT: self\n \"\"\"\n loss = self.tf_session.run(self.loss_function,\n feed_dict=self._create_feed_dict(validation_set))\n\n if self.verbose == 1:\n tqdm.write(\"Validation cost at step %s: %s\" % (epoch, loss))\n\n \n def _create_feed_dict(self, data):\n\n \"\"\" Create the dictionary of data to feed to TensorFlow's session during training.\n :param data: training/validation set batch\n :return: dictionary(self.input_data: data, self.hrand: random_uniform)\n \"\"\"\n\n return {\n self.input_data: data,\n self.hrand: np.random.rand(data.shape[0], self.num_hidden),\n }\n\n \n \n \n def _build_model(self):\n \n \"\"\"\n BUilding the Restriced Boltzman Machine in Tensorflow\n \"\"\"\n \n self.input_data, self.hrand = self._create_placeholders() #check the function below\n self.W, self.bh_, self.bv_, self.dw, self.dbh_, self.dbv_ = self._create_variables()#check the function below\n \n hprobs0, hstates0, vprobs, hprobs1, hstates1 = self.gibbs_sampling_step(self.input_data)\n positive = self.compute_positive_association(self.input_data, hprobs0, hstates0)\n \n nn_input = vprobs \n \n for step in range(self.gibbs_sampling_steps - 1):\n hprobs, hstates, vprobs, hprobs1, hstates1 = self.gibbs_sampling_step(nn_input)\n nn_input = vprobs\n \n self.reconstruct = vprobs \n \n negative = tf.matmul(tf.transpose(vprobs), hprobs1)\n self.encode = hprobs1\n \n #exact formula in my paper \n dw = positive - negative\n self.dw = self.momentum*self.dw + (1-self.momentum)*dw\n self.w_upd8 = self.W.assign_add(self.learning_rate*self.dw - self.learning_rate*self.l2*self.W)\n\n dbh_ = tf.reduce_mean(hprobs0 - hprobs1, 0)\n self.dbh_ = self.momentum*self.dbh_ + self.learning_rate*dbh_\n self.bh_upd8 = self.bh_.assign_add(self.dbh_)\n \n dbv_ = tf.reduce_mean(self.input_data - vprobs, 0)\n self.dbv_ = self.momentum*self.dbv_ + self.learning_rate*dbv_\n self.bv_upd8 = self.bv_.assign_add(self.dbv_)\n\n \n self.loss_function = tf.sqrt(tf.reduce_mean(tf.square(self.input_data - vprobs)))\n\n self.batch_cost = tf.sqrt(tf.reduce_mean(tf.square(self.input_data - vprobs), 1))\n \n self._create_free_energy_for_batch()\n \n def _create_free_energy_for_batch(self):\n\n \"\"\" Create free energy ops to batch input data \n :return: self\n \"\"\"\n\n if self.visible_unit_type == 'bin':\n self._create_free_energy_for_bin() \n elif self.visible_unit_type == 'gauss':\n self._create_free_energy_for_gauss()\n else:\n self.batch_free_energy = None\n \n def _create_free_energy_for_bin(self):\n\n \"\"\" Create free energy for mdoel with Bin visible layer\n :return: self\n \"\"\"\n #Refer to the Binary Free Energy Equation \n self.batch_free_energy = - (tf.matmul(self.input_data, tf.reshape(self.bv_, [-1, 1])) + tf.reshape(tf.reduce_sum(tf.log(tf.exp(tf.matmul(self.input_data, self.W) + self.bh_) + 1), 1), [-1, 1]))\n\n \n \n\n def _create_free_energy_for_gauss(self):\n\n \"\"\" Create free energy for model with Gauss visible layer \n :return: self\n \"\"\"\n #Refer to the Gaussian Free Energy Equation\n self.batch_free_energy = - (tf.matmul(self.input_data, tf.reshape(self.bv_, [-1, 1])) - tf.reshape(tf.reduce_sum(0.5 * self.input_data * self.input_data, 1), [-1, 1]) + tf.reshape(tf.reduce_sum(tf.log(tf.exp(tf.matmul(self.input_data, self.W) + self.bh_) + 1), 1), [-1, 1]))\n\n def _create_placeholders(self):\n\n \"\"\" Create the TensorFlow placeholders for the model.\n :return: tuple(input(shape(None, num_visible)), \n hrand(shape(None, num_hidden)))\n \"\"\"\n\n x = tf.placeholder('float', [None, self.num_visible], name='x-input')\n hrand = tf.placeholder('float', [None, self.num_hidden], name='hrand')\n\n return x, hrand\n \n def _create_variables(self):\n\n \"\"\" Create the TensorFlow variables for the model.\n :return: tuple(weights(shape(num_visible, num_hidden),\n hidden bias(shape(num_hidden)),\n visible bias(shape(num_visible)))\n \"\"\"\n\n W = tf.Variable(tf.random_normal((self.num_visible, self.num_hidden), mean=0.0, stddev=0.01), name='weights')\n dw = tf.Variable(tf.zeros([self.num_visible, self.num_hidden]), name = 'derivative-weights')\n\n bh_ = tf.Variable(tf.zeros([self.num_hidden]), name='hidden-bias')\n dbh_ = tf.Variable(tf.zeros([self.num_hidden]), name='derivative-hidden-bias')\n\n bv_ = tf.Variable(tf.zeros([self.num_visible]), name='visible-bias')\n dbv_ = tf.Variable(tf.zeros([self.num_visible]), name='derivative-visible-bias')\n\n return W, bh_, bv_, dw, dbh_, dbv_\n \n def gibbs_sampling_step(self, visible):\n\n \"\"\" Performs one step of gibbs sampling.\n :param visible: activations of the visible units\n :return: tuple(hidden probs, hidden states, visible probs,\n new hidden probs, new hidden states)\n \"\"\"\n\n hprobs, hstates = self.sample_hidden_from_visible(visible)\n vprobs = self.sample_visible_from_hidden(hprobs)\n hprobs1, hstates1 = self.sample_hidden_from_visible(vprobs)\n\n return hprobs, hstates, vprobs, hprobs1, hstates1\n\n def sample_hidden_from_visible(self, visible):\n\n \"\"\" Sample the hidden units from the visible units.\n This is the Positive phase of the Contrastive Divergence algorithm.\n :param visible: activations of the visible units\n :return: tuple(hidden probabilities, hidden binary states)\n \"\"\"\n\n hprobs = tf.nn.sigmoid(tf.matmul(visible, self.W) + self.bh_)\n hstates = self.sample_prob(hprobs, self.hrand)\n\n return hprobs, hstates\n\n def sample_visible_from_hidden(self, hidden):\n\n \"\"\" Sample the visible units from the hidden units.\n This is the Negative phase of the Contrastive Divergence algorithm.\n :param hidden: activations of the hidden units\n :return: visible probabilities\n \"\"\"\n\n visible_activation = tf.matmul(hidden, tf.transpose(self.W)) + self.bv_\n\n if self.visible_unit_type == 'bin':\n vprobs = tf.nn.sigmoid(visible_activation)\n\n elif self.visible_unit_type == 'gauss':\n vprobs = tf.truncated_normal((1, self.num_visible), mean=visible_activation, stddev=self.stddev)\n else:\n vprobs = None\n\n return vprobs\n\n def compute_positive_association(self, visible, hidden_probs, hidden_states):\n\n \"\"\" Compute positive associations between visible and hidden units.\n :param visible: visible units\n :param hidden_probs: hidden units probabilities\n :param hidden_states: hidden units states\n :return: positive association = dot(visible.T, hidden)\n \"\"\"\n\n if self.visible_unit_type == 'bin':\n positive = tf.matmul(tf.transpose(visible), hidden_states)\n\n elif self.visible_unit_type == 'gauss':\n positive = tf.matmul(tf.transpose(visible), hidden_probs)\n\n else:\n positive = None\n\n return positive\n\n def _create_model_directory(self):\n\n \"\"\" Create the directory for storing the model\n :return: self\n \"\"\"\n\n if not os.path.isdir(self.main_dir):\n print(\"Created dir: \", self.main_dir)\n os.mkdir(self.main_dir)\n\n def getRecontructError(self, data):\n\n \"\"\" return Reconstruction Error (loss) from data in batch.\n :param data: input data of shape num_samples x visible_size\n :return: Reconstruction cost for each sample in the batch\n \"\"\"\n\n with tf.Session() as self.tf_session:\n\n self.tf_saver.restore(self.tf_session, self.model_path)\n\n batch_loss = self.tf_session.run(self.batch_cost,\n feed_dict=self._create_feed_dict(data))\n return batch_loss\n\n def getFreeEnergy(self, data):\n\n \"\"\" return Free Energy from data.\n :param data: input data of shape num_samples x visible_size\n :return: Free Energy for each sample: p(x)\n \"\"\"\n\n with tf.Session() as self.tf_session:\n\n self.tf_saver.restore(self.tf_session, self.model_path)\n\n batch_FE = self.tf_session.run(self.batch_free_energy,\n feed_dict=self._create_feed_dict(data))\n\n return batch_FE\n\n def getRecontruction(self, data):\n\n with tf.Session() as self.tf_session:\n \n self.tf_saver.restore(self.tf_session, self.model_path)\n\n batch_reconstruct = self.tf_session.run(self.recontruct, \n feed_dict=self._create_feed_dict(data))\n\n return batch_reconstruct\n\n def load_model(self, shape, gibbs_sampling_steps, model_path):\n\n \"\"\" Load a trained model from disk. The shape of the model\n (num_visible, num_hidden) and the number of gibbs sampling steps\n must be known in order to restore the model.\n :param shape: tuple(num_visible, num_hidden)\n :param gibbs_sampling_steps:\n :param model_path:\n :return: self\n \"\"\"\n\n self.num_visible, self.num_hidden = shape[0], shape[1]\n self.gibbs_sampling_steps = gibbs_sampling_steps\n \n tf.reset_default_graph()\n\n self._build_model()\n\n init_op = tf.global_variables_initializer()\n self.tf_saver = tf.train.Saver()\n\n with tf.Session() as self.tf_session:\n\n self.tf_session.run(init_op)\n self.tf_saver.restore(self.tf_session, model_path)\n\n def get_model_parameters(self):\n\n \"\"\" Return the model parameters in the form of numpy arrays.\n :return: model parameters\n \"\"\"\n\n with tf.Session() as self.tf_session:\n\n self.tf_saver.restore(self.tf_session, self.model_path)\n\n return {\n 'W': self.W.eval(),\n 'bh_': self.bh_.eval(),\n 'bv_': self.bv_.eval()\n }\n \n\n\n#The MIT License (MIT)\n\n#Copyright (c) 2016 Gabriele Angeletti\n\n#Permission is hereby granted, free of charge, to any person obtaining a copy\n#of this software and associated documentation files (the \"Software\"), to deal\n#in the Software without restriction, including without limitation the rights\n#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n#copies of the Software, and to permit persons to whom the Software is\n#furnished to do so, subject to the following conditions:\n\n#The above copyright notice and this permission notice shall be included in all\n#copies or substantial portions of the Software.\n\n#THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n#SOFTWARE.\n#© 2019 GitHub, Inc.\n\n" ]
[ [ "tensorflow.sign", "tensorflow.zeros", "tensorflow.reduce_sum", "matplotlib.pyplot.plot", "tensorflow.reset_default_graph", "tensorflow.Session", "tensorflow.square", "tensorflow.train.Saver", "tensorflow.matmul", "tensorflow.nn.sigmoid", "tensorflow.truncated_normal", "matplotlib.pyplot.title", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "numpy.random.rand", "numpy.array", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "tensorflow.transpose", "tensorflow.reduce_mean", "tensorflow.reshape", "numpy.random.shuffle", "matplotlib.pyplot.xlabel", "tensorflow.random_normal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
GueroudjiAmal/dask-ml
[ "54a8913bfb22775c72ffd781bf29d6e53b5dd363" ]
[ "tests/metrics/test_metrics.py" ]
[ "import dask\nimport dask.array as da\nimport numpy as np\nimport numpy.testing as npt\nimport pytest\nimport sklearn\nimport sklearn.linear_model\nimport sklearn.metrics\nfrom dask.array.utils import assert_eq\n\nimport dask_ml.metrics\nimport dask_ml.wrappers\n\n\ndef test_pairwise_distances(X_blobs):\n centers = X_blobs[::100].compute()\n result = dask_ml.metrics.pairwise_distances(X_blobs, centers)\n expected = sklearn.metrics.pairwise_distances(X_blobs.compute(), centers)\n assert_eq(result, expected, atol=1e-4)\n\n\ndef test_pairwise_distances_argmin_min(X_blobs):\n centers = X_blobs[::100].compute()\n\n # X_blobs has 500 rows per block.\n # Ensure 500 rows in the scikit-learn version too.\n working_memory = float(80 * 500) / 2 ** 20\n\n ctx = sklearn.config_context(working_memory=working_memory)\n\n with ctx:\n a_, b_ = sklearn.metrics.pairwise_distances_argmin_min(\n X_blobs.compute(), centers\n )\n a, b = dask_ml.metrics.pairwise_distances_argmin_min(X_blobs, centers)\n a, b = dask.compute(a, b)\n\n npt.assert_array_equal(a, a_)\n npt.assert_array_equal(b, b_)\n\n\ndef test_euclidean_distances():\n X = da.random.uniform(size=(100, 4), chunks=50)\n Y = da.random.uniform(size=(100, 4), chunks=50)\n a = dask_ml.metrics.euclidean_distances(X, Y)\n b = sklearn.metrics.euclidean_distances(X, Y)\n assert_eq(a, b)\n\n x_norm_squared = (X ** 2).sum(axis=1).compute()[:, np.newaxis]\n a = dask_ml.metrics.euclidean_distances(X, Y, X_norm_squared=x_norm_squared)\n b = sklearn.metrics.euclidean_distances(X, Y, X_norm_squared=x_norm_squared)\n assert_eq(a, b)\n\n y_norm_squared = (Y ** 2).sum(axis=1).compute()[np.newaxis, :]\n a = dask_ml.metrics.euclidean_distances(X, Y, Y_norm_squared=y_norm_squared)\n b = sklearn.metrics.euclidean_distances(X, Y, Y_norm_squared=y_norm_squared)\n assert_eq(a, b)\n\n\ndef test_euclidean_distances_same():\n X = da.random.uniform(size=(100, 4), chunks=50)\n a = dask_ml.metrics.euclidean_distances(X, X)\n b = sklearn.metrics.euclidean_distances(X, X)\n assert_eq(a, b, atol=1e-4)\n\n a = dask_ml.metrics.euclidean_distances(X)\n b = sklearn.metrics.euclidean_distances(X)\n assert_eq(a, b, atol=1e-4)\n\n x_norm_squared = (X ** 2).sum(axis=1).compute()[:, np.newaxis]\n assert_eq(X, X, Y_norm_squared=x_norm_squared, atol=1e-4)\n\n\[email protected](\"kernel\", [\"linear\", \"polynomial\", \"rbf\", \"sigmoid\"])\ndef test_pairwise_kernels(kernel):\n X = da.random.uniform(size=(100, 4), chunks=(50, 4))\n a = dask_ml.metrics.pairwise.PAIRWISE_KERNEL_FUNCTIONS[kernel]\n b = sklearn.metrics.pairwise.PAIRWISE_KERNEL_FUNCTIONS[kernel]\n\n r1 = a(X)\n r2 = b(X.compute())\n assert isinstance(X, da.Array)\n assert_eq(r1, r2)\n\n\[email protected](\"sample_weight\", [True, False])\[email protected](\"normalize\", [True, False])\[email protected](\"labels\", [[0, 1], [0, 1, 3], [1, 0]])\[email protected](\"daskify\", [True, False])\ndef test_log_loss(labels, normalize, sample_weight, daskify):\n n = 100\n c = 25\n y_true = np.random.choice(labels, size=n)\n y_pred = np.random.uniform(size=(n, len(labels)))\n y_pred /= y_pred.sum(1, keepdims=True)\n\n if sample_weight:\n sample_weight = np.random.uniform(size=n)\n sample_weight /= sample_weight.sum()\n dsample_weight = da.from_array(sample_weight, chunks=c)\n else:\n sample_weight = None\n dsample_weight = None\n\n if daskify:\n dy_true = da.from_array(y_true, chunks=c)\n dy_pred = da.from_array(y_pred, chunks=c)\n else:\n dy_true = y_true\n dy_pred = y_pred\n (dsample_weight,) = dask.compute(dsample_weight)\n\n a = sklearn.metrics.log_loss(\n y_true, y_pred, normalize=normalize, sample_weight=sample_weight\n )\n b = dask_ml.metrics.log_loss(\n dy_true,\n dy_pred,\n labels=labels,\n normalize=normalize,\n sample_weight=dsample_weight,\n )\n\n assert_eq(a, b)\n\n\[email protected](\n \"yhat\",\n [\n da.from_array(np.array([0.25, 0.25, 0.75, 0.75]), chunks=2),\n da.from_array(np.array([0, 0, 1, 1]), chunks=2),\n da.from_array(\n np.array([[0.75, 0.25], [0.75, 0.25], [0.25, 0.75], [0.25, 0.75]]), chunks=2\n ),\n ],\n)\ndef test_log_loss_shape(yhat):\n y = da.from_array(np.array([0, 0, 1, 1]), chunks=2)\n labels = [0, 1]\n a = sklearn.metrics.log_loss(y, yhat)\n b = dask_ml.metrics.log_loss(y, yhat, labels=labels)\n assert_eq(a, b)\n\n\[email protected](\"y\", [[0, 1, 1, 0], [0, 1, 2, 0]])\ndef test_log_loss_scoring(y):\n # a_scorer = sklearn.metrics.get_scorer('neg_log_loss')\n # b_scorer = dask_ml.metrics.get_scorer('neg_log_loss')\n X = da.random.uniform(size=(4, 2), chunks=2)\n labels = np.unique(y)\n y = da.from_array(np.array(y), chunks=2)\n\n a_scorer = sklearn.metrics.make_scorer(\n sklearn.metrics.log_loss,\n greater_is_better=False,\n needs_proba=True,\n labels=labels,\n )\n b_scorer = sklearn.metrics.make_scorer(\n dask_ml.metrics.log_loss,\n greater_is_better=False,\n needs_proba=True,\n labels=labels,\n )\n\n clf = dask_ml.wrappers.ParallelPostFit(\n sklearn.linear_model.LogisticRegression(\n n_jobs=1, solver=\"lbfgs\", multi_class=\"auto\"\n )\n )\n clf.fit(*dask.compute(X, y))\n\n result = b_scorer(clf, X, y)\n expected = a_scorer(clf, *dask.compute(X, y))\n\n assert_eq(result, expected)\n" ]
[ [ "sklearn.linear_model.LogisticRegression", "numpy.random.choice", "sklearn.config_context", "numpy.unique", "sklearn.metrics.euclidean_distances", "numpy.testing.assert_array_equal", "sklearn.metrics.log_loss", "sklearn.metrics.make_scorer", "numpy.random.uniform", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
python-hydro/hydro_examples
[ "55b7750a7644f3e2187f7fe338b6bc1d6fb9c139", "55b7750a7644f3e2187f7fe338b6bc1d6fb9c139" ]
[ "multigrid/patch1d.py", "burgers/burgers.py" ]
[ "\"\"\"\nThe patch module allows for a grid to be created and for data to be\ndefined on that grid.\n\nTypical usage:\n\n -- create the grid\n\n grid = Grid1d(nx)\n\n\n -- create the data that lives on that grid\n\n data = CellCenterData1d(grid)\n\n bcObj = bcObject(xlb=\"reflect\", xrb=\"reflect\"_\n data.registerVar(\"density\", bcObj)\n ...\n\n data.create()\n\n\n -- initialize some data\n\n dens = data.get_var(\"density\")\n dens[:,:] = ...\n\n\n -- fill the ghost cells\n\n data.fil_lBC(\"density\")\n\n\"\"\"\n\nfrom __future__ import print_function\n\nimport sys\nimport numpy\n\nvalid = [\"outflow\", \"periodic\",\n \"reflect\", \"reflect-even\", \"reflect-odd\",\n \"dirichlet\", \"neumann\"]\n\nclass BCObject(object):\n \"\"\"\n Boundary condition container -- hold the BCs on each boundary\n for a single variable\n \"\"\"\n\n def __init__(self,\n xlb=\"outflow\", xrb=\"outflow\",\n odd_reflect_dir=\"\"):\n\n\n # note: \"reflect\" is ambiguous and will be converted into\n # either reflect-even (the default) or reflect-odd\n if xlb not in valid or xrb not in valid:\n sys.exit(\"ERROR: invalid BC\")\n\n # -x boundary\n self.xlb = xlb\n if self.xlb == \"reflect\":\n self.xlb = numpy.where(odd_reflect_dir == \"x\",\n \"reflect-odd\", \"reflect-even\")\n\n # +x boundary\n self.xrb = xrb\n if self.xrb == \"reflect\":\n self.xrb = numpy.where(odd_reflect_dir == \"x\",\n \"reflect-odd\", \"reflect-even\")\n\n # periodic checks\n if ((xlb == \"periodic\" and xrb != \"periodic\") or\n (xrb == \"periodic\" and xlb != \"periodic\")):\n sys.exit(\"ERROR: both xlb and xrb must be periodic\")\n\n\n def __str__(self):\n \"\"\" print out some basic information about the BC object \"\"\"\n\n string = \"BCs: -x: %s +x: %s \" % \\\n (self.xlb, self.xrb)\n\n return string\n\n\nclass Grid1d(object):\n \"\"\"\n the 1-d grid class. The grid object will contain the coordinate\n information (at various centerings).\n\n A basic (1-d) representation of the layout is:\n\n | | | X | | | | X | | |\n +--*--+- // -+--*--X--*--+--*--+- // -+--*--+--*--X--*--+- // -+--*--+\n 0 ng-1 ng ng+1 ... ng+nx-1 ng+nx 2ng+nx-1\n\n ilo ihi\n\n |<- ng ghostcells->|<---- nx interior zones ----->|<- ng ghostcells->|\n\n The '*' marks the data locations.\n \"\"\"\n\n def __init__(self, nx, ng=1, xmin=0.0, xmax=1.0):\n\n \"\"\"\n The class constructor function.\n\n The only data that we require is the number of points that\n make up the mesh.\n\n We optionally take the extrema of the domain, number of ghost\n cells (assume 1)\n \"\"\"\n\n # size of grid\n self.nx = nx\n self.ng = ng\n\n self.qx = 2*ng+nx\n\n # domain extrema\n self.xmin = xmin\n self.xmax = xmax\n\n # compute the indices of the block interior (excluding guardcells)\n self.ilo = ng\n self.ihi = ng+nx-1\n\n # define the coordinate information at the left, center, and right\n # zone coordinates\n self.dx = (xmax - xmin)/nx\n\n self.xl = (numpy.arange(nx+2*ng) - ng)*self.dx + xmin\n self.xr = (numpy.arange(nx+2*ng) + 1.0 - ng)*self.dx + xmin\n self.x = 0.5*(self.xl + self.xr)\n\n def scratch_array(self):\n return numpy.zeros((self.qx), dtype=numpy.float64)\n\n\n def __str__(self):\n \"\"\" print out some basic information about the grid object \"\"\"\n\n return \"1-d grid: nx = {}, ng = {}\".format(self.nx, self.ng)\n\n\nclass CellCenterData1d(object):\n \"\"\"\n the cell-centered data that lives on a grid.\n\n a CellCenterData1d object is built in a multi-step process before it can\n be used. We pass in a grid object to describe where the data\n lives:\n\n my_data = patch.CellCenterData1d(myGrid)\n\n register any variables that we expect to live on this patch. Here\n bcObject describes the boundary conditions for that variable.\n\n my_data.registerVar('density', bcObject)\n my_data.registerVar('x-momentum', bcObject)\n ...\n\n finally, finish the initialization of the patch\n\n my_data.create()\n\n This last step actually allocates the storage for the state\n variables. Once this is done, the patch is considered to be\n locked. New variables cannot be added.\n\n \"\"\"\n\n def __init__(self, grid, dtype=numpy.float64):\n\n self.grid = grid\n\n self.dtype = dtype\n self.data = None\n\n self.vars = []\n self.nvar = 0\n\n self.BCs = {}\n\n # time\n self.t = -1\n\n self.initialized = 0\n\n\n def register_var(self, name, bc_object):\n \"\"\"\n register a variable with CellCenterData1d object. Here we pass in a\n BCObject that describes the boundary conditions for that\n variable.\n \"\"\"\n\n if self.initialized == 1:\n sys.exit(\"ERROR: grid already initialized\")\n\n self.vars.append(name)\n self.nvar += 1\n\n self.BCs[name] = bc_object\n\n\n def create(self):\n \"\"\"\n called after all the variables are registered and allocates\n the storage for the state data\n \"\"\"\n\n if self.initialized == 1:\n sys.exit(\"ERROR: grid already initialized\")\n\n self.data = numpy.zeros((self.nvar, self.grid.qx), dtype=self.dtype)\n self.initialized = 1\n\n\n def __str__(self):\n \"\"\" print out some basic information about the ccData2d object \"\"\"\n\n if self.initialized == 0:\n mystr = \"CellCenterData1d object not yet initialized\"\n return mystr\n\n mystr = \"cc data: nx = {}, ng = {}\\n\".format(self.grid.nx, self.grid.ng) + \\\n \" nvars = {}\\n\".format(self.nvar) + \\\n \"variables: \\n\"\n\n ilo = self.grid.ilo\n ihi = self.grid.ihi\n\n for n in range(self.nvar):\n mystr += \"%16s: min: %15.10f max: %15.10f\\n\" % \\\n (self.vars[n],\n numpy.min(self.data[n, ilo:ihi+1]),\n numpy.max(self.data[n, ilo:ihi+1]))\n mystr += \"%16s BCs: -x: %-12s +x: %-12s \\n\" %\\\n (\" \", self.BCs[self.vars[n]].xlb,\n self.BCs[self.vars[n]].xrb)\n\n return mystr\n\n\n def get_var(self, name):\n \"\"\"\n return a data array the variable described by name. Any changes\n made to this are automatically reflected in the CellCenterData1d\n object.\n \"\"\"\n n = self.vars.index(name)\n return self.data[n, :]\n\n\n def zero(self, name):\n n = self.vars.index(name)\n self.data[n, :] = 0.0\n\n\n def fill_BC_all(self):\n \"\"\"\n fill boundary conditions on all variables\n \"\"\"\n for name in self.vars:\n self.fill_BC(name)\n\n\n def fill_BC(self, name):\n \"\"\"\n fill the boundary conditions. This operates on a single state\n variable at a time, to allow for maximum flexibility\n\n we do periodic, reflect-even, reflect-odd, and outflow\n\n each variable name has a corresponding bc_object stored in the\n ccData2d object -- we refer to this to figure out the action\n to take at each boundary.\n \"\"\"\n\n # there is only a single grid, so every boundary is on\n # a physical boundary (except if we are periodic)\n\n # Note: we piggy-back on outflow and reflect-odd for\n # Neumann and Dirichlet homogeneous BCs respectively, but\n # this only works for a single ghost cell\n\n\n n = self.vars.index(name)\n\n # -x boundary\n if self.BCs[name].xlb == \"outflow\" or self.BCs[name].xlb == \"neumann\":\n for i in range(0, self.grid.ilo):\n self.data[n, i] = self.data[n, self.grid.ilo]\n\n elif self.BCs[name].xlb == \"reflect-even\":\n for i in range(0, self.grid.ilo):\n self.data[n, i] = self.data[n, 2*self.grid.ng-i-1]\n\n elif self.BCs[name].xlb in [\"reflect-odd\", \"dirichlet\"]:\n for i in range(0, self.grid.ilo):\n self.data[n, i] = -self.data[n, 2*self.grid.ng-i-1]\n\n elif self.BCs[name].xlb == \"periodic\":\n for i in range(0, self.grid.ilo):\n self.data[n, i] = self.data[n, self.grid.ihi-self.grid.ng+i+1]\n\n # +x boundary\n if self.BCs[name].xrb == \"outflow\" or self.BCs[name].xrb == \"neumann\":\n for i in range(self.grid.ihi+1, self.grid.nx+2*self.grid.ng):\n self.data[n, i] = self.data[n, self.grid.ihi]\n\n elif self.BCs[name].xrb == \"reflect-even\":\n for i in range(0, self.grid.ng):\n i_bnd = self.grid.ihi+1+i\n i_src = self.grid.ihi-i\n self.data[n, i_bnd] = self.data[n, i_src]\n\n elif self.BCs[name].xrb in [\"reflect-odd\", \"dirichlet\"]:\n for i in range(0, self.grid.ng):\n i_bnd = self.grid.ihi+1+i\n i_src = self.grid.ihi-i\n self.data[n, i_bnd] = -self.data[n, i_src]\n\n elif self.BCs[name].xrb == \"periodic\":\n for i in range(self.grid.ihi+1, 2*self.grid.ng + self.grid.nx):\n self.data[n, i] = self.data[n, i-self.grid.ihi-1+self.grid.ng]\n\n\n def restrict(self, varname):\n \"\"\"\n restrict the variable varname to a coarser grid (factor of 2\n coarser) and return an array with the resulting data (and same\n number of ghostcells)\n \"\"\"\n\n fG = self.grid\n fData = self.get_var(varname)\n\n # allocate an array for the coarsely gridded data\n ng_c = fG.ng\n nx_c = fG.nx//2\n\n cData = numpy.zeros((2*ng_c+nx_c), dtype=self.dtype)\n\n ilo_c = ng_c\n ihi_c = ng_c+nx_c-1\n\n # fill the coarse array with the restricted data -- just\n # average the 2 fine cells into the corresponding coarse cell\n # that encompasses them.\n\n # This is done by shifting our view into the fData array and\n # using a stride of 2 in the indexing.\n cData[ilo_c:ihi_c+1] = \\\n 0.5*(fData[fG.ilo :fG.ihi+1:2] + fData[fG.ilo+1:fG.ihi+1:2])\n\n return cData\n\n\n def prolong(self, varname):\n \"\"\"\n prolong the data in the current (coarse) grid to a finer\n (factor of 2 finer) grid. Return an array with the resulting\n data (and same number of ghostcells).\n\n We will reconstruct the data in the zone from the\n zone-averaged variables using the centered-difference slopes\n\n (x)\n f(x,y) = m x/dx + <f>\n\n When averaged over the parent cell, this reproduces <f>.\n\n Each zone's reconstrution will be averaged over 2 children.\n\n | | | | |\n | <f> | --> | | |\n | | | 1 | 2 |\n +-----------+ +-----+-----+\n\n We will fill each of the finer resolution zones by filling all\n the 1's together, using a stride 2 into the fine array. Then\n the 2's, this allows us to operate in a vector\n fashion. All operations will use the same slopes for their\n respective parents.\n\n \"\"\"\n\n cG = self.grid\n cData = self.get_var(varname)\n\n # allocate an array for the coarsely gridded data\n ng_f = cG.ng\n nx_f = cG.nx*2\n\n fData = numpy.zeros((2*ng_f+nx_f), dtype=self.dtype)\n\n ilo_f = ng_f\n ihi_f = ng_f+nx_f-1\n\n # slopes for the coarse data\n m_x = cG.scratch_array()\n m_x[cG.ilo:cG.ihi+1] = \\\n 0.5*(cData[cG.ilo+1:cG.ihi+2] - cData[cG.ilo-1:cG.ihi])\n\n\n # fill the '1' children\n fData[ilo_f:ihi_f+1:2] = \\\n cData[cG.ilo:cG.ihi+1] - 0.25*m_x[cG.ilo:cG.ihi+1]\n\n # fill the '2' children\n fData[ilo_f+1:ihi_f+1:2] = \\\n cData[cG.ilo:cG.ihi+1] + 0.25*m_x[cG.ilo:cG.ihi+1]\n\n return fData\n\n\nif __name__ == \"__main__\":\n\n # illustrate basic mesh operations\n\n myg = Grid1d(16, xmax=1.0)\n\n mydata = CellCenterData1d(myg)\n\n bc = BCObject()\n\n mydata.register_var(\"a\", bc)\n mydata.create()\n\n\n a = mydata.get_var(\"a\")\n a[:] = numpy.exp(-(myg.x - 0.5)**2/0.1**2)\n\n print(mydata)\n", "# 2nd-order accurate finite-volume implementation of the inviscid Burger's\n# equation with piecewise linear slope reconstruction\n#\n# We are solving u_t + u u_x = 0 with outflow boundary conditions\n#\n# M. Zingale (2013-03-26)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport sys\n\nmpl.rcParams['mathtext.fontset'] = 'cm'\nmpl.rcParams['mathtext.rm'] = 'serif'\n\nmpl.rcParams['font.size'] = 12\nmpl.rcParams['legend.fontsize'] = 'large'\nmpl.rcParams['figure.titlesize'] = 'medium'\n\nclass Grid1d(object):\n\n def __init__(self, nx, ng, xmin=0.0, xmax=1.0, bc=\"outflow\"):\n\n self.nx = nx\n self.ng = ng\n\n self.xmin = xmin\n self.xmax = xmax\n\n self.bc=bc\n\n # python is zero-based. Make easy intergers to know where the\n # real data lives\n self.ilo = ng\n self.ihi = ng+nx-1\n\n # physical coords -- cell-centered, left and right edges\n self.dx = (xmax - xmin)/(nx)\n self.x = xmin + (np.arange(nx+2*ng)-ng+0.5)*self.dx\n\n # storage for the solution\n self.u = np.zeros((nx+2*ng), dtype=np.float64)\n\n\n def scratch_array(self):\n \"\"\" return a scratch array dimensioned for our grid \"\"\"\n return np.zeros((self.nx+2*self.ng), dtype=np.float64)\n\n\n def fill_BCs(self):\n \"\"\" fill all ghostcells as periodic \"\"\"\n\n if self.bc == \"periodic\":\n\n # left boundary\n self.u[0:self.ilo] = self.u[self.ihi-self.ng+1:self.ihi+1]\n\n # right boundary\n self.u[self.ihi+1:] = self.u[self.ilo:self.ilo+self.ng]\n\n elif self.bc == \"outflow\":\n\n # left boundary\n self.u[0:self.ilo] = self.u[self.ilo]\n\n # right boundary\n self.u[self.ihi+1:] = self.u[self.ihi]\n\n else:\n sys.exit(\"invalid BC\")\n\n\n def norm(self, e):\n \"\"\" return the norm of quantity e which lives on the grid \"\"\"\n if len(e) != 2*self.ng + self.nx:\n return None\n\n return np.sqrt(self.dx*np.sum(e[self.ilo:self.ihi+1]**2))\n\n\nclass Simulation(object):\n\n def __init__(self, grid):\n self.grid = grid\n self.t = 0.0\n\n\n def init_cond(self, type=\"tophat\"):\n\n if type == \"tophat\":\n self.grid.u[np.logical_and(self.grid.x >= 0.333,\n self.grid.x <= 0.666)] = 1.0\n\n elif type == \"sine\":\n self.grid.u[:] = 1.0\n\n index = np.logical_and(self.grid.x >= 0.333,\n self.grid.x <= 0.666)\n self.grid.u[index] += \\\n 0.5*np.sin(2.0*np.pi*(self.grid.x[index]-0.333)/0.333)\n\n elif type == \"rarefaction\":\n self.grid.u[:] = 1.0\n self.grid.u[self.grid.x > 0.5] = 2.0\n\n\n\n def timestep(self, C):\n return C*self.grid.dx/max(abs(self.grid.u[self.grid.ilo:\n self.grid.ihi+1]))\n\n\n def states(self, dt):\n \"\"\" compute the left and right interface states \"\"\"\n\n g = self.grid\n # compute the piecewise linear slopes -- 2nd order MC limiter\n # we pick a range of cells that includes 1 ghost cell on either\n # side\n ib = g.ilo-1\n ie = g.ihi+1\n\n u = g.u\n\n # this is the MC limiter from van Leer (1977), as given in\n # LeVeque (2002). Note that this is slightly different than\n # the expression from Colella (1990)\n\n dc = g.scratch_array()\n dl = g.scratch_array()\n dr = g.scratch_array()\n\n dc[ib:ie+1] = 0.5*(u[ib+1:ie+2] - u[ib-1:ie ])\n dl[ib:ie+1] = u[ib+1:ie+2] - u[ib :ie+1]\n dr[ib:ie+1] = u[ib :ie+1] - u[ib-1:ie ]\n\n # these where's do a minmod()\n d1 = 2.0*np.where(np.fabs(dl) < np.fabs(dr), dl, dr)\n d2 = np.where(np.fabs(dc) < np.fabs(d1), dc, d1)\n ldeltau = np.where(dl*dr > 0.0, d2, 0.0)\n\n # now the interface states. Note that there are 1 more interfaces\n # than zones\n ul = g.scratch_array()\n ur = g.scratch_array()\n\n # are these indices right?\n #\n # --+-----------------+------------------+\n # ^ i ^ ^ i+1\n # ur(i) ul(i+1) ur(i+1)\n #\n ur[ib:ie+2] = u[ib:ie+2] - \\\n 0.5*(1.0 + u[ib:ie+2]*dt/self.grid.dx)*ldeltau[ib:ie+2]\n\n ul[ib+1:ie+2] = u[ib:ie+1] + \\\n 0.5*(1.0 - u[ib:ie+1]*dt/self.grid.dx)*ldeltau[ib:ie+1]\n\n return ul, ur\n\n\n def riemann(self, ul, ur):\n \"\"\"\n Riemann problem for Burgers' equation.\n \"\"\"\n\n S = 0.5*(ul + ur)\n ushock = np.where(S > 0.0, ul, ur)\n ushock = np.where(S == 0.0, 0.0, ushock)\n\n # rarefaction solution\n urare = np.where(ur <= 0.0, ur, 0.0)\n urare = np.where(ul >= 0.0, ul, urare)\n\n us = np.where(ul > ur, ushock, urare)\n\n return 0.5*us*us\n\n\n def update(self, dt, flux):\n \"\"\" conservative update \"\"\"\n\n g = self.grid\n\n unew = g.scratch_array()\n\n unew[g.ilo:g.ihi+1] = g.u[g.ilo:g.ihi+1] + \\\n dt/g.dx * (flux[g.ilo:g.ihi+1] - flux[g.ilo+1:g.ihi+2])\n\n return unew\n\n\n def evolve(self, C, tmax):\n\n self.t = 0.0\n\n g = self.grid\n\n # main evolution loop\n while (self.t < tmax):\n\n # fill the boundary conditions\n g.fill_BCs()\n\n # get the timestep\n dt = self.timestep(C)\n\n if (self.t + dt > tmax):\n dt = tmax - self.t\n\n # get the interface states\n ul, ur = self.states(dt)\n\n # solve the Riemann problem at all interfaces\n flux = self.riemann(ul, ur)\n\n # do the conservative update\n unew = self.update(dt, flux)\n\n self.grid.u[:] = unew[:]\n\n self.t += dt\n\n\nif __name__ == \"__main__\":\n #-----------------------------------------------------------------------------\n # sine\n\n xmin = 0.0\n xmax = 1.0\n nx = 256\n ng = 2\n g = Grid1d(nx, ng, bc=\"periodic\")\n\n # maximum evolution time based on period for unit velocity\n tmax = (xmax - xmin)/1.0\n\n C = 0.8\n\n plt.clf()\n\n s = Simulation(g)\n\n for i in range(0, 10):\n tend = (i+1)*0.02*tmax\n s.init_cond(\"sine\")\n\n uinit = s.grid.u.copy()\n\n s.evolve(C, tend)\n\n c = 1.0 - (0.1 + i*0.1)\n g = s.grid\n plt.plot(g.x[g.ilo:g.ihi+1], g.u[g.ilo:g.ihi+1], color=str(c))\n\n\n g = s.grid\n plt.plot(g.x[g.ilo:g.ihi+1], uinit[g.ilo:g.ihi+1], ls=\":\", color=\"0.9\", zorder=-1)\n\n plt.xlabel(\"$x$\")\n plt.ylabel(\"$u$\")\n plt.savefig(\"fv-burger-sine.pdf\")\n\n\n #-----------------------------------------------------------------------------\n # rarefaction\n\n xmin = 0.0\n xmax = 1.0\n nx = 256\n ng = 2\n g = Grid1d(nx, ng, bc=\"outflow\")\n\n # maximum evolution time based on period for unit velocity\n tmax = (xmax - xmin)/1.0\n\n C = 0.8\n\n plt.clf()\n\n s = Simulation(g)\n\n for i in range(0, 10):\n tend = (i+1)*0.02*tmax\n\n s.init_cond(\"rarefaction\")\n\n uinit = s.grid.u.copy()\n\n s.evolve(C, tend)\n\n c = 1.0 - (0.1 + i*0.1)\n plt.plot(g.x[g.ilo:g.ihi+1], g.u[g.ilo:g.ihi+1], color=str(c))\n\n\n plt.plot(g.x[g.ilo:g.ihi+1], uinit[g.ilo:g.ihi+1], ls=\":\", color=\"0.9\", zorder=-1)\n\n plt.xlabel(\"$x$\")\n plt.ylabel(\"$u$\")\n\n plt.savefig(\"fv-burger-rarefaction.pdf\")\n" ]
[ [ "numpy.min", "numpy.arange", "numpy.max", "numpy.exp", "numpy.zeros", "numpy.where" ], [ "numpy.sum", "numpy.arange", "matplotlib.pyplot.savefig", "numpy.sin", "matplotlib.pyplot.plot", "matplotlib.pyplot.clf", "matplotlib.pyplot.xlabel", "numpy.logical_and", "numpy.zeros", "numpy.where", "numpy.fabs", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hyperdo/python2-baselines
[ "ef2319bb18fa694ff8db34b667fb3702acebe608" ]
[ "baselines/deepq/simple.py" ]
[ "from backports import tempfile\nimport numpy as np\nimport os\nimport dill\nimport tensorflow as tf\nimport zipfile\n\nimport baselines.common.tf_util as U\n\nfrom build_graph import build_act, build_train\nfrom baselines import logger\nfrom baselines.common.schedules import LinearSchedule\nfrom baselines.deepq.replay_buffer import ReplayBuffer, PrioritizedReplayBuffer\n\n\nclass ActWrapper(object):\n def __init__(self, act, act_params):\n self._act = act\n self._act_params = act_params\n\n @staticmethod\n def load(path, num_cpu=16):\n with open(path, \"rb\") as f:\n model_data, act_params = dill.load(f)\n act = build_act(**act_params)\n sess = U.make_session(num_cpu=num_cpu)\n sess.__enter__()\n with tempfile.TemporaryDirectory() as td:\n arc_path = os.path.join(td, \"packed.zip\")\n with open(arc_path, \"wb\") as f:\n f.write(model_data)\n\n zipfile.ZipFile(arc_path, 'r', zipfile.ZIP_DEFLATED).extractall(td)\n U.load_state(os.path.join(td, \"model\"))\n\n return ActWrapper(act, act_params)\n\n def __call__(self, *args, **kwargs):\n return self._act(*args, **kwargs)\n\n def save(self, path):\n \"\"\"Save model to a pickle located at `path`\"\"\"\n with tempfile.TemporaryDirectory() as td:\n U.save_state(os.path.join(td, \"model\"))\n arc_name = os.path.join(td, \"packed.zip\")\n with zipfile.ZipFile(arc_name, 'w') as zipf:\n for root, dirs, files in os.walk(td):\n for fname in files:\n file_path = os.path.join(root, fname)\n if file_path != arc_name:\n zipf.write(file_path, os.path.relpath(file_path, td))\n with open(arc_name, \"rb\") as f:\n model_data = f.read()\n with open(path, \"wb\") as f:\n dill.dump((model_data, self._act_params), f)\n\n\ndef load(path, num_cpu=16):\n \"\"\"Load act function that was returned by learn function.\n\n Parameters\n ----------\n path: str\n path to the act function pickle\n num_cpu: int\n number of cpus to use for executing the policy\n\n Returns\n -------\n act: ActWrapper\n function that takes a batch of observations\n and returns actions.\n \"\"\"\n return ActWrapper.load(path, num_cpu=num_cpu)\n\n\ndef learn(env,\n q_func,\n lr=5e-4,\n max_timesteps=100000,\n buffer_size=50000,\n exploration_fraction=0.1,\n exploration_final_eps=0.02,\n train_freq=1,\n batch_size=32,\n print_freq=1,\n checkpoint_freq=10000,\n learning_starts=1000,\n gamma=1.0,\n target_network_update_freq=500,\n prioritized_replay=False,\n prioritized_replay_alpha=0.6,\n prioritized_replay_beta0=0.4,\n prioritized_replay_beta_iters=None,\n prioritized_replay_eps=1e-6,\n num_cpu=16,\n callback=None):\n \"\"\"Train a deepq model.\n\n Parameters\n -------\n env : gym.Env\n environment to train on\n q_func: (tf.Variable, int, str, bool) -> tf.Variable\n the model that takes the following inputs:\n observation_in: object\n the output of observation placeholder\n num_actions: int\n number of actions\n scope: str\n reuse: bool\n should be passed to outer variable scope\n and returns a tensor of shape (batch_size, num_actions) with values of every action.\n lr: float\n learning rate for adam optimizer\n max_timesteps: int\n number of env steps to optimizer for\n buffer_size: int\n size of the replay buffer\n exploration_fraction: float\n fraction of entire training period over which the exploration rate is annealed\n exploration_final_eps: float\n final value of random action probability\n train_freq: int\n update the model every `train_freq` steps.\n batch_size: int\n size of a batched sampled from replay buffer for training\n print_freq: int\n how often to print out training progress\n set to None to disable printing\n checkpoint_freq: int\n how often to save the model. This is so that the best version is restored\n at the end of the training. If you do not wish to restore the best version at\n the end of the training set this variable to None.\n learning_starts: int\n how many steps of the model to collect transitions for before learning starts\n gamma: float\n discount factor\n target_network_update_freq: int\n update the target network every `target_network_update_freq` steps.\n prioritized_replay: True\n if True prioritized replay buffer will be used.\n prioritized_replay_alpha: float\n alpha parameter for prioritized replay buffer\n prioritized_replay_beta0: float\n initial value of beta for prioritized replay buffer\n prioritized_replay_beta_iters: int\n number of iterations over which beta will be annealed from initial value\n to 1.0. If set to None equals to max_timesteps.\n prioritized_replay_eps: float\n epsilon to add to the TD errors when updating priorities.\n num_cpu: int\n number of cpus to use for training\n callback: (locals, globals) -> None\n function called at every steps with state of the algorithm.\n If callback returns true training stops.\n\n Returns\n -------\n act: ActWrapper\n Wrapper over act function. Adds ability to save it and load it.\n See header of baselines/deepq/categorical.py for details on the act function.\n \"\"\"\n # Create all the functions necessary to train the model\n\n sess = U.make_session(num_cpu=num_cpu)\n sess.__enter__()\n\n def make_obs_ph(name):\n return U.BatchInput(env.observation_space.shape, name=name)\n\n act, train, update_target, debug = build_train(\n make_obs_ph=make_obs_ph,\n q_func=q_func,\n num_actions=env.action_space.n,\n optimizer=tf.train.AdamOptimizer(learning_rate=lr),\n gamma=gamma,\n grad_norm_clipping=10\n )\n act_params = {\n 'make_obs_ph': make_obs_ph,\n 'q_func': q_func,\n 'num_actions': env.action_space.n,\n }\n # Create the replay buffer\n if prioritized_replay:\n replay_buffer = PrioritizedReplayBuffer(buffer_size, alpha=prioritized_replay_alpha)\n if prioritized_replay_beta_iters is None:\n prioritized_replay_beta_iters = max_timesteps\n beta_schedule = LinearSchedule(prioritized_replay_beta_iters,\n initial_p=prioritized_replay_beta0,\n final_p=1.0)\n else:\n replay_buffer = ReplayBuffer(buffer_size)\n beta_schedule = None\n # Create the schedule for exploration starting from 1.\n exploration = LinearSchedule(schedule_timesteps=int(exploration_fraction * max_timesteps),\n initial_p=1.0,\n final_p=exploration_final_eps)\n\n # Initialize the parameters and copy them to the target network.\n U.initialize()\n update_target()\n\n episode_rewards = [0.0]\n saved_mean_reward = None\n obs = env.reset()\n with tempfile.TemporaryDirectory() as td:\n model_saved = False\n model_file = os.path.join(td, \"model\")\n for t in range(max_timesteps):\n if callback is not None:\n if callback(locals(), globals()):\n break\n # Take action and update exploration to the newest value\n action = act(np.array(obs)[None], update_eps=exploration.value(t))[0]\n new_obs, rew, done, _ = env.step(action)\n # Store transition in the replay buffer.\n replay_buffer.add(obs, action, rew, new_obs, float(done))\n obs = new_obs\n\n episode_rewards[-1] += rew\n if done:\n obs = env.reset()\n episode_rewards.append(0.0)\n\n if t > learning_starts and t % train_freq == 0:\n # Minimize the error in Bellman's equation on a batch sampled from replay buffer.\n if prioritized_replay:\n experience = replay_buffer.sample(batch_size, beta=beta_schedule.value(t))\n (obses_t, actions, rewards, obses_tp1, dones, weights, batch_idxes) = experience\n else:\n obses_t, actions, rewards, obses_tp1, dones = replay_buffer.sample(batch_size)\n weights, batch_idxes = np.ones_like(rewards), None\n td_errors = train(obses_t, actions, rewards, obses_tp1, dones, weights)\n if prioritized_replay:\n new_priorities = np.abs(td_errors) + prioritized_replay_eps\n replay_buffer.update_priorities(batch_idxes, new_priorities)\n\n if t > learning_starts and t % target_network_update_freq == 0:\n # Update target network periodically.\n update_target()\n\n mean_100ep_reward = round(np.mean(episode_rewards[-101:-1]), 1)\n num_episodes = len(episode_rewards)\n if done and print_freq is not None and len(episode_rewards) % print_freq == 0:\n logger.record_tabular(\"steps\", t)\n logger.record_tabular(\"episodes\", num_episodes)\n logger.record_tabular(\"mean 100 episode reward\", mean_100ep_reward)\n logger.record_tabular(\"% time spent exploring\", int(100 * exploration.value(t)))\n logger.dump_tabular()\n\n if (checkpoint_freq is not None and t > learning_starts and\n num_episodes > 100 and t % checkpoint_freq == 0):\n if saved_mean_reward is None or mean_100ep_reward > saved_mean_reward:\n if print_freq is not None:\n logger.log(\"Saving model due to mean reward increase: {} -> {}\".format(\n saved_mean_reward, mean_100ep_reward))\n U.save_state(model_file)\n model_saved = True\n saved_mean_reward = mean_100ep_reward\n if model_saved:\n if print_freq is not None:\n logger.log(\"Restored model with mean reward: {}\".format(saved_mean_reward))\n U.load_state(model_file)\n\n return ActWrapper(act, act_params)\n" ]
[ [ "numpy.ones_like", "numpy.abs", "numpy.mean", "tensorflow.train.AdamOptimizer", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
ViduraPrasangana/faster-rcnn-caffe
[ "af6f5ee89c6e82d295bddd192d9dfcebd60d7c52", "af6f5ee89c6e82d295bddd192d9dfcebd60d7c52" ]
[ ".env/lib/python2.7/site-packages/skimage/segmentation/boundaries.py", ".env/lib/python2.7/site-packages/skimage/feature/tests/test_orb.py" ]
[ "from __future__ import division\n\nimport numpy as np\nfrom scipy import ndimage as ndi\nfrom ..morphology import dilation, erosion, square\nfrom ..util import img_as_float, view_as_windows\nfrom ..color import gray2rgb\n\n\ndef _find_boundaries_subpixel(label_img):\n \"\"\"See ``find_boundaries(..., mode='subpixel')``.\n\n Notes\n -----\n This function puts in an empty row and column between each *actual*\n row and column of the image, for a corresponding shape of $2s - 1$\n for every image dimension of size $s$. These \"interstitial\" rows\n and columns are filled as ``True`` if they separate two labels in\n `label_img`, ``False`` otherwise.\n\n I used ``view_as_windows`` to get the neighborhood of each pixel.\n Then I check whether there are two labels or more in that\n neighborhood.\n \"\"\"\n ndim = label_img.ndim\n max_label = np.iinfo(label_img.dtype).max\n\n label_img_expanded = np.zeros([(2 * s - 1) for s in label_img.shape],\n label_img.dtype)\n pixels = (slice(None, None, 2), ) * ndim\n label_img_expanded[pixels] = label_img\n\n edges = np.ones(label_img_expanded.shape, dtype=bool)\n edges[pixels] = False\n label_img_expanded[edges] = max_label\n windows = view_as_windows(np.pad(label_img_expanded, 1,\n mode='constant', constant_values=0),\n (3,) * ndim)\n\n boundaries = np.zeros_like(edges)\n for index in np.ndindex(label_img_expanded.shape):\n if edges[index]:\n values = np.unique(windows[index].ravel())\n if len(values) > 2: # single value and max_label\n boundaries[index] = True\n return boundaries\n\n\ndef find_boundaries(label_img, connectivity=1, mode='thick', background=0):\n \"\"\"Return bool array where boundaries between labeled regions are True.\n\n Parameters\n ----------\n label_img : array of int or bool\n An array in which different regions are labeled with either different\n integers or boolean values.\n connectivity: int in {1, ..., `label_img.ndim`}, optional\n A pixel is considered a boundary pixel if any of its neighbors\n has a different label. `connectivity` controls which pixels are\n considered neighbors. A connectivity of 1 (default) means\n pixels sharing an edge (in 2D) or a face (in 3D) will be\n considered neighbors. A connectivity of `label_img.ndim` means\n pixels sharing a corner will be considered neighbors.\n mode: string in {'thick', 'inner', 'outer', 'subpixel'}\n How to mark the boundaries:\n\n - thick: any pixel not completely surrounded by pixels of the\n same label (defined by `connectivity`) is marked as a boundary.\n This results in boundaries that are 2 pixels thick.\n - inner: outline the pixels *just inside* of objects, leaving\n background pixels untouched.\n - outer: outline pixels in the background around object\n boundaries. When two objects touch, their boundary is also\n marked.\n - subpixel: return a doubled image, with pixels *between* the\n original pixels marked as boundary where appropriate.\n background: int, optional\n For modes 'inner' and 'outer', a definition of a background\n label is required. See `mode` for descriptions of these two.\n\n Returns\n -------\n boundaries : array of bool, same shape as `label_img`\n A bool image where ``True`` represents a boundary pixel. For\n `mode` equal to 'subpixel', ``boundaries.shape[i]`` is equal\n to ``2 * label_img.shape[i] - 1`` for all ``i`` (a pixel is\n inserted in between all other pairs of pixels).\n\n Examples\n --------\n >>> labels = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n ... [0, 0, 0, 0, 0, 5, 5, 5, 0, 0],\n ... [0, 0, 1, 1, 1, 5, 5, 5, 0, 0],\n ... [0, 0, 1, 1, 1, 5, 5, 5, 0, 0],\n ... [0, 0, 1, 1, 1, 5, 5, 5, 0, 0],\n ... [0, 0, 0, 0, 0, 5, 5, 5, 0, 0],\n ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8)\n >>> find_boundaries(labels, mode='thick').astype(np.uint8)\n array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 1, 0],\n [0, 1, 1, 1, 1, 1, 0, 1, 1, 0],\n [0, 1, 1, 0, 1, 1, 0, 1, 1, 0],\n [0, 1, 1, 1, 1, 1, 0, 1, 1, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 1, 0],\n [0, 0, 0, 0, 0, 1, 1, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)\n >>> find_boundaries(labels, mode='inner').astype(np.uint8)\n array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 0, 1, 0, 0],\n [0, 0, 1, 0, 1, 1, 0, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 1, 1, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)\n >>> find_boundaries(labels, mode='outer').astype(np.uint8)\n array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 0, 0, 1, 0],\n [0, 1, 0, 0, 1, 1, 0, 0, 1, 0],\n [0, 1, 0, 0, 1, 1, 0, 0, 1, 0],\n [0, 1, 0, 0, 1, 1, 0, 0, 1, 0],\n [0, 0, 1, 1, 1, 1, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 1, 1, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)\n >>> labels_small = labels[::2, ::3]\n >>> labels_small\n array([[0, 0, 0, 0],\n [0, 0, 5, 0],\n [0, 1, 5, 0],\n [0, 0, 5, 0],\n [0, 0, 0, 0]], dtype=uint8)\n >>> find_boundaries(labels_small, mode='subpixel').astype(np.uint8)\n array([[0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 1, 1, 0],\n [0, 0, 0, 1, 0, 1, 0],\n [0, 1, 1, 1, 0, 1, 0],\n [0, 1, 0, 1, 0, 1, 0],\n [0, 1, 1, 1, 0, 1, 0],\n [0, 0, 0, 1, 0, 1, 0],\n [0, 0, 0, 1, 1, 1, 0],\n [0, 0, 0, 0, 0, 0, 0]], dtype=uint8)\n >>> bool_image = np.array([[False, False, False, False, False],\n ... [False, False, False, False, False],\n ... [False, False, True, True, True],\n ... [False, False, True, True, True],\n ... [False, False, True, True, True]], dtype=np.bool)\n >>> find_boundaries(bool_image)\n array([[False, False, False, False, False],\n [False, False, True, True, True],\n [False, True, True, True, True],\n [False, True, True, False, False],\n [False, True, True, False, False]], dtype=bool)\n \"\"\"\n if label_img.dtype == 'bool':\n label_img = label_img.astype(np.uint8)\n ndim = label_img.ndim\n selem = ndi.generate_binary_structure(ndim, connectivity)\n if mode != 'subpixel':\n boundaries = dilation(label_img, selem) != erosion(label_img, selem)\n if mode == 'inner':\n foreground_image = (label_img != background)\n boundaries &= foreground_image\n elif mode == 'outer':\n max_label = np.iinfo(label_img.dtype).max\n background_image = (label_img == background)\n selem = ndi.generate_binary_structure(ndim, ndim)\n inverted_background = np.array(label_img, copy=True)\n inverted_background[background_image] = max_label\n adjacent_objects = ((dilation(label_img, selem) !=\n erosion(inverted_background, selem)) &\n ~background_image)\n boundaries &= (background_image | adjacent_objects)\n return boundaries\n else:\n boundaries = _find_boundaries_subpixel(label_img)\n return boundaries\n\n\ndef mark_boundaries(image, label_img, color=(1, 1, 0),\n outline_color=None, mode='outer', background_label=0):\n \"\"\"Return image with boundaries between labeled regions highlighted.\n\n Parameters\n ----------\n image : (M, N[, 3]) array\n Grayscale or RGB image.\n label_img : (M, N) array of int\n Label array where regions are marked by different integer values.\n color : length-3 sequence, optional\n RGB color of boundaries in the output image.\n outline_color : length-3 sequence, optional\n RGB color surrounding boundaries in the output image. If None, no\n outline is drawn.\n mode : string in {'thick', 'inner', 'outer', 'subpixel'}, optional\n The mode for finding boundaries.\n background_label : int, optional\n Which label to consider background (this is only useful for\n modes ``inner`` and ``outer``).\n\n Returns\n -------\n marked : (M, N, 3) array of float\n An image in which the boundaries between labels are\n superimposed on the original image.\n\n See Also\n --------\n find_boundaries\n \"\"\"\n marked = img_as_float(image, force_copy=True)\n if marked.ndim == 2:\n marked = gray2rgb(marked)\n if mode == 'subpixel':\n # Here, we want to interpose an extra line of pixels between\n # each original line - except for the last axis which holds\n # the RGB information. ``ndi.zoom`` then performs the (cubic)\n # interpolation, filling in the values of the interposed pixels\n marked = ndi.zoom(marked, [2 - 1/s for s in marked.shape[:-1]] + [1],\n mode='reflect')\n boundaries = find_boundaries(label_img, mode=mode,\n background=background_label)\n if outline_color is not None:\n outlines = dilation(boundaries, square(3))\n marked[outlines] = outline_color\n marked[boundaries] = color\n return marked\n", "import numpy as np\nfrom skimage._shared.testing import assert_equal, assert_almost_equal\nfrom skimage.feature import ORB\nfrom skimage._shared import testing\nfrom skimage import data\nfrom skimage._shared.testing import test_parallel, xfail, arch32\n\n\nimg = data.coins()\n\n\n@test_parallel()\ndef test_keypoints_orb_desired_no_of_keypoints():\n detector_extractor = ORB(n_keypoints=10, fast_n=12, fast_threshold=0.20)\n detector_extractor.detect(img)\n\n exp_rows = np.array([ 141. , 108. , 214.56 , 131. , 214.272,\n 67. , 206. , 177. , 108. , 141. ])\n exp_cols = np.array([ 323. , 328. , 282.24 , 292. , 281.664,\n 85. , 260. , 284. , 328.8 , 267. ])\n\n exp_scales = np.array([1, 1, 1.44, 1, 1.728, 1, 1, 1, 1.2, 1])\n\n exp_orientations = np.array([ -53.97446153, 59.5055285 , -96.01885186,\n -149.70789506, -94.70171899, -45.76429535,\n -51.49752849, 113.57081195, 63.30428063,\n -79.56091118])\n exp_response = np.array([ 1.01168357, 0.82934145, 0.67784179, 0.57176438,\n 0.56637459, 0.52248355, 0.43696175, 0.42992376,\n 0.37700486, 0.36126832])\n\n assert_almost_equal(exp_rows, detector_extractor.keypoints[:, 0])\n assert_almost_equal(exp_cols, detector_extractor.keypoints[:, 1])\n assert_almost_equal(exp_scales, detector_extractor.scales)\n assert_almost_equal(exp_response, detector_extractor.responses)\n assert_almost_equal(exp_orientations,\n np.rad2deg(detector_extractor.orientations), 5)\n\n detector_extractor.detect_and_extract(img)\n assert_almost_equal(exp_rows, detector_extractor.keypoints[:, 0])\n assert_almost_equal(exp_cols, detector_extractor.keypoints[:, 1])\n\n\ndef test_keypoints_orb_less_than_desired_no_of_keypoints():\n detector_extractor = ORB(n_keypoints=15, fast_n=12,\n fast_threshold=0.33, downscale=2, n_scales=2)\n detector_extractor.detect(img)\n\n exp_rows = np.array([ 58., 65., 108., 140., 203.])\n exp_cols = np.array([ 291., 130., 293., 202., 267.])\n\n exp_scales = np.array([1., 1., 1., 1., 1.])\n\n exp_orientations = np.array([-158.26941428, -59.42996346, 151.93905955,\n -79.46341354, -56.90052451])\n\n exp_response = np.array([ 0.2667641 , 0.04009017, -0.17641695, -0.03243431,\n 0.26521259])\n\n assert_almost_equal(exp_rows, detector_extractor.keypoints[:, 0])\n assert_almost_equal(exp_cols, detector_extractor.keypoints[:, 1])\n assert_almost_equal(exp_scales, detector_extractor.scales)\n assert_almost_equal(exp_response, detector_extractor.responses)\n assert_almost_equal(exp_orientations,\n np.rad2deg(detector_extractor.orientations), 5)\n\n detector_extractor.detect_and_extract(img)\n assert_almost_equal(exp_rows, detector_extractor.keypoints[:, 0])\n assert_almost_equal(exp_cols, detector_extractor.keypoints[:, 1])\n\n\n@xfail(condition=arch32,\n reason=('Known test failure on 32-bit platforms. See links for details:'\n 'https://github.com/scikit-image/scikit-image/issues/3091 '\n 'https://github.com/scikit-image/scikit-image/issues/2529'))\ndef test_descriptor_orb():\n detector_extractor = ORB(fast_n=12, fast_threshold=0.20)\n\n exp_descriptors = np.array([[0, 1, 1, 1, 0, 1, 0, 1, 0, 1],\n [1, 1, 1, 0, 0, 1, 0, 0, 1, 1],\n [1, 0, 1, 1, 0, 0, 1, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],\n [0, 1, 0, 0, 0, 0, 0, 0, 1, 0],\n [1, 1, 0, 1, 1, 1, 0, 0, 1, 1],\n [1, 1, 0, 1, 0, 0, 1, 0, 1, 1],\n [0, 0, 1, 0, 1, 0, 0, 1, 1, 0],\n [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],\n [0, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n [1, 1, 0, 1, 0, 1, 0, 0, 1, 1],\n [1, 1, 1, 0, 0, 0, 1, 1, 1, 0],\n [1, 1, 1, 1, 1, 1, 0, 0, 0, 0],\n [1, 1, 1, 0, 1, 1, 1, 1, 0, 0],\n [1, 1, 0, 0, 1, 0, 0, 1, 0, 1],\n [1, 1, 0, 0, 0, 0, 1, 0, 0, 1],\n [0, 0, 0, 0, 1, 1, 1, 0, 1, 0],\n [0, 0, 0, 0, 1, 1, 1, 0, 0, 1],\n [0, 0, 0, 0, 0, 1, 1, 0, 1, 1],\n [0, 0, 0, 0, 1, 0, 1, 0, 1, 1]], dtype=bool)\n detector_extractor.detect(img)\n detector_extractor.extract(img, detector_extractor.keypoints,\n detector_extractor.scales,\n detector_extractor.orientations)\n assert_equal(exp_descriptors,\n detector_extractor.descriptors[100:120, 10:20])\n\n detector_extractor.detect_and_extract(img)\n assert_equal(exp_descriptors,\n detector_extractor.descriptors[100:120, 10:20])\n\n\ndef test_no_descriptors_extracted_orb():\n img = np.ones((128, 128))\n detector_extractor = ORB()\n with testing.raises(RuntimeError):\n detector_extractor.detect_and_extract(img)\n" ]
[ [ "numpy.pad", "scipy.ndimage.generate_binary_structure", "scipy.ndimage.zoom", "numpy.ones", "numpy.zeros_like", "numpy.iinfo", "numpy.ndindex", "numpy.array", "numpy.zeros" ], [ "numpy.array", "numpy.rad2deg", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
nitsaick/pytorch-kit
[ "ebbbc228e2dbae37a055de0d40580140d5a51613", "ebbbc228e2dbae37a055de0d40580140d5a51613" ]
[ "network/r2unet.py", "network/idanet.py" ]
[ "import torch\nimport torch.nn as nn\n\nfrom .subnet import DoubleConv, UpConv, RRCU\n\n\nclass R2UNet(nn.Module):\n def __init__(self, in_ch, out_ch, base_ch=64):\n super(R2UNet, self).__init__()\n self.inc = DoubleConv(in_ch, base_ch)\n self.down = nn.MaxPool2d(kernel_size=2, stride=2)\n self.down1 = self._Down(base_ch, base_ch * 2)\n self.down2 = self._Down(base_ch * 2, base_ch * 4)\n self.down3 = self._Down(base_ch * 4, base_ch * 8)\n self.down4 = self._Down(base_ch * 8, base_ch * 16)\n self.up1 = self._Up(base_ch * 16, base_ch * 8)\n self.up2 = self._Up(base_ch * 8, base_ch * 4)\n self.up3 = self._Up(base_ch * 4, base_ch * 2)\n self.up4 = self._Up(base_ch * 2, base_ch)\n self.outc = nn.Conv2d(base_ch, out_ch, kernel_size=1, stride=1, padding=0)\n \n def forward(self, x):\n x1 = self.inc(x)\n x2 = self.down1(x1)\n x3 = self.down2(x2)\n x4 = self.down3(x3)\n x5 = self.down4(x4)\n \n x = self.up1(x5, x4)\n x = self.up2(x, x3)\n x = self.up3(x, x2)\n x = self.up4(x, x1)\n x = self.outc(x)\n return x\n \n class _Down(nn.Module):\n def __init__(self, in_ch, out_ch):\n super(R2UNet._Down, self).__init__()\n self.down = nn.Sequential(\n nn.MaxPool2d(kernel_size=2),\n RRCU(in_ch, out_ch)\n )\n \n def forward(self, x):\n x = self.down(x)\n return x\n \n class _Up(nn.Module):\n def __init__(self, in_ch, out_ch):\n super(R2UNet._Up, self).__init__()\n self.up = UpConv(in_ch, out_ch)\n self.conv = RRCU(in_ch, out_ch)\n \n def forward(self, x1, x2):\n x1 = self.up(x1)\n x = torch.cat([x2, x1], dim=1)\n x = self.conv(x)\n return x\n", "import torch\nimport torch.nn as nn\n\nfrom .subnet import DoubleConv, PlainNode2\n\n\nclass IDANet(nn.Module):\n def __init__(self, in_ch, out_ch, base_ch=64):\n super(IDANet, self).__init__()\n\n self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2)\n\n self.Conv2 = DoubleConv(in_ch=in_ch, out_ch=base_ch * 2)\n self.Conv4 = DoubleConv(in_ch=base_ch * 2, out_ch=base_ch * 4)\n self.Conv8 = DoubleConv(in_ch=base_ch * 4, out_ch=base_ch * 8)\n self.Conv16 = DoubleConv(in_ch=base_ch * 8, out_ch=base_ch * 16)\n self.Conv32 = DoubleConv(in_ch=base_ch * 16, out_ch=base_ch * 32)\n\n self.agn2_1 = PlainNode2(in_ch=base_ch * (2 + 4), out_ch=base_ch * 2)\n self.agn2_2 = PlainNode2(in_ch=base_ch * (2 + 4), out_ch=base_ch * 2)\n self.agn2_3 = PlainNode2(in_ch=base_ch * (2 + 4), out_ch=base_ch * 2)\n self.agn2_4 = PlainNode2(in_ch=base_ch * (2 + 4), out_ch=base_ch * 2)\n\n self.agn4_1 = PlainNode2(in_ch=base_ch * (4 + 8), out_ch=base_ch * 4)\n self.agn4_2 = PlainNode2(in_ch=base_ch * (4 + 8), out_ch=base_ch * 4)\n self.agn4_3 = PlainNode2(in_ch=base_ch * (4 + 8), out_ch=base_ch * 4)\n\n self.agn8_1 = PlainNode2(in_ch=base_ch * (8 + 16), out_ch=base_ch * 8)\n self.agn8_2 = PlainNode2(in_ch=base_ch * (8 + 16), out_ch=base_ch * 8)\n\n self.agn16_1 = PlainNode2(in_ch=base_ch * (16 + 32), out_ch=base_ch * 16)\n\n self.outc = nn.Conv2d(base_ch * 2, out_ch, kernel_size=1, stride=1, padding=0)\n\n def forward(self, x):\n x2 = self.Conv2(x)\n\n x4 = self.maxpool(x2)\n x4 = self.Conv4(x4)\n\n x8 = self.maxpool(x4)\n x8 = self.Conv8(x8)\n\n x16 = self.maxpool(x8)\n x16 = self.Conv16(x16)\n\n x32 = self.maxpool(x16)\n x32 = self.Conv32(x32)\n\n x2 = self.agn2_1(x2, x4)\n x4 = self.agn4_1(x4, x8)\n x8 = self.agn8_1(x8, x16)\n x16 = self.agn16_1(x16, x32)\n\n x2 = self.agn2_2(x2, x4)\n x4 = self.agn4_2(x4, x8)\n x8 = self.agn8_2(x8, x16)\n\n x2 = self.agn2_3(x2, x4)\n x4 = self.agn4_3(x4, x8)\n\n x2 = self.agn2_4(x2, x4)\n\n out = self.outc(x2)\n\n return out\n" ]
[ [ "torch.nn.MaxPool2d", "torch.nn.Conv2d", "torch.cat" ], [ "torch.nn.MaxPool2d", "torch.nn.Conv2d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Daupler/CA-MTL
[ "d417b039dee973e32f42ba5c1c346738cd29ab3c" ]
[ "src/mtl_trainer.py" ]
[ "import os\nimport json\nimport logging\nfrom dataclasses import dataclass, field\nfrom typing import Dict, Optional, Callable\n\nimport torch\nimport wandb\nimport numpy as np\nfrom tqdm.auto import tqdm\nfrom torch.utils.data.dataloader import DataLoader\nfrom torch.utils.data.dataset import Dataset\nfrom torch.utils.data.distributed import DistributedSampler\nfrom torch.utils.data.sampler import RandomSampler\nfrom transformers import (\n Trainer, \n TrainingArguments, \n EvalPrediction, \n DataCollator,\n DefaultDataCollator,\n)\nfrom transformers.trainer_utils import PredictionOutput\nfrom transformers.training_args import is_tpu_available\n\nfrom src.data.task_data_processors import task_output_modes\n\nfrom src.data.data_utils import compute_task_metrics\n\nif is_tpu_available():\n import torch_xla.core.xla_model as xm\n import torch_xla.debug.metrics as met\n import torch_xla.distributed.parallel_loader as pl\n \nlogger = logging.getLogger(__name__)\n\n\n@dataclass\nclass MultiTaskTrainingArguments(TrainingArguments):\n use_mt_uncertainty: bool = field(\n default=False,\n metadata={\"help\": \"Use MT-Uncertainty sampling method\"},\n )\n uniform_mt_sampling: bool = field(\n default=False,\n metadata={\"help\": \"Sample each task an equal amount to times per epoch.\"},\n )\n percent_of_max_data_size: float = field(\n default=1.0,\n metadata={\n \"help\": \"If uniform_mt_sampling=True, specify the samples per task per \"\n \"epoch based on the maximum dataset length. If below 0.0 or above 1.0,\"\n \"it will be set to the closest of 0.0 or 1.0.\"\n },\n )\n\n\nclass MultiTaskTrainer(Trainer):\n def __init__(\n self,\n tokenizer,\n data_args,\n eval_datasets=None,\n test_datasets=None,\n *args,\n **kwargs,\n ):\n super(MultiTaskTrainer, self).__init__(*args, **kwargs)\n self.tokenizer = tokenizer\n self.data_args = data_args\n self.eval_datasets = eval_datasets\n self.test_datasets = test_datasets\n# self.data_collator = DefaultDataCollator()\n\n def get_train_dataloader(self) -> DataLoader:\n if self.args.use_mt_uncertainty:\n return self._create_custom_dataloader()\n else:\n return super().get_train_dataloader()\n\n def _create_custom_dataloader(self):\n class MtUcertaintyIterator:\n \"\"\"Sample tasks using uncertainty measure.\"\"\"\n\n def __init__(self, my_loader):\n self.my_loader = my_loader\n self.loader_iters = [iter(loader) for loader in self.my_loader.loaders]\n self.loader_iter_sizes = [len(i) for i in self.loader_iters]\n self.max_count = len(self.my_loader)\n self.batch_count = 0\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.batch_count == self.max_count:\n self.batch_count = 0\n raise StopIteration()\n\n test_batch = {}\n for idx, loader_iter in enumerate(self.loader_iters):\n try:\n batch = loader_iter.__next__()\n except StopIteration:\n new_loader_iter = iter(self.my_loader.loaders[idx])\n self.loader_iters[idx] = new_loader_iter\n batch = new_loader_iter.__next__()\n\n test_batch = self.batchify_data(batch, test_batch)\n\n inputs = {}\n for k, v in test_batch.items():\n if k not in [\"labels\"]:\n inputs[k] = v.detach().to(self.my_loader.args.device)\n\n with torch.no_grad():\n model.select_batch_mode = True\n outputs = model(**inputs)\n model.select_batch_mode = False\n\n (\n test_batch_entropy,\n test_batch_entropy_mean,\n max_mean_batch_entropy,\n ) = outputs[-3:]\n\n for _, v in inputs.items():\n del v # free GPU mem\n del inputs\n\n test_batch_entropy_mean = (\n test_batch_entropy_mean / max_mean_batch_entropy\n )\n test_batch_entropy = test_batch_entropy * test_batch_entropy_mean\n\n select_size = min(\n self.my_loader.args.train_batch_size,\n test_batch[\"input_ids\"].shape[0],\n ) # Handled the last batch if it is lower than the batch size\n\n top_entropy = torch.topk(test_batch_entropy, select_size)\n\n for k, v in test_batch.items():\n test_batch[k] = torch.index_select(v, 0, top_entropy.indices)\n\n self.batch_count += 1\n\n return test_batch\n\n @staticmethod\n def batchify_data(data, curr_batch):\n for k in data.keys():\n if k in curr_batch.keys():\n curr_batch[k] = torch.cat((curr_batch[k], data[k]), dim=0)\n else:\n curr_batch[k] = data[k]\n return curr_batch\n\n class CustomLoader:\n def __init__(self, loaders, datasets, loader_args):\n self.loaders = loaders\n self.dataset = datasets\n self.args = loader_args\n self.current_epoch = 0\n\n def __iter__(self):\n iterator = MtUcertaintyIterator(self)\n\n # for determinism across runs\n # https://github.com/pytorch/examples/issues/501\n for l in self.loaders:\n if isinstance(l.sampler, DistributedSampler):\n l.sampler.set_epoch(self.current_epoch)\n self.current_epoch += 1\n return iterator\n\n def __len__(self):\n loader_len = [len(loader) for loader in self.loaders]\n if self.args.uniform_mt_sampling:\n return int(\n self.args.percent_of_max_data_size\n * max(loader_len)\n * len(self.loaders)\n / self.args.train_batch_size\n )\n elif self.args.uncert_batch:\n return int(\n max(loader_len)\n * len(self.loaders)\n * self.args.percent_of_max_data_size\n )\n else:\n return sum(loader_len)\n\n model = self.model\n tasks = self.data_args.tasks\n\n data_loaders = []\n for dataset in self.train_dataset.datasets:\n train_sampler = (\n RandomSampler(dataset)\n if self.args.local_rank == -1\n else DistributedSampler(dataset)\n )\n\n data_loader = DataLoader(\n dataset,\n batch_size=self.args.train_batch_size,\n sampler=train_sampler,\n collate_fn=self.data_collator.collate_batch,\n )\n data_loaders.append(data_loader)\n\n return CustomLoader(data_loaders, self.train_dataset, self.args)\n\n def evaluate(\n self,\n eval_dataset: Optional[Dataset] = None,\n prediction_loss_only: Optional[bool] = None,\n context: str = None,\n do_test_if_needed: bool = True,\n ):\n datasets = eval_dataset or self.eval_datasets\n logger.info(\"*** Evaluate on dev ***\")\n for task_name, eval_dataset in datasets.items():\n logger.info(task_name)\n self.compute_metrics = self.build_compute_metrics_fn(eval_dataset)\n eval_dataloader = self.get_eval_dataloader(eval_dataset)\n \n eval_result = self._prediction_loop(\n eval_dataloader, description=\"Evaluation\", task_name=task_name, \n mode=eval_dataset.mode)\n \n self._log(eval_result.metrics)\n\n for key, value in eval_result.metrics.items():\n logger.info(\" %s = %s\", key, value)\n\n if self.args.tpu_metrics_debug:\n # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)\n xm.master_print(met.metrics_report())\n \n \n def predict(\n self,\n eval_dataset: Optional[Dataset] = None,\n prediction_loss_only: Optional[bool] = None,\n scoring_model: Optional[str] = None\n ):\n logging.info(\"*** Test ***\")\n datasets = eval_dataset or self.test_datasets\n for task_name, test_dataset in datasets.items():\n logger.info(task_name)\n \n test_dataloader = self.get_test_dataloader(test_dataset)\n test_result = self._prediction_loop(\n test_dataloader, description=\"Prediction\", task_name=task_name, \n mode=test_dataset.mode)\n \n self._log(test_result.metrics)\n for key, value in test_result.metrics.items():\n logger.info(\" %s = %s\", key, value)\n \n softmax = torch.nn.Softmax(dim=1)\n probs = softmax(torch.Tensor(test_result.predictions)).numpy().astype('float64')\n logits = test_result.predictions.astype('float64')\n output_mode = task_output_modes[task_name] \n if output_mode == \"classification\":\n predictions = np.argmax(logits, axis=1)\n \n self.run_name = wandb.run.name\n output_test_file = os.path.join(\n self.args.output_dir,\n f\"{task_name}_test_iter_{self.run_name}.tsv\",\n )\n if scoring_model is None:\n scoring_model = self.run_name\n if self.is_world_master():\n with open(output_test_file, \"w\") as writer:\n logger.info(\"***** Test results {} *****\".format(task_name))\n logger.info(\"***** Writing as {} *****\".format(self.run_name))\n if output_mode == \"regression\":\n writer.write(\"index\\tprediction\\n\")\n else:\n writer.write(\"index\\tscoring_model\\tprediction\\tprobability\\tlogits\\n\")\n for index, item in enumerate(predictions):\n if output_mode == \"regression\":\n writer.write(\"%d\\t%3.3f\\n\" % (index, item))\n else:\n i_probs = probs[index,:]\n i_logits = logits[index,:]\n i_logits = json.dumps(dict(zip(test_dataset.get_labels(), i_logits)))\n writer.write(\n \"%d\\t%s\\t%s\\t%3.6f\\t%s\\n\" % (\n index, scoring_model, test_dataset.get_labels()[item], \n i_probs[item], i_logits)\n )\n \n def _prediction_loop(\n self, dataloader: DataLoader, description: str, task_name: str, mode: str,\n prediction_loss_only: Optional[bool] = None, \n ) -> PredictionOutput:\n \"\"\"\n Prediction/evaluation loop, shared by `evaluate()` and `predict()`.\n Works both with or without labels.\n \"\"\"\n\n prediction_loss_only = prediction_loss_only if prediction_loss_only is not None else self.prediction_loss_only\n\n model = self.model\n # multi-gpu eval\n if self.args.n_gpu > 1:\n model = torch.nn.DataParallel(model)\n else:\n model = self.model\n # Note: in torch.distributed mode, there's no point in wrapping the model\n # inside a DistributedDataParallel as we'll be under `no_grad` anyways.\n\n batch_size = dataloader.batch_size\n logger.info(\"***** Running %s *****\", description)\n logger.info(\" Num examples = %d\", self.num_examples(dataloader))\n logger.info(\" Batch size = %d\", batch_size)\n eval_losses: List[float] = []\n preds: torch.Tensor = None\n label_ids: torch.Tensor = None\n model.eval()\n\n if is_tpu_available():\n dataloader = pl.ParallelLoader(dataloader,\n [self.args.device]).per_device_loader(self.args.device)\n\n for inputs in tqdm(dataloader, desc=description):\n has_labels = any(\n inputs.get(k) is not None for k in [\"labels\", \"lm_labels\", \"masked_lm_labels\"])\n\n for k, v in inputs.items():\n inputs[k] = v.to(self.args.device)\n\n with torch.no_grad():\n outputs = model(**inputs)\n if has_labels:\n step_eval_loss, logits = outputs[:2]\n eval_losses += [step_eval_loss.mean().item()]\n else:\n logits = outputs[0]\n\n if not prediction_loss_only:\n if preds is None:\n preds = logits.detach()\n else:\n preds = torch.cat((preds, logits.detach()), dim=0)\n if inputs.get(\"labels\") is not None:\n if label_ids is None:\n label_ids = inputs[\"labels\"].detach()\n else:\n label_ids = torch.cat((label_ids, inputs[\"labels\"].detach()), dim=0)\n\n if self.args.local_rank != -1:\n # In distributed mode, concatenate all results from all nodes:\n if preds is not None:\n preds = self.distributed_concat(preds,\n num_total_examples=self.num_examples(dataloader))\n if label_ids is not None:\n label_ids = self.distributed_concat(label_ids,\n num_total_examples=self.num_examples(dataloader))\n elif is_tpu_available():\n # tpu-comment: Get all predictions and labels from all worker shards of eval dataset\n if preds is not None:\n preds = xm.mesh_reduce(\"eval_preds\", preds, torch.cat)\n if label_ids is not None:\n label_ids = xm.mesh_reduce(\"eval_label_ids\", label_ids, torch.cat)\n\n # Finally, turn the aggregated tensors into numpy arrays.\n if preds is not None:\n preds = preds.cpu().numpy()\n if label_ids is not None:\n label_ids = label_ids.cpu().numpy()\n\n if self.compute_metrics is not None and preds is not None and label_ids is not None:\n metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=label_ids))\n else:\n metrics = {}\n if len(eval_losses) > 0:\n metrics[f\"{task_name}_{mode}_loss\"] = np.mean(eval_losses)\n\n # Prefix all keys with {task_name}_{model}_\n for key in list(metrics.keys()):\n if not key.startswith(f\"{task_name}_{mode}_\"):\n metrics[f\"{task_name}_{mode}_{key}\"] = metrics.pop(key)\n\n return PredictionOutput(predictions=preds, label_ids=label_ids, metrics=metrics)\n \n \n \n \n @staticmethod\n def build_compute_metrics_fn(\n eval_dataset\n ) -> Callable[[EvalPrediction], Dict]:\n def compute_metrics_fn(p: EvalPrediction):\n return compute_task_metrics(eval_dataset.task_name, p)\n\n return compute_metrics_fn\n" ]
[ [ "torch.nn.Softmax", "torch.utils.data.distributed.DistributedSampler", "torch.cat", "torch.Tensor", "torch.nn.DataParallel", "numpy.argmax", "numpy.mean", "torch.no_grad", "torch.topk", "torch.utils.data.dataloader.DataLoader", "torch.utils.data.sampler.RandomSampler", "torch.index_select" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Graveheart/ProteinSSPrediction
[ "21bada89a592ff77e0d12063b7225b4f3da4fb1f" ]
[ "cnn_phi_psi.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport os\nimport os.path\nimport math\n\nimport tensorflow as tf\nfrom sklearn.model_selection import KFold\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import mean_absolute_error\n\nLOGDIR = \"/tmp/cnn_backbone_angles/\"\n\n# Parameters\nbatch_size = 5\ntraining_epochs = 10\ndisplay_step = 1\ninternal_channels_1 = 100\ninternal_channels_2 = 100\ninternal_channels_3 = 100\ninternal_channels_4 = 50\n\nwindow_size = 11\nbeta = 0.001\nvalues_to_predict = 2\nnum_splits = 10\nalpha = 0.2\ndropout_keep_rate = 0.5\nlearning_rate = 1E-3\nkeep_prob = tf.placeholder_with_default(1.0, shape=(), name=\"keep_prob\")\nkeep_prob_input = tf.placeholder_with_default(1.0, shape=(), name=\"keep_prob_input\")\n\ndef fc_layer(input, size_in, size_out, name=\"fc\"):\n with tf.name_scope(name):\n w = tf.Variable(tf.truncated_normal([window_size, size_in, size_out], stddev=0.1), name=\"W\")\n b = tf.Variable(tf.constant(0.1, shape=[size_out]), name=\"B\")\n act = conv1d(input, w) + b\n tf.summary.histogram(\"weights\", w)\n tf.summary.histogram(\"biases\", b)\n tf.summary.histogram(\"activations\", act)\n return act, w\n\n\ndef convnn(x, channels_num, layers_num, window_size = 11):\n W_arr = []\n layers = []\n # First convolutional layer\n input_dimensions = x.get_shape().as_list()[1:]\n filter_shape = [window_size, input_dimensions[-1], channels_num]\n W_input = weight_variable(filter_shape)\n W_arr.append(W_input)\n b_input = bias_variable([input_dimensions[0], channels_num])\n input_layer = tf.nn.relu(conv1d(x, W_input) + b_input)\n dropout_input = tf.nn.dropout(input_layer, keep_prob_input)\n layers.append(dropout_input)\n # Hidden layers\n filter_shape = [window_size, channels_num, channels_num]\n W_hidden = tf.constant([], dtype=tf.float32)\n for i in range(layers_num):\n with tf.name_scope(\"conv\"):\n W_hidden = weight_variable(filter_shape)\n W_arr.append(W_hidden)\n b_hidden = bias_variable([input_dimensions[0], channels_num])\n conv_layer = tf.nn.tanh(alpha*conv1d(layers[i], W_hidden) + b_hidden)\n tf.summary.histogram(\"weights\", W_hidden)\n tf.summary.histogram(\"biases\", b_hidden)\n tf.summary.histogram(\"activations\", conv_layer)\n with tf.name_scope(\"dropout\"):\n dropout = tf.nn.dropout(conv_layer, keep_prob)\n layers.append(dropout)\n # Output convolutional layer\n layer_out, W_out = fc_layer(layers[-1], channels_num, values_to_predict)\n W_arr.append(W_out)\n # layer_out = tf.atan2(tf.sin(layer_out), tf.cos(layer_out))\n\n # Loss function with L2 Regularization with beta=0.001\n regularizers = tf.nn.l2_loss(W_input) + tf.nn.l2_loss(W_hidden) * layers_num + tf.nn.l2_loss(W_out)\n\n # regularizers = tf.constant(0, dtype=tf.float32)\n # for W in W_arr:\n # regularizers += tf.nn.l2_loss(W)\n\n return layer_out, regularizers\n\ndef weight_variable(shape):\n \"\"\"weight_variable generates a weight variable of a given shape.\"\"\"\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial, name=\"W\")\n\n\ndef bias_variable(shape):\n \"\"\"bias_variable generates a bias variable of a given shape.\"\"\"\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial, name=\"B\")\n\ndef conv1d(x, W):\n \"\"\"conv1d returns a 1d convolution layer.\"\"\"\n return tf.nn.conv1d(x, W, 1, 'SAME')\n\ndef avgpool2d(x, k=2):\n # MaxPool2D wrapper\n return tf.nn.avg_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],\n padding='SAME')\n\ndef calculate_accuracy(predictions, labels):\n num_proteins = predictions.shape[0]\n protein_accuracy = np.zeros(num_proteins, dtype=np.float32)\n label_accuracy = {1: {\"total\": 0, \"correct\": 0}, 2: {\"total\": 0, \"correct\": 0},\n 3: {\"total\": 0, \"correct\": 0}}\n for i in range(num_proteins):\n total_predictions = 0\n correct_predictions = 0\n for j in range(predictions.shape[1]):\n phi = math.degrees(labels[i][j][0])\n phi0 = math.degrees(predictions[i][j][0])\n psi = math.degrees(labels[i][j][1])\n psi0 = math.degrees(predictions[i][j][1])\n if (phi != 0) or (psi != 0):\n total_predictions += 1\n expected_state = get_backbone_distribution(labels[i][j])\n predicted_state = get_backbone_distribution(predictions[i][j])\n label_accuracy[predicted_state][\"total\"] += 1\n if (predicted_state == expected_state):\n # correct_predictions += 1\n label_accuracy[predicted_state][\"correct\"] += 1\n # print(\"REAL PHI->>>>>\"+str(labels[i][j][0]))\n # print(\"PREDICTED PHI->>>>>\" + str(predictions[i][j][0]))\n diff = math.sqrt(math.pow(phi - phi0, 2)+math.pow(psi - psi0, 2))\n diff_phi = phi0 - phi0\n diff_psi = psi - psi0\n criteria_1 = (np.abs(diff_phi) < 60) & (np.abs(diff_psi) < 60)\n criteria_2 = (np.abs(diff_phi+diff_psi) < 60) & (np.abs(diff_psi) < 90) & (np.abs(diff_phi) < 90)\n if (diff < 60):\n correct_predictions += 1\n # print(\"CORRECT->>>>>\"+str(correct_predictions))\n # print(\"TOTAL->>>>>\" + str(total_predictions))\n if (total_predictions > 0):\n protein_accuracy[i] = correct_predictions / float(total_predictions)\n\n accuracy_dist = {}\n total = 0\n correct = 0\n for label, val in label_accuracy.iteritems():\n if (val[\"total\"] > 0):\n accuracy_dist[label] = val[\"correct\"]/val[\"total\"]\n total += val[\"total\"]\n correct += val[\"correct\"]\n if (total > 0):\n accuracy_dist[\"total\"] = correct/total\n return protein_accuracy, accuracy_dist\n\ndef get_backbone_distribution(angles):\n phi = math.degrees(angles[0])\n psi = math.degrees(angles[1])\n # A: -160 < phi <0 and -70 < psi < 60\n if (-160 < phi < 0) & (-70 < psi < 60):\n return 1\n # P: 0 < phi < 160 and -60 < psi < 95\n elif (0 < phi < 160) & (-60 < psi < 95):\n return 2\n else:\n return 3\n\ndef plot_ramachandran(predictions, title):\n phi_angles = predictions[:][:][0].flatten()\n phi_angles = list(map(lambda x: math.degrees(x), phi_angles))\n psi_angles = predictions[:][:][1].flatten()\n psi_angles = list(map(lambda x: math.degrees(x), psi_angles))\n colors = np.random.rand(len(psi_angles))\n fig = plt.figure()\n plt.xlim([-180, 180])\n plt.ylim([-180, 180])\n plt.title(title)\n plt.xlabel('phi')\n plt.ylabel('psi')\n plt.grid()\n plt.scatter(phi_angles, psi_angles, alpha=0.5, c=colors)\n fig.savefig(\"./plots/\" + title + \".png\", bbox_inches='tight')\n # plt.show()\n # fig.savefig(\"./plots/\" + title + \".png\", bbox_inches='tight')\n plt.close()\n\ndef plot_loss(loss_arr):\n l = plt.figure()\n plt.plot(loss_arr)\n plt.title('Loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(plot_legend, loc='upper left')\n l.show()\n\ndef make_hparam_string(layers_num, channels_num, test_session):\n return \"nl_%s,nc_%s, session%s\" % (layers_num, channels_num, test_session)\n\ndef convert_to_degrees(arr):\n \"\"\"Covert all phi and psi angles to degrees\"\"\"\n arr[0] = math.degrees(arr[0])\n arr[1] = math.degrees(arr[1])\n return arr\n\ndata = np.load('phipsi_features.npz')['features']\nall_data = data.reshape(data.shape[0],700,69)\n# all_data = all_data[0:300]\nall_sets = all_data[:,:,0:21]\nall_sets = np.concatenate([all_sets, all_data[:,:,21:42]], axis=-1)\nall_sets = np.concatenate([all_sets, all_data[:,:,42:63]], axis=-1)\n# all_labels = all_data[:,:,63:67]\nall_angles = all_data[:,:,67:69]\nwhere_are_NaNs = np.isnan(all_angles)\nall_angles[where_are_NaNs] = 0.0\nk_fold = KFold(n_splits=num_splits)\n\nlayers_channels = [(6, 100), (7, 100)]\n# Build the convolutional network\nfor layers_num, channels_num in layers_channels:\n for use_l2 in [False, True]:\n for use_early_stopping in [True, False]:\n crossvalidation_train_accuracy = 0\n crossvalidation_test_accuracy = 0\n crossvalidation_accuracy_distr = {'total': 0, 1: 0, 2: 0, 3: 0}\n crossvalidation_test_mae = 0\n executed_epochs = 0\n train_session = 0\n test_session = 0\n learning_rate_type = 1\n for train_index, test_index in k_fold.split(all_sets):\n train_set, test_set = all_sets[train_index], all_sets[test_index]\n train_labels, test_labels = all_angles[train_index], all_angles[test_index]\n train_size = train_set.shape[0]\n train_y = train_labels\n test_y = test_labels\n test_session += 1\n\n # Create the model\n x = tf.placeholder(tf.float32, [None, 700, train_set[0].shape[-1]], name=\"x\")\n\n # Define loss and optimizer\n y_ = tf.placeholder(tf.float32, [None, 700, values_to_predict], name=\"labels\")\n\n y_nn, regularizers = convnn(x, channels_num, layers_num, window_size)\n prediction = y_nn\n\n with tf.name_scope(\"loss\"):\n deviations = tf.subtract(prediction, y_)\n ae = tf.abs(deviations)\n mae = tf.reduce_mean(ae)\n atan2 = tf.atan2(tf.sin(deviations), tf.cos(deviations))\n loss = tf.square(atan2, name=\"loss\")\n mean_loss = tf.reduce_mean(loss)\n loss_summary = tf.summary.scalar(\"loss\", mean_loss)\n\n with tf.name_scope(\"loss2\"):\n # print(tf.shape(prediction))\n # print(tf.shape(y_))\n phi = prediction[:, :, 0]\n phi0 = y_[:, :, 0]\n psi = prediction[:, :, 1]\n psi0 = y_[:,:, 1]\n # cos_phi_diff = tf.square(tf.subtract(tf.cos(phi), tf.cos(phi0)))\n # sin_phi_diff = tf.square(tf.subtract(tf.sin(phi), tf.sin(phi0)))\n # cos_psi_diff = tf.square(tf.subtract(tf.cos(psi), tf.cos(psi0)))\n # sin_psi_diff = tf.square(tf.subtract(tf.sin(psi), tf.sin(psi0)))\n # phi_squared_sum = tf.add(cos_phi_diff, sin_phi_diff)\n # psi_squared_sum = tf.add(cos_psi_diff, sin_psi_diff)\n phi_diff = tf.reduce_sum(tf.squared_difference(phi, phi0))/2\n psi_diff = tf.reduce_sum(tf.squared_difference(psi, psi0))/2\n loss2 = tf.add(phi_diff, psi_diff)\n\n with tf.name_scope(\"mse\"):\n mse = tf.squared_difference(prediction, y_)\n mse_summary = tf.summary.scalar(\"mse\", mse)\n\n with tf.name_scope(\"l2_loss\"):\n l2_loss = beta * regularizers\n if (use_l2):\n loss = loss + l2_loss\n loss = tf.reduce_mean(loss)\n l2_summary = tf.summary.scalar(\"l2_loss\", l2_loss)\n\n with tf.name_scope(\"train\"):\n # Use Adam optimizer\n optimization = tf.train.AdamOptimizer(learning_rate).minimize(loss)\n # with tf.name_scope(\"accuracy\"):\n # correct_prediction = tf.equal(prediction, y)\n # accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n # tf.summary.scalar(\"accuracy\", accuracy)\n\n summ = tf.summary.merge_all()\n\n print(\"Window size: \" + str(window_size))\n print(\"Layers: \" + str(layers_num))\n print(\"Channels: \" + str(channels_num))\n print(\"Beta: \" + str(beta))\n print(\"Use L2: \" + str(use_l2))\n print(\"Use Early stopping: \" + str(use_early_stopping))\n sess = tf.InteractiveSession()\n init = tf.global_variables_initializer()\n sess.run(init)\n saver = tf.train.Saver()\n\n min_delta = 0.01\n plot_legend = []\n previous_epoch_min = 100\n min_validation_loss = 100\n for epoch in range(training_epochs):\n train_session += 1\n loss_arr = []\n previous_batch_loss = 0.0\n patience = 6\n patience_cnt = 0\n\n hparam = make_hparam_string(layers_num, channels_num, train_session)\n writer = tf.summary.FileWriter(LOGDIR + hparam)\n writer.add_graph(sess.graph)\n total_batches = int(train_size/batch_size)\n # Loop over all batches\n for i in range(total_batches):\n start_index = i * batch_size\n stop_index = (i+1) * batch_size\n batch_x = train_set[start_index:stop_index]\n batch_y = train_y[start_index:stop_index]\n # Run optimization op\n # backprop and cost op (to get loss value)\n if i % 5 == 0:\n batch_predictions, l_summ, batch_loss = sess.run([prediction, loss_summary, loss], feed_dict={x: batch_x, y_: batch_y, keep_prob: dropout_keep_rate, keep_prob_input: 0.8})\n writer.add_summary(l_summ, i+1)\n loss_arr.append(batch_loss)\n saver.save(sess, os.path.join(LOGDIR, \"model.ckpt\"), i)\n # batch_predictions = np.apply_along_axis(convert_to_degrees, 2, batch_predictions)\n batch_accuracy, batch_distr = calculate_accuracy(batch_predictions, batch_y)\n # print('step %d, training accuracy %g' % (i, np.average(batch_accuracy)))\n # early stopping\n if(use_early_stopping):\n if (epoch > 2 and i > total_batches / 2 and batch_loss < previous_epoch_min):\n previous_epoch_min = min(loss_arr)\n print(\"Early stopping!!\")\n break\n optimization.run(feed_dict={x: batch_x, y_: batch_y})\n previous_epoch_min = min(loss_arr)\n # Display logs per epoch step\n if epoch % display_step == 0:\n predictions, train_loss = sess.run([prediction,loss], feed_dict={x: train_set, y_: train_y, keep_prob: dropout_keep_rate, keep_prob_input: 0.8})\n # predictions = np.apply_along_axis(convert_to_degrees, 2, predictions)\n # plot_ramachandran(train_y, \"Real values_\"+str(epoch))\n # raw_input()\n train_accuracy, train_acc_distr = calculate_accuracy(predictions, train_y)\n train_accuracy = np.average(train_accuracy)\n crossvalidation_train_accuracy += train_accuracy\n plot_legend.append('train_' + str(epoch))\n # plot_loss(loss_arr)\n\n # print(\"Training accuracy: \", \\\n # \"{:.6f}\".format(train_accuracy))\n if (epoch > training_epochs / 2):\n valid_predictions, valid_loss, valid_mae = sess.run([prediction, loss, mae], feed_dict={x: test_set, y_: test_y})\n # valid_predictions = np.apply_along_axis(convert_to_degrees, 2, valid_predictions)\n valid_accuracy, valid_acc_distr = calculate_accuracy(valid_predictions, test_y)\n valid_accuracy = np.average(valid_accuracy)\n if (epoch >= training_epochs - 1):\n if (valid_loss < min_validation_loss):\n training_epochs += 1\n print(\"INCREASING EPOCHS\")\n else:\n crossvalidation_test_accuracy += valid_accuracy\n crossvalidation_test_mae += valid_mae\n for label in valid_acc_distr:\n crossvalidation_accuracy_distr[label] += valid_acc_distr[label]\n print(crossvalidation_accuracy_distr)\n\n if (epoch >= training_epochs - 2):\n min_validation_loss = valid_loss\n print(valid_acc_distr)\n print(\"Validation accuracy: \", \\\n \"{:.6f}\".format(valid_accuracy))\n\n\n executed_epochs += 1\n # Test trained model\n test_predictions, test_summ, test_mae = sess.run([prediction, loss_summary, mae], feed_dict={x: test_set, y_: test_y})\n writer.add_summary(test_summ, i + 1)\n test_accuracy, test_acc_distr = calculate_accuracy(test_predictions, test_y)\n plot_ramachandran(test_predictions, \"Predictions Fold \"+str(test_session))\n plot_ramachandran(test_y, \"Real values Fold \"+str(test_session))\n\n # plot_legend.append('validation')\n\n print(test_acc_distr)\n # test_accuracy = np.average(test_accuracy)\n # crossvalidation_test_accuracy += test_accuracy\n # crossvalidation_test_mae += test_mae\n # print(\"Testing accuracy: \", \\\n # \"{:.6f}\".format(test_accuracy))\n for label in crossvalidation_accuracy_distr:\n crossvalidation_accuracy_distr[label] /= num_splits\n print(crossvalidation_accuracy_distr)\n # print(\"Final Testing DISTR: \", \\\n # \"{:.6f}\".format(crossvalidation_test_mae / num_splits))\n print(\"Final Testing MAE: \", \\\n \"{:.6f}\".format(crossvalidation_test_mae / num_splits))\n # print(\"Final Training accuracy: \", \\\n # \"{:.6f}\".format(crossvalidation_train_accuracy / (num_splits*training_epochs)))\n print(\"Final Test accuracy: \", \\\n \"{:.6f}\".format(crossvalidation_test_accuracy / num_splits))\n print('Run `tensorboard --logdir=%s` to see the results.' % LOGDIR)\n\n # valid_predictions = sess.run(tf.argmax(prediction, 2), feed_dict={x: valid_x, y_: valid_y})\n # valid_labels = np.argmax(valid_y, 2)\n # valid_accuracy = calculate_accuracy(valid_predictions, valid_labels)\n # print(\"Validation accuracy: \", \\\n # \"{:.6f}\".format(valid_accuracy))" ]
[ [ "matplotlib.pyplot.legend", "sklearn.model_selection.KFold", "numpy.concatenate", "matplotlib.pyplot.plot", "tensorflow.nn.l2_loss", "tensorflow.train.AdamOptimizer", "tensorflow.nn.conv1d", "tensorflow.summary.scalar", "tensorflow.Variable", "tensorflow.placeholder_with_default", "tensorflow.subtract", "tensorflow.add", "tensorflow.name_scope", "matplotlib.pyplot.close", "tensorflow.square", "tensorflow.train.Saver", "numpy.load", "numpy.zeros", "matplotlib.pyplot.figure", "tensorflow.nn.dropout", "tensorflow.truncated_normal", "tensorflow.InteractiveSession", "matplotlib.pyplot.title", "numpy.isnan", "matplotlib.pyplot.ylim", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.summary.merge_all", "tensorflow.nn.avg_pool", "matplotlib.pyplot.ylabel", "tensorflow.summary.histogram", "tensorflow.sin", "tensorflow.constant", "tensorflow.summary.FileWriter", "matplotlib.pyplot.scatter", "tensorflow.reduce_mean", "numpy.abs", "tensorflow.cos", "matplotlib.pyplot.xlim", "matplotlib.pyplot.grid", "matplotlib.pyplot.xlabel", "numpy.average", "tensorflow.squared_difference", "tensorflow.abs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
cipher982/Wine-o-matic
[ "a8000bf5ec86554e9c3c746aae51ba509ab59162" ]
[ "extra_code/transformers-gpt2-finetune.py" ]
[ "import os\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n\n# import deepspeed\n# import mpi4py\n# import pandas\nimport torch\nimport transformers\nimport wandb\n\n#%env WANDB_PROJECT=wine_gpt2_Trainer_42\n\nMODEL_NAME = \"gpt2-medium\"\n\n# wandb.login(anonymous='never', key=\"222a37baaf0c1b0d1499ec003e5c2fe49f97b107\")\nwandb.init()\n# wandb.watch(log='all')\n\nprint(torch.cuda.is_available())\nprint(f\"transformers version: {transformers.__version__}\")\nprint(f\"PyTorch version: {torch.__version__}\")\n\n# Tokenizers\ntokenizer = transformers.AutoTokenizer.from_pretrained(MODEL_NAME)\nprint(len(tokenizer))\n\ntokenizer.add_special_tokens(\n {\"eos_token\": \"<|startoftext|>\", \"bos_token\": \"<|startoftext|>\"}\n)\ntokenizer.add_tokens(\n [\n \"[prompt]\",\n \"[response]\",\n \"[category_1]\",\n \"[category_2]\",\n \"[origin]\",\n \"[description]\",\n \"<|endoftext|>\",\n ]\n)\n\ntokenizer.pad_token = tokenizer.eos_token\n\ntokenizer.save_pretrained(\"data/modeling/trainer_42/\")\n\nprint(len(tokenizer))\nprint(\"Created tokenizer\")\n\n\nclass wineDataset(torch.utils.data.Dataset):\n def __init__(self, encodings):\n self.encodings = encodings\n\n def __len__(self):\n return len(self.encodings[\"input_ids\"])\n\n def __getitem__(self, idx):\n item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}\n item[\"labels\"] = item[\"input_ids\"]\n return item\n\n\nwith open(\"data/scraped/name_desc_nlp_ready_train.txt\", \"r\", encoding=\"utf8\") as file:\n wines_raw_train = file.read().splitlines()\nwith open(\"data/scraped/name_desc_nlp_ready_test.txt\", \"r\", encoding=\"utf8\") as file:\n wines_raw_test = file.read().splitlines()\nprint(\"Loaded dataset\")\n\n# wines_raw_train, wines_raw_test = train_test_split(wines_raw,test_size=0.2)\n\n# wine_encodings_train = tokenizer(wines_raw_train, max_length=200, truncation=True, padding=True)\nwine_encodings_test = tokenizer(\n wines_raw_test, max_length=200, truncation=True, padding=True\n)\nprint(\"Encoded dataset\")\n\n# wine_dataset_train = wineDataset(wine_encodings_train)\nwine_dataset_test = wineDataset(wine_encodings_test)\nprint(\"Created PyTorch DataSet\")\n\n# train_loader = torch.utils.data.DataLoader(wine_dataset_train)\n\nmodel = transformers.AutoModelForCausalLM.from_pretrained(MODEL_NAME)\n# model.to('cuda')\nmodel.resize_token_embeddings(len(tokenizer))\n\nprint(f\"model parameters: {model.num_parameters():,}\")\n\ntraining_args = transformers.TrainingArguments(\n output_dir=\"data/modeling/trainer_42/\",\n overwrite_output_dir=True,\n num_train_epochs=1,\n per_device_train_batch_size=2,\n save_steps=100,\n save_total_limit=2,\n fp16=True,\n # deepspeed='data/ds_config.json'\n)\n\ntrainer = transformers.Trainer(\n model=model, args=training_args, train_dataset=wine_dataset_test,\n)\n\ntrainer.train()\n" ]
[ [ "torch.cuda.is_available", "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
IronOnet/tensor2robot
[ "351cecbf76b71d09b56a766b981e1a15f85d9528", "351cecbf76b71d09b56a766b981e1a15f85d9528" ]
[ "utils/train_eval_test.py", "research/vrgripper/vrgripper_env_models.py" ]
[ "# coding=utf-8\n# Copyright 2019 The Tensor2Robot Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python2, python3\n\"\"\"Tests for tensor2robot.train_eval.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport os\nfrom absl import flags\nimport gin\nimport mock\nimport numpy as np\n\nfrom six.moves import zip\nfrom tensor2robot.hooks import hook_builder\nfrom tensor2robot.models import abstract_model\nfrom tensor2robot.preprocessors import noop_preprocessor\nfrom tensor2robot.utils import mocks\nfrom tensor2robot.utils import train_eval\nimport tensorflow.compat.v1 as tf\nfrom tensorflow.contrib import predictor as contrib_predictor\n\nFLAGS = flags.FLAGS\n\n_MAX_TRAIN_STEPS = 400\n_EVAL_STEPS = 40\n_BATCH_SIZE = 4\n_EVAL_THROTTLE_SECS = 0.0\n\n\nclass FakeHook(tf.train.SessionRunHook):\n\n def __init__(self):\n self._mock = mock.MagicMock()\n\n def begin(self):\n self._mock.begin()\n return\n\n @property\n def mock(self):\n return self._mock\n\n\nclass FakeHookBuilder(hook_builder.HookBuilder):\n\n def __init__(self):\n self._hook = FakeHook()\n\n def create_hooks(self, *args, **kwargs):\n del args, kwargs\n return [self._hook]\n\n @property\n def hook_mock(self):\n return self._hook.mock\n\n\nclass TrainEvalTest(tf.test.TestCase):\n\n def _compute_total_loss(self, labels, logits):\n \"\"\"Summation of the categorical hinge loss for labels and logits.\"\"\"\n error = 0.\n for label, logit in zip(labels, logits):\n # Reference tensorflow implementation can be found in keras.losses.\n positive = (label * logit)\n negative = ((1 - label) * logit)\n error += np.maximum(0., negative - positive + 1.)\n return error\n\n def test_train_eval_model(self):\n \"\"\"Tests that a simple model trains and exported models are valid.\"\"\"\n gin.bind_parameter('tf.estimator.RunConfig.save_checkpoints_steps', 100)\n model_dir = self.create_tempdir().full_path\n mock_t2r_model = mocks.MockT2RModel(\n preprocessor_cls=noop_preprocessor.NoOpPreprocessor)\n\n mock_input_generator_train = mocks.MockInputGenerator(\n batch_size=_BATCH_SIZE)\n mock_input_generator_eval = mocks.MockInputGenerator(batch_size=1)\n fake_hook_builder = FakeHookBuilder()\n\n train_eval.train_eval_model(\n t2r_model=mock_t2r_model,\n input_generator_train=mock_input_generator_train,\n input_generator_eval=mock_input_generator_eval,\n max_train_steps=_MAX_TRAIN_STEPS,\n model_dir=model_dir,\n train_hook_builders=[fake_hook_builder],\n eval_hook_builders=[fake_hook_builder],\n eval_steps=_EVAL_STEPS,\n eval_throttle_secs=_EVAL_THROTTLE_SECS,\n create_exporters_fn=train_eval.create_default_exporters)\n\n self.assertTrue(fake_hook_builder.hook_mock.begin.called)\n\n # We ensure that both numpy and tf_example inference models are exported.\n best_exporter_numpy_path = os.path.join(model_dir, 'export',\n 'best_exporter_numpy', '*')\n numpy_model_paths = sorted(tf.io.gfile.glob(best_exporter_numpy_path))\n # There should be at least 1 exported model.\n self.assertGreater(len(numpy_model_paths), 0)\n # This mock network converges nicely which is why we have several best\n # models, by default we keep the best 5 and the latest one is always the\n # best.\n self.assertLessEqual(len(numpy_model_paths), 5)\n\n best_exporter_tf_example_path = os.path.join(\n model_dir, 'export', 'best_exporter_tf_example', '*')\n\n tf_example_model_paths = sorted(\n tf.io.gfile.glob(best_exporter_tf_example_path))\n # There should be at least 1 exported model.\n self.assertGreater(len(tf_example_model_paths), 0)\n # This mock network converges nicely which is why we have several best\n # models, by default we keep the best 5 and the latest one is always the\n # best.\n self.assertLessEqual(len(tf_example_model_paths), 5)\n\n # We test both saved models within one test since the bulk of the time\n # is spent training the model in the firstplace.\n\n # Verify that the serving estimator does exactly the same as the normal\n # estimator with all the parameters.\n estimator_predict = tf.estimator.Estimator(\n model_fn=mock_t2r_model.model_fn,\n config=tf.estimator.RunConfig(model_dir=model_dir))\n\n prediction_ref = estimator_predict.predict(\n input_fn=mock_input_generator_eval.create_dataset_input_fn(\n mode=tf.estimator.ModeKeys.EVAL))\n\n # Now we can load our exported estimator graph with the numpy feed_dict\n # interface, there are no dependencies on the model_fn or preprocessor\n # anymore.\n # We load the latest model since it had the best eval performance.\n numpy_predictor_fn = contrib_predictor.from_saved_model(\n numpy_model_paths[-1])\n\n features, labels = mock_input_generator_eval.create_numpy_data()\n\n ref_error = self._compute_total_loss(\n labels, [val['logit'].flatten() for val in prediction_ref])\n\n numpy_predictions = []\n for feature, label in zip(features, labels):\n predicted = numpy_predictor_fn({'x': feature.reshape(\n 1, -1)})['logit'].flatten()\n numpy_predictions.append(predicted)\n # This ensures that we actually achieve near-perfect classification.\n if label > 0:\n self.assertGreater(predicted[0], 0)\n else:\n self.assertLess(predicted[0], 0)\n numpy_error = self._compute_total_loss(labels, numpy_predictions)\n\n # Now we can load our exported estimator graph with the tf_example feed_dict\n # interface, there are no dependencies on the model_fn or preprocessor\n # anymore.\n # We load the latest model since it had the best eval performance.\n tf_example_predictor_fn = contrib_predictor.from_saved_model(\n tf_example_model_paths[-1])\n tf_example_predictions = []\n for feature, label in zip(features, labels):\n # We have to create our serialized tf.Example proto.\n example = tf.train.Example()\n example.features.feature['measured_position'].float_list.value.extend(\n feature)\n feed_dict = {\n 'input_example_tensor':\n np.array(example.SerializeToString()).reshape(1,)\n }\n predicted = tf_example_predictor_fn(feed_dict)['logit'].flatten()\n tf_example_predictions.append(predicted)\n # This ensures that we actually achieve perfect classification.\n if label > 0:\n self.assertGreater(predicted[0], 0)\n else:\n self.assertLess(predicted[0], 0)\n tf_example_error = self._compute_total_loss(labels, tf_example_predictions)\n\n np.testing.assert_almost_equal(tf_example_error, numpy_error)\n # The exported saved models both have to have the same performance and since\n # we train on eval on the same fixed dataset the latest and greatest\n # model error should also be the best.\n np.testing.assert_almost_equal(ref_error, tf_example_error, decimal=3)\n\n def test_init_from_checkpoint_global_step(self):\n \"\"\"Tests that a simple model trains and exported models are valid.\"\"\"\n gin.bind_parameter('tf.estimator.RunConfig.save_checkpoints_steps', 100)\n gin.bind_parameter('tf.estimator.RunConfig.keep_checkpoint_max', 3)\n model_dir = self.create_tempdir().full_path\n mock_t2r_model = mocks.MockT2RModel(\n preprocessor_cls=noop_preprocessor.NoOpPreprocessor)\n\n mock_input_generator_train = mocks.MockInputGenerator(\n batch_size=_BATCH_SIZE)\n\n train_eval.train_eval_model(\n t2r_model=mock_t2r_model,\n input_generator_train=mock_input_generator_train,\n max_train_steps=_MAX_TRAIN_STEPS,\n model_dir=model_dir,\n eval_steps=_EVAL_STEPS,\n eval_throttle_secs=_EVAL_THROTTLE_SECS,\n create_exporters_fn=train_eval.create_default_exporters)\n # The model trains for 200 steps and saves a checkpoint each 100 steps and\n # keeps 3 -> len == 3.\n self.assertLen(tf.io.gfile.glob(os.path.join(model_dir, 'model*.meta')), 3)\n\n # The continuous training has its own directory.\n continue_model_dir = self.create_tempdir().full_path\n init_from_checkpoint_fn = functools.partial(\n abstract_model.default_init_from_checkpoint_fn, checkpoint=model_dir)\n continue_mock_t2r_model = mocks.MockT2RModel(\n preprocessor_cls=noop_preprocessor.NoOpPreprocessor,\n init_from_checkpoint_fn=init_from_checkpoint_fn)\n continue_mock_input_generator_train = mocks.MockInputGenerator(\n batch_size=_BATCH_SIZE)\n train_eval.train_eval_model(\n t2r_model=continue_mock_t2r_model,\n input_generator_train=continue_mock_input_generator_train,\n model_dir=continue_model_dir,\n max_train_steps=_MAX_TRAIN_STEPS + 100,\n eval_steps=_EVAL_STEPS,\n eval_throttle_secs=_EVAL_THROTTLE_SECS,\n create_exporters_fn=train_eval.create_default_exporters)\n # If the model was successful restored including the global step, only 1\n # additional checkpoint to the init one should be created -> len == 2.\n self.assertLen(\n tf.io.gfile.glob(os.path.join(continue_model_dir, 'model*.meta')), 2)\n\n def test_init_from_checkpoint_use_avg_model_params_and_weights(self):\n \"\"\"Tests that a simple model trains and exported models are valid.\"\"\"\n gin.bind_parameter('tf.estimator.RunConfig.save_checkpoints_steps', 100)\n gin.bind_parameter('tf.estimator.RunConfig.keep_checkpoint_max', 3)\n model_dir = self.create_tempdir().full_path\n mock_t2r_model = mocks.MockT2RModel(\n preprocessor_cls=noop_preprocessor.NoOpPreprocessor,\n use_avg_model_params=True)\n\n mock_input_generator_train = mocks.MockInputGenerator(\n batch_size=_BATCH_SIZE)\n\n mock_input_generator = mocks.MockInputGenerator(batch_size=1)\n mock_input_generator.set_specification_from_model(\n mock_t2r_model, tf.estimator.ModeKeys.TRAIN)\n\n train_eval.train_eval_model(\n t2r_model=mock_t2r_model,\n input_generator_train=mock_input_generator_train,\n max_train_steps=_MAX_TRAIN_STEPS,\n model_dir=model_dir)\n\n init_checkpoint = tf.train.NewCheckpointReader(\n tf.train.latest_checkpoint(model_dir))\n\n # Verify that the serving estimator does exactly the same as the normal\n # estimator with all the parameters.\n initial_estimator_predict = tf.estimator.Estimator(\n model_fn=mock_t2r_model.model_fn,\n config=tf.estimator.RunConfig(model_dir=model_dir))\n\n # pylint: disable=g-complex-comprehension\n initial_predictions = [\n prediction['logit'] for prediction in list(\n initial_estimator_predict.predict(\n input_fn=mock_input_generator.create_dataset_input_fn(\n mode=tf.estimator.ModeKeys.EVAL)))\n ]\n\n # The continuous training has its own directory.\n continue_model_dir = self.create_tempdir().full_path\n init_from_checkpoint_fn = functools.partial(\n abstract_model.default_init_from_checkpoint_fn, checkpoint=model_dir)\n continue_mock_t2r_model = mocks.MockT2RModel(\n preprocessor_cls=noop_preprocessor.NoOpPreprocessor,\n init_from_checkpoint_fn=init_from_checkpoint_fn)\n continue_mock_input_generator_train = mocks.MockInputGenerator(\n batch_size=_BATCH_SIZE)\n # Re-initialize the model and train for one step, basically the same\n # performance as the original model.\n train_eval.train_eval_model(\n t2r_model=continue_mock_t2r_model,\n input_generator_train=continue_mock_input_generator_train,\n model_dir=continue_model_dir,\n max_train_steps=_MAX_TRAIN_STEPS)\n\n continue_checkpoint = tf.train.NewCheckpointReader(\n tf.train.latest_checkpoint(continue_model_dir))\n\n for tensor_name, _ in tf.train.list_variables(model_dir):\n if 'ExponentialMovingAverage' in tensor_name:\n # These values are replaced by the swapping saver when using the\n # use_avg_model_params.\n continue\n if 'Adam' in tensor_name:\n # The adam optimizer values are not required.\n continue\n if 'global_step' in tensor_name:\n # The global step will be incremented by 1.\n continue\n self.assertAllClose(\n init_checkpoint.get_tensor(tensor_name),\n continue_checkpoint.get_tensor(tensor_name),\n atol=1e-3)\n\n # Verify that the serving estimator does exactly the same as the normal\n # estimator with all the parameters.\n continue_estimator_predict = tf.estimator.Estimator(\n model_fn=mock_t2r_model.model_fn,\n config=tf.estimator.RunConfig(model_dir=continue_model_dir))\n\n continue_predictions = [\n prediction['logit'] for prediction in list(\n continue_estimator_predict.predict(\n input_fn=mock_input_generator.create_dataset_input_fn(\n mode=tf.estimator.ModeKeys.EVAL)))\n ]\n\n self.assertTrue(\n np.allclose(initial_predictions, continue_predictions, atol=1e-1))\n\n # A randomly initialized model estimator with all the parameters.\n random_estimator_predict = tf.estimator.Estimator(\n model_fn=mock_t2r_model.model_fn)\n\n random_predictions = [\n prediction['logit'] for prediction in list(\n random_estimator_predict.predict(\n input_fn=mock_input_generator.create_dataset_input_fn(\n mode=tf.estimator.ModeKeys.EVAL)))\n ]\n self.assertFalse(\n np.allclose(initial_predictions, random_predictions, atol=1e-2))\n\nif __name__ == '__main__':\n tf.test.main()\n", "# coding=utf-8\n# Copyright 2019 The Tensor2Robot 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\"\"\"T2RModels for VRGripper env tasks.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nfrom __future__ import print_function\n\nimport gin\nimport numpy as np\nfrom tensor2robot.google import distortion\nfrom tensor2robot.layers import mdn\nfrom tensor2robot.layers import vision_layers\nfrom tensor2robot.meta_learning import meta_tfdata\nfrom tensor2robot.models import abstract_model\nfrom tensor2robot.models import regression_model\nfrom tensor2robot.preprocessors import abstract_preprocessor\nfrom tensor2robot.utils import tensorspec_utils\nimport tensorflow.compat.v1 as tf # tf\nimport tensorflow_probability as tfp\nfrom typing import Callable, Dict, List, Optional, Text, Tuple\n\nfrom tensorflow.contrib import layers as contrib_layers\n\nTensorSpec = tensorspec_utils.ExtendedTensorSpec\nTRAIN = tf.estimator.ModeKeys.TRAIN\nPREDICT = tf.estimator.ModeKeys.PREDICT\nFLOAT_DTYPES = [tf.bfloat16, tf.float32, tf.float64]\n\n\[email protected]\nclass DefaultVRGripperPreprocessor(abstract_preprocessor.AbstractPreprocessor):\n \"\"\"The default VRGripperEnv preprocessor.\"\"\"\n\n def __init__(self,\n src_img_res = (220, 300),\n crop_size = (200, 280),\n mixup_alpha = 0.0,\n **kwargs):\n \"\"\"Construct the preprocessor.\n\n Args:\n src_img_res: The true height and width of the image data. If the model\n expects images of a different size, we automatically resize the images.\n crop_size: Before resizing the image, take a crop of the image to this\n height and width. Is a no-op if equal to src_img_res. Crop is done\n randomly at train time, and is take from the center otherwise.\n mixup_alpha: If > 0., turns on Mixup data augmentation for features and\n labels.\n **kwargs: Keyword args passed to parent class.\n \"\"\"\n super(DefaultVRGripperPreprocessor, self).__init__(**kwargs)\n self._src_img_res = src_img_res\n self._crop_size = crop_size\n self._mixup_alpha = mixup_alpha\n\n def get_in_feature_specification(self, mode\n ):\n \"\"\"See base class.\"\"\"\n feature_spec = tensorspec_utils.copy_tensorspec(\n self._model_feature_specification_fn(mode))\n # Don't want to parse the original_image, since we don't want to parse it\n # and we are adding this feature in preprocess_fn to satisfy the model's\n # inputs.\n if mode != PREDICT and 'original_image' in feature_spec:\n del feature_spec['original_image']\n\n if 'image' in feature_spec:\n true_img_shape = feature_spec.image.shape.as_list()\n # Overwrite the H, W dimensions.\n true_img_shape[-3:-1] = self._src_img_res\n feature_spec.image = TensorSpec.from_spec(\n feature_spec.image, shape=true_img_shape, dtype=tf.uint8)\n return tensorspec_utils.flatten_spec_structure(feature_spec)\n\n def get_in_label_specification(self, mode\n ):\n \"\"\"See base class.\"\"\"\n return tensorspec_utils.flatten_spec_structure(\n self._model_label_specification_fn(mode))\n\n def get_out_feature_specification(self, mode\n ):\n \"\"\"See base class.\"\"\"\n return tensorspec_utils.flatten_spec_structure(\n self._model_feature_specification_fn(mode))\n\n def get_out_label_specification(self, mode\n ):\n \"\"\"See base class.\"\"\"\n return tensorspec_utils.flatten_spec_structure(\n self._model_label_specification_fn(mode))\n\n def _preprocess_fn(\n self, features,\n labels,\n mode\n ):\n \"\"\"Resize images and convert them from uint8 -> float32.\"\"\"\n if 'image' in features:\n ndim = len(features.image.shape)\n is_sequence = (ndim > 4)\n input_size = self._src_img_res\n target_size = self._crop_size\n features.original_image = features.image\n features.image = distortion.preprocess_image(features.image, mode,\n is_sequence, input_size,\n target_size)\n\n features.image = tf.image.convert_image_dtype(features.image, tf.float32)\n out_feature_spec = self.get_out_feature_specification(mode)\n if out_feature_spec.image.shape != features.image.shape:\n features.image = meta_tfdata.multi_batch_apply(\n tf.image.resize_images, 2, features.image,\n out_feature_spec.image.shape.as_list()[-3:-1])\n\n if self._mixup_alpha > 0. and labels and mode == TRAIN:\n lmbda = tfp.distributions.Beta(\n self._mixup_alpha, self._mixup_alpha).sample()\n for key, x in features.items():\n if x.dtype in FLOAT_DTYPES:\n features[key] = lmbda * x + (1-lmbda)*tf.reverse(x, axis=[0])\n if labels is not None:\n for key, x in labels.items():\n if x.dtype in FLOAT_DTYPES:\n labels[key] = lmbda * x + (1 - lmbda) * tf.reverse(x, axis=[0])\n return features, labels\n\n\[email protected]\nclass VRGripperRegressionModel(regression_model.RegressionModel):\n \"\"\"Continuous regression output model for VRGripper Env.\"\"\"\n\n def __init__(self,\n use_gripper_input = True,\n normalize_outputs = False,\n output_mean = None,\n output_stddev = None,\n outer_loss_multiplier = 1.,\n num_mixture_components = 1,\n output_mixture_sample = False,\n condition_mixture_stddev = False,\n episode_length = 40,\n **kwargs):\n \"\"\"Initialize the VRGripperRegressionModel.\n\n Args:\n use_gripper_input: If True, concatenate gripper pose with input to the\n fully connected layers when predicting actions.\n normalize_outputs: If True, scale actions by `output_stddev` and\n translate by `output_mean`.\n output_mean: The empirical mean of demonstration actions.\n output_stddev: The empirical standard deviation of demonstration actions.\n outer_loss_multiplier: A scaling factor for the outer loss.\n num_mixture_components: The number of gaussian mixture components. Use 1\n for standard mean squared error regression.\n output_mixture_sample: If True (and num_mixture_components > 1), output\n actions by sampling from a gaussian mixture. Otherwise, we use the mean\n of the most likely component.\n condition_mixture_stddev: If True, the mixture standard deviations will be\n output from a neural net and thus conditioned on image/state. Otherwise,\n they will simply be learned variables (unconditioned on image/state).\n episode_length: The fixed length of an episode in the data.\n **kwargs: Passed to parent.\n\n Raises:\n ValueError: If `output_mean` or `output_stddev` have incorrect length.\n \"\"\"\n super(VRGripperRegressionModel, self).__init__(**kwargs)\n self._use_gripper_input = use_gripper_input\n self._normalize_outputs = normalize_outputs\n self._output_mean = None\n self._output_stddev = None\n self._outer_loss_multiplier = outer_loss_multiplier\n self._num_mixture_components = num_mixture_components\n self._output_mixture_sample = output_mixture_sample\n self._condition_mixture_stddev = condition_mixture_stddev\n self._episode_length = episode_length\n if output_mean and output_stddev:\n if not len(output_mean) == len(output_stddev) == self.action_size:\n raise ValueError(\n 'Output mean and stddev have lengths {:d} and {:d}.'.format(\n len(output_mean), len(output_stddev)))\n self._output_mean = np.array([output_mean])\n self._output_stddev = np.array([output_stddev])\n\n @property\n def default_preprocessor_cls(self):\n return DefaultVRGripperPreprocessor\n\n def get_feature_specification(self, mode):\n del mode\n image_spec = TensorSpec(\n shape=(100, 100, 3),\n dtype=tf.float32,\n name='image0',\n data_format='jpeg')\n gripper_pose_spec = TensorSpec(\n shape=(14,), dtype=tf.float32, name='world_pose_gripper')\n tspec = tensorspec_utils.TensorSpecStruct(\n image=image_spec, gripper_pose=gripper_pose_spec)\n return tensorspec_utils.copy_tensorspec(\n tspec, batch_size=self._episode_length)\n\n def get_label_specification(self, mode):\n del mode\n action_spec = TensorSpec(\n shape=(self._action_size,), dtype=tf.float32, name='action_world')\n tspec = tensorspec_utils.TensorSpecStruct(action=action_spec)\n return tensorspec_utils.copy_tensorspec(\n tspec, batch_size=self._episode_length)\n\n @property\n def action_size(self):\n return self._action_size\n\n def _single_batch_a_func(self,\n features,\n scope,\n mode,\n context_fn=None,\n reuse=tf.AUTO_REUSE):\n \"\"\"A state -> action regression function that expects a single batch dim.\"\"\"\n gripper_pose = features.gripper_pose if self._use_gripper_input else None\n with tf.variable_scope(scope, reuse=reuse, use_resource=True):\n with tf.variable_scope('state_features', reuse=reuse, use_resource=True):\n feature_points, end_points = vision_layers.BuildImagesToFeaturesModel(\n features.image,\n is_training=(mode == TRAIN),\n normalizer_fn=contrib_layers.layer_norm)\n\n if context_fn:\n feature_points = context_fn(feature_points)\n\n fc_input = tf.concat([feature_points, gripper_pose], -1)\n outputs = {}\n if self._num_mixture_components > 1:\n dist_params = mdn.predict_mdn_params(\n fc_input,\n self._num_mixture_components,\n self._action_size,\n condition_sigmas=self._condition_mixture_stddev)\n gm = mdn.get_mixture_distribution(\n dist_params, self._num_mixture_components, self._action_size,\n self._output_mean if self._normalize_outputs else None)\n if self._output_mixture_sample:\n # Output a mixture sample as action.\n action = gm.sample()\n else:\n action = mdn.gaussian_mixture_approximate_mode(gm)\n outputs['dist_params'] = dist_params\n else:\n action, _ = vision_layers.BuildImageFeaturesToPoseModel(\n fc_input, num_outputs=self._action_size)\n action = self._output_mean + self._output_stddev * action\n outputs.update({\n 'inference_output': action,\n 'image': features.image,\n 'feature_points': feature_points,\n 'softmax': end_points['softmax']\n })\n return outputs\n\n def a_func(self,\n features,\n scope,\n mode,\n context_fn=None,\n reuse=tf.AUTO_REUSE,\n config=None,\n params=None):\n \"\"\"A (state) regression function.\n\n This function can return a stochastic or a deterministic tensor.\n\n Args:\n features: This is the first item returned from the input_fn and parsed by\n tensorspec_utils.validate_and_pack. A spec_structure which fulfills the\n requirements of the self.get_feature_spefication.\n scope: String specifying variable scope.\n mode: (ModeKeys) Specifies if this is training, evaluation or prediction.\n context_fn: Optional python function that takes in features and returns\n new features of same shape. For merging information like in RL^2.\n reuse: Whether or not to reuse variables under variable scope 'scope'.\n config: Optional configuration object. Will receive what is passed to\n Estimator in config parameter, or the default config. Allows updating\n things in your model_fn based on configuration such as num_ps_replicas,\n or model_dir.\n params: An optional dict of hyper parameters that will be passed into\n input_fn and model_fn. Keys are names of parameters, values are basic\n python types. There are reserved keys for TPUEstimator, including\n 'batch_size'.\n\n Returns:\n outputs: A {key: Tensor} mapping. The key 'action' is required.\n \"\"\"\n del config, params\n return meta_tfdata.multi_batch_apply(self._single_batch_a_func, 2, features,\n scope, mode, context_fn, reuse)\n\n def loss_fn(self, labels, inference_outputs, mode, params=None):\n \"\"\"This implements outer loss and configurable inner losses.\"\"\"\n if params and params.get('is_outer_loss', False):\n pass\n if self._num_mixture_components > 1:\n gm = mdn.get_mixture_distribution(\n inference_outputs['dist_params'], self._num_mixture_components,\n self._action_size,\n self._output_mean if self._normalize_outputs else None)\n return -tf.reduce_mean(gm.log_prob(labels.action))\n else:\n return self._outer_loss_multiplier * tf.losses.mean_squared_error(\n labels=labels.action,\n predictions=inference_outputs['inference_output'])\n\n\[email protected]\nclass VRGripperDomainAdaptiveModel(VRGripperRegressionModel):\n \"\"\"Base model which uses a learned loss to do domain adaptive imitation.\n\n The model conditions on video only (no actions or gripper pose).\n \"\"\"\n\n def __init__(self,\n predict_con_gripper_pose = False,\n learned_loss_conv1d_layers = (10, 10,\n 6),\n **kwargs):\n \"\"\"Initialize the model.\n\n Args:\n predict_con_gripper_pose: If True, predict the condition gripper pose\n input from the image features. Otherwise, set to zeros.\n learned_loss_conv1d_layers: A tuple describing the conv1d layers of the\n learned loss. If None, the learned loss won't use conv1d layers.\n **kwargs: Passed to parent.\n \"\"\"\n super(VRGripperDomainAdaptiveModel, self).__init__(**kwargs)\n self._predict_con_gripper_pose = predict_con_gripper_pose\n self._learned_loss_conv1d_layers = learned_loss_conv1d_layers\n\n def _predict_gripper_pose(self, feature_points):\n \"\"\"Predict the condition gripper pose from feature points.\"\"\"\n out = feature_points\n out = tf.layers.dense(out, 40, activation=tf.nn.relu, use_bias=False)\n out = contrib_layers.layer_norm(out)\n out = tf.layers.dense(out, 14, activation=None)\n return out\n\n def single_batch_a_func(\n self, features, scope,\n mode,\n context_fn, reuse,\n config,\n params):\n \"\"\"Single step action predictor when there is a single batch dim.\"\"\"\n del config\n with tf.variable_scope(scope, reuse=reuse, use_resource=True):\n with tf.variable_scope('state_features', reuse=reuse, use_resource=True):\n feature_points, end_points = vision_layers.BuildImagesToFeaturesModel(\n features.image,\n is_training=(mode == TRAIN),\n normalizer_fn=contrib_layers.layer_norm)\n\n if context_fn:\n feature_points = context_fn(feature_points)\n\n if params and params.get('is_inner_loop', False):\n if self._predict_con_gripper_pose:\n gripper_pose = self._predict_gripper_pose(feature_points)\n else:\n gripper_pose = tf.zeros_like(features.gripper_pose)\n else:\n gripper_pose = features.gripper_pose\n\n action, _ = vision_layers.BuildImageFeaturesToPoseModel(\n feature_points, aux_input=gripper_pose, num_outputs=self._action_size)\n action = self._output_mean + self._output_stddev * action\n return {\n 'inference_output': action,\n 'image': features.image,\n 'feature_points': feature_points,\n 'softmax': end_points['softmax'],\n }\n\n def a_func(self,\n features,\n scope,\n mode,\n context_fn = None,\n reuse=tf.AUTO_REUSE,\n config = None,\n params = None\n ):\n \"\"\"Single step action predictor. See parent class.\"\"\"\n return meta_tfdata.multi_batch_apply(self.single_batch_a_func, 2, features,\n scope, mode, context_fn, reuse, config,\n params)\n\n def model_train_fn(self,\n features,\n labels,\n inference_outputs,\n mode,\n config = None,\n params = None\n ):\n \"\"\"Output learned loss if inner loop, or behavior clone if outer loop.\"\"\"\n if params and params.get('is_outer_loss', False):\n # Outer loss case: use standard RegressionModel loss.\n return self.loss_fn(labels, inference_outputs, mode, params)\n # Inner loss case: compute learned loss function.\n with tf.variable_scope(\n 'learned_loss', reuse=tf.AUTO_REUSE, use_resource=True):\n predicted_action, _ = meta_tfdata.multi_batch_apply(\n vision_layers.BuildImageFeaturesToPoseModel,\n 2,\n inference_outputs['feature_points'],\n num_outputs=self._action_size)\n if self._learned_loss_conv1d_layers is None:\n return tf.losses.mean_squared_error(predicted_action,\n inference_outputs['action'])\n ll_input = tf.concat([\n predicted_action, inference_outputs['feature_points'],\n inference_outputs['inference_output']\n ], -1)\n net = ll_input\n for num_filters in self._learned_loss_conv1d_layers[:-1]:\n net = tf.layers.conv1d(\n net, num_filters, 10, activation=tf.nn.relu, use_bias=False)\n net = contrib_layers.layer_norm(net)\n net = tf.layers.conv1d(net, self._learned_loss_conv1d_layers[-1],\n 1) # 1x1 convolution.\n return tf.reduce_mean(tf.reduce_sum(tf.square(net), axis=(1, 2)))\n" ]
[ [ "numpy.maximum", "numpy.allclose", "tensorflow.compat.v1.train.list_variables", "tensorflow.compat.v1.test.main", "tensorflow.compat.v1.estimator.Estimator", "numpy.testing.assert_almost_equal", "tensorflow.compat.v1.train.Example", "tensorflow.compat.v1.io.gfile.glob", "tensorflow.compat.v1.estimator.RunConfig", "tensorflow.contrib.predictor.from_saved_model", "tensorflow.compat.v1.train.latest_checkpoint" ], [ "tensorflow.compat.v1.square", "tensorflow.compat.v1.reverse", "tensorflow.compat.v1.concat", "tensorflow.compat.v1.layers.conv1d", "tensorflow.contrib.layers.layer_norm", "tensorflow.compat.v1.image.convert_image_dtype", "tensorflow.compat.v1.zeros_like", "numpy.array", "tensorflow.compat.v1.variable_scope", "tensorflow.compat.v1.layers.dense", "tensorflow.compat.v1.losses.mean_squared_error" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
diceroll/metric_learning
[ "272c7ba13208e14b91d294456d1f7fe762fe80d5" ]
[ "train_cifar.py" ]
[ "import argparse\nimport multiprocessing\nimport random\nimport shutil\nfrom datetime import datetime\nfrom functools import partial\nfrom pathlib import Path\n\nimport chainer\nimport chainer.functions as F\nimport chainer.links as L\nimport cupy\nimport numpy as np\nfrom chainer import iterators, optimizers, serializers\nfrom chainer.datasets import TransformDataset, get_cifar10\nfrom chainer.training import StandardUpdater, Trainer, extensions\n\nimport augmentation\nfrom metric_learning import MetricLearnClassifier\nfrom modified_evaluator import ModifiedEvaluator\nfrom modified_updater import ModifiedUpdater\nfrom resnet import ResNet50\n\n\ndef apply_augmentation(inputs, mean, std, angle=(-5, 5), scale=(1, 1.2),\n crop_size=None, train=True):\n img, label = inputs\n img = img.copy()\n img = img.transpose(1, 2, 0)\n\n if train:\n img, _ = augmentation.gamma_correction(img)\n\n img -= mean[None, None, :]\n img /= std[None, None, :]\n\n if train:\n img, _ = augmentation.random_rotate(img, angle=angle)\n if np.random.rand() < 0.5:\n img, _ = augmentation.mirror(img)\n if np.random.rand() < 0.5:\n img, _ = augmentation.flip(img)\n img, _ = augmentation.random_resize(img, scale=scale)\n if crop_size is not None:\n rnd1 = np.random.randint(img.shape[0] - crop_size)\n rnd2 = np.random.randint(img.shape[1] - crop_size)\n img = img[rnd1:rnd1 + crop_size, rnd2:rnd2 + crop_size, :]\n\n img = img.transpose(2, 0, 1)\n\n return img, label\n\n\ndef main():\n parser = argparse.ArgumentParser(description='training mnist')\n parser.add_argument('--gpu', '-g', default=-1, type=int,\n help='GPU ID (negative value indicates CPU)')\n parser.add_argument('--epoch', '-e', type=int, default=100,\n help='Number of sweeps over the dataset to train')\n parser.add_argument('--batchsize', '-b', type=int, default=8,\n help='Number of images in each mini-batch')\n parser.add_argument('--seed', '-s', type=int, default=0,\n help='Random seed')\n parser.add_argument('--report_trigger', '-rt', type=str, default='1e',\n help='Interval for reporting(Ex.100i, default:1e)')\n parser.add_argument('--save_trigger', '-st', type=str, default='1e',\n help='Interval for saving the model(Ex.100i, default:1e)')\n parser.add_argument('--load_model', '-lm', type=str, default=None,\n help='Path of the model object to load')\n parser.add_argument('--load_optimizer', '-lo', type=str, default=None,\n help='Path of the optimizer object to load')\n args = parser.parse_args()\n\n start_time = datetime.now()\n save_dir = Path('output/{}'.format(start_time.strftime('%Y%m%d_%H%M')))\n\n random.seed(args.seed)\n np.random.seed(args.seed)\n cupy.random.seed(args.seed)\n\n model = MetricLearnClassifier(ResNet50(), 512, 10,\n method='arcface', final_margin=0.5,\n final_scale=64, target_epoch=100)\n\n if args.load_model is not None:\n serializers.load_npz(args.load_model, model)\n\n if args.gpu >= 0:\n chainer.cuda.get_device_from_id(args.gpu).use()\n model.to_gpu()\n\n optimizer = optimizers.Adam(alpha=1e-3, weight_decay_rate=5e-4, amsgrad=True)\n optimizer.setup(model)\n optimizer.add_hook(chainer.optimizer.WeightDecay(5e-4))\n if args.load_optimizer is not None:\n serializers.load_npz(args.load_optimizer, optimizer)\n\n train_data, valid_data = get_cifar10(scale=255.)\n mean = np.mean([x for x, _ in train_data], axis=(0, 2, 3))\n std = np.std([x for x, _ in train_data], axis=(0, 2, 3))\n\n train_transform = partial(apply_augmentation, mean=mean, std=std, crop_size=28, train=True)\n valid_transform = partial(apply_augmentation, mean=mean, std=std, crop_size=28, train=True)\n\n train_data = TransformDataset(train_data, train_transform)\n valid_data = TransformDataset(valid_data, valid_transform)\n\n train_iter = iterators.SerialIterator(train_data, args.batchsize)\n valid_iter = iterators.SerialIterator(valid_data, args.batchsize, repeat=False, shuffle=False)\n\n updater = ModifiedUpdater(train_iter, optimizer, device=args.gpu)\n trainer = Trainer(updater, (args.epoch, 'epoch'), out=save_dir)\n\n report_trigger = (int(args.report_trigger[:-1]), 'iteration' if args.report_trigger[-1] == 'i' else 'epoch')\n trainer.extend(extensions.LogReport(trigger=report_trigger))\n trainer.extend(ModifiedEvaluator(valid_iter, model, device=args.gpu), name='val', trigger=report_trigger)\n trainer.extend(extensions.PrintReport(['epoch', 'iteration', 'main/loss', 'main/accuracy', 'val/main/loss',\n 'val/main/accuracy', 'elapsed_time']), trigger=report_trigger)\n trainer.extend(extensions.PlotReport(['main/loss', 'val/main/loss'], x_key=report_trigger[1],\n marker='.', file_name='loss.png', trigger=report_trigger))\n trainer.extend(extensions.PlotReport(['main/accuracy', 'val/main/accuracy'], x_key=report_trigger[1],\n marker='.', file_name='accuracy.png', trigger=report_trigger))\n\n save_trigger = (int(args.save_trigger[:-1]), 'iteration' if args.save_trigger[-1] == 'i' else 'epoch')\n trainer.extend(extensions.snapshot_object(model, filename='model_{0}-{{.updater.{0}}}.npz'\n .format(save_trigger[1])), trigger=save_trigger)\n trainer.extend(extensions.snapshot_object(optimizer, filename='optimizer_{0}-{{.updater.{0}}}.npz'\n .format(save_trigger[1])), trigger=save_trigger)\n trainer.extend(extensions.ProgressBar())\n trainer.extend(extensions.ExponentialShift('lr', 0.5), trigger=(30, 'epoch'))\n\n if save_dir.exists():\n shutil.rmtree(save_dir)\n save_dir.mkdir()\n (save_dir / 'training_details').mkdir()\n\n # Write parameters text\n with open(save_dir / 'training_details/train_params.txt', 'w') as f:\n f.write('model: {}\\n'.format(model.predictor.__class__.__name__))\n f.write('n_epoch: {}\\n'.format(args.epoch))\n f.write('batch_size: {}\\n'.format(args.batchsize))\n f.write('n_data_train: {}\\n'.format(len(train_data)))\n f.write('n_data_val: {}\\n'.format(len(valid_data)))\n f.write('seed: {}\\n'.format(args.seed))\n\n trainer.run()\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.random.seed", "numpy.std", "numpy.mean", "numpy.random.rand", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
thanhkaist/garage
[ "1d840df357282a675b8fce839bb0e5f72a8abba9", "1d840df357282a675b8fce839bb0e5f72a8abba9", "1d840df357282a675b8fce839bb0e5f72a8abba9", "1d840df357282a675b8fce839bb0e5f72a8abba9", "1d840df357282a675b8fce839bb0e5f72a8abba9", "1d840df357282a675b8fce839bb0e5f72a8abba9" ]
[ "tests/garage/tf/models/test_gru.py", "src/garage/tf/_functions.py", "tests/garage/tf/q_functions/test_continuous_mlp_q_function.py", "src/garage/tf/misc/tensor_utils.py", "tests/garage/tf/models/test_categorical_cnn_model.py", "tests/garage/tf/models/test_cnn.py" ]
[ "import numpy as np\nimport pytest\nimport tensorflow as tf\n\nfrom garage.tf.models.gru import gru\nfrom tests.fixtures import TfGraphTestCase\nfrom tests.helpers import recurrent_step_gru\n\n\nclass TestGRU(TfGraphTestCase):\n\n def setup_method(self):\n super().setup_method()\n self.batch_size = 2\n self.hidden_dim = 2\n\n self.step_hidden_var = tf.compat.v1.placeholder(\n shape=(self.batch_size, self.hidden_dim),\n name='initial_hidden',\n dtype=tf.float32)\n\n self.gru_cell = tf.keras.layers.GRUCell(\n units=self.hidden_dim,\n activation=tf.nn.tanh,\n kernel_initializer=tf.constant_initializer(1),\n recurrent_activation=tf.nn.sigmoid,\n recurrent_initializer=tf.constant_initializer(1),\n name='lstm_layer')\n\n # yapf: disable\n @pytest.mark.parametrize('time_step, input_dim, output_dim, '\n 'hidden_init', [\n (1, 1, 1, 0), # noqa: E122\n (1, 1, 3, 0),\n (1, 3, 1, 0),\n (3, 1, 1, 0),\n (3, 3, 1, 0),\n (3, 3, 3, 0),\n (1, 1, 1, 0.5),\n (1, 1, 3, 0.5),\n (1, 3, 1, 0.5),\n (3, 1, 1, 0.5),\n (3, 3, 1, 0.5),\n (3, 3, 3, 0.5),\n ])\n # yapf: enable\n def test_output_shapes(self, time_step, input_dim, output_dim,\n hidden_init):\n obs_inputs = np.full((self.batch_size, time_step, input_dim), 1.)\n obs_input = np.full((self.batch_size, input_dim), 1.)\n\n input_var = tf.compat.v1.placeholder(tf.float32,\n shape=(None, None, input_dim),\n name='input')\n step_input_var = tf.compat.v1.placeholder(tf.float32,\n shape=(None, input_dim),\n name='step_input')\n output_nonlinearity = tf.keras.layers.Dense(\n units=output_dim,\n activation=None,\n kernel_initializer=tf.constant_initializer(1))\n with tf.compat.v1.variable_scope('GRU'):\n self.gru = gru(\n all_input_var=input_var,\n name='gru',\n gru_cell=self.gru_cell,\n step_input_var=step_input_var,\n step_hidden_var=self.step_hidden_var,\n hidden_state_init=tf.constant_initializer(hidden_init),\n output_nonlinearity_layer=output_nonlinearity)\n\n self.sess.run(tf.compat.v1.global_variables_initializer())\n\n # Compute output by doing t step() on the gru cell\n outputs_t, output_t, h_t, hidden_init = self.gru\n hidden = np.full((self.batch_size, self.hidden_dim),\n hidden_init.eval())\n\n for _ in range(time_step):\n output, hidden = self.sess.run([output_t, h_t],\n feed_dict={\n step_input_var: obs_input,\n self.step_hidden_var: hidden,\n }) # noqa: E126\n assert output.shape == (self.batch_size, output_dim)\n assert hidden.shape == (self.batch_size, self.hidden_dim)\n\n full_output = self.sess.run(outputs_t,\n feed_dict={input_var: obs_inputs})\n\n assert full_output.shape == (self.batch_size, time_step, output_dim)\n\n # yapf: disable\n @pytest.mark.parametrize('time_step, input_dim, output_dim, '\n 'hidden_init', [\n (1, 1, 1, 0), # noqa: E122\n (1, 1, 3, 0),\n (1, 3, 1, 0),\n (3, 1, 1, 0),\n (3, 3, 1, 0),\n (3, 3, 3, 0),\n (1, 1, 1, 0.5),\n (1, 1, 3, 0.5),\n (1, 3, 1, 0.5),\n (3, 1, 1, 0.5),\n (3, 3, 1, 0.5),\n (3, 3, 3, 0.5),\n ])\n # yapf: enable\n def test_output_value(self, time_step, input_dim, output_dim, hidden_init):\n obs_inputs = np.full((self.batch_size, time_step, input_dim), 1.)\n obs_input = np.full((self.batch_size, input_dim), 1.)\n\n input_var = tf.compat.v1.placeholder(tf.float32,\n shape=(None, None, input_dim),\n name='input')\n step_input_var = tf.compat.v1.placeholder(tf.float32,\n shape=(None, input_dim),\n name='step_input')\n output_nonlinearity = tf.keras.layers.Dense(\n units=output_dim,\n activation=None,\n kernel_initializer=tf.constant_initializer(1))\n with tf.compat.v1.variable_scope('GRU'):\n self.gru = gru(\n all_input_var=input_var,\n name='gru',\n gru_cell=self.gru_cell,\n step_input_var=step_input_var,\n step_hidden_var=self.step_hidden_var,\n hidden_state_init=tf.constant_initializer(hidden_init),\n output_nonlinearity_layer=output_nonlinearity)\n\n self.sess.run(tf.compat.v1.global_variables_initializer())\n\n # Compute output by doing t step() on the gru cell\n outputs_t, output_t, h_t, hidden_init = self.gru\n hidden1 = hidden2 = np.full((self.batch_size, self.hidden_dim),\n hidden_init.eval())\n\n for i in range(time_step):\n output1, hidden1 = self.sess.run([output_t, h_t],\n feed_dict={\n step_input_var: obs_input,\n self.step_hidden_var: hidden1\n }) # noqa: E126\n\n hidden2 = recurrent_step_gru(input_val=obs_input,\n num_units=self.hidden_dim,\n step_hidden=hidden2,\n w_x_init=1.,\n w_h_init=1.,\n b_init=0.,\n nonlinearity=np.tanh,\n gate_nonlinearity=lambda x: 1. /\n (1. + np.exp(-x)))\n\n output_nonlinearity = np.full(\n (np.prod(hidden2.shape[1:]), output_dim), 1.)\n output2 = np.matmul(hidden2, output_nonlinearity)\n\n assert np.allclose(output1, output2)\n assert np.allclose(hidden1, hidden2)\n\n full_output1 = self.sess.run(outputs_t,\n feed_dict={input_var: obs_inputs})\n\n hidden2 = np.full((self.batch_size, self.hidden_dim),\n hidden_init.eval())\n stack_hidden = None\n for i in range(time_step):\n hidden2 = recurrent_step_gru(input_val=obs_inputs[:, i, :],\n num_units=self.hidden_dim,\n step_hidden=hidden2,\n w_x_init=1.,\n w_h_init=1.,\n b_init=0.,\n nonlinearity=np.tanh,\n gate_nonlinearity=lambda x: 1. /\n (1. + np.exp(-x)))\n if stack_hidden is None:\n stack_hidden = hidden2[:, np.newaxis, :]\n else:\n stack_hidden = np.concatenate(\n (stack_hidden, hidden2[:, np.newaxis, :]), axis=1)\n output_nonlinearity = np.full((np.prod(hidden2.shape[1:]), output_dim),\n 1.)\n full_output2 = np.matmul(stack_hidden, output_nonlinearity)\n assert np.allclose(full_output1, full_output2)\n\n # yapf: disable\n @pytest.mark.parametrize('time_step, input_dim, output_dim', [\n (1, 1, 1),\n (1, 1, 3),\n (1, 3, 1),\n (3, 1, 1),\n (3, 3, 1),\n (3, 3, 3),\n ])\n # yapf: enable\n def test_output_value_trainable_hidden_and_cell(self, time_step, input_dim,\n output_dim):\n obs_inputs = np.full((self.batch_size, time_step, input_dim), 1.)\n obs_input = np.full((self.batch_size, input_dim), 1.)\n\n input_var = tf.compat.v1.placeholder(tf.float32,\n shape=(None, None, input_dim),\n name='input')\n step_input_var = tf.compat.v1.placeholder(tf.float32,\n shape=(None, input_dim),\n name='step_input')\n output_nonlinearity = tf.keras.layers.Dense(\n units=output_dim,\n activation=None,\n kernel_initializer=tf.constant_initializer(1))\n with tf.compat.v1.variable_scope('GRU'):\n self.gru = gru(all_input_var=input_var,\n name='gru',\n gru_cell=self.gru_cell,\n step_input_var=step_input_var,\n step_hidden_var=self.step_hidden_var,\n hidden_state_init_trainable=True,\n output_nonlinearity_layer=output_nonlinearity)\n\n self.sess.run(tf.compat.v1.global_variables_initializer())\n\n # Compute output by doing t step() on the gru cell\n outputs_t, output_t, h_t, hidden_init = self.gru\n hidden = np.full((self.batch_size, self.hidden_dim),\n hidden_init.eval())\n\n _, hidden = self.sess.run([output_t, h_t],\n feed_dict={\n step_input_var: obs_input,\n self.step_hidden_var: hidden,\n }) # noqa: E126\n with tf.compat.v1.variable_scope('GRU/gru', reuse=True):\n hidden_init_var = tf.compat.v1.get_variable(name='initial_hidden')\n assert hidden_init_var in tf.compat.v1.trainable_variables()\n\n full_output1 = self.sess.run(outputs_t,\n feed_dict={input_var: obs_inputs})\n\n hidden2 = np.full((self.batch_size, self.hidden_dim),\n hidden_init.eval())\n stack_hidden = None\n for i in range(time_step):\n hidden2 = recurrent_step_gru(input_val=obs_inputs[:, i, :],\n num_units=self.hidden_dim,\n step_hidden=hidden2,\n w_x_init=1.,\n w_h_init=1.,\n b_init=0.,\n nonlinearity=np.tanh,\n gate_nonlinearity=lambda x: 1. /\n (1. + np.exp(-x)))\n if stack_hidden is None:\n stack_hidden = hidden2[:, np.newaxis, :]\n else:\n stack_hidden = np.concatenate(\n (stack_hidden, hidden2[:, np.newaxis, :]), axis=1)\n output_nonlinearity = np.full((np.prod(hidden2.shape[1:]), output_dim),\n 1.)\n full_output2 = np.matmul(stack_hidden, output_nonlinearity)\n assert np.allclose(full_output1, full_output2)\n\n def test_gradient_paths(self):\n time_step = 3\n input_dim = 2\n output_dim = 4\n obs_inputs = np.full((self.batch_size, time_step, input_dim), 1.)\n obs_input = np.full((self.batch_size, input_dim), 1.)\n\n input_var = tf.compat.v1.placeholder(tf.float32,\n shape=(None, None, input_dim),\n name='input')\n step_input_var = tf.compat.v1.placeholder(tf.float32,\n shape=(None, input_dim),\n name='step_input')\n output_nonlinearity = tf.keras.layers.Dense(\n units=output_dim,\n activation=None,\n kernel_initializer=tf.constant_initializer(1))\n with tf.compat.v1.variable_scope('GRU'):\n self.gru = gru(all_input_var=input_var,\n name='gru',\n gru_cell=self.gru_cell,\n step_input_var=step_input_var,\n step_hidden_var=self.step_hidden_var,\n output_nonlinearity_layer=output_nonlinearity)\n\n self.sess.run(tf.compat.v1.global_variables_initializer())\n\n # Compute output by doing t step() on the gru cell\n outputs_t, output_t, h_t, hidden_init = self.gru\n hidden = np.full((self.batch_size, self.hidden_dim),\n hidden_init.eval())\n\n grads_step_o_i = tf.gradients(output_t, step_input_var)\n grads_step_o_h = tf.gradients(output_t, self.step_hidden_var)\n grads_step_h = tf.gradients(h_t, step_input_var)\n\n self.sess.run([grads_step_o_i, grads_step_o_h, grads_step_h],\n feed_dict={\n step_input_var: obs_input,\n self.step_hidden_var: hidden,\n }) # noqa: E126\n\n grads_step_o_i = tf.gradients(outputs_t, step_input_var)\n grads_step_o_h = tf.gradients(outputs_t, self.step_hidden_var)\n grads_step_h = tf.gradients(h_t, input_var)\n\n # No gradient flow\n with pytest.raises(TypeError):\n self.sess.run(grads_step_o_i,\n feed_dict={\n step_input_var: obs_input,\n self.step_hidden_var: hidden,\n })\n with pytest.raises(TypeError):\n self.sess.run(grads_step_o_h,\n feed_dict={\n step_input_var: obs_input,\n self.step_hidden_var: hidden,\n })\n with pytest.raises(TypeError):\n self.sess.run(grads_step_h, feed_dict={input_var: obs_inputs})\n\n # yapf: disable\n @pytest.mark.parametrize('time_step, input_dim, output_dim, '\n 'hidden_init', [\n (1, 1, 1, 0), # noqa: E122\n (1, 1, 3, 0),\n (1, 3, 1, 0),\n (3, 1, 1, 0),\n (3, 3, 1, 0),\n (3, 3, 3, 0),\n (1, 1, 1, 0.5),\n (1, 1, 3, 0.5),\n (1, 3, 1, 0.5),\n (3, 1, 1, 0.5),\n (3, 3, 1, 0.5),\n (3, 3, 3, 0.5),\n ])\n # yapf: enable\n def test_output_same_as_rnn(self, time_step, input_dim, output_dim,\n hidden_init):\n obs_inputs = np.full((self.batch_size, time_step, input_dim), 1.)\n obs_input = np.full((self.batch_size, input_dim), 1.)\n\n input_var = tf.compat.v1.placeholder(tf.float32,\n shape=(None, None, input_dim),\n name='input')\n step_input_var = tf.compat.v1.placeholder(tf.float32,\n shape=(None, input_dim),\n name='step_input')\n output_nonlinearity = tf.keras.layers.Dense(\n units=output_dim,\n activation=None,\n kernel_initializer=tf.constant_initializer(1))\n with tf.compat.v1.variable_scope('GRU'):\n self.gru = gru(\n all_input_var=input_var,\n name='gru',\n gru_cell=self.gru_cell,\n step_input_var=step_input_var,\n step_hidden_var=self.step_hidden_var,\n hidden_state_init=tf.constant_initializer(hidden_init),\n output_nonlinearity_layer=output_nonlinearity)\n\n self.sess.run(tf.compat.v1.global_variables_initializer())\n\n # Create a RNN and compute the entire outputs\n rnn_layer = tf.keras.layers.RNN(cell=self.gru_cell,\n return_sequences=True,\n return_state=True)\n\n # Set initial state to all 0s\n hidden_var = tf.compat.v1.get_variable(\n name='initial_hidden',\n shape=(self.batch_size, self.hidden_dim),\n initializer=tf.constant_initializer(hidden_init),\n trainable=False,\n dtype=tf.float32)\n outputs, hiddens = rnn_layer(input_var, initial_state=[hidden_var])\n outputs = output_nonlinearity(outputs)\n\n self.sess.run(tf.compat.v1.global_variables_initializer())\n\n outputs, hiddens = self.sess.run([outputs, hiddens],\n feed_dict={input_var: obs_inputs})\n\n # Compute output by doing t step() on the gru cell\n hidden = np.full((self.batch_size, self.hidden_dim), hidden_init)\n _, output_t, hidden_t, _ = self.gru\n for i in range(time_step):\n output, hidden = self.sess.run([output_t, hidden_t],\n feed_dict={\n step_input_var: obs_input,\n self.step_hidden_var: hidden,\n }) # noqa: E126\n # The output from i-th timestep\n assert np.array_equal(output, outputs[:, i, :])\n assert np.array_equal(hidden, hiddens)\n\n # Also the full output from lstm\n full_outputs = self.sess.run(self.gru[0],\n feed_dict={input_var: obs_inputs})\n assert np.array_equal(outputs, full_outputs)\n", "\"\"\"Utility functions for tf-based Reinforcement learning algorithms.\"\"\"\nimport numpy as np\n\nfrom garage.misc import tensor_utils as np_tensor_utils\nfrom garage.tf.misc import tensor_utils\n\n\ndef paths_to_tensors(paths, max_path_length, baseline_predictions, discount,\n gae_lambda):\n \"\"\"Return processed sample data based on the collected paths.\n\n Args:\n paths (list[dict]): A list of collected paths.\n max_path_length (int): Maximum length of a single rollout.\n baseline_predictions(numpy.ndarray): : Predicted value of GAE\n (Generalized Advantage Estimation) Baseline.\n discount (float): Environment reward discount.\n gae_lambda (float): Lambda used for generalized advantage\n estimation.\n\n Returns:\n dict: Processed sample data, with key\n * observations: (numpy.ndarray)\n * actions: (numpy.ndarray)\n * rewards: (numpy.ndarray)\n * baselines: (numpy.ndarray)\n * returns: (numpy.ndarray)\n * valids: (numpy.ndarray)\n * agent_infos: (dict)\n * env_infos: (dict)\n * paths: (list[dict])\n\n \"\"\"\n baselines = []\n returns = []\n total_steps = 0\n\n for idx, path in enumerate(paths):\n total_steps += len(path['rewards'])\n path_baselines = np.append(baseline_predictions[idx], 0)\n deltas = (path['rewards'] + discount * path_baselines[1:] -\n path_baselines[:-1])\n path['advantages'] = np_tensor_utils.discount_cumsum(\n deltas, discount * gae_lambda)\n path['deltas'] = deltas\n\n for idx, path in enumerate(paths):\n # baselines\n path['baselines'] = baseline_predictions[idx]\n baselines.append(path['baselines'])\n\n # returns\n path['returns'] = np_tensor_utils.discount_cumsum(\n path['rewards'], discount)\n returns.append(path['returns'])\n\n # make all paths the same length\n obs = [path['observations'] for path in paths]\n obs = tensor_utils.pad_tensor_n(obs, max_path_length)\n\n actions = [path['actions'] for path in paths]\n actions = tensor_utils.pad_tensor_n(actions, max_path_length)\n\n rewards = [path['rewards'] for path in paths]\n rewards = tensor_utils.pad_tensor_n(rewards, max_path_length)\n\n returns = [path['returns'] for path in paths]\n returns = tensor_utils.pad_tensor_n(returns, max_path_length)\n\n baselines = tensor_utils.pad_tensor_n(baselines, max_path_length)\n\n agent_infos = [path['agent_infos'] for path in paths]\n agent_infos = tensor_utils.stack_tensor_dict_list([\n tensor_utils.pad_tensor_dict(p, max_path_length) for p in agent_infos\n ])\n\n env_infos = [path['env_infos'] for path in paths]\n env_infos = tensor_utils.stack_tensor_dict_list(\n [tensor_utils.pad_tensor_dict(p, max_path_length) for p in env_infos])\n\n valids = [np.ones_like(path['returns']) for path in paths]\n valids = tensor_utils.pad_tensor_n(valids, max_path_length)\n\n lengths = np.asarray([v.sum() for v in valids])\n\n samples_data = dict(\n observations=obs,\n actions=actions,\n rewards=rewards,\n baselines=baselines,\n returns=returns,\n valids=valids,\n lengths=lengths,\n agent_infos=agent_infos,\n env_infos=env_infos,\n paths=paths,\n )\n\n return samples_data\n", "import pickle\nfrom unittest import mock\n\nimport numpy as np\nimport pytest\nimport tensorflow as tf\n\nfrom garage.envs import GarageEnv\nfrom garage.tf.q_functions import ContinuousMLPQFunction\nfrom tests.fixtures import TfGraphTestCase\nfrom tests.fixtures.envs.dummy import DummyBoxEnv, DummyDictEnv\nfrom tests.fixtures.models import SimpleMLPMergeModel\n\n\nclass TestContinuousMLPQFunction(TfGraphTestCase):\n\n @pytest.mark.parametrize('obs_dim, action_dim', [\n ((1, ), (1, )),\n ((2, ), (2, )),\n ((1, 1), (1, )),\n ((2, 2), (2, )),\n ])\n def test_q_vals(self, obs_dim, action_dim):\n env = GarageEnv(DummyBoxEnv(obs_dim=obs_dim, action_dim=action_dim))\n with mock.patch(('garage.tf.q_functions.'\n 'continuous_mlp_q_function.MLPMergeModel'),\n new=SimpleMLPMergeModel):\n qf = ContinuousMLPQFunction(env_spec=env.spec)\n env.reset()\n obs, _, _, _ = env.step(1)\n obs = obs.flatten()\n act = np.full(action_dim, 0.5).flatten()\n\n expected_output = np.full((1, ), 0.5)\n\n outputs = qf.get_qval([obs], [act])\n assert np.array_equal(outputs[0], expected_output)\n\n outputs = qf.get_qval([obs, obs, obs], [act, act, act])\n\n for output in outputs:\n assert np.array_equal(output, expected_output)\n\n def test_q_vals_goal_conditioned(self):\n env = GarageEnv(DummyDictEnv())\n with mock.patch(('garage.tf.q_functions.'\n 'continuous_mlp_q_function.MLPMergeModel'),\n new=SimpleMLPMergeModel):\n qf = ContinuousMLPQFunction(env_spec=env.spec)\n env.reset()\n obs, _, _, _ = env.step(1)\n obs = np.concatenate(\n (obs['observation'], obs['desired_goal'], obs['achieved_goal']),\n axis=-1)\n act = np.full((1, ), 0.5).flatten()\n\n expected_output = np.full((1, ), 0.5)\n\n outputs = qf.get_qval([obs], [act])\n assert np.array_equal(outputs[0], expected_output)\n\n outputs = qf.get_qval([obs, obs, obs], [act, act, act])\n for output in outputs:\n assert np.array_equal(output, expected_output)\n\n @pytest.mark.parametrize('obs_dim, action_dim', [\n ((1, ), (1, )),\n ((2, ), (2, )),\n ((1, 1), (1, )),\n ((2, 2), (2, )),\n ])\n def test_output_shape(self, obs_dim, action_dim):\n env = GarageEnv(DummyBoxEnv(obs_dim=obs_dim, action_dim=action_dim))\n with mock.patch(('garage.tf.q_functions.'\n 'continuous_mlp_q_function.MLPMergeModel'),\n new=SimpleMLPMergeModel):\n qf = ContinuousMLPQFunction(env_spec=env.spec)\n env.reset()\n obs, _, _, _ = env.step(1)\n obs = obs.flatten()\n act = np.full(action_dim, 0.5).flatten()\n\n outputs = qf.get_qval([obs], [act])\n\n assert outputs.shape == (1, 1)\n\n @pytest.mark.parametrize('obs_dim, action_dim', [\n ((1, ), (1, )),\n ((2, ), (2, )),\n ((1, 1), (1, )),\n ((2, 2), (2, )),\n ])\n def test_get_qval_sym(self, obs_dim, action_dim):\n env = GarageEnv(DummyBoxEnv(obs_dim=obs_dim, action_dim=action_dim))\n with mock.patch(('garage.tf.q_functions.'\n 'continuous_mlp_q_function.MLPMergeModel'),\n new=SimpleMLPMergeModel):\n qf = ContinuousMLPQFunction(env_spec=env.spec)\n env.reset()\n obs, _, _, _ = env.step(1)\n obs = obs.flatten()\n act = np.full(action_dim, 0.5).flatten()\n\n output1 = qf.get_qval([obs], [act])\n\n input_var1 = tf.compat.v1.placeholder(tf.float32,\n shape=(None, obs.shape[0]))\n input_var2 = tf.compat.v1.placeholder(tf.float32,\n shape=(None, act.shape[0]))\n q_vals = qf.get_qval_sym(input_var1, input_var2, 'another')\n output2 = self.sess.run(q_vals,\n feed_dict={\n input_var1: [obs],\n input_var2: [act]\n })\n\n expected_output = np.full((1, ), 0.5)\n\n assert np.array_equal(output1, output2)\n assert np.array_equal(output2[0], expected_output)\n\n @pytest.mark.parametrize('obs_dim, action_dim', [\n ((1, ), (1, )),\n ((2, ), (2, )),\n ((1, 1), (1, )),\n ((2, 2), (2, )),\n ])\n def test_is_pickleable(self, obs_dim, action_dim):\n env = GarageEnv(DummyBoxEnv(obs_dim=obs_dim, action_dim=action_dim))\n with mock.patch(('garage.tf.q_functions.'\n 'continuous_mlp_q_function.MLPMergeModel'),\n new=SimpleMLPMergeModel):\n qf = ContinuousMLPQFunction(env_spec=env.spec)\n env.reset()\n obs, _, _, _ = env.step(1)\n obs = obs.flatten()\n act = np.full(action_dim, 0.5).flatten()\n\n with tf.compat.v1.variable_scope(\n 'ContinuousMLPQFunction/SimpleMLPMergeModel', reuse=True):\n return_var = tf.compat.v1.get_variable('return_var')\n # assign it to all one\n return_var.load(tf.ones_like(return_var).eval())\n\n output1 = qf.get_qval([obs], [act])\n\n h_data = pickle.dumps(qf)\n with tf.compat.v1.Session(graph=tf.Graph()):\n qf_pickled = pickle.loads(h_data)\n output2 = qf_pickled.get_qval([obs], [act])\n\n assert np.array_equal(output1, output2)\n\n @pytest.mark.parametrize('obs_dim, action_dim, hidden_sizes', [\n ((1, ), (1, ), (3, )),\n ((2, ), (2, ), (32, )),\n ((1, 1), (1, ), (3, 3)),\n ((2, 2), (2, ), (32, 32)),\n ])\n def test_clone(self, obs_dim, action_dim, hidden_sizes):\n env = GarageEnv(DummyBoxEnv(obs_dim=obs_dim, action_dim=action_dim))\n with mock.patch(('garage.tf.q_functions.'\n 'continuous_mlp_q_function.MLPMergeModel'),\n new=SimpleMLPMergeModel):\n qf = ContinuousMLPQFunction(env_spec=env.spec,\n hidden_sizes=hidden_sizes)\n qf_clone = qf.clone('another_qf')\n assert qf_clone._hidden_sizes == qf._hidden_sizes\n", "\"\"\"Tensor utility functions for tensorflow.\"\"\"\nfrom collections import namedtuple\nfrom collections.abc import Iterable\n\nimport numpy as np\nimport tensorflow as tf\n\n\n# pylint: disable=unused-argument\n# yapf: disable\n# pylint: disable=missing-return-doc, missing-return-type-doc\ndef compile_function(inputs, outputs, log_name=None):\n \"\"\"Compiles a tensorflow function using the current session.\n\n Args:\n inputs (list[tf.Tensor]): Inputs to the function. Can be a list of\n inputs or just one.\n outputs (list[tf.Tensor]): Outputs of the function. Can be a list of\n outputs or just one.\n log_name (string): Name of the function. This is None by default.\n\n Returns:\n function: Compiled tensorflow function.\n \"\"\"\n\n def run(*input_vals):\n sess = tf.compat.v1.get_default_session()\n return sess.run(outputs, feed_dict=dict(list(zip(inputs, input_vals))))\n\n return run\n\n\n# yapf: enable\n# pylint: enable=missing-return-doc, missing-return-type-doc\n# pylint: enable=unused-argument\n\n\ndef get_target_ops(variables, target_variables, tau=None):\n \"\"\"Get target variables update operations.\n\n In RL algorithms we often update target network every n\n steps. This function returns the tf.Operation for updating\n target variables (denoted by target_var) from variables\n (denote by var) with fraction tau. In other words, each time\n we want to keep tau of the var and add (1 - tau) of target_var\n to var.\n\n Args:\n variables (list[tf.Variable]): Soure variables for update.\n target_variables (list[tf.Variable]): Target variables to\n be updated.\n tau (float): Fraction to update. Set it to be None for\n hard-update.\n\n Returns:\n tf.Operation: Operation for updating the target variables.\n \"\"\"\n update_ops = []\n init_ops = []\n assert len(variables) == len(target_variables)\n for var, target_var in zip(variables, target_variables):\n init_ops.append(tf.compat.v1.assign(target_var, var))\n if tau is not None:\n update_ops.append(\n tf.compat.v1.assign(target_var,\n tau * var + (1.0 - tau) * target_var))\n\n if tau is not None:\n return init_ops, update_ops\n else:\n return init_ops\n\n\ndef flatten_batch(t, name='flatten_batch'):\n \"\"\"Flatten a batch of observations.\n\n Reshape a tensor of size (X, Y, Z) into (X*Y, Z)\n\n Args:\n t (tf.Tensor): Tensor to flatten.\n name (string): Name of the operation.\n\n Returns:\n tf.Tensor: Flattened tensor.\n \"\"\"\n return tf.reshape(t, [-1] + list(t.shape[2:]), name=name)\n\n\ndef flatten_batch_dict(d, name='flatten_batch_dict'):\n \"\"\"Flatten a batch of observations represented as a dict.\n\n Args:\n d (dict[tf.Tensor]): A dict of Tensors to flatten.\n name (string): The name of the operation (None by default).\n\n Returns:\n dict[tf.Tensor]: A dict with flattened tensors.\n \"\"\"\n with tf.name_scope(name):\n return {k: flatten_batch(v) for k, v in d.items()}\n\n\ndef filter_valids(t, valid, name='filter_valids'):\n \"\"\"Filter out tensor using valid array.\n\n Args:\n t (tf.Tensor): The tensor to filter.\n valid (list[float]): Array of length of the valid values (either\n 0 or 1).\n name (string): Name of the operation.\n\n Returns:\n tf.Tensor: Filtered Tensor.\n \"\"\"\n # Must round before cast to prevent floating-error\n return tf.dynamic_partition(t,\n tf.cast(tf.round(valid), tf.int32),\n 2,\n name=name)[1]\n\n\ndef filter_valids_dict(d, valid, name='filter_valids_dict'):\n \"\"\"Filter valid values on a dict.\n\n Args:\n d (dict[tf.Tensor]): Dict of tensors to be filtered.\n valid (list[float]): Array of length of the valid values (elements\n can be either 0 or 1).\n name (string): Name of the operation. None by default.\n\n Returns:\n dict[tf.Tensor]: Dict with filtered tensors.\n \"\"\"\n with tf.name_scope(name):\n return {k: filter_valids(v, valid) for k, v in d.items()}\n\n\ndef graph_inputs(name, **kwargs):\n \"\"\"Creates a namedtuple of the given keys and values.\n\n Args:\n name (string): Name of the tuple.\n kwargs (tf.Tensor): One or more tensor(s) to add to the\n namedtuple's values. The parameter names are used as keys\n in the namedtuple. Ex. obs1=tensor1, obs2=tensor2.\n\n Returns:\n namedtuple: Namedtuple containing the collection of variables\n passed.\n \"\"\"\n Singleton = namedtuple(name, kwargs.keys())\n return Singleton(**kwargs)\n\n\n# yapf: disable\n# pylint: disable=missing-yield-doc\n# pylint: disable=missing-yield-type-doc\ndef flatten_inputs(deep):\n \"\"\"Flattens an Iterable recursively.\n\n Args:\n deep (Iterable): An Iterable to flatten.\n\n Returns:\n List: The flattened result.\n \"\"\"\n def flatten(deep):\n for d in deep:\n if isinstance(d, Iterable) and not isinstance(\n d, (str, bytes, tf.Tensor, np.ndarray)):\n yield from flatten(d)\n else:\n yield d\n\n return list(flatten(deep))\n\n# pylint: enable=missing-yield-doc\n# pylint: enable=missing-yield-type-doc\n# yapf: enable\n\n\ndef flatten_tensor_variables(ts):\n \"\"\"Flattens a list of tensors into a single, 1-dimensional tensor.\n\n Args:\n ts (Iterable): Iterable containing either tf.Tensors or arrays.\n\n Returns:\n tf.Tensor: Flattened Tensor.\n \"\"\"\n return tf.concat(axis=0,\n values=[tf.reshape(x, [-1]) for x in ts],\n name='flatten_tensor_variables')\n\n\ndef new_tensor(name, ndim, dtype):\n \"\"\"Creates a placeholder tf.Tensor with the specified arguments.\n\n Args:\n name (string): Name of the tf.Tensor.\n ndim (int): Number of dimensions of the tf.Tensor.\n dtype (type): Data type of the tf.Tensor's contents.\n\n Returns:\n tf.Tensor: Placeholder tensor.\n \"\"\"\n return tf.compat.v1.placeholder(dtype=dtype,\n shape=[None] * ndim,\n name=name)\n\n\ndef new_tensor_like(name, arr_like):\n \"\"\"Creates a new placeholder tf.Tensor similar to arr_like.\n\n The new tf.Tensor has the same number of dimensions and\n dtype as arr_like.\n\n Args:\n name (string): Name of the new tf.Tensor.\n arr_like (tf.Tensor): Tensor to copy attributes from.\n\n Returns:\n tf.Tensor: New placeholder tensor.\n \"\"\"\n return new_tensor(name,\n arr_like.get_shape().ndims, arr_like.dtype.base_dtype)\n\n\ndef concat_tensor_list(tensor_list):\n \"\"\"Concatenates a list of tensors into one tensor.\n\n Args:\n tensor_list (list[ndarray]): list of tensors.\n\n Return:\n ndarray: Concatenated tensor.\n \"\"\"\n return np.concatenate(tensor_list, axis=0)\n\n\ndef concat_tensor_dict_list(tensor_dict_list):\n \"\"\"Concatenates a dict of tensors lists.\n\n Each list of tensors gets concatenated into one tensor.\n\n Args:\n tensor_dict_list (dict[list[ndarray]]): Dict with lists of tensors.\n\n Returns:\n dict[ndarray]: A dict with the concatenated tensors.\n \"\"\"\n keys = list(tensor_dict_list[0].keys())\n ret = dict()\n for k in keys:\n example = tensor_dict_list[0][k]\n if isinstance(example, dict):\n v = concat_tensor_dict_list([x[k] for x in tensor_dict_list])\n else:\n v = concat_tensor_list([x[k] for x in tensor_dict_list])\n ret[k] = v\n return ret\n\n\ndef stack_tensor_dict_list(tensor_dict_list):\n \"\"\"Stack a list of dictionaries of {tensors or dictionary of tensors}.\n\n Args:\n tensor_dict_list (dict): a list of dictionaries of {tensors or\n dictionary of tensors}.\n\n Returns:\n dict: a dictionary of {stacked tensors or dictionary of stacked\n tensors}.\n \"\"\"\n keys = list(tensor_dict_list[0].keys())\n ret = dict()\n for k in keys:\n example = tensor_dict_list[0][k]\n if isinstance(example, dict):\n v = stack_tensor_dict_list([x[k] for x in tensor_dict_list])\n else:\n v = np.array([x[k] for x in tensor_dict_list])\n ret[k] = v\n return ret\n\n\ndef split_tensor_dict_list(tensor_dict):\n \"\"\"Split a list of dictionaries of {tensors or dictionary of tensors}.\n\n Args:\n tensor_dict (dict): a list of dictionaries of {tensors or\n dictionary of tensors}.\n\n Returns:\n dict: a dictionary of {split tensors or dictionary of split tensors}.\n \"\"\"\n keys = list(tensor_dict.keys())\n ret = None\n for k in keys:\n vals = tensor_dict[k]\n if isinstance(vals, dict):\n vals = split_tensor_dict_list(vals)\n if ret is None:\n ret = [{k: v} for v in vals]\n else:\n for v, cur_dict in zip(vals, ret):\n cur_dict[k] = v\n return ret\n\n\ndef pad_tensor(x, max_len):\n \"\"\"Pad tensors with zeros.\n\n Args:\n x (numpy.ndarray): Tensors to be padded.\n max_len (int): Maximum length.\n\n Returns:\n numpy.ndarray: Padded tensor.\n \"\"\"\n return np.concatenate([\n x,\n np.tile(np.zeros_like(x[0]),\n (max_len - len(x), ) + (1, ) * np.ndim(x[0]))\n ])\n\n\ndef pad_tensor_n(xs, max_len):\n \"\"\"Pad array of tensors.\n\n Args:\n xs (numpy.ndarray): Tensors to be padded.\n max_len (int): Maximum length.\n\n Returns:\n numpy.ndarray: Padded tensor.\n \"\"\"\n ret = np.zeros((len(xs), max_len) + xs[0].shape[1:], dtype=xs[0].dtype)\n for idx, x in enumerate(xs):\n ret[idx][:len(x)] = x\n return ret\n\n\ndef pad_tensor_dict(tensor_dict, max_len):\n \"\"\"Pad dictionary of tensors with zeros.\n\n Args:\n tensor_dict (dict[numpy.ndarray]): Tensors to be padded.\n max_len (int): Maximum length.\n\n Returns:\n dict[numpy.ndarray]: Padded tensor.\n \"\"\"\n keys = list(tensor_dict.keys())\n ret = dict()\n for k in keys:\n if isinstance(tensor_dict[k], dict):\n ret[k] = pad_tensor_dict(tensor_dict[k], max_len)\n else:\n ret[k] = pad_tensor(tensor_dict[k], max_len)\n return ret\n\n\ndef compute_advantages(discount,\n gae_lambda,\n max_len,\n baselines,\n rewards,\n name='compute_advantages'):\n \"\"\"Calculate advantages.\n\n Advantages are a discounted cumulative sum.\n\n The discount cumulative sum can be represented as an IIR\n filter ob the reversed input vectors, i.e.\n\n y[t] - discount*y[t+1] = x[t], or\n rev(y)[t] - discount*rev(y)[t-1] = rev(x)[t]\n\n Given the time-domain IIR filter step response, we can\n calculate the filter response to our signal by convolving the\n signal with the filter response function. The time-domain IIR\n step response is calculated below as discount_filter:\n\n discount_filter = [1, discount, discount^2, ..., discount^N-1]\n where the epsiode length is N.\n\n We convolve discount_filter with the reversed time-domain\n signal deltas to calculate the reversed advantages:\n\n rev(advantages) = discount_filter (X) rev(deltas)\n\n TensorFlow's tf.nn.conv1d op is not a true convolution, but\n actually a cross-correlation, so its input and output are\n already implicitly reversed for us.\n\n advantages = discount_filter (tf.nn.conv1d) deltas\n\n Args:\n discount (float): Discount factor.\n gae_lambda (float): Lambda, as used for Generalized Advantage\n Estimation (GAE).\n max_len (int): Maximum length of a single rollout.\n baselines (tf.Tensor): A 2D vector of value function estimates with\n shape (N, T), where N is the batch dimension (number of episodes)\n and T is the maximum path length experienced by the agent.\n rewards (tf.Tensor): A 2D vector of per-step rewards with shape\n (N, T), where N is the batch dimension (number of episodes) and T\n is the maximum path length experienced by the agent.\n name (string): Name of the operation.\n\n Returns:\n tf.Tensor: A 2D vector of calculated advantage values with shape\n (N, T), where N is the batch dimension (number of episodes) and T\n is the maximum path length experienced by the agent.\n \"\"\"\n with tf.name_scope(name):\n\n # Prepare convolutional IIR filter to calculate advantages\n gamma_lambda = tf.constant(float(discount) * float(gae_lambda),\n dtype=tf.float32,\n shape=[max_len, 1, 1])\n advantage_filter = tf.compat.v1.cumprod(gamma_lambda, exclusive=True)\n\n # Calculate deltas\n pad = tf.zeros_like(baselines[:, :1])\n baseline_shift = tf.concat([baselines[:, 1:], pad], 1)\n deltas = rewards + discount * baseline_shift - baselines\n\n # Convolve deltas with the discount filter to get advantages\n deltas_pad = tf.expand_dims(tf.concat(\n [deltas, tf.zeros_like(deltas[:, :-1])], axis=1),\n axis=2)\n adv = tf.nn.conv1d(deltas_pad,\n advantage_filter,\n stride=1,\n padding='VALID')\n advantages = tf.reshape(adv, [-1])\n return advantages\n\n\ndef center_advs(advs, axes, eps, offset=0, scale=1, name='center_adv'):\n \"\"\"Normalize the advs tensor.\n\n This calculates the mean and variance using the axes specified\n and normalizes the tensor using those values.\n\n Args:\n advs (tf.Tensor): Tensor to normalize.\n axes (array[int]): Axes along which to compute the mean and variance.\n eps (float): Small number to avoid dividing by zero.\n offset (tf.Tensor): Offset added to the normalized tensor.\n This is zero by default.\n scale (tf.Tensor): Scale to apply to the normalized tensor. This is\n 1 by default but can also be None.\n name (string): Name of the operation. None by default.\n\n Returns:\n tf.Tensor: Normalized, scaled and offset tensor.\n \"\"\"\n with tf.name_scope(name):\n mean, var = tf.nn.moments(advs, axes=axes)\n advs = tf.nn.batch_normalization(advs, mean, var, offset, scale, eps)\n return advs\n\n\ndef positive_advs(advs, eps, name='positive_adv'):\n \"\"\"Make all the values in the advs tensor positive.\n\n Offsets all values in advs by the minimum value in\n the tensor, plus an epsilon value to avoid dividing by zero.\n\n Args:\n advs (tf.Tensor): The tensor to offset.\n eps (tf.float32): A small value to avoid by-zero division.\n name (string): Name of the operation.\n\n Returns:\n tf.Tensor: Tensor with modified (postiive) values.\n \"\"\"\n with tf.name_scope(name):\n m = tf.reduce_min(advs)\n advs = (advs - m) + eps\n return advs\n\n\ndef discounted_returns(discount, max_len, rewards, name='discounted_returns'):\n \"\"\"Calculate discounted returns.\n\n Args:\n discount (float): Discount factor.\n max_len (int): Maximum length of a single rollout.\n rewards (tf.Tensor): A 2D vector of per-step rewards with shape\n (N, T), where N is the batch dimension (number of episodes) and T\n is the maximum path length experienced by the agent.\n name (string): Name of the operation. None by default.\n\n Returns:\n tf.Tensor: Tensor of discounted returns.\n \"\"\"\n with tf.name_scope(name):\n gamma = tf.constant(float(discount),\n dtype=tf.float32,\n shape=[max_len, 1, 1])\n return_filter = tf.math.cumprod(gamma, exclusive=True)\n rewards_pad = tf.expand_dims(tf.concat(\n [rewards, tf.zeros_like(rewards[:, :-1])], axis=1),\n axis=2)\n returns = tf.nn.conv1d(rewards_pad,\n return_filter,\n stride=1,\n padding='VALID')\n return returns\n", "import pickle\n\nimport numpy as np\nimport pytest\nimport tensorflow as tf\nimport tensorflow_probability as tfp\n\nfrom garage.tf.models import CategoricalCNNModel\nfrom tests.fixtures import TfGraphTestCase\n\n\nclass TestCategoricalMLPModel(TfGraphTestCase):\n\n def setup_method(self):\n super().setup_method()\n batch_size = 5\n input_width = 10\n input_height = 10\n self._obs_input = np.ones(\n (batch_size, 1, input_width, input_height, 3))\n self._input_shape = (input_width, input_height, 3\n ) # height, width, channel\n self._input_ph = tf.compat.v1.placeholder(tf.float32,\n shape=(None, None) +\n self._input_shape,\n name='input')\n\n def test_dist(self):\n model = CategoricalCNNModel(output_dim=1,\n filters=((5, (3, 3)), ),\n strides=(1, ),\n padding='VALID')\n dist = model.build(self._input_ph).dist\n assert isinstance(dist, tfp.distributions.OneHotCategorical)\n\n def test_instantiate_with_different_name(self):\n model = CategoricalCNNModel(output_dim=1,\n filters=((5, (3, 3)), ),\n strides=(1, ),\n padding='VALID')\n model.build(self._input_ph)\n model.build(self._input_ph, name='another_model')\n\n # yapf: disable\n @pytest.mark.parametrize(\n 'output_dim, filters, strides, padding, hidden_sizes', [\n (1, ((1, (1, 1)), ), (1, ), 'SAME', (1, )),\n (1, ((3, (3, 3)), ), (2, ), 'VALID', (2, )),\n (1, ((3, (3, 3)), ), (2, ), 'SAME', (3, )),\n (2, ((3, (3, 3)), (32, (3, 3))), (2, 2), 'VALID', (1, 1)),\n (3, ((3, (3, 3)), (32, (3, 3))), (2, 2), 'SAME', (2, 2)),\n ])\n # yapf: enable\n def test_is_pickleable(self, output_dim, filters, strides, padding,\n hidden_sizes):\n model = CategoricalCNNModel(output_dim=output_dim,\n filters=filters,\n strides=strides,\n padding=padding,\n hidden_sizes=hidden_sizes,\n hidden_nonlinearity=None,\n hidden_w_init=tf.ones_initializer(),\n output_w_init=tf.ones_initializer())\n dist = model.build(self._input_ph).dist\n # assign bias to all one\n with tf.compat.v1.variable_scope('CategoricalCNNModel', reuse=True):\n cnn_bias = tf.compat.v1.get_variable('CNNModel/cnn/h0/bias')\n bias = tf.compat.v1.get_variable('MLPModel/mlp/hidden_0/bias')\n\n bias.load(tf.ones_like(bias).eval())\n cnn_bias.load(tf.ones_like(cnn_bias).eval())\n\n output1 = self.sess.run(dist.probs,\n feed_dict={self._input_ph: self._obs_input})\n\n h = pickle.dumps(model)\n with tf.compat.v1.Session(graph=tf.Graph()) as sess:\n input_var = tf.compat.v1.placeholder(tf.float32,\n shape=(None, None) +\n self._input_shape)\n model_pickled = pickle.loads(h)\n dist2 = model_pickled.build(input_var).dist\n output2 = sess.run(dist2.probs,\n feed_dict={input_var: self._obs_input})\n\n assert np.array_equal(output1, output2)\n", "import numpy as np\nimport pytest\nimport tensorflow as tf\n\nfrom garage.tf.models.cnn import cnn\nfrom garage.tf.models.cnn import cnn_with_max_pooling\nfrom tests.fixtures import TfGraphTestCase\nfrom tests.helpers import convolve\nfrom tests.helpers import max_pooling\n\n\nclass TestCNN(TfGraphTestCase):\n\n def setup_method(self):\n super().setup_method()\n self.batch_size = 5\n self.input_width = 10\n self.input_height = 10\n self.obs_input = np.ones(\n (self.batch_size, self.input_width, self.input_height, 3))\n\n input_shape = self.obs_input.shape[1:] # height, width, channel\n self._input_ph = tf.compat.v1.placeholder(tf.float32,\n shape=(None, ) + input_shape,\n name='input')\n self.hidden_nonlinearity = tf.nn.relu\n\n @pytest.mark.parametrize('filters, strides', [\n (((32, (1, 1)), ), (1, )),\n (((32, (3, 3)), ), (1, )),\n (((32, (2, 3)), ), (1, )),\n (((32, (3, 3)), ), (2, )),\n (((32, (2, 3)), ), (2, )),\n (((32, (1, 1)), (64, (1, 1))), (1, 1)),\n (((32, (3, 3)), (64, (3, 3))), (1, 1)),\n (((32, (2, 3)), (64, (3, 3))), (1, 1)),\n (((32, (3, 3)), (64, (3, 3))), (2, 2)),\n (((32, (2, 3)), (64, (3, 3))), (2, 2)),\n ])\n def test_output_shape_same(self, filters, strides):\n with tf.compat.v1.variable_scope('CNN'):\n self.cnn = cnn(input_var=self._input_ph,\n filters=filters,\n strides=strides,\n name='cnn',\n padding='SAME',\n hidden_w_init=tf.constant_initializer(1),\n hidden_nonlinearity=self.hidden_nonlinearity)\n\n self.sess.run(tf.compat.v1.global_variables_initializer())\n\n result = self.sess.run(self.cnn,\n feed_dict={self._input_ph: self.obs_input})\n\n height_size = self.input_height\n width_size = self.input_width\n for stride in strides:\n height_size = int((height_size + stride - 1) / stride)\n width_size = int((width_size + stride - 1) / stride)\n flatten_shape = width_size * height_size * filters[-1][0]\n assert result.shape == (5, flatten_shape)\n\n @pytest.mark.parametrize('filters, strides', [\n (((32, (1, 1)), ), (1, )),\n (((32, (3, 3)), ), (1, )),\n (((32, (2, 3)), ), (1, )),\n (((32, (3, 3)), ), (2, )),\n (((32, (2, 3)), ), (2, )),\n (((32, (1, 1)), (64, (1, 1))), (1, 1)),\n (((32, (3, 3)), (64, (3, 3))), (1, 1)),\n (((32, (2, 3)), (64, (3, 3))), (1, 1)),\n (((32, (3, 3)), (64, (3, 3))), (2, 2)),\n (((32, (2, 3)), (64, (3, 3))), (2, 2)),\n ])\n def test_output_shape_valid(self, filters, strides):\n with tf.compat.v1.variable_scope('CNN'):\n self.cnn = cnn(input_var=self._input_ph,\n filters=filters,\n strides=strides,\n name='cnn',\n padding='VALID',\n hidden_w_init=tf.constant_initializer(1),\n hidden_nonlinearity=self.hidden_nonlinearity)\n\n self.sess.run(tf.compat.v1.global_variables_initializer())\n\n result = self.sess.run(self.cnn,\n feed_dict={self._input_ph: self.obs_input})\n\n height_size = self.input_height\n width_size = self.input_width\n for filter_iter, stride in zip(filters, strides):\n height_size = int((height_size - filter_iter[1][0]) / stride) + 1\n width_size = int((width_size - filter_iter[1][1]) / stride) + 1\n flatten_shape = height_size * width_size * filters[-1][0]\n assert result.shape == (self.batch_size, flatten_shape)\n\n @pytest.mark.parametrize('filters, in_channels, strides',\n [(((32, (1, 1)), ), (3, ), (1, )),\n (((32, (3, 3)), ), (3, ), (1, )),\n (((32, (2, 3)), ), (3, ), (1, )),\n (((32, (3, 3)), ), (3, ), (2, )),\n (((32, (2, 3)), ), (3, ), (2, )),\n (((32, (1, 1)), (64, (1, 1))), (3, 32), (1, 1)),\n (((32, (3, 3)), (64, (3, 3))), (3, 32), (1, 1)),\n (((32, (2, 3)), (64, (3, 3))), (3, 32), (1, 1)),\n (((32, (3, 3)), (64, (3, 3))), (3, 32), (2, 2)),\n (((32, (2, 3)), (64, (3, 3))), (3, 32), (2, 2))])\n def test_output_with_identity_filter(self, filters, in_channels, strides):\n with tf.compat.v1.variable_scope('CNN'):\n self.cnn = cnn(input_var=self._input_ph,\n filters=filters,\n strides=strides,\n name='cnn1',\n padding='VALID',\n hidden_w_init=tf.constant_initializer(1),\n hidden_nonlinearity=self.hidden_nonlinearity)\n\n self.sess.run(tf.compat.v1.global_variables_initializer())\n\n result = self.sess.run(self.cnn,\n feed_dict={self._input_ph: self.obs_input})\n\n filter_sum = 1\n # filter value after 3 layers of conv\n for filter_iter, in_channel in zip(filters, in_channels):\n filter_sum *= filter_iter[1][0] * filter_iter[1][1] * in_channel\n\n height_size = self.input_height\n width_size = self.input_width\n for filter_iter, stride in zip(filters, strides):\n height_size = int((height_size - filter_iter[1][0]) / stride) + 1\n width_size = int((width_size - filter_iter[1][1]) / stride) + 1\n flatten_shape = height_size * width_size * filters[-1][0]\n\n # flatten\n h_out = np.full((self.batch_size, flatten_shape),\n filter_sum,\n dtype=np.float32)\n np.testing.assert_array_equal(h_out, result)\n\n # yapf: disable\n @pytest.mark.parametrize('filters, in_channels, strides',\n [(((32, (1, 1)), ), (3, ), (1, )),\n (((32, (3, 3)), ), (3, ), (1, )),\n (((32, (2, 3)), ), (3, ), (1, )),\n (((32, (3, 3)), ), (3, ), (2, )),\n (((32, (2, 3)), ), (3, ), (2, )),\n (((32, (1, 1)), (64, (1, 1))), (3, 32), (1, 1)),\n (((32, (3, 3)), (64, (3, 3))), (3, 32), (1, 1)),\n (((32, (2, 3)), (64, (3, 3))), (3, 32), (1, 1)),\n (((32, (3, 3)), (64, (3, 3))), (3, 32), (2, 2)),\n (((32, (2, 3)), (64, (3, 3))), (3, 32), (2, 2))])\n # yapf: enable\n def test_output_with_random_filter(self, filters, in_channels, strides):\n # Build a cnn with random filter weights\n with tf.compat.v1.variable_scope('CNN'):\n self.cnn2 = cnn(input_var=self._input_ph,\n filters=filters,\n strides=strides,\n name='cnn1',\n padding='VALID',\n hidden_nonlinearity=self.hidden_nonlinearity)\n\n self.sess.run(tf.compat.v1.global_variables_initializer())\n\n result = self.sess.run(self.cnn2,\n feed_dict={self._input_ph: self.obs_input})\n\n two_layer = len(filters) == 2\n # get weight values\n with tf.compat.v1.variable_scope('CNN', reuse=True):\n h0_w = tf.compat.v1.get_variable('cnn1/h0/weight').eval()\n h0_b = tf.compat.v1.get_variable('cnn1/h0/bias').eval()\n if two_layer:\n h1_w = tf.compat.v1.get_variable('cnn1/h1/weight').eval()\n h1_b = tf.compat.v1.get_variable('cnn1/h1/bias').eval()\n filter_weights = (h0_w, h1_w) if two_layer else (h0_w, )\n filter_bias = (h0_b, h1_b) if two_layer else (h0_b, )\n\n # convolution according to TensorFlow's approach\n input_val = convolve(_input=self.obs_input,\n filter_weights=filter_weights,\n filter_bias=filter_bias,\n strides=strides,\n filters=filters,\n in_channels=in_channels,\n hidden_nonlinearity=self.hidden_nonlinearity)\n\n # flatten\n dense_out = input_val.reshape((self.batch_size, -1)).astype(np.float32)\n np.testing.assert_array_almost_equal(dense_out, result)\n\n # yapf: disable\n @pytest.mark.parametrize(\n 'filters, in_channels, strides, pool_shape, pool_stride', [\n (((32, (1, 1)), ), (3, ), (1, ), 1, 1),\n (((32, (3, 3)), ), (3, ), (1, ), 1, 1),\n (((32, (2, 3)), ), (3, ), (1, ), 1, 1),\n (((32, (3, 3)), ), (3, ), (2, ), 2, 2),\n (((32, (2, 3)), ), (3, ), (2, ), 2, 2),\n (((32, (1, 1)), (64, (1, 1))), (3, 32), (1, 1), 1, 1),\n (((32, (3, 3)), (64, (3, 3))), (3, 32), (1, 1), 1, 1),\n (((32, (2, 3)), (64, (3, 3))), (3, 32), (1, 1), 1, 1)\n ])\n # yapf: enable\n def test_output_with_max_pooling(self, filters, in_channels, strides,\n pool_shape, pool_stride):\n # Build a cnn with random filter weights\n with tf.compat.v1.variable_scope('CNN'):\n self.cnn2 = cnn_with_max_pooling(\n input_var=self._input_ph,\n filters=filters,\n strides=strides,\n name='cnn1',\n pool_shapes=(pool_shape, pool_shape),\n pool_strides=(pool_stride, pool_stride),\n padding='VALID',\n hidden_w_init=tf.constant_initializer(1),\n hidden_nonlinearity=self.hidden_nonlinearity)\n\n self.sess.run(tf.compat.v1.global_variables_initializer())\n\n result = self.sess.run(self.cnn2,\n feed_dict={self._input_ph: self.obs_input})\n\n two_layer = len(filters) == 2\n # get weight values\n with tf.compat.v1.variable_scope('CNN', reuse=True):\n h0_w = tf.compat.v1.get_variable('cnn1/h0/weight').eval()\n h0_b = tf.compat.v1.get_variable('cnn1/h0/bias').eval()\n if two_layer:\n h1_w = tf.compat.v1.get_variable('cnn1/h1/weight').eval()\n h1_b = tf.compat.v1.get_variable('cnn1/h1/bias').eval()\n\n filter_weights = (h0_w, h1_w) if two_layer else (h0_w, )\n filter_bias = (h0_b, h1_b) if two_layer else (h0_b, )\n\n input_val = self.obs_input\n\n # convolution according to TensorFlow's approach\n # and perform max pooling on each layer\n for filter_iter, filter_weight, _filter_bias, in_channel in zip(\n filters, filter_weights, filter_bias, in_channels):\n input_val = convolve(_input=input_val,\n filter_weights=(filter_weight, ),\n filter_bias=(_filter_bias, ),\n strides=strides,\n filters=(filter_iter, ),\n in_channels=(in_channel, ),\n hidden_nonlinearity=self.hidden_nonlinearity)\n\n # max pooling\n input_val = max_pooling(_input=input_val,\n pool_shape=pool_shape,\n pool_stride=pool_stride)\n\n # flatten\n dense_out = input_val.reshape((self.batch_size, -1)).astype(np.float32)\n np.testing.assert_array_equal(dense_out, result)\n\n def test_invalid_padding(self):\n with pytest.raises(ValueError):\n with tf.compat.v1.variable_scope('CNN'):\n self.cnn = cnn(input_var=self._input_ph,\n filters=((32, (3, 3)), ),\n strides=(1, ),\n name='cnn',\n padding='UNKNOWN')\n\n def test_invalid_padding_max_pooling(self):\n with pytest.raises(ValueError):\n with tf.compat.v1.variable_scope('CNN'):\n self.cnn = cnn_with_max_pooling(input_var=self._input_ph,\n filters=((32, (3, 3)), ),\n strides=(1, ),\n name='cnn',\n pool_shapes=(1, 1),\n pool_strides=(1, 1),\n padding='UNKNOWN')\n" ]
[ [ "numpy.allclose", "tensorflow.keras.layers.RNN", "numpy.array_equal", "tensorflow.compat.v1.get_variable", "tensorflow.gradients", "numpy.matmul", "tensorflow.compat.v1.trainable_variables", "numpy.full", "tensorflow.compat.v1.global_variables_initializer", "tensorflow.constant_initializer", "tensorflow.compat.v1.placeholder", "numpy.concatenate", "numpy.prod", "numpy.exp", "tensorflow.compat.v1.variable_scope" ], [ "numpy.append", "numpy.ones_like" ], [ "tensorflow.Graph", "numpy.array_equal", "tensorflow.compat.v1.get_variable", "tensorflow.ones_like", "numpy.full", "numpy.concatenate", "tensorflow.compat.v1.placeholder", "tensorflow.compat.v1.variable_scope" ], [ "numpy.array", "tensorflow.nn.batch_normalization", "tensorflow.concat", "tensorflow.compat.v1.assign", "tensorflow.nn.moments", "tensorflow.reshape", "tensorflow.compat.v1.get_default_session", "tensorflow.round", "numpy.concatenate", "tensorflow.zeros_like", "tensorflow.compat.v1.placeholder", "tensorflow.reduce_min", "tensorflow.math.cumprod", "tensorflow.name_scope", "numpy.zeros_like", "numpy.ndim", "tensorflow.compat.v1.cumprod", "tensorflow.nn.conv1d" ], [ "tensorflow.Graph", "numpy.array_equal", "tensorflow.compat.v1.get_variable", "tensorflow.ones_like", "numpy.ones", "tensorflow.compat.v1.placeholder", "tensorflow.ones_initializer", "tensorflow.compat.v1.variable_scope" ], [ "tensorflow.compat.v1.get_variable", "numpy.full", "numpy.testing.assert_array_equal", "numpy.ones", "tensorflow.compat.v1.placeholder", "tensorflow.compat.v1.global_variables_initializer", "tensorflow.constant_initializer", "tensorflow.compat.v1.variable_scope", "numpy.testing.assert_array_almost_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
KrisThielemans/parallelproj
[ "b9e1cb27aaec9a1605e1842b7b3be8b6f32765d3" ]
[ "examples/projector_order_test.py" ]
[ "# small demo for listmode TOF MLEM without subsets\n\nimport os\nimport matplotlib.pyplot as py\nimport pyparallelproj as ppp\nfrom pyparallelproj.wrapper import joseph3d_fwd, joseph3d_fwd_tof, joseph3d_back, joseph3d_back_tof\nimport numpy as np\nimport argparse\nimport ctypes\n\nfrom time import time\n\n#---------------------------------------------------------------------------------\n# parse the command line\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--ngpus', help = 'number of GPUs to use', default = 0, type = int)\nparser.add_argument('--nsubsets', help = 'number of subsets', default = 28, type = int)\nparser.add_argument('--tpb', help = 'threads per block', default = 64, type = int)\nparser.add_argument('--nontof', help = 'non-TOF instead of TOF', action = 'store_true')\nparser.add_argument('--img_mem_order', help = 'memory layout for image', default = 'C',\n choices = ['C','F'])\nargs = parser.parse_args()\n\n#---------------------------------------------------------------------------------\n\nngpus = args.ngpus\nnsubsets = args.nsubsets\ntpb = args.tpb\ntof = not args.nontof\n\nimg_mem_order = args.img_mem_order\nsubset = 0\n\nif tof:\n ntofbins = 27\nelse:\n ntofbins = 1\n\nnp.random.seed(1)\n\n#---------------------------------------------------------------------------------\n\n# setup a scanner with one ring\nscanner = ppp.RegularPolygonPETScanner(ncrystals_per_module = np.array([16,9]),\n nmodules = np.array([28,5]))\n\n# setup a test image\nvoxsize = np.array([2.,2.,2.])\nn0 = 250\nn1 = 250\nn2 = max(1,int((scanner.xc2.max() - scanner.xc2.min()) / voxsize[2]))\n\n# setup a random image\nimg = np.zeros((n0,n1,n2), dtype = np.float32, order = img_mem_order)\nimg[(n0//6):(5*n0//6),(n1//6):(5*n1//6),:] = 1\nimg_origin = (-(np.array(img.shape) / 2) + 0.5) * voxsize\n\n# generate sinogram parameters and the projector\nsd = np.array([[0,1,2],\n [0,2,1],\n [1,2,0],\n [1,0,2],\n [2,0,1],\n [2,1,0]])\n\nfor sdo in sd:\n sino_params = ppp.PETSinogramParameters(scanner, ntofbins = ntofbins, tofbin_width = 23.,\n spatial_dim_order = sdo)\n proj = ppp.SinogramProjector(scanner, sino_params, img.shape, nsubsets = nsubsets,\n voxsize = voxsize, img_origin = img_origin, ngpus = ngpus,\n tof = tof, sigma_tof = 60./2.35, n_sigmas = 3.,\n threadsperblock = tpb)\n\n \n # do a forward / back projection of subset 0 - same as img_fwd = proj.fwd_project(img, 0)\n # we just write out the single steps to time the python overhead separately\n \n #img_fwd = proj.fwd_project(img, 0)\n #ones_sino = np.ones(img_fwd.shape, dtype = np.float32)\n #back = proj.back_project(ones_sino, 0)\n\n subset_slice = proj.subset_slices[subset]\n \n sigma_tof = np.full(proj.nLORs[subset], proj.sigma_tof, dtype = ctypes.c_float).ravel()\n tofcenter_offset = np.zeros(proj.nLORs[subset], dtype = ctypes.c_float).ravel()\n\n xstart = proj.xstart[subset_slice].ravel()\n xend = proj.xend[subset_slice].ravel()\n img_ravel = img.ravel(order = img_mem_order)\n subset_nLORs = proj.nLORs[subset]\n\n img_fwd = np.zeros(subset_nLORs*proj.ntofbins, dtype = ctypes.c_float) \n\n back_img = np.zeros(proj.nvox, dtype = ctypes.c_float) \n sino = np.ones(subset_nLORs*proj.ntofbins, dtype = ctypes.c_float) \n\n #--- time fwd projection\n t0 = time()\n if tof:\n ok = joseph3d_fwd_tof(xstart, xend, img_ravel, proj.img_origin, proj.voxsize, \n img_fwd, subset_nLORs, proj.img_dim,\n proj.tofbin_width, sigma_tof, tofcenter_offset, \n proj.nsigmas, proj.ntofbins, \n threadsperblock = proj.threadsperblock, ngpus = proj.ngpus, lm = False) \n else:\n ok = joseph3d_fwd(xstart, xend, img_ravel, proj.img_origin, proj.voxsize, \n img_fwd, subset_nLORs, proj.img_dim,\n threadsperblock = proj.threadsperblock, ngpus = proj.ngpus, lm = False) \n \n t1 = time()\n\n\n #--- time back projection\n t2 = time()\n if tof:\n ok = joseph3d_back_tof(xstart, xend, back_img, proj.img_origin, proj.voxsize, \n sino, subset_nLORs, proj.img_dim,\n proj.tofbin_width, sigma_tof, tofcenter_offset, \n proj.nsigmas, proj.ntofbins, \n threadsperblock = proj.threadsperblock, ngpus = proj.ngpus, lm = False) \n else:\n ok = joseph3d_back(xstart, xend, back_img, proj.img_origin, proj.voxsize, \n sino, subset_nLORs, proj.img_dim,\n threadsperblock = proj.threadsperblock, ngpus = proj.ngpus, lm = False) \n t3 = time()\n\n print(f'{sdo} {t1-t0} {t3-t2}')\n" ]
[ [ "numpy.random.seed", "numpy.full", "numpy.ones", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vballoli/jax
[ "bbf7a432e86053024419ec8adb90aae3d06afb18" ]
[ "tests/lax_numpy_test.py" ]
[ "# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# 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\n\nimport collections\nimport functools\nfrom functools import partial\nimport itertools\nimport operator\nfrom typing import cast, Optional\nimport unittest\nfrom unittest import SkipTest\nimport warnings\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n\nimport numpy as onp\n\nimport jax\nimport jax.ops\nfrom jax import api\nfrom jax import lax\nfrom jax import linear_util\nfrom jax import numpy as jnp\nfrom jax import test_util as jtu\nfrom jax import dtypes\nfrom jax import tree_util\nfrom jax.interpreters import partial_eval, xla\nfrom jax.test_util import check_grads\n\nfrom jax.config import config\nconfig.parse_flags_with_absl()\nFLAGS = config.FLAGS\n\nnonempty_nonscalar_array_shapes = [(4,), (3, 4), (3, 1), (1, 4), (2, 1, 4), (2, 3, 4)]\nnonempty_array_shapes = [()] + nonempty_nonscalar_array_shapes\none_dim_array_shapes = [(1,), (6,), (12,)]\nempty_array_shapes = [(0,), (0, 4), (3, 0),]\n\nscalar_shapes = [jtu.NUMPY_SCALAR_SHAPE, jtu.PYTHON_SCALAR_SHAPE]\narray_shapes = nonempty_array_shapes + empty_array_shapes\nnonzerodim_shapes = nonempty_nonscalar_array_shapes + empty_array_shapes\nnonempty_shapes = scalar_shapes + nonempty_array_shapes\nall_shapes = scalar_shapes + array_shapes\n\ndef supported_dtypes(dtypes):\n return [t for t in dtypes if t in jtu.supported_dtypes()]\n\nfloat_dtypes = supported_dtypes([jnp.bfloat16, onp.float16, onp.float32,\n onp.float64])\ncomplex_dtypes = [onp.complex64, onp.complex128]\nint_dtypes = [onp.int32, onp.int64]\nuint_dtypes = [onp.uint32, onp.uint64]\nunsigned_dtypes = [onp.uint32, onp.uint64]\nbool_dtypes = [onp.bool_]\ndefault_dtypes = float_dtypes + int_dtypes\ninexact_dtypes = float_dtypes + complex_dtypes\nnumber_dtypes = float_dtypes + complex_dtypes + int_dtypes\nall_dtypes = number_dtypes + bool_dtypes\n\n\npython_scalar_dtypes = [jnp.bool_, jnp.int_, jnp.float_, jnp.complex_]\n\ndef _valid_dtypes_for_shape(shape, dtypes):\n # Not all (shape, dtype) pairs are valid. In particular, Python scalars only\n # have one type in each category (float, bool, etc.)\n if shape is jtu.PYTHON_SCALAR_SHAPE:\n return [t for t in dtypes if t in python_scalar_dtypes]\n return dtypes\n\ndef _shape_and_dtypes(shapes, dtypes):\n for shape in shapes:\n for dtype in _valid_dtypes_for_shape(shape, dtypes):\n yield (shape, dtype)\n\nOpRecord = collections.namedtuple(\n \"OpRecord\",\n [\"name\", \"nargs\", \"dtypes\", \"shapes\", \"rng_factory\", \"diff_modes\",\n \"test_name\", \"check_dtypes\", \"tolerance\", \"inexact\"])\n\ndef op_record(name, nargs, dtypes, shapes, rng_factory, diff_modes,\n test_name=None, check_dtypes=True, tolerance=None, inexact=False):\n test_name = test_name or name\n return OpRecord(name, nargs, dtypes, shapes, rng_factory, diff_modes,\n test_name, check_dtypes, tolerance, inexact)\n\nJAX_ONE_TO_ONE_OP_RECORDS = [\n op_record(\"abs\", 1, number_dtypes, all_shapes, jtu.rand_default, [\"rev\"]),\n op_record(\"add\", 2, all_dtypes, all_shapes, jtu.rand_default, [\"rev\"]),\n op_record(\"ceil\", 1, float_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"conj\", 1, number_dtypes, all_shapes, jtu.rand_default, [\"rev\"]),\n op_record(\"equal\", 2, all_dtypes, all_shapes, jtu.rand_some_equal, []),\n op_record(\"exp\", 1, number_dtypes, all_shapes, jtu.rand_default, [\"rev\"],\n inexact=True),\n op_record(\"fabs\", 1, float_dtypes, all_shapes, jtu.rand_default, [\"rev\"]),\n op_record(\"float_power\", 2, inexact_dtypes, all_shapes,\n partial(jtu.rand_default, scale=1), [\"rev\"],\n tolerance={jnp.bfloat16: 1e-2, onp.float32: 1e-3,\n onp.float64: 1e-12, onp.complex64: 2e-4,\n onp.complex128: 1e-12}, check_dtypes=False),\n op_record(\"floor\", 1, float_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"greater\", 2, all_dtypes, all_shapes, jtu.rand_some_equal, []),\n op_record(\"greater_equal\", 2, all_dtypes, all_shapes, jtu.rand_some_equal, []),\n op_record(\"less\", 2, all_dtypes, all_shapes, jtu.rand_some_equal, []),\n op_record(\"less_equal\", 2, all_dtypes, all_shapes, jtu.rand_some_equal, []),\n op_record(\"log\", 1, number_dtypes, all_shapes, jtu.rand_positive, [\"rev\"],\n inexact=True),\n op_record(\"logical_and\", 2, all_dtypes, all_shapes, jtu.rand_bool, []),\n op_record(\"logical_not\", 1, all_dtypes, all_shapes, jtu.rand_bool, []),\n op_record(\"logical_or\", 2, all_dtypes, all_shapes, jtu.rand_bool, []),\n op_record(\"logical_xor\", 2, all_dtypes, all_shapes, jtu.rand_bool, []),\n op_record(\"maximum\", 2, all_dtypes, all_shapes, jtu.rand_some_inf, []),\n op_record(\"minimum\", 2, all_dtypes, all_shapes, jtu.rand_some_inf, []),\n op_record(\"multiply\", 2, all_dtypes, all_shapes, jtu.rand_default, [\"rev\"]),\n op_record(\"negative\", 1, number_dtypes, all_shapes, jtu.rand_default, [\"rev\"]),\n op_record(\"nextafter\", 2, [f for f in float_dtypes if f != jnp.bfloat16],\n all_shapes, jtu.rand_default, [\"rev\"], inexact=True, tolerance=0),\n op_record(\"not_equal\", 2, all_dtypes, all_shapes, jtu.rand_some_equal, [\"rev\"]),\n op_record(\"array_equal\", 2, number_dtypes, all_shapes, jtu.rand_some_equal, [\"rev\"]),\n op_record(\"reciprocal\", 1, inexact_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"subtract\", 2, number_dtypes, all_shapes, jtu.rand_default, [\"rev\"]),\n op_record(\"signbit\", 1, default_dtypes + bool_dtypes, all_shapes,\n jtu.rand_some_inf_and_nan, [\"rev\"]),\n op_record(\"trunc\", 1, float_dtypes, all_shapes, jtu.rand_some_inf_and_nan, []),\n op_record(\"sin\", 1, number_dtypes, all_shapes, jtu.rand_default, [\"rev\"],\n inexact=True),\n op_record(\"cos\", 1, number_dtypes, all_shapes, jtu.rand_default, [\"rev\"],\n inexact=True),\n op_record(\"tan\", 1, number_dtypes, all_shapes,\n partial(jtu.rand_uniform, -1.5, 1.5), [\"rev\"], inexact=True),\n op_record(\"sinh\", 1, number_dtypes, all_shapes, jtu.rand_default, [\"rev\"],\n inexact=True),\n op_record(\"cosh\", 1, number_dtypes, all_shapes, jtu.rand_default, [\"rev\"],\n inexact=True),\n # TODO(b/142975473): on CPU, tanh for complex128 is only accurate to\n # ~float32 precision.\n # TODO(b/143135720): on GPU, tanh has only ~float32 precision.\n op_record(\"tanh\", 1, number_dtypes, all_shapes, jtu.rand_default, [\"rev\"],\n tolerance={onp.float64: 1e-7, onp.complex128: 1e-7},\n inexact=True),\n op_record(\"arcsin\", 1, float_dtypes, all_shapes, jtu.rand_small, [\"rev\"],\n inexact=True),\n op_record(\"arccos\", 1, float_dtypes, all_shapes, jtu.rand_small, [\"rev\"],\n inexact=True),\n op_record(\"arctan\", 1, float_dtypes, all_shapes, jtu.rand_small, [\"rev\"],\n inexact=True),\n op_record(\"arctan2\", 2, float_dtypes, all_shapes, jtu.rand_small, [\"rev\"],\n inexact=True),\n op_record(\"arcsinh\", 1, number_dtypes, all_shapes, jtu.rand_positive, [\"rev\"],\n inexact=True),\n op_record(\"arccosh\", 1, number_dtypes, all_shapes, jtu.rand_positive, [\"rev\"],\n inexact=True),\n op_record(\"arctanh\", 1, number_dtypes, all_shapes, jtu.rand_small, [\"rev\"],\n inexact=True),\n]\n\nJAX_COMPOUND_OP_RECORDS = [\n # angle has inconsistent 32/64-bit return types across numpy versions.\n op_record(\"angle\", 1, number_dtypes, all_shapes, jtu.rand_default, [],\n check_dtypes=False, inexact=True),\n op_record(\"atleast_1d\", 1, default_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"atleast_2d\", 1, default_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"atleast_3d\", 1, default_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"cbrt\", 1, default_dtypes, all_shapes, jtu.rand_default, [\"rev\"],\n inexact=True),\n op_record(\"conjugate\", 1, number_dtypes, all_shapes, jtu.rand_default, [\"rev\"]),\n op_record(\"deg2rad\", 1, float_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"divide\", 2, number_dtypes, all_shapes, jtu.rand_nonzero, [\"rev\"],\n inexact=True),\n op_record(\"divmod\", 2, int_dtypes + float_dtypes, all_shapes,\n jtu.rand_nonzero, []),\n op_record(\"exp2\", 1, number_dtypes, all_shapes, jtu.rand_default, [\"rev\"],\n tolerance={jnp.bfloat16: 2e-2, onp.float16: 1e-2}, inexact=True),\n # TODO(b/142975473): on CPU, expm1 for float64 is only accurate to ~float32\n # precision.\n op_record(\"expm1\", 1, number_dtypes, all_shapes, jtu.rand_positive, [],\n test_name=\"expm1_large\", tolerance={onp.float64: 1e-8}, inexact=True),\n op_record(\"expm1\", 1, number_dtypes, all_shapes, jtu.rand_small_positive,\n [], tolerance={onp.float64: 1e-8}, inexact=True),\n op_record(\"fix\", 1, float_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"floor_divide\", 2, number_dtypes, all_shapes,\n jtu.rand_nonzero, [\"rev\"]),\n op_record(\"floor_divide\", 2, uint_dtypes, all_shapes,\n jtu.rand_nonzero, [\"rev\"]),\n op_record(\"heaviside\", 2, default_dtypes, all_shapes, jtu.rand_default, [],\n inexact=True),\n op_record(\"hypot\", 2, default_dtypes, all_shapes, jtu.rand_default, [],\n inexact=True),\n op_record(\"kron\", 2, number_dtypes, nonempty_shapes, jtu.rand_default, []),\n op_record(\"outer\", 2, number_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"imag\", 1, number_dtypes, all_shapes, jtu.rand_some_inf, []),\n op_record(\"iscomplex\", 1, number_dtypes, all_shapes, jtu.rand_some_inf, []),\n op_record(\"isfinite\", 1, inexact_dtypes, all_shapes, jtu.rand_some_inf_and_nan, []),\n op_record(\"isinf\", 1, inexact_dtypes, all_shapes, jtu.rand_some_inf_and_nan, []),\n op_record(\"isnan\", 1, inexact_dtypes, all_shapes, jtu.rand_some_inf_and_nan, []),\n op_record(\"isneginf\", 1, float_dtypes, all_shapes, jtu.rand_some_inf_and_nan, []),\n op_record(\"isposinf\", 1, float_dtypes, all_shapes, jtu.rand_some_inf_and_nan, []),\n op_record(\"isreal\", 1, number_dtypes, all_shapes, jtu.rand_some_inf, []),\n op_record(\"isrealobj\", 1, number_dtypes, all_shapes, jtu.rand_some_inf, []),\n op_record(\"log2\", 1, number_dtypes, all_shapes, jtu.rand_positive, [\"rev\"],\n inexact=True),\n op_record(\"log10\", 1, number_dtypes, all_shapes, jtu.rand_positive, [\"rev\"],\n inexact=True),\n op_record(\"log1p\", 1, number_dtypes, all_shapes, jtu.rand_positive, [],\n test_name=\"log1p_large\", tolerance={onp.float64: 1e-12},\n inexact=True),\n op_record(\"log1p\", 1, number_dtypes, all_shapes, jtu.rand_small_positive, [],\n tolerance={onp.float64: 1e-12}, inexact=True),\n op_record(\"logaddexp\", 2, float_dtypes, all_shapes,\n jtu.rand_some_inf_and_nan, [\"rev\"],\n tolerance={onp.float64: 1e-12}, inexact=True),\n op_record(\"logaddexp2\", 2, float_dtypes, all_shapes,\n jtu.rand_some_inf_and_nan, [\"rev\"],\n tolerance={onp.float16: 1e-2}, inexact=True),\n op_record(\"polyval\", 2, number_dtypes, nonempty_nonscalar_array_shapes,\n jtu.rand_default, [], check_dtypes=False,\n tolerance={onp.float16: 1e-2, onp.float64: 1e-12}),\n op_record(\"positive\", 1, number_dtypes, all_shapes, jtu.rand_default, [\"rev\"]),\n op_record(\"power\", 2, number_dtypes, all_shapes, jtu.rand_positive, [\"rev\"],\n tolerance={onp.complex128: 1e-14}),\n op_record(\"rad2deg\", 1, float_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"ravel\", 1, all_dtypes, all_shapes, jtu.rand_default, [\"rev\"]),\n op_record(\"real\", 1, number_dtypes, all_shapes, jtu.rand_some_inf, []),\n op_record(\"remainder\", 2, default_dtypes, all_shapes, jtu.rand_nonzero, [],\n tolerance={onp.float16: 1e-2}),\n op_record(\"mod\", 2, default_dtypes, all_shapes, jtu.rand_nonzero, []),\n op_record(\"sign\", 1, number_dtypes + uint_dtypes, all_shapes,\n jtu.rand_some_inf_and_nan, []),\n op_record('copysign', 2, default_dtypes, all_shapes, jtu.rand_some_inf_and_nan, [],\n check_dtypes=False),\n op_record(\"sinc\", 1, [t for t in number_dtypes if t != jnp.bfloat16],\n all_shapes, jtu.rand_default, [\"rev\"],\n tolerance={onp.complex64: 1e-5}, inexact=True,\n check_dtypes=False),\n op_record(\"square\", 1, number_dtypes, all_shapes, jtu.rand_default, [\"rev\"]),\n op_record(\"sqrt\", 1, number_dtypes, all_shapes, jtu.rand_positive, [\"rev\"],\n inexact=True),\n op_record(\"transpose\", 1, all_dtypes, all_shapes, jtu.rand_default, [\"rev\"],\n check_dtypes=False),\n op_record(\"true_divide\", 2, all_dtypes, all_shapes, jtu.rand_nonzero,\n [\"rev\"], inexact=True),\n op_record(\"diff\", 1, number_dtypes, nonzerodim_shapes, jtu.rand_default, [\"rev\"]),\n]\n\nJAX_BITWISE_OP_RECORDS = [\n op_record(\"bitwise_and\", 2, int_dtypes + unsigned_dtypes, all_shapes,\n jtu.rand_bool, []),\n op_record(\"bitwise_not\", 1, int_dtypes + unsigned_dtypes, all_shapes,\n jtu.rand_bool, []),\n op_record(\"bitwise_or\", 2, int_dtypes + unsigned_dtypes, all_shapes,\n jtu.rand_bool, []),\n op_record(\"bitwise_xor\", 2, int_dtypes + unsigned_dtypes, all_shapes,\n jtu.rand_bool, []),\n]\n\nJAX_REDUCER_RECORDS = [\n op_record(\"mean\", 1, number_dtypes, nonempty_shapes, jtu.rand_default, [],\n inexact=True),\n op_record(\"prod\", 1, all_dtypes, all_shapes, jtu.rand_small_positive, []),\n op_record(\"sum\", 1, all_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"nanmean\", 1, inexact_dtypes, nonempty_shapes, jtu.rand_some_nan,\n [], inexact=True),\n op_record(\"nanprod\", 1, inexact_dtypes, all_shapes, jtu.rand_some_nan, []),\n op_record(\"nansum\", 1, number_dtypes, all_shapes, jtu.rand_some_nan, []),\n]\n\nJAX_REDUCER_NO_DTYPE_RECORDS = [\n op_record(\"all\", 1, all_dtypes, all_shapes, jtu.rand_some_zero, []),\n op_record(\"any\", 1, all_dtypes, all_shapes, jtu.rand_some_zero, []),\n op_record(\"max\", 1, all_dtypes, nonempty_shapes, jtu.rand_default, []),\n op_record(\"min\", 1, all_dtypes, nonempty_shapes, jtu.rand_default, []),\n op_record(\"var\", 1, all_dtypes, nonempty_shapes, jtu.rand_default, [],\n inexact=True),\n op_record(\"std\", 1, all_dtypes, nonempty_shapes, jtu.rand_default, [],\n inexact=True),\n]\n\nJAX_ARGMINMAX_RECORDS = [\n op_record(\"argmin\", 1, all_dtypes, nonempty_shapes, jtu.rand_some_equal, []),\n op_record(\"argmax\", 1, all_dtypes, nonempty_shapes, jtu.rand_some_equal, []),\n]\n\nJAX_OPERATOR_OVERLOADS = [\n op_record(\"__add__\", 2, number_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"__sub__\", 2, number_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"__mul__\", 2, number_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"__eq__\", 2, number_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"__ne__\", 2, number_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"__lt__\", 2, default_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"__le__\", 2, default_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"__gt__\", 2, default_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"__ge__\", 2, default_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"__pos__\", 1, number_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"__neg__\", 1, number_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"__pow__\", 2, inexact_dtypes, all_shapes, jtu.rand_positive, [],\n tolerance={onp.float32: 2e-4, onp.complex64: 2e-4, onp.complex128: 1e-14}),\n op_record(\"__mod__\", 2, default_dtypes, all_shapes, jtu.rand_nonzero, [],\n tolerance={onp.float16: 1e-1}),\n op_record(\"__floordiv__\", 2, default_dtypes, all_shapes,\n jtu.rand_nonzero, []),\n op_record(\"__truediv__\", 2, number_dtypes, all_shapes, jtu.rand_nonzero, [],\n inexact=True),\n op_record(\"__abs__\", 1, number_dtypes, all_shapes, jtu.rand_default, []),\n # TODO(mattjj): __invert__ fails on bool dtypes because ~True == -2\n op_record(\"__invert__\", 1, int_dtypes, all_shapes, jtu.rand_default, []),\n # TODO(mattjj): investigate these failures\n # op_record(\"__or__\", 2, number_dtypes, all_shapes, jtu.rand_bool, []),\n # op_record(\"__and__\", 2, number_dtypes, all_shapes, jtu.rand_default, []),\n # op_record(\"__xor__\", 2, number_dtypes, all_shapes, jtu.rand_bool, []),\n # op_record(\"__divmod__\", 2, number_dtypes, all_shapes, jtu.rand_nonzero, []),\n # TODO(mattjj): lshift, rshift\n]\n\nJAX_RIGHT_OPERATOR_OVERLOADS = [\n op_record(\"__radd__\", 2, number_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"__rsub__\", 2, number_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"__rmul__\", 2, number_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"__rpow__\", 2, inexact_dtypes, all_shapes, jtu.rand_positive, [],\n tolerance={onp.float32: 2e-4, onp.complex64: 1e-3}),\n op_record(\"__rmod__\", 2, default_dtypes, all_shapes, jtu.rand_nonzero, [],\n tolerance={onp.float16: 1e-1}),\n op_record(\"__rfloordiv__\", 2, default_dtypes, all_shapes,\n jtu.rand_nonzero, []),\n op_record(\"__rtruediv__\", 2, number_dtypes, all_shapes, jtu.rand_nonzero, [],\n inexact=True),\n # op_record(\"__ror__\", 2, number_dtypes, all_shapes, jtu.rand_bool, []),\n # op_record(\"__rand__\", 2, number_dtypes, all_shapes, jtu.rand_default, []),\n # op_record(\"__rxor__\", 2, number_dtypes, all_shapes, jtu.rand_bool, []),\n # op_record(\"__rdivmod__\", 2, number_dtypes, all_shapes, jtu.rand_nonzero, []),\n]\n\nclass _OverrideEverything(object):\n pass\n\nfor rec in JAX_OPERATOR_OVERLOADS + JAX_RIGHT_OPERATOR_OVERLOADS:\n if rec.nargs == 2:\n setattr(_OverrideEverything, rec.name, lambda self, other: self)\n\nclass _OverrideNothing(object):\n pass\n\nfor rec in JAX_OPERATOR_OVERLOADS + JAX_RIGHT_OPERATOR_OVERLOADS:\n if rec.nargs == 2:\n setattr(_OverrideNothing, rec.name, lambda self, other: NotImplemented)\n\n\nnumpy_version = tuple(map(int, onp.version.version.split('.')))\nif numpy_version >= (1, 15):\n JAX_COMPOUND_OP_RECORDS += [\n op_record(\"isclose\", 2, [t for t in all_dtypes if t != jnp.bfloat16],\n all_shapes, jtu.rand_small_positive, []),\n op_record(\"gcd\", 2, int_dtypes, all_shapes, jtu.rand_default, []),\n op_record(\"lcm\", 2, int_dtypes, all_shapes, jtu.rand_default, []),\n ]\n JAX_REDUCER_NO_DTYPE_RECORDS += [\n op_record(\"ptp\", 1, number_dtypes, nonempty_shapes, jtu.rand_default, []),\n ]\n\nCombosWithReplacement = itertools.combinations_with_replacement\n\n\ndef _dtypes_are_compatible_for_bitwise_ops(args):\n if len(args) <= 1:\n return True\n is_signed = lambda dtype: jnp.issubdtype(dtype, onp.signedinteger)\n width = lambda dtype: jnp.iinfo(dtype).bits\n x, y = args\n if width(x) > width(y):\n x, y = y, x\n # The following condition seems a little ad hoc, but seems to capture what\n # numpy actually implements.\n return (\n is_signed(x) == is_signed(y)\n or (width(x) == 32 and width(y) == 32)\n or (width(x) == 32 and width(y) == 64 and is_signed(y)))\n\ndef _shapes_are_broadcast_compatible(shapes):\n accumulator = onp.zeros([])\n for shape in shapes:\n try:\n accumulator = accumulator + onp.zeros(shape)\n except ValueError:\n return False\n return True\n\ndef _shapes_are_equal_length(shapes):\n return all(len(shape) == len(shapes[0]) for shape in shapes[1:])\n\n\ndef _promote_like_jnp(fun, inexact=False):\n \"\"\"Decorator that promotes the arguments of `fun` to `jnp.result_type(*args)`.\n\n jnp and onp have different type promotion semantics; this decorator allows\n tests make an onp reference implementation act more like an jnp\n implementation.\n \"\"\"\n def wrapper(*args, **kw):\n flat_args = tree_util.tree_leaves(args)\n if inexact and not any(jnp.issubdtype(jnp.result_type(x), jnp.inexact)\n for x in flat_args):\n dtype = jnp.result_type(jnp.float_, *flat_args)\n else:\n dtype = jnp.result_type(*flat_args)\n args = tree_util.tree_map(lambda a: onp.asarray(a, dtype), args)\n return fun(*args, **kw)\n return wrapper\n\n\nclass LaxBackedNumpyTests(jtu.JaxTestCase):\n \"\"\"Tests for LAX-backed Numpy implementation.\"\"\"\n\n def _GetArgsMaker(self, rng, shapes, dtypes, onp_arrays=True):\n def f():\n out = [rng(shape, dtype or jnp.float_)\n for shape, dtype in zip(shapes, dtypes)]\n if onp_arrays:\n return out\n return [jnp.asarray(a) if isinstance(a, (onp.ndarray, onp.generic)) else a\n for a in out]\n return f\n\n @parameterized.named_parameters(itertools.chain.from_iterable(\n jtu.cases_from_list(\n {\"testcase_name\": jtu.format_test_name_suffix(rec.test_name, shapes,\n dtypes),\n \"rng_factory\": rec.rng_factory, \"shapes\": shapes, \"dtypes\": dtypes,\n \"onp_op\": getattr(onp, rec.name), \"jnp_op\": getattr(jnp, rec.name),\n \"check_dtypes\": rec.check_dtypes, \"tolerance\": rec.tolerance,\n \"inexact\": rec.inexact}\n for shapes in filter(\n _shapes_are_broadcast_compatible,\n CombosWithReplacement(rec.shapes, rec.nargs))\n for dtypes in itertools.product(\n *(_valid_dtypes_for_shape(s, rec.dtypes) for s in shapes)))\n for rec in itertools.chain(JAX_ONE_TO_ONE_OP_RECORDS,\n JAX_COMPOUND_OP_RECORDS)))\n def testOp(self, onp_op, jnp_op, rng_factory, shapes, dtypes, check_dtypes,\n tolerance, inexact):\n if onp_op is onp.float_power:\n onp_op = jtu.ignore_warning(category=RuntimeWarning,\n message=\"invalid value.*\")(onp_op)\n\n rng = rng_factory()\n args_maker = self._GetArgsMaker(rng, shapes, dtypes, onp_arrays=False)\n tol = max(jtu.tolerance(dtype, tolerance) for dtype in dtypes)\n tol = functools.reduce(jtu.join_tolerance,\n [tolerance, tol, jtu.default_tolerance()])\n self._CheckAgainstNumpy(_promote_like_jnp(onp_op, inexact), jnp_op,\n args_maker, check_dtypes=check_dtypes, tol=tol)\n self._CompileAndCheck(jnp_op, args_maker, check_dtypes=check_dtypes,\n atol=tol, rtol=tol)\n\n @parameterized.named_parameters(itertools.chain.from_iterable(\n jtu.cases_from_list(\n {\"testcase_name\": jtu.format_test_name_suffix(rec.test_name, shapes,\n dtypes),\n \"rng_factory\": rec.rng_factory, \"shapes\": shapes, \"dtypes\": dtypes, \"name\": rec.name,\n \"tol\": rec.tolerance}\n for shapes in filter(\n _shapes_are_broadcast_compatible,\n CombosWithReplacement(rec.shapes, rec.nargs))\n for dtypes in itertools.product(\n *(_valid_dtypes_for_shape(s, rec.dtypes) for s in shapes)))\n for rec in JAX_OPERATOR_OVERLOADS))\n def testOperatorOverload(self, name, rng_factory, shapes, dtypes, tol):\n rng = rng_factory()\n # onp and jnp arrays have different type promotion rules; force the use of\n # jnp arrays.\n args_maker = self._GetArgsMaker(rng, shapes, dtypes, onp_arrays=False)\n fun = lambda *xs: getattr(operator, name.strip('_'))(*xs)\n scalar_arg = (jtu.PYTHON_SCALAR_SHAPE in shapes or\n jtu.NUMPY_SCALAR_SHAPE in shapes or\n () in shapes)\n empty_shape = any(isinstance(s, tuple) and 0 in s for s in shapes)\n self._CompileAndCheck(\n fun, args_maker, check_dtypes=True, #not scalar_arg and not empty_shape,\n atol=tol, rtol=tol)\n\n @parameterized.named_parameters(itertools.chain.from_iterable(\n jtu.cases_from_list(\n {\"testcase_name\": jtu.format_test_name_suffix(rec.test_name, shapes,\n dtypes),\n \"rng_factory\": rec.rng_factory, \"shapes\": shapes, \"dtypes\": dtypes, \"name\": rec.name,\n \"op_tolerance\": rec.tolerance}\n for shapes in filter(\n _shapes_are_broadcast_compatible,\n CombosWithReplacement(rec.shapes, rec.nargs))\n for dtypes in itertools.product(\n *(_valid_dtypes_for_shape(s, rec.dtypes) for s in shapes)))\n for rec in JAX_RIGHT_OPERATOR_OVERLOADS))\n def testRightOperatorOverload(self, name, rng_factory, shapes, dtypes,\n op_tolerance):\n if shapes[1] is jtu.PYTHON_SCALAR_SHAPE:\n raise SkipTest(\"scalars not implemented\") # TODO(mattjj): clean up\n rng = rng_factory()\n args_maker = self._GetArgsMaker(rng, shapes, dtypes, onp_arrays=False)\n fun = lambda fst, snd: getattr(snd, name)(fst)\n tol = max(jtu.tolerance(dtype, op_tolerance) for dtype in dtypes)\n scalar_arg = (jtu.PYTHON_SCALAR_SHAPE in shapes or\n jtu.NUMPY_SCALAR_SHAPE in shapes or\n () in shapes)\n empty_shape = any(isinstance(s, tuple) and 0 in s for s in shapes)\n self._CompileAndCheck(\n fun, args_maker, check_dtypes=True, # not scalar_arg and not empty_shape,\n atol=tol, rtol=tol)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": rec.test_name + \"_{}\".format(dtype),\n \"rng_factory\": rec.rng_factory,\n \"op_name\": rec.name, \"dtype\": dtype}\n for rec in JAX_OPERATOR_OVERLOADS if rec.nargs == 2\n for dtype in rec.dtypes))\n def testBinaryOperatorDefers(self, op_name, rng_factory, dtype):\n rng = rng_factory()\n arg = jax.device_put(rng((), dtype))\n op = getattr(operator, op_name)\n\n other = _OverrideEverything()\n assert op(other, arg) is other\n assert op(arg, other) is other\n\n other = _OverrideNothing()\n if op_name == \"__eq__\":\n assert op(other, arg) is False\n assert op(arg, other) is False\n elif op_name == \"__ne__\":\n assert op(other, arg) is True\n assert op(arg, other) is True\n else:\n with self.assertRaises(TypeError):\n op(other, arg)\n with self.assertRaises(TypeError):\n op(arg, other)\n\n @parameterized.named_parameters(itertools.chain.from_iterable(\n jtu.cases_from_list(\n {\"testcase_name\": jtu.format_test_name_suffix(\n rec.test_name, shapes, dtypes),\n \"rng_factory\": rec.rng_factory, \"shapes\": shapes, \"dtypes\": dtypes,\n \"onp_op\": getattr(onp, rec.name), \"jnp_op\": getattr(jnp, rec.name)}\n for shapes in filter(\n _shapes_are_broadcast_compatible,\n CombosWithReplacement(rec.shapes, rec.nargs))\n for dtypes in filter(\n _dtypes_are_compatible_for_bitwise_ops,\n CombosWithReplacement(rec.dtypes, rec.nargs)))\n for rec in JAX_BITWISE_OP_RECORDS))\n def testBitwiseOp(self, onp_op, jnp_op, rng_factory, shapes, dtypes):\n rng = rng_factory()\n if not FLAGS.jax_enable_x64 and any(\n jnp.iinfo(dtype).bits == 64 for dtype in dtypes):\n self.skipTest(\"x64 types are disabled by jax_enable_x64\")\n args_maker = self._GetArgsMaker(rng, shapes, dtypes)\n self._CheckAgainstNumpy(onp_op, jnp_op, args_maker,\n check_dtypes=jtu.PYTHON_SCALAR_SHAPE not in shapes)\n self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(itertools.chain.from_iterable(\n jtu.cases_from_list(\n {\"testcase_name\": \"{}_inshape={}_axis={}_dtype={}_keepdims={}\".format(\n rec.test_name.capitalize(),\n jtu.format_shape_dtype_string(shape, dtype), axis,\n \"None\" if out_dtype is None else onp.dtype(out_dtype).name, keepdims),\n \"rng_factory\": rec.rng_factory, \"shape\": shape, \"dtype\": dtype, \"out_dtype\": out_dtype,\n \"onp_op\": getattr(onp, rec.name), \"jnp_op\": getattr(jnp, rec.name),\n \"axis\": axis, \"keepdims\": keepdims, \"inexact\": rec.inexact}\n for shape in rec.shapes for dtype in rec.dtypes\n for out_dtype in [None] + rec.dtypes\n for axis in list(range(-len(shape), len(shape))) + [None]\n for keepdims in [False, True])\n for rec in JAX_REDUCER_RECORDS))\n def testReducer(self, onp_op, jnp_op, rng_factory, shape, dtype, out_dtype,\n axis, keepdims, inexact):\n rng = rng_factory()\n @jtu.ignore_warning(category=onp.ComplexWarning)\n @jtu.ignore_warning(category=RuntimeWarning,\n message=\"mean of empty slice.*\")\n def onp_fun(x):\n x_cast = x if dtype != jnp.bfloat16 else x.astype(onp.float32)\n t = out_dtype if out_dtype != jnp.bfloat16 else onp.float32\n return onp_op(x_cast, axis, dtype=t, keepdims=keepdims)\n onp_fun = _promote_like_jnp(onp_fun, inexact)\n jnp_fun = lambda x: jnp_op(x, axis, dtype=out_dtype, keepdims=keepdims)\n jnp_fun = jtu.ignore_warning(category=jnp.ComplexWarning)(jnp_fun)\n args_maker = lambda: [rng(shape, dtype)]\n tol_spec = {onp.float16: 1e-2, onp.float32: 1e-3, onp.complex64: 1e-3,\n onp.float64: 1e-5, onp.complex128: 1e-5}\n tol = jtu.tolerance(dtype, tol_spec)\n tol = max(tol, jtu.tolerance(out_dtype, tol_spec)) if out_dtype else tol\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker,\n check_dtypes=jnp.bfloat16 not in (dtype, out_dtype),\n tol=tol)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True, atol=tol,\n rtol=tol)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"{}_inshape={}_axis={}_keepdims={}\".format(\n rec.test_name.capitalize(),\n jtu.format_shape_dtype_string(shape, dtype), axis, keepdims),\n \"rng_factory\": rec.rng_factory, \"shape\": shape, \"dtype\": dtype,\n \"onp_op\": getattr(onp, rec.name), \"jnp_op\": getattr(jnp, rec.name),\n \"axis\": axis, \"keepdims\": keepdims, \"inexact\": rec.inexact}\n for rec in JAX_REDUCER_NO_DTYPE_RECORDS\n for shape in rec.shapes for dtype in rec.dtypes\n for axis in list(range(-len(shape), len(shape))) + [None]\n for keepdims in [False, True]))\n def testReducerNoDtype(self, onp_op, jnp_op, rng_factory, shape, dtype, axis,\n keepdims, inexact):\n rng = rng_factory()\n onp_fun = lambda x: onp_op(x, axis, keepdims=keepdims)\n onp_fun = _promote_like_jnp(onp_fun, inexact)\n onp_fun = jtu.ignore_warning(category=onp.ComplexWarning)(onp_fun)\n jnp_fun = lambda x: jnp_op(x, axis, keepdims=keepdims)\n jnp_fun = jtu.ignore_warning(category=jnp.ComplexWarning)(jnp_fun)\n args_maker = lambda: [rng(shape, dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_axis={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), axis),\n \"shape\": shape, \"dtype\": dtype, \"axis\": axis}\n for shape in all_shapes for dtype in all_dtypes\n for axis in list(range(-len(shape), len(shape))) + [None]))\n def testCountNonzero(self, shape, dtype, axis):\n rng = jtu.rand_some_zero()\n onp_fun = lambda x: onp.count_nonzero(x, axis)\n jnp_fun = lambda x: jnp.count_nonzero(x, axis)\n args_maker = lambda: [rng(shape, dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}\".format(\n jtu.format_shape_dtype_string(shape, dtype)),\n \"shape\": shape, \"dtype\": dtype}\n for shape in all_shapes for dtype in all_dtypes))\n def testNonzero(self, shape, dtype):\n rng = jtu.rand_some_zero()\n onp_fun = lambda x: onp.nonzero(x)\n onp_fun = jtu.ignore_warning(\n category=DeprecationWarning,\n message=\"Calling nonzero on 0d arrays.*\")(onp_fun)\n jnp_fun = lambda x: jnp.nonzero(x)\n args_maker = lambda: [rng(shape, dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"{}_inshape={}_axis={}\".format(\n rec.test_name.capitalize(),\n jtu.format_shape_dtype_string(shape, dtype), axis),\n \"rng_factory\": rec.rng_factory, \"shape\": shape, \"dtype\": dtype,\n \"onp_op\": getattr(onp, rec.name), \"jnp_op\": getattr(jnp, rec.name),\n \"axis\": axis}\n for rec in JAX_ARGMINMAX_RECORDS\n for shape, dtype in _shape_and_dtypes(rec.shapes, rec.dtypes)\n for axis in range(-len(shape), len(shape))))\n def testArgMinMax(self, onp_op, jnp_op, rng_factory, shape, dtype, axis):\n rng = rng_factory()\n if dtype == onp.complex128 and jtu.device_under_test() == \"gpu\":\n raise unittest.SkipTest(\"complex128 reductions not supported on GPU\")\n\n def onp_fun(array_to_reduce):\n return onp_op(array_to_reduce, axis).astype(jnp.int_)\n\n def jnp_fun(array_to_reduce):\n return jnp_op(array_to_reduce, axis)\n\n args_maker = lambda: [rng(shape, dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_{}_{}\".format(\n jtu.format_shape_dtype_string(lhs_shape, lhs_dtype),\n jtu.format_shape_dtype_string(rhs_shape, rhs_dtype),\n axes),\n \"lhs_shape\": lhs_shape, \"lhs_dtype\": lhs_dtype,\n \"rhs_shape\": rhs_shape, \"rhs_dtype\": rhs_dtype,\n \"axes\": axes, \"rng_factory\": rng_factory}\n for rng_factory in [jtu.rand_default]\n for lhs_shape, rhs_shape, axes in [\n [(2,), (2,), (-1, -1, -1, None)], # scalar output\n [(2, 4), (2, 4), (-1, -1, -1, 0)], # 2D vectors\n [(3, 4), (3, 4), (-1, -1, -1, 0)], # 3D vectors\n [(3, 4), (3, 6, 5, 4), (-1, -1, -1, 0)], # broadcasting\n [(4, 3), (3, 6, 5, 4), (1, 0, -1, None)], # different axes\n [(6, 1, 3), (5, 3), (-1, -1, -1, None)], # more broadcasting\n [(6, 1, 2), (5, 3), (-1, -1, -1, None)], # mixed 2D and 3D vectors\n [(10, 5, 2, 8), (1, 5, 1, 3), (-2, -1, -3, None)], # axes/broadcasting\n [(4, 5, 2), (4, 5, 2), (-1, -1, 0, None)], # axisc should do nothing\n [(4, 5, 2), (4, 5, 2), (-1, -1, -1, None)] # same as before\n ]\n for lhs_dtype, rhs_dtype in CombosWithReplacement(number_dtypes, 2)))\n def testCross(self, lhs_shape, lhs_dtype, rhs_shape, rhs_dtype, axes, rng_factory):\n rng = rng_factory()\n args_maker = lambda: [rng(lhs_shape, lhs_dtype), rng(rhs_shape, rhs_dtype)]\n axisa, axisb, axisc, axis = axes\n jnp_fun = lambda a, b: jnp.cross(a, b, axisa, axisb, axisc, axis)\n def onp_fun(a, b):\n a = a.astype(onp.float32) if lhs_dtype == jnp.bfloat16 else a\n b = b.astype(onp.float32) if rhs_dtype == jnp.bfloat16 else b\n out = onp.cross(a, b, axisa, axisb, axisc, axis)\n return out.astype(jnp.promote_types(lhs_dtype, rhs_dtype))\n tol_spec = {dtypes.bfloat16: 3e-1, onp.float16: 0.15}\n tol = max(jtu.tolerance(lhs_dtype, tol_spec),\n jtu.tolerance(rhs_dtype, tol_spec))\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True,\n tol=tol)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True, atol=tol,\n rtol=tol)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_{}_{}\".format(\n name,\n jtu.format_shape_dtype_string(lhs_shape, lhs_dtype),\n jtu.format_shape_dtype_string(rhs_shape, rhs_dtype)),\n \"lhs_shape\": lhs_shape, \"lhs_dtype\": lhs_dtype,\n \"rhs_shape\": rhs_shape, \"rhs_dtype\": rhs_dtype,\n \"rng_factory\": rng_factory}\n for rng_factory in [jtu.rand_default]\n for name, lhs_shape, rhs_shape in [\n (\"matrix-scalar\", (3, 3), ()),\n (\"scalar-matrix\", (), (3, 3)),\n (\"matrix-vector\", (4, 5), (5,)),\n (\"vector-matrix\", (6,), (6, 4)),\n (\"matrix-matrix\", (3, 4), (4, 5)),\n (\"tensor-vector\", (4, 3, 2), (2,)),\n (\"vector-tensor\", (2,), (3, 2, 4)),\n (\"tensor-matrix\", (4, 3, 2), (2, 5)),\n (\"matrix-tensor\", (5, 2), (3, 2, 4)),\n (\"tensor-tensor\", (2, 3, 4), (5, 4, 1))]\n for lhs_dtype, rhs_dtype in CombosWithReplacement(number_dtypes, 2)))\n def testDot(self, lhs_shape, lhs_dtype, rhs_shape, rhs_dtype, rng_factory):\n rng = rng_factory()\n args_maker = lambda: [rng(lhs_shape, lhs_dtype), rng(rhs_shape, rhs_dtype)]\n tol = {onp.float16: 1e-2, onp.float32: 1e-5, onp.float64: 1e-14,\n onp.complex128: 1e-14}\n if jtu.device_under_test() == \"tpu\":\n tol[onp.float32] = tol[onp.complex64] = 2e-1\n def onp_dot(x, y):\n x = x.astype(onp.float32) if lhs_dtype == jnp.bfloat16 else x\n y = y.astype(onp.float32) if rhs_dtype == jnp.bfloat16 else y\n return onp.dot(x, y).astype(jnp.promote_types(lhs_dtype, rhs_dtype))\n self._CheckAgainstNumpy(onp_dot, jnp.dot, args_maker, check_dtypes=True,\n tol=tol)\n self._CompileAndCheck(jnp.dot, args_maker, check_dtypes=True, atol=tol,\n rtol=tol)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_{}_{}\".format(\n name,\n jtu.format_shape_dtype_string(lhs_shape, lhs_dtype),\n jtu.format_shape_dtype_string(rhs_shape, rhs_dtype)),\n \"lhs_shape\": lhs_shape, \"lhs_dtype\": lhs_dtype,\n \"rhs_shape\": rhs_shape, \"rhs_dtype\": rhs_dtype,\n \"rng_factory\": rng_factory}\n for rng_factory in [jtu.rand_default]\n for name, lhs_shape, rhs_shape in [\n (\"vector-vector\", (3,), (3,)),\n (\"matrix-vector\", (3, 3), (3,)),\n (\"vector-matrix\", (3,), (3, 3)),\n (\"matrix-matrix\", (3, 3), (3, 3)),\n (\"vector-tensor\", (3,), (5, 3, 2)),\n (\"tensor-vector\", (5, 3, 2), (2,)),\n (\"matrix-tensor\", (5, 2), (3, 2, 4)),\n (\"tensor-matrix\", (5, 2, 3), (3, 2)),\n (\"tensor-tensor\", (5, 3, 4), (5, 4, 1)),\n (\"tensor-tensor-broadcast\", (3, 1, 3, 4), (5, 4, 1))]\n for lhs_dtype, rhs_dtype in CombosWithReplacement(number_dtypes, 2)))\n def testMatmul(self, lhs_shape, lhs_dtype, rhs_shape, rhs_dtype, rng_factory):\n rng = rng_factory()\n def onp_fun(x, y):\n dtype = jnp.promote_types(lhs_dtype, rhs_dtype)\n return onp.matmul(x, y).astype(dtype)\n args_maker = lambda: [rng(lhs_shape, lhs_dtype), rng(rhs_shape, rhs_dtype)]\n tol = {onp.float16: 1e-2, onp.float32: 2e-2, onp.float64: 1e-12,\n onp.complex128: 1e-12}\n if jtu.device_under_test() == \"tpu\":\n tol[onp.float32] = tol[onp.complex64] = 4e-2\n self._CheckAgainstNumpy(onp_fun, jnp.matmul, args_maker,\n check_dtypes=True, tol=tol)\n self._CompileAndCheck(jnp.matmul, args_maker, check_dtypes=True, atol=tol,\n rtol=tol)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_{}_{}\".format(\n jtu.format_shape_dtype_string(lhs_shape, lhs_dtype),\n jtu.format_shape_dtype_string(rhs_shape, rhs_dtype),\n axes),\n \"lhs_shape\": lhs_shape, \"lhs_dtype\": lhs_dtype,\n \"rhs_shape\": rhs_shape, \"rhs_dtype\": rhs_dtype,\n \"axes\": axes, \"rng_factory\": rng_factory}\n for rng_factory in [jtu.rand_default]\n for lhs_shape, rhs_shape, axes in [\n [(3,), (), 0],\n [(2, 3, 4), (5, 6, 7), 0], # from issue #740\n [(2, 3, 4), (3, 4, 5, 6), 2],\n [(2, 3, 4), (5, 4, 3, 6), [1, 2]],\n [(2, 3, 4), (5, 4, 3, 6), [[1, 2], [2, 1]]],\n [(1, 2, 3, 4), (4, 5, 3, 6), [[2, 3], [2, 0]]],\n ]\n for lhs_dtype, rhs_dtype in CombosWithReplacement(number_dtypes, 2)))\n def testTensordot(self, lhs_shape, lhs_dtype, rhs_shape, rhs_dtype, axes, rng_factory):\n rng = rng_factory()\n args_maker = lambda: [rng(lhs_shape, lhs_dtype), rng(rhs_shape, rhs_dtype)]\n jnp_fun = lambda a, b: jnp.tensordot(a, b, axes)\n def onp_fun(a, b):\n a = a if lhs_dtype != jnp.bfloat16 else a.astype(onp.float32)\n b = b if rhs_dtype != jnp.bfloat16 else b.astype(onp.float32)\n dtype = jnp.promote_types(lhs_dtype, rhs_dtype)\n return onp.tensordot(a, b, axes).astype(dtype)\n tol = {onp.float16: 1e-1, onp.float32: 1e-3, onp.float64: 1e-12,\n onp.complex64: 1e-3, onp.complex128: 1e-12}\n if jtu.device_under_test() == \"tpu\":\n tol[onp.float32] = tol[onp.complex64] = 2e-1\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True,\n tol=tol)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n def testTensordotErrors(self):\n a = onp.random.random((3, 2, 2))\n b = onp.random.random((2,))\n self.assertRaisesRegex(\n TypeError, \"Number of tensordot axes.*exceeds input ranks.*\",\n lambda: jnp.tensordot(a, b, axes=2))\n\n self.assertRaisesRegex(\n TypeError, \"tensordot requires axes lists to have equal length.*\",\n lambda: jnp.tensordot(a, b, axes=([0], [0, 1])))\n\n self.assertRaisesRegex(\n TypeError, \"tensordot requires both axes lists to be either ints, tuples or lists.*\",\n lambda: jnp.tensordot(a, b, axes=('bad', 'axes')))\n\n self.assertRaisesRegex(\n TypeError, \"tensordot axes argument must be an int, a pair of ints, or a pair of lists.*\",\n lambda: jnp.tensordot(a, b, axes='badaxes'))\n\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_{}\".format(\n jtu.format_shape_dtype_string(lhs_shape, lhs_dtype),\n jtu.format_shape_dtype_string(rhs_shape, rhs_dtype)),\n \"lhs_shape\": lhs_shape, \"lhs_dtype\": lhs_dtype,\n \"rhs_shape\": rhs_shape, \"rhs_dtype\": rhs_dtype,\n \"rng_factory\": jtu.rand_default}\n # TODO(phawkins): support integer dtypes too.\n for lhs_shape, lhs_dtype in _shape_and_dtypes(all_shapes, inexact_dtypes)\n for rhs_shape, rhs_dtype in _shape_and_dtypes(all_shapes, inexact_dtypes)\n if len(jtu._dims_of_shape(lhs_shape)) == 0\n or len(jtu._dims_of_shape(rhs_shape)) == 0\n or lhs_shape[-1] == rhs_shape[-1]))\n def testInner(self, lhs_shape, lhs_dtype, rhs_shape, rhs_dtype, rng_factory):\n rng = rng_factory()\n args_maker = lambda: [rng(lhs_shape, lhs_dtype), rng(rhs_shape, rhs_dtype)]\n def onp_fun(lhs, rhs):\n lhs = lhs if lhs_dtype != jnp.bfloat16 else lhs.astype(onp.float32)\n rhs = rhs if rhs_dtype != jnp.bfloat16 else rhs.astype(onp.float32)\n dtype = jnp.promote_types(lhs_dtype, rhs_dtype)\n return onp.inner(lhs, rhs).astype(dtype)\n jnp_fun = lambda lhs, rhs: jnp.inner(lhs, rhs)\n tol_spec = {onp.float16: 1e-2, onp.float32: 1e-5, onp.float64: 1e-13}\n if jtu.device_under_test() == \"tpu\":\n tol_spec[onp.float32] = tol_spec[onp.complex64] = 2e-1\n tol = max(jtu.tolerance(lhs_dtype, tol_spec),\n jtu.tolerance(rhs_dtype, tol_spec))\n # TODO(phawkins): there are float32/float64 disagreements for some inputs.\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False,\n tol=tol)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=False, atol=tol,\n rtol=tol)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_amin={}_amax={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), a_min, a_max),\n \"shape\": shape, \"dtype\": dtype, \"a_min\": a_min, \"a_max\": a_max,\n \"rng_factory\": jtu.rand_default}\n for shape in all_shapes for dtype in number_dtypes\n for a_min, a_max in [(-1, None), (None, 1), (-1, 1),\n (-onp.ones(1), None),\n (None, onp.ones(1)),\n (-onp.ones(1), onp.ones(1))]))\n def testClipStaticBounds(self, shape, dtype, a_min, a_max, rng_factory):\n rng = rng_factory()\n onp_fun = lambda x: onp.clip(x, a_min=a_min, a_max=a_max)\n jnp_fun = lambda x: jnp.clip(x, a_min=a_min, a_max=a_max)\n args_maker = lambda: [rng(shape, dtype)]\n # TODO(phawkins): the promotion behavior changed in Numpy 1.17.\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n def testClipError(self):\n with self.assertRaisesRegex(ValueError, \"At most one of a_min and a_max.*\"):\n jnp.clip(jnp.zeros((3,)))\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_decimals={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), decimals),\n \"shape\": shape, \"dtype\": dtype, \"decimals\": decimals,\n \"rng_factory\": jtu.rand_default}\n for shape, dtype in _shape_and_dtypes(all_shapes, number_dtypes)\n for decimals in [0, 1, -2]))\n def testRoundStaticDecimals(self, shape, dtype, decimals, rng_factory):\n rng = rng_factory()\n if jnp.issubdtype(dtype, onp.integer) and decimals < 0:\n self.skipTest(\"Integer rounding with decimals < 0 not implemented\")\n onp_fun = lambda x: onp.round(x, decimals=decimals)\n jnp_fun = lambda x: jnp.round(x, decimals=decimals)\n args_maker = lambda: [rng(shape, dtype)]\n tol = {jnp.bfloat16: 5e-2, onp.float16: 1e-2}\n check_dtypes = shape is not jtu.PYTHON_SCALAR_SHAPE\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker,\n check_dtypes=check_dtypes, tol=tol)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=check_dtypes,\n atol=tol, rtol=tol)\n\n def testOperatorRound(self):\n self.assertAllClose(round(onp.float32(7.532), 1),\n round(jnp.float32(7.5), 1), check_dtypes=True)\n self.assertAllClose(round(onp.float32(1.234), 2),\n round(jnp.float32(1.234), 2), check_dtypes=True)\n self.assertAllClose(round(onp.float32(1.234)),\n round(jnp.float32(1.234)), check_dtypes=False)\n self.assertAllClose(round(onp.float32(7.532), 1),\n round(jnp.array(7.5, jnp.float32), 1), check_dtypes=True)\n self.assertAllClose(round(onp.float32(1.234), 2),\n round(jnp.array(1.234, jnp.float32), 2), check_dtypes=True)\n self.assertAllClose(round(onp.float32(1.234)),\n round(jnp.array(1.234, jnp.float32)),\n check_dtypes=False)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_mode={}_rpadwidth={}_rconstantvalues={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), mode, pad_width_rank,\n constant_values_rank),\n \"shape\": shape, \"dtype\": dtype, \"mode\": mode,\n \"pad_width_rank\": pad_width_rank,\n \"constant_values_rank\": constant_values_rank,\n \"rng_factory\": jtu.rand_default,\n \"irng_factory\": partial(jtu.rand_int, 3)}\n for mode, constant_values_rank, shapes in [\n ('constant', 0, all_shapes),\n ('constant', 1, all_shapes),\n ('constant', 2, all_shapes),\n ('symmetric', None, nonempty_shapes),\n ('reflect', None, nonempty_shapes),\n ('wrap', None, nonempty_shapes),\n ('edge', None, nonempty_shapes),\n ]\n for shape, dtype in _shape_and_dtypes(shapes, all_dtypes)\n for pad_width_rank in range(3)))\n def testPad(self, shape, dtype, mode, pad_width_rank, constant_values_rank,\n rng_factory, irng_factory):\n rng = rng_factory()\n irng = irng_factory()\n pad_width = irng([len(shape), 2][2 - pad_width_rank:], onp.int32)\n def onp_fun(x, kwargs):\n if pad_width.size == 0:\n return x\n return onp.pad(x, pad_width, mode=mode, **kwargs)\n def jnp_fun(x, kwargs):\n return jnp.pad(x, pad_width, mode=mode, **kwargs)\n\n def args_maker():\n kwargs = {}\n if constant_values_rank:\n kwargs[\"constant_values\"] = rng(\n [len(shape), 2][2 - constant_values_rank:], dtype)\n return rng(shape, dtype), kwargs\n\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker,\n check_dtypes=shape is not jtu.PYTHON_SCALAR_SHAPE)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape=[{}]_reps={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), reps),\n \"shape\": shape, \"dtype\": dtype, \"reps\": reps,\n \"rng_factory\": jtu.rand_default}\n for reps in [(), (2,), (3, 4), (2, 3, 4)]\n for shape, dtype in _shape_and_dtypes(all_shapes, default_dtypes)\n ))\n def testTile(self, shape, dtype, reps, rng_factory):\n rng = rng_factory()\n onp_fun = lambda arg: onp.tile(arg, reps)\n jnp_fun = lambda arg: jnp.tile(arg, reps)\n\n args_maker = lambda: [rng(shape, dtype)]\n\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker,\n check_dtypes=shape is not jtu.PYTHON_SCALAR_SHAPE)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_axis={}_baseshape=[{}]_dtypes=[{}]\".format(\n axis, \",\".join(str(d) for d in base_shape),\n \",\".join(onp.dtype(dtype).name for dtype in arg_dtypes)),\n \"axis\": axis, \"base_shape\": base_shape, \"arg_dtypes\": arg_dtypes,\n \"rng_factory\": jtu.rand_default}\n for num_arrs in [3]\n for arg_dtypes in CombosWithReplacement(default_dtypes, num_arrs)\n for base_shape in [(4,), (3, 4), (2, 3, 4)]\n for axis in range(-len(base_shape)+1, len(base_shape))))\n def testConcatenate(self, axis, base_shape, arg_dtypes, rng_factory):\n rng = rng_factory()\n wrapped_axis = axis % len(base_shape)\n shapes = [base_shape[:wrapped_axis] + (size,) + base_shape[wrapped_axis+1:]\n for size, _ in zip(itertools.cycle([3, 1, 4]), arg_dtypes)]\n def onp_fun(*args):\n args = [x if x.dtype != jnp.bfloat16 else x.astype(onp.float32)\n for x in args]\n dtype = functools.reduce(jnp.promote_types, arg_dtypes)\n return onp.concatenate(args, axis=axis).astype(dtype)\n jnp_fun = lambda *args: jnp.concatenate(args, axis=axis)\n\n def args_maker():\n return [rng(shape, dtype) for shape, dtype in zip(shapes, arg_dtypes)]\n\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_axis={}_baseshape=[{}]_dtypes=[{}]\".format(\n axis, \",\".join(str(d) for d in base_shape),\n \",\".join(onp.dtype(dtype).name for dtype in arg_dtypes)),\n \"axis\": axis, \"base_shape\": base_shape, \"arg_dtypes\": arg_dtypes,\n \"rng_factory\": jtu.rand_default}\n for arg_dtypes in CombosWithReplacement(default_dtypes, 2)\n for base_shape in [(4,), (3, 4), (2, 3, 4)]\n for axis in range(-len(base_shape)+1, len(base_shape))))\n def testAppend(self, axis, base_shape, arg_dtypes, rng_factory):\n rng = rng_factory()\n wrapped_axis = axis % len(base_shape)\n shapes = [base_shape[:wrapped_axis] + (size,) + base_shape[wrapped_axis+1:]\n for size, _ in zip(itertools.cycle([3, 1, 4]), arg_dtypes)]\n def onp_fun(arr, values):\n arr = arr.astype(onp.float32) if arr.dtype == jnp.bfloat16 else arr\n values = (values.astype(onp.float32) if values.dtype == jnp.bfloat16\n else values)\n out = onp.append(arr, values, axis=axis)\n return out.astype(jnp.promote_types(*arg_dtypes))\n jnp_fun = lambda arr, values: jnp.append(arr, values, axis=axis)\n\n def args_maker():\n return [rng(shape, dtype) for shape, dtype in zip(shapes, arg_dtypes)]\n\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape=[{}]_axis={}_repeats={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), axis, repeats),\n \"axis\": axis, \"shape\": shape, \"dtype\": dtype, \"repeats\": repeats,\n \"rng_factory\": jtu.rand_default}\n for repeats in [0, 1, 2]\n for shape, dtype in _shape_and_dtypes(all_shapes, default_dtypes)\n for axis in [None] + list(range(-len(shape), len(shape)))))\n def testRepeat(self, axis, shape, dtype, repeats, rng_factory):\n rng = rng_factory()\n onp_fun = lambda arg: onp.repeat(arg, repeats=repeats, axis=axis)\n onp_fun = _promote_like_jnp(onp_fun)\n jnp_fun = lambda arg: jnp.repeat(arg, repeats=repeats, axis=axis)\n\n args_maker = lambda: [rng(shape, dtype)]\n\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n def testIssue1233(self):\n '''\n Following numpy test suite from `test_repeat` at https://github.com/numpy/numpy/blob/master/numpy/core/tests/test_multiarray.py\n '''\n tol = 1e-5\n\n def test_single(m, args_maker, repeats, axis):\n lax_ans = jnp.repeat(m, repeats, axis)\n numpy_ans = onp.repeat(m, repeats, axis)\n\n self.assertAllClose(lax_ans, numpy_ans, check_dtypes=True, rtol=tol, atol=tol)\n\n jnp_fun = lambda arg: jnp.repeat(arg, repeats = repeats, axis=axis)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n m = jnp.array([1,2,3,4,5,6])\n args_maker = lambda: [m]\n\n for repeats in [2, [1,3,2,1,1,2], [1,3,0,1,1,2], [2], jnp.array([1,3,2,1,1,2]), jnp.array([2])]:\n test_single(m, args_maker, repeats, None)\n\n m_rect = m.reshape((2,3))\n args_maker = lambda: [m_rect]\n\n for repeats in [2, [2,1], [2], jnp.array([2,1]), jnp.array([2])]:\n test_single(m_rect, args_maker, repeats, axis=0)\n\n for repeats in [2, [1,3,2], [2], jnp.array([1,3,2]), jnp.array([2])]:\n test_single(m_rect, args_maker, repeats, axis=1)\n\n def testIssue2330(self):\n '''\n Make sure return value of jnp.concatenate is a jax.ndarray and is side-effect save\n '''\n def attempt_sideeffect(x):\n x = [x]\n x = jnp.concatenate(x)\n x -= 1.\n return x\n\n onp_input = onp.ones((1))\n jnp_input = jnp.ones((1))\n expected_onp_input_after_call = onp.ones((1))\n expected_jnp_input_after_call = jnp.ones((1))\n\n self.assertIs(type(jnp.concatenate([onp_input])), jnp.DeviceArray)\n\n attempt_sideeffect(onp_input)\n attempt_sideeffect(jnp_input)\n\n self.assertAllClose(onp_input, expected_onp_input_after_call, check_dtypes=True)\n self.assertAllClose(jnp_input, expected_jnp_input_after_call, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"op={}_xshape=[{}]_yshape=[{}]_mode={}\".format(\n op,\n jtu.format_shape_dtype_string(xshape, dtype),\n jtu.format_shape_dtype_string(yshape, dtype),\n mode),\n \"xshape\": xshape, \"yshape\": yshape, \"dtype\": dtype, \"mode\": mode,\n \"rng_factory\": jtu.rand_default,\n \"jnp_op\": getattr(jnp, op),\n \"onp_op\": getattr(onp, op)}\n for mode in ['full', 'same', 'valid']\n for op in ['convolve', 'correlate']\n for dtype in default_dtypes\n for xshape in one_dim_array_shapes\n for yshape in one_dim_array_shapes))\n def testConvolutions(self, xshape, yshape, dtype, mode, rng_factory, jnp_op, onp_op):\n rng = rng_factory()\n args_maker = lambda: [rng(xshape, dtype), rng(yshape, dtype)]\n onp_fun = partial(onp_op, mode=mode)\n jnp_fun = partial(jnp_op, mode=mode)\n tol = 1e-2 if jtu.device_under_test() != \"tpu\" else 0.5\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False, tol=tol)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"op={}_shape=[{}]_axis={}_out_dtype={}\".format(\n op, jtu.format_shape_dtype_string(shape, dtype), axis,\n out_dtype.__name__),\n \"axis\": axis, \"shape\": shape, \"dtype\": dtype, \"out_dtype\": out_dtype,\n \"rng_factory\": jtu.rand_default, \"jnp_op\": getattr(jnp, op),\n \"onp_op\": getattr(onp, op)}\n for op in [\"cumsum\", \"cumprod\"]\n for dtype in all_dtypes\n for out_dtype in default_dtypes\n for shape in all_shapes\n for axis in [None] + list(range(-len(shape), len(shape)))))\n def testCumSumProd(self, axis, shape, dtype, out_dtype, onp_op, jnp_op, rng_factory):\n rng = rng_factory()\n onp_fun = lambda arg: onp_op(arg, axis=axis, dtype=out_dtype)\n onp_fun = jtu.ignore_warning(category=onp.ComplexWarning)(onp_fun)\n jnp_fun = lambda arg: jnp_op(arg, axis=axis, dtype=out_dtype)\n jnp_fun = jtu.ignore_warning(category=jnp.ComplexWarning)(jnp_fun)\n\n args_maker = lambda: [rng(shape, dtype)]\n\n tol = max(jtu.tolerance(dtype), jtu.tolerance(out_dtype))\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True,\n tol=tol)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_dtype={}_m={}_n={}_k={}\".format(\n onp.dtype(dtype).name, m, n, k),\n \"m\": m, \"n\": n, \"k\": k, \"dtype\": dtype, \"rng_factory\": jtu.rand_default}\n for dtype in default_dtypes\n for n in [0, 4]\n for m in [None, 0, 1, 3, 4]\n for k in list(range(-4, 4))))\n def testTri(self, m, n, k, dtype, rng_factory):\n rng = rng_factory()\n onp_fun = lambda: onp.tri(n, M=m, k=k, dtype=dtype)\n jnp_fun = lambda: jnp.tri(n, M=m, k=k, dtype=dtype)\n args_maker = lambda: []\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_op={}_shape={}_k={}\".format(\n op, jtu.format_shape_dtype_string(shape, dtype), k),\n \"dtype\": dtype, \"shape\": shape, \"op\": op, \"k\": k,\n \"rng_factory\": jtu.rand_default}\n for dtype in default_dtypes\n for shape in [shape for shape in all_shapes if len(shape) >= 2]\n for op in [\"tril\", \"triu\"]\n for k in list(range(-3, 3))))\n def testTriLU(self, dtype, shape, op, k, rng_factory):\n rng = rng_factory()\n onp_fun = lambda arg: getattr(onp, op)(arg, k=k)\n jnp_fun = lambda arg: getattr(jnp, op)(arg, k=k)\n args_maker = lambda: [rng(shape, dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_ndim={}_n={}\".format(ndim, n),\n \"ndim\": ndim, \"n\": n}\n for ndim in [0, 1, 4]\n for n in [0, 1, 7]))\n def testDiagIndices(self, ndim, n):\n onp.testing.assert_equal(onp.diag_indices(n, ndim),\n jnp.diag_indices(n, ndim))\n\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_k={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), k),\n \"dtype\": dtype, \"shape\": shape, \"k\": k, \"rng_factory\": jtu.rand_default}\n for dtype in default_dtypes\n for shape in [shape for shape in all_shapes if len(shape) in (1, 2)]\n for k in list(range(-4, 4))))\n def testDiag(self, shape, dtype, k, rng_factory):\n rng = rng_factory()\n onp_fun = lambda arg: onp.diag(arg, k)\n jnp_fun = lambda arg: jnp.diag(arg, k)\n args_maker = lambda: [rng(shape, dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_offset={}_axis1={}_axis2={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), offset, axis1, axis2),\n \"dtype\": dtype, \"shape\": shape, \"offset\": offset, \"axis1\": axis1,\n \"axis2\": axis2, \"rng_factory\": jtu.rand_default}\n for dtype in default_dtypes\n for shape in [shape for shape in all_shapes if len(shape) >= 2]\n for axis1 in range(-len(shape), len(shape))\n for axis2 in [a for a in range(-len(shape), len(shape))\n if a % len(shape) != axis1 % len(shape)]\n for offset in list(range(-4, 4))))\n def testDiagonal(self, shape, dtype, offset, axis1, axis2, rng_factory):\n rng = rng_factory()\n onp_fun = lambda arg: onp.diagonal(arg, offset, axis1, axis2)\n jnp_fun = lambda arg: jnp.diagonal(arg, offset, axis1, axis2)\n args_maker = lambda: [rng(shape, dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_n={}\".format(onp.dtype(dtype).name, n),\n \"dtype\": dtype, \"n\": n}\n for dtype in default_dtypes\n for n in list(range(4))))\n def testIdentity(self, n, dtype):\n onp_fun = lambda: onp.identity(n, dtype)\n jnp_fun = lambda: jnp.identity(n, dtype)\n args_maker = lambda: []\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_x1={}_x2={}_x1_rng={}\".format(\n jtu.format_shape_dtype_string(x1_shape, x1_dtype),\n jtu.format_shape_dtype_string(x2_shape, onp.int32),\n x1_rng_factory_id),\n \"x1_shape\": x1_shape, \"x1_dtype\": x1_dtype,\n \"x2_shape\": x2_shape, \"x1_rng_factory\": x1_rng_factory,\n \"x2_rng_factory\": x2_rng_factory}\n for x1_rng_factory_id, x1_rng_factory in\n enumerate([jtu.rand_some_inf_and_nan, jtu.rand_some_zero])\n for x2_rng_factory in [partial(jtu.rand_int, -1075, 1024)]\n for x1_shape, x2_shape in filter(_shapes_are_broadcast_compatible,\n CombosWithReplacement(array_shapes, 2))\n for x1_dtype in default_dtypes))\n @jtu.skip_on_devices(\"tpu\") # TODO(b/153053081)\n def testLdexp(self, x1_shape, x1_dtype, x2_shape, x1_rng_factory, x2_rng_factory):\n # integer types are converted to float64 in numpy's implementation\n if (x1_dtype not in [jnp.bfloat16, onp.float16, onp.float32]\n and not FLAGS.jax_enable_x64):\n self.skipTest(\"Only run float64 testcase when float64 is enabled.\")\n x1_rng = x1_rng_factory()\n x2_rng = x2_rng_factory()\n onp_fun = lambda x1, x2: onp.ldexp(x1, x2)\n onp_fun = jtu.ignore_warning(category=RuntimeWarning,\n message=\"overflow.*\")(onp_fun)\n jnp_fun = lambda x1, x2: jnp.ldexp(x1, x2)\n args_maker = lambda: [x1_rng(x1_shape, x1_dtype),\n x2_rng(x2_shape, onp.int32)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_x={}_rng_factory={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), rng_factory_id),\n \"shape\": shape, \"dtype\": dtype, \"rng_factory\": rng_factory}\n for rng_factory_id, rng_factory in enumerate([\n jtu.rand_some_inf_and_nan,\n jtu.rand_some_zero,\n partial(jtu.rand_not_small, offset=1e8),\n ])\n for shape in all_shapes\n for dtype in default_dtypes))\n @jtu.skip_on_devices(\"tpu\")\n def testFrexp(self, shape, dtype, rng_factory):\n # integer types are converted to float64 in numpy's implementation\n if (dtype not in [jnp.bfloat16, onp.float16, onp.float32]\n and not FLAGS.jax_enable_x64):\n self.skipTest(\"Only run float64 testcase when float64 is enabled.\")\n rng = rng_factory()\n onp_fun = lambda x: onp.frexp(x)\n jnp_fun = lambda x: jnp.frexp(x)\n args_maker = lambda: [rng(shape, dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_dtype_{}_offset={}_axis1={}_axis2={}\".format(\n jtu.format_shape_dtype_string(shape, dtype),\n out_dtype, offset, axis1, axis2),\n \"dtype\": dtype, \"out_dtype\": out_dtype, \"shape\": shape, \"offset\": offset,\n \"axis1\": axis1, \"axis2\": axis2, \"rng_factory\": jtu.rand_default}\n for dtype in default_dtypes\n for out_dtype in [None] + number_dtypes\n for shape in [shape for shape in all_shapes if len(shape) >= 2]\n for axis1 in range(-len(shape), len(shape))\n for axis2 in range(-len(shape), len(shape))\n if (axis1 % len(shape)) != (axis2 % len(shape))\n for offset in list(range(-4, 4))))\n def testTrace(self, shape, dtype, out_dtype, offset, axis1, axis2, rng_factory):\n rng = rng_factory()\n def onp_fun(arg):\n if out_dtype == jnp.bfloat16:\n return onp.trace(arg, offset, axis1, axis2, onp.float32).astype(jnp.bfloat16)\n else:\n return onp.trace(arg, offset, axis1, axis2, out_dtype)\n jnp_fun = lambda arg: jnp.trace(arg, offset, axis1, axis2, out_dtype)\n args_maker = lambda: [rng(shape, dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_axis={}\".format(\n jtu.format_test_name_suffix(\"\", [shape] * len(dtypes), dtypes), axis),\n \"shape\": shape, \"axis\": axis, \"dtypes\": dtypes, \"rng_factory\": rng_factory}\n for dtypes in [\n [onp.float32],\n [onp.float32, onp.float32],\n [onp.float32, onp.int32, onp.float32],\n [onp.float32, onp.int64, onp.float32],\n [onp.float32, onp.int32, onp.float64],\n ]\n for shape in [(), (2,), (3, 4), (1, 100)]\n for axis in range(-len(shape), len(shape) + 1)\n for rng_factory in [jtu.rand_default]))\n def testStack(self, shape, axis, dtypes, rng_factory):\n rng = rng_factory()\n args_maker = lambda: [[rng(shape, dtype) for dtype in dtypes]]\n onp_fun = _promote_like_jnp(partial(onp.stack, axis=axis))\n jnp_fun = partial(jnp.stack, axis=axis)\n self._CheckAgainstNumpy(jnp_fun, onp_fun, args_maker, check_dtypes=True)\n\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_op={}_{}\".format(\n op, jtu.format_test_name_suffix(\"\", [shape] * len(dtypes), dtypes)),\n \"shape\": shape, \"op\": op, \"dtypes\": dtypes, \"rng_factory\": rng_factory}\n for op in [\"hstack\", \"vstack\", \"dstack\"]\n for dtypes in [\n [onp.float32],\n [onp.float32, onp.float32],\n [onp.float32, onp.int32, onp.float32],\n [onp.float32, onp.int64, onp.float32],\n [onp.float32, onp.int32, onp.float64],\n ]\n for shape in [(), (2,), (3, 4), (1, 100), (2, 3, 4)]\n for rng_factory in [jtu.rand_default]))\n def testHVDStack(self, shape, op, dtypes, rng_factory):\n rng = rng_factory()\n args_maker = lambda: [[rng(shape, dtype) for dtype in dtypes]]\n onp_fun = _promote_like_jnp(getattr(onp, op))\n jnp_fun = getattr(jnp, op)\n self._CheckAgainstNumpy(jnp_fun, onp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_inshape={}_outdtype={}\".format(\n jtu.format_shape_dtype_string(shape, fill_value_dtype),\n onp.dtype(out_dtype).name if out_dtype else \"None\"),\n \"shape\": shape, \"fill_value_dtype\": fill_value_dtype,\n \"out_dtype\": out_dtype, \"rng_factory\": jtu.rand_default}\n for shape in array_shapes + [3, onp.array(7, dtype=onp.int32)]\n for fill_value_dtype in default_dtypes\n for out_dtype in [None] + default_dtypes))\n def testFull(self, shape, fill_value_dtype, out_dtype, rng_factory):\n rng = rng_factory()\n onp_fun = lambda fill_value: onp.full(shape, fill_value, dtype=out_dtype)\n jnp_fun = lambda fill_value: jnp.full(shape, fill_value, dtype=out_dtype)\n args_maker = lambda: [rng((), fill_value_dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(\n jtu.cases_from_list(\n {\"testcase_name\": (\"_op={}_shape={}_dtype={}\").format(op, shape, dtype),\n \"onp_op\": getattr(onp, op), \"jnp_op\": getattr(jnp, op),\n \"shape\": shape, \"dtype\": dtype}\n for op in [\"zeros\", \"ones\"]\n for shape in [2, (), (2,), (3, 0), onp.array((4, 5, 6), dtype=onp.int32),\n onp.array(4, dtype=onp.int32)]\n for dtype in all_dtypes))\n def testZerosOnes(self, onp_op, jnp_op, shape, dtype):\n rng = jtu.rand_default()\n def args_maker(): return []\n onp_op = partial(onp_op, shape, dtype)\n jnp_op = partial(jnp_op, shape, dtype)\n self._CheckAgainstNumpy(onp_op, jnp_op, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)\n\n def testOnesWithInvalidShape(self):\n with self.assertRaises(TypeError):\n jnp.ones((-1, 1))\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_inshape={}_filldtype={}_outdtype={}\".format(\n jtu.format_shape_dtype_string(shape, in_dtype),\n onp.dtype(fill_value_dtype).name,\n onp.dtype(out_dtype).name),\n \"shape\": shape, \"in_dtype\": in_dtype,\n \"fill_value_dtype\": fill_value_dtype, \"out_dtype\": out_dtype,\n \"rng_factory\": jtu.rand_default}\n for shape in array_shapes\n for in_dtype in default_dtypes\n for fill_value_dtype in default_dtypes\n for out_dtype in default_dtypes))\n def testFullLike(self, shape, in_dtype, fill_value_dtype, out_dtype, rng_factory):\n rng = rng_factory()\n onp_fun = lambda x, fill_value: onp.full_like(x, fill_value, dtype=out_dtype)\n jnp_fun = lambda x, fill_value: jnp.full_like(x, fill_value, dtype=out_dtype)\n args_maker = lambda: [rng(shape, in_dtype), rng((), fill_value_dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_axis={}_{}sections\".format(\n jtu.format_shape_dtype_string(shape, dtype), axis, num_sections),\n \"shape\": shape, \"num_sections\": num_sections, \"axis\": axis,\n \"dtype\": dtype, \"rng_factory\": jtu.rand_default}\n for shape, axis, num_sections in [\n ((3,), 0, 3), ((12,), 0, 3), ((12, 4), 0, 4), ((12, 4), 1, 2),\n ((2, 3, 4), -1, 2), ((2, 3, 4), -2, 3)]\n for dtype in default_dtypes))\n def testSplitStaticInt(self, shape, num_sections, axis, dtype, rng_factory):\n rng = rng_factory()\n onp_fun = lambda x: onp.split(x, num_sections, axis=axis)\n jnp_fun = lambda x: jnp.split(x, num_sections, axis=axis)\n args_maker = lambda: [rng(shape, dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_axis={}_{}sections\".format(\n jtu.format_shape_dtype_string(shape, dtype), axis, num_sections),\n \"shape\": shape, \"num_sections\": num_sections, \"axis\": axis,\n \"dtype\": dtype, \"rng_factory\": jtu.rand_default}\n for shape, axis, num_sections in [\n ((12, 4), 0, 4), ((12, 4), 1, 2),\n ((2, 3, 4), 2, 2), ((4, 3, 4), 0, 2)]\n for dtype in default_dtypes))\n def testHVDSplit(self, shape, num_sections, axis, dtype, rng_factory):\n rng = rng_factory()\n def fn(module, axis):\n if axis == 0:\n return module.vsplit\n elif axis == 1:\n return module.hsplit\n else:\n assert axis == 2\n return module.dsplit\n\n onp_fun = lambda x: fn(onp, axis)(x, num_sections)\n jnp_fun = lambda x: fn(jnp, axis)(x, num_sections)\n args_maker = lambda: [rng(shape, dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_inshape={}_outshape={}_order={}\".format(\n jtu.format_shape_dtype_string(arg_shape, dtype),\n jtu.format_shape_dtype_string(out_shape, dtype),\n order),\n \"arg_shape\": arg_shape, \"out_shape\": out_shape, \"dtype\": dtype,\n \"order\": order, \"rng_factory\": jtu.rand_default}\n for dtype in default_dtypes\n for order in [\"C\", \"F\"]\n for arg_shape, out_shape in [\n (jtu.NUMPY_SCALAR_SHAPE, (1, 1, 1)),\n ((), (1, 1, 1)),\n ((7, 0), (0, 42, 101)),\n ((3, 4), 12),\n ((3, 4), (12,)),\n ((3, 4), -1),\n ((2, 1, 4), (-1,)),\n ((2, 2, 4), (2, 8))\n ]))\n def testReshape(self, arg_shape, out_shape, dtype, order, rng_factory):\n rng = rng_factory()\n onp_fun = lambda x: onp.reshape(x, out_shape, order=order)\n jnp_fun = lambda x: jnp.reshape(x, out_shape, order=order)\n args_maker = lambda: [rng(arg_shape, dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_inshape={}_outshape={}\".format(\n jtu.format_shape_dtype_string(arg_shape, dtype),\n jtu.format_shape_dtype_string(out_shape, dtype)),\n \"arg_shape\": arg_shape, \"out_shape\": out_shape, \"dtype\": dtype,\n \"rng_factory\": jtu.rand_default}\n for dtype in default_dtypes\n for arg_shape, out_shape in [\n ((7, 0), (0, 42, 101)),\n ((2, 1, 4), (-1,)),\n ((2, 2, 4), (2, 8))\n ]))\n def testReshapeMethod(self, arg_shape, out_shape, dtype, rng_factory):\n rng = rng_factory()\n onp_fun = lambda x: onp.reshape(x, out_shape)\n jnp_fun = lambda x: x.reshape(*out_shape)\n args_maker = lambda: [rng(arg_shape, dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_inshape={}_expanddim={}\".format(\n jtu.format_shape_dtype_string(arg_shape, dtype), dim),\n \"arg_shape\": arg_shape, \"dtype\": dtype, \"dim\": dim,\n \"rng_factory\": jtu.rand_default}\n for arg_shape in [(), (3,), (3, 4)]\n for dtype in default_dtypes\n for dim in range(-len(arg_shape)+1, len(arg_shape))))\n def testExpandDimsStaticDim(self, arg_shape, dtype, dim, rng_factory):\n rng = rng_factory()\n onp_fun = lambda x: onp.expand_dims(x, dim)\n jnp_fun = lambda x: jnp.expand_dims(x, dim)\n args_maker = lambda: [rng(arg_shape, dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_inshape={}_axes=({},{})\".format(\n jtu.format_shape_dtype_string(arg_shape, dtype), ax1, ax2),\n \"arg_shape\": arg_shape, \"dtype\": dtype, \"ax1\": ax1, \"ax2\": ax2,\n \"rng_factory\": jtu.rand_default}\n for arg_shape, ax1, ax2 in [\n ((3, 4), 0, 1), ((3, 4), 1, 0), ((3, 4, 5), 1, 2),\n ((3, 4, 5), -1, -2), ((3, 4, 5), 0, 1)]\n for dtype in default_dtypes))\n def testSwapAxesStaticAxes(self, arg_shape, dtype, ax1, ax2, rng_factory):\n rng = rng_factory()\n onp_fun = lambda x: onp.swapaxes(x, ax1, ax2)\n jnp_fun = lambda x: jnp.swapaxes(x, ax1, ax2)\n args_maker = lambda: [rng(arg_shape, dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_inshape={}_axis={}\".format(\n jtu.format_shape_dtype_string(arg_shape, dtype), ax),\n \"arg_shape\": arg_shape, \"dtype\": dtype, \"ax\": ax,\n \"rng_factory\": jtu.rand_default}\n for arg_shape, ax in [\n ((3, 1), None),\n ((3, 1), 1),\n ((1, 3, 1), (0, 2)),\n ((1, 4, 1), (0,))]\n for dtype in default_dtypes))\n def testSqueeze(self, arg_shape, dtype, ax, rng_factory):\n rng = rng_factory()\n onp_fun = lambda x: onp.squeeze(x, ax)\n jnp_fun = lambda x: jnp.squeeze(x, ax)\n args_maker = lambda: [rng(arg_shape, dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_inshape={}_axis={}\".format(\n jtu.format_shape_dtype_string(arg_shape, dtype), ax),\n \"arg_shape\": arg_shape, \"dtype\": dtype, \"ax\": ax,\n \"rng_factory\": jtu.rand_default}\n for arg_shape, ax in [\n ((3,), 0),\n ((1, 3), 1),\n ((1, 3, 1), (0, 1))]\n for dtype in default_dtypes))\n def testSqueezeFailsOnNonsingletonAxis(self, arg_shape, dtype, ax,\n rng_factory):\n rng = rng_factory()\n x = jnp.zeros(arg_shape, dtype=dtype)\n fun = lambda: jnp.squeeze(x, ax)\n self.assertRaisesRegex(ValueError, \"cannot select an axis to squeeze\", fun)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_axis={}_weights={}_returned={}\".format(\n jtu.format_shape_dtype_string(shape, dtype),\n axis,\n (None if weights_shape is None else jtu.format_shape_dtype_string(weights_shape, dtype)),\n returned),\n \"rng_factory\": jtu.rand_default, \"shape\": shape, \"dtype\": dtype, \"axis\": axis,\n \"weights_shape\": weights_shape, \"returned\": returned}\n for shape, dtype in _shape_and_dtypes(nonempty_shapes, number_dtypes)\n for axis in list(range(-len(shape), len(shape))) + [None]\n # `weights_shape` is either `None`, same as the averaged axis, or same as\n # that of the input\n for weights_shape in ([None, shape] if axis is None or len(shape) == 1\n else [None, (shape[axis],), shape])\n for returned in [False, True]))\n def testAverage(self, shape, dtype, axis, weights_shape, returned, rng_factory):\n rng = rng_factory()\n if weights_shape is None:\n onp_fun = lambda x: onp.average(x, axis, returned=returned)\n jnp_fun = lambda x: jnp.average(x, axis, returned=returned)\n args_maker = lambda: [rng(shape, dtype)]\n else:\n onp_fun = lambda x, weights: onp.average(x, axis, weights, returned)\n jnp_fun = lambda x, weights: jnp.average(x, axis, weights, returned)\n args_maker = lambda: [rng(shape, dtype), rng(weights_shape, dtype)]\n onp_fun = _promote_like_jnp(onp_fun, inexact=True)\n tol = {onp.float16: 1e-2, onp.float32: 1e-6, onp.float64: 1e-12,}\n check_dtypes = shape is not jtu.PYTHON_SCALAR_SHAPE\n try:\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker,\n check_dtypes=check_dtypes, tol=tol)\n except ZeroDivisionError:\n self.skipTest(\"don't support checking for ZeroDivisionError\")\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=check_dtypes,\n rtol=tol, atol=tol)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_arg{}_ndmin={}\".format(i, ndmin),\n \"arg\": arg, \"ndmin\": ndmin, \"dtype\": dtype}\n for i, (arg, dtype) in enumerate([\n ([True, False, True], jnp.bool_),\n (3., jnp.float_),\n ([1, 2, 3], jnp.int_),\n ([1., 2., 3.], jnp.float_),\n ([[1, 2], [3, 4], [5, 6]], jnp.int_),\n ([[1, 2.], [3, 4], [5, 6]], jnp.float_),\n ([[1., 2j], [3., 4.], [5., 6.]], jnp.complex_),\n ([[3, onp.array(2, dtype=jnp.float_), 1],\n onp.arange(3., dtype=jnp.float_)], jnp.float_),\n ])\n for ndmin in [None, onp.ndim(arg), onp.ndim(arg) + 1, onp.ndim(arg) + 2]))\n def testArray(self, arg, ndmin, dtype):\n args_maker = lambda: [arg]\n dtype = dtypes.canonicalize_dtype(dtype)\n if ndmin is not None:\n onp_fun = partial(onp.array, ndmin=ndmin, dtype=dtype)\n jnp_fun = partial(jnp.array, ndmin=ndmin)\n else:\n onp_fun = partial(onp.array, dtype=dtype)\n jnp_fun = jnp.array\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n def testIssue121(self):\n assert not onp.isscalar(jnp.array(3))\n\n def testArrayMethod(self):\n class arraylike(object):\n dtype = onp.float32\n def __array__(self, dtype=None):\n return 3.\n a = arraylike()\n ans = jnp.array(a)\n assert ans == 3.\n\n @jtu.skip_on_devices(\"tpu\") # TODO(b/32368900): TPUs don't support uint8 yet.\n def testMemoryView(self):\n ans = jnp.array(bytearray(b'\\x2a'))\n self.assertAllClose(\n ans,\n onp.array([0x2a], dtype=onp.uint8),\n check_dtypes=True)\n\n def testIsClose(self):\n c_isclose = api.jit(jnp.isclose)\n c_isclose_nan = api.jit(partial(jnp.isclose, equal_nan=True))\n n = 2\n\n rng = onp.random.RandomState(0)\n x = rng.randn(n, 1)\n y = rng.randn(n, 1)\n inf = onp.asarray(n * [onp.inf]).reshape([n, 1])\n nan = onp.asarray(n * [onp.nan]).reshape([n, 1])\n args = [x, y, inf, -inf, nan]\n\n for arg0 in args:\n for arg1 in args:\n result_np = onp.isclose(arg0, arg1)\n result_jax = jnp.isclose(arg0, arg1)\n result_jit = c_isclose(arg0, arg1)\n self.assertTrue(jnp.all(jnp.equal(result_np, result_jax)))\n self.assertTrue(jnp.all(jnp.equal(result_np, result_jit)))\n result_np = onp.isclose(arg0, arg1, equal_nan=True)\n result_jax = jnp.isclose(arg0, arg1, equal_nan=True)\n result_jit = c_isclose_nan(arg0, arg1)\n self.assertTrue(jnp.all(jnp.equal(result_np, result_jax)))\n self.assertTrue(jnp.all(jnp.equal(result_np, result_jit)))\n\n def testAllClose(self):\n rng = onp.random.RandomState(0)\n x = rng.randn(2, 2)\n y = rng.randn(2)\n\n def same(list1, list2):\n allclose = functools.partial(jnp.allclose, atol=1e-3, rtol=1e-3)\n elements_close = list(map(allclose, list1, list2))\n return jnp.all(jnp.array(elements_close))\n\n csame = api.jit(same)\n\n a1 = same((x, y), (x, y))\n a2 = csame((x, y), (x, y))\n a3 = csame((x, y), (x, 2 * y))\n\n self.assertTrue(a1)\n self.assertTrue(a2)\n self.assertFalse(a3)\n\n @jtu.skip_on_devices(\"tpu\") # TODO(mattjj): investigate this failure\n def testOnesBroadcastingConstantHandler(self):\n # TODO(mattjj): update this test for jax3\n self.skipTest(\"test needs jax3 update\")\n\n def fun(x):\n ones = jnp.ones((3, 4))\n assert isinstance(ones, onp.ndarray) and ones.strides == (0, 0)\n\n # To check that the constant handler generates a Broadcast for stride-zero\n # arrays, we monkey-patch the client instance.\n # TODO(mattjj): once we have better HLO dumping and inspecting facilities,\n # we can check the HLO more directly.\n c = x._node.c\n Broadcast = c.Broadcast # pylint: disable=invalid-name\n was_called = []\n c.Broadcast = lambda *args: was_called.append(True) or Broadcast(*args)\n out = x + ones # the ndarray constant handler should call Broadcast here\n assert was_called, \"Broadcast was not called.\"\n\n return out\n\n fun = api.jit(fun)\n out_val = fun(jnp.ones(4))\n self.assertAllClose(out_val, onp.full((3, 4), 2.), check_dtypes=False)\n\n def testZeroStridesConstantHandler(self):\n raw_const = onp.random.RandomState(0).randn(1, 2, 1, 1, 5, 1)\n const = onp.broadcast_to(raw_const, (3, 2, 3, 4, 5, 6))\n\n def fun(x):\n return x * const\n\n fun = api.jit(fun)\n out_val = fun(3.)\n self.assertAllClose(out_val, 3. * const, check_dtypes=False)\n\n def testIsInstanceNdarrayDuringTracing(self):\n arr = onp.ones(3)\n\n @api.jit\n def f(x):\n self.assertIsInstance(x, jnp.ndarray)\n return jnp.sum(x)\n\n f(arr)\n\n def testNonArrayErrorMessage(self):\n x = [1., 2.]\n y = onp.array([3., 4.])\n\n def g(x, y):\n return jnp.add(x, y)\n\n def f(x, y):\n return jnp.dot(x, y)\n\n self.assertRaises(TypeError, lambda: g(x, y))\n self.assertRaises(TypeError, lambda: f(x, y))\n self.assertRaises(TypeError, lambda: api.jit(g)(x, y))\n self.assertRaises(TypeError, lambda: api.jit(f)(x, y))\n\n def testAbstractionErrorMessage(self):\n\n @api.jit\n def f(x, n):\n for _ in range(n):\n x = x * x\n return x\n\n self.assertRaises(TypeError, lambda: f(3., 3))\n\n @api.jit\n def g(x):\n if x > 0.:\n return x * 2\n else:\n return x + 2\n\n self.assertRaises(TypeError, lambda: g(3.))\n\n def testTracingPrimitiveWithNoTranslationErrorMessage(self):\n # TODO(mattjj): update this for jax3\n self.skipTest(\"test needs jax3 update\")\n foo = jnp._not_implemented(lambda x: x)\n\n # No error if there's no tracing.\n foo(onp.arange(3))\n\n cfoo = api.jit(foo)\n self.assertRaises(NotImplementedError, lambda: cfoo(onp.arange(3)))\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_axis={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), axis),\n \"rng_factory\": rng_factory, \"shape\": shape, \"dtype\": dtype, \"axis\": axis}\n for shape in [(3,), (2, 3)]\n for dtype in default_dtypes\n for axis in list(range(-len(shape), len(shape))) + [None] # Test negative axes\n for rng_factory in [jtu.rand_default]))\n def testFlip(self, shape, dtype, axis, rng_factory):\n rng = rng_factory()\n args_maker = self._GetArgsMaker(rng, [shape], [dtype])\n jnp_op = lambda x: jnp.flip(x, axis)\n onp_op = lambda x: onp.flip(x, axis)\n self._CheckAgainstNumpy(onp_op, jnp_op, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}\".format(\n jtu.format_shape_dtype_string(shape, dtype)),\n \"rng_factory\": rng_factory, \"shape\": shape, \"dtype\": dtype}\n for shape in [(3,), (2, 3), (3, 2, 4)]\n for dtype in default_dtypes\n for rng_factory in [jtu.rand_default]))\n def testFlipud(self, shape, dtype, rng_factory):\n rng = rng_factory()\n args_maker = self._GetArgsMaker(rng, [shape], [dtype])\n jnp_op = lambda x: jnp.flipud(x)\n onp_op = lambda x: onp.flipud(x)\n self._CheckAgainstNumpy(onp_op, jnp_op, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)\n\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}\".format(\n jtu.format_shape_dtype_string(shape, dtype)),\n \"rng_factory\": rng_factory, \"shape\": shape, \"dtype\": dtype}\n for shape in [(3, 2), (2, 3), (3, 2, 4)]\n for dtype in default_dtypes\n for rng_factory in [jtu.rand_default]))\n def testFliplr(self, shape, dtype, rng_factory):\n rng = rng_factory()\n args_maker = self._GetArgsMaker(rng, [shape], [dtype])\n jnp_op = lambda x: jnp.fliplr(x)\n onp_op = lambda x: onp.fliplr(x)\n self._CheckAgainstNumpy(onp_op, jnp_op, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)\n\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_k={}_axes={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), k, axes),\n \"rng_factory\": rng_factory, \"shape\": shape, \"dtype\": dtype, \"k\": k, \"axes\": axes}\n for shape, axes in [\n [(2, 3), (0, 1)],\n [(2, 3), (1, 0)],\n [(4, 3, 2), (0, 2)],\n [(4, 3, 2), (2, 1)],\n ]\n for k in range(-3, 4)\n for dtype in default_dtypes\n for rng_factory in [jtu.rand_default]))\n def testRot90(self, shape, dtype, k, axes, rng_factory):\n rng = rng_factory()\n args_maker = self._GetArgsMaker(rng, [shape], [dtype])\n jnp_op = lambda x: jnp.rot90(x, k, axes)\n onp_op = lambda x: onp.rot90(x, k, axes)\n self._CheckAgainstNumpy(onp_op, jnp_op, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)\n\n # TODO(mattjj): test infix operator overrides\n\n def testRavel(self):\n rng = onp.random.RandomState(0)\n args_maker = lambda: [rng.randn(3, 4).astype(\"float32\")]\n self._CompileAndCheck(lambda x: x.ravel(), args_maker, check_dtypes=True)\n\n def testAstype(self):\n rng = onp.random.RandomState(0)\n args_maker = lambda: [rng.randn(3, 4).astype(\"float32\")]\n op = lambda x: x.astype(jnp.int32)\n self._CheckAgainstNumpy(op, op, args_maker, check_dtypes=True)\n self._CompileAndCheck(op, args_maker, check_dtypes=True)\n\n # TODO(mattjj): test other ndarray-like method overrides\n\n def testOnpMean(self):\n # from https://github.com/google/jax/issues/125\n x = lax.add(jnp.eye(3, dtype=jnp.float_), 0.)\n ans = onp.mean(x)\n self.assertAllClose(ans, onp.array(1./3), check_dtypes=False)\n\n def testArangeOnFloats(self):\n # from https://github.com/google/jax/issues/145\n expected = onp.arange(0.0, 1.0, 0.1, dtype=jnp.float_)\n ans = jnp.arange(0.0, 1.0, 0.1)\n self.assertAllClose(expected, ans, check_dtypes=True)\n\n def testSortManually(self):\n # manual tests for sort are nice because we don't have to worry about ties.\n # lax.sort is tested combinatorially.\n ans = jnp.sort(onp.array([16, 15, 23, 42, 8, 4]))\n expected = onp.array([4, 8, 15, 16, 23, 42])\n self.assertAllClose(expected, ans, check_dtypes=True)\n\n a = onp.array([[1, 4], [3, 1]])\n ans = jnp.sort(a, axis=None)\n expected = onp.array([1, 1, 3, 4])\n self.assertAllClose(expected, ans, check_dtypes=True)\n\n a = onp.array([[1, 4], [3, 1]])\n ans = jnp.sort(a) # last axis\n expected = onp.array([[1, 4], [1, 3]])\n self.assertAllClose(expected, ans, check_dtypes=True)\n\n a = onp.array([[1, 4], [3, 1]])\n ans = jnp.sort(a, axis=0)\n expected = onp.array([[1, 1], [3, 4]])\n self.assertAllClose(expected, ans, check_dtypes=True)\n\n def testArgsortManually(self):\n x = onp.array([16, 15, 23, 42, 8, 4])\n ans = jnp.argsort(x)\n expected = onp.argsort(x)\n self.assertAllClose(expected, ans, check_dtypes=False)\n\n x = onp.array([[16, 15, 23], [42, 8, 4]])\n ans = jnp.argsort(x, axis=0)\n expected = onp.argsort(x, axis=0)\n self.assertAllClose(expected, ans, check_dtypes=False)\n\n x = onp.array([[16, 15, 23], [42, 8, 4]])\n ans = jnp.argsort(x, axis=1)\n expected = onp.argsort(x, axis=1)\n self.assertAllClose(expected, ans, check_dtypes=False)\n\n x = onp.array([[16, 15, 23], [42, 8, 4]])\n ans = jnp.argsort(x, axis=None)\n expected = onp.argsort(x, axis=None)\n self.assertAllClose(expected, ans, check_dtypes=False)\n\n x = onp.array([[16, 15, 23], [42, 8, 4]])\n ans = jnp.argsort(x)\n expected = onp.argsort(x)\n self.assertAllClose(expected, ans, check_dtypes=False)\n\n def testMsortManually(self):\n args_maker = lambda: [onp.random.randint(50, size=(5 ,5))]\n jnp_op = lambda x: jnp.msort(x)\n onp_op = lambda x: onp.msort(x)\n self._CheckAgainstNumpy(jnp_op, onp_op, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_shifts={}_axis={}\".format(\n jtu.format_shape_dtype_string(shape, dtype),\n shifts, axis),\n \"rng_factory\": rng_factory, \"shape\": shape, \"dtype\": dtype, \"shifts\": shifts,\n \"axis\": axis}\n for dtype in all_dtypes\n for shape in [(3, 4), (3, 4, 5), (7, 4, 0)]\n for shifts, axis in [\n (3, None),\n (1, 1),\n ((3,), (0,)),\n ((-2,), (-2,)),\n ((1, 2), (0, -1)),\n ((4, 2, 5, 5, 2, 4), None),\n (100, None),\n ]\n for rng_factory in [jtu.rand_default]))\n def testRoll(self, shape, dtype, shifts, axis, rng_factory):\n rng = rng_factory()\n args_maker = lambda: [rng(shape, dtype), onp.array(shifts)]\n jnp_op = partial(jnp.roll, axis=axis)\n onp_op = partial(onp.roll, axis=axis)\n self._CheckAgainstNumpy(jnp_op, onp_op, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_axis={}_start={}\".format(\n jtu.format_shape_dtype_string(shape, dtype),\n axis, start),\n \"rng_factory\": rng_factory, \"shape\": shape, \"dtype\": dtype, \"axis\": axis,\n \"start\": start}\n for dtype in all_dtypes\n for shape in [(1, 2, 3, 4)]\n for axis in [-3, 0, 2, 3]\n for start in [-4, -1, 2, 4]\n for rng_factory in [jtu.rand_default]))\n def testRollaxis(self, shape, dtype, start, axis, rng_factory):\n rng = rng_factory()\n args_maker = lambda: [rng(shape, dtype)]\n jnp_op = partial(jnp.rollaxis, axis=axis, start=start)\n onp_op = partial(onp.rollaxis, axis=axis, start=start)\n self._CheckAgainstNumpy(jnp_op, onp_op, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_axis={}_bitorder={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), axis, bitorder),\n \"rng_factory\": rng_factory, \"shape\": shape, \"dtype\": dtype, \"axis\": axis,\n \"bitorder\": bitorder}\n for dtype in [onp.uint8, onp.bool_]\n for bitorder in ['big', 'little']\n for shape in [(1, 2, 3, 4)]\n for axis in [None, 0, 1, -2, -1]\n for rng_factory in [jtu.rand_some_zero]))\n def testPackbits(self, shape, dtype, axis, bitorder, rng_factory):\n if numpy_version < (1, 17, 0):\n raise SkipTest(\"bitorder arg added in numpy 1.17.0\")\n rng = rng_factory()\n args_maker = lambda: [rng(shape, dtype)]\n jnp_op = partial(jnp.packbits, axis=axis, bitorder=bitorder)\n onp_op = partial(onp.packbits, axis=axis, bitorder=bitorder)\n self._CheckAgainstNumpy(jnp_op, onp_op, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_axis={}_bitorder={}_count={}\".format(\n jtu.format_shape_dtype_string(shape, dtype), axis, bitorder, count),\n \"rng_factory\": rng_factory, \"shape\": shape, \"dtype\": dtype, \"axis\": axis,\n \"bitorder\": bitorder, \"count\": count}\n for dtype in [onp.uint8]\n for bitorder in ['big', 'little']\n for shape in [(1, 2, 3, 4)]\n for axis in [None, 0, 1, -2, -1]\n for count in [None, 20]\n for rng_factory in [jtu.rand_int]))\n def testUnpackbits(self, shape, dtype, axis, bitorder, count, rng_factory):\n if numpy_version < (1, 17, 0):\n raise SkipTest(\"bitorder arg added in numpy 1.17.0\")\n rng = rng_factory(0, 256)\n args_maker = lambda: [rng(shape, dtype)]\n jnp_op = partial(jnp.unpackbits, axis=axis, bitorder=bitorder)\n onp_op = partial(onp.unpackbits, axis=axis, bitorder=bitorder)\n self._CheckAgainstNumpy(jnp_op, onp_op, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_index={}_axis={}_mode={}\".format(\n jtu.format_shape_dtype_string(shape, dtype),\n jtu.format_shape_dtype_string(index_shape, index_dtype),\n axis, mode),\n \"rng_factory\": rng_factory, \"rng_indices_factory\": rng_indices_factory,\n \"shape\": shape, \"index_shape\": index_shape, \"dtype\": dtype,\n \"index_dtype\": index_dtype, \"axis\": axis, \"mode\": mode}\n for shape in [(3,), (3, 4), (3, 4, 5)]\n for index_shape in scalar_shapes + [(3,), (2, 1, 3)]\n for axis in itertools.chain(range(-len(shape), len(shape)),\n [cast(Optional[int], None)])\n for dtype in all_dtypes\n for index_dtype in int_dtypes\n for mode in ['wrap', 'clip']\n for rng_factory in [jtu.rand_default]\n for rng_indices_factory in [partial(jtu.rand_int, -5, 5)]))\n def testTake(self, shape, dtype, index_shape, index_dtype, axis, mode,\n rng_factory, rng_indices_factory):\n def args_maker():\n x = rng(shape, dtype)\n i = rng_indices(index_shape, index_dtype)\n return x, i\n\n rng = rng_factory()\n rng_indices = rng_indices_factory()\n jnp_op = lambda x, i: jnp.take(x, i, axis=axis, mode=mode)\n onp_op = lambda x, i: onp.take(x, i, axis=axis, mode=mode)\n self._CheckAgainstNumpy(jnp_op, onp_op, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}_ishape={}_axis={}\".format(\n jtu.format_shape_dtype_string(x_shape, dtype), i_shape, axis),\n \"rng_factory\": rng_factory, \"x_shape\": x_shape, \"i_shape\": i_shape, \"dtype\": dtype,\n \"axis\": axis}\n for x_shape, i_shape in filter(\n _shapes_are_equal_length,\n filter(_shapes_are_broadcast_compatible,\n CombosWithReplacement(nonempty_nonscalar_array_shapes, 2)))\n for axis in itertools.chain(range(len(x_shape)), [-1],\n [cast(Optional[int], None)])\n for dtype in default_dtypes\n for rng_factory in [jtu.rand_default]))\n def testTakeAlongAxis(self, x_shape, i_shape, dtype, axis, rng_factory):\n rng = rng_factory()\n i_shape = onp.array(i_shape)\n if axis is None:\n i_shape = [onp.prod(i_shape, dtype=onp.int64)]\n else:\n # Test the case where the size of the axis doesn't necessarily broadcast.\n i_shape[axis] *= 3\n i_shape = list(i_shape)\n def args_maker():\n x = rng(x_shape, dtype)\n n = onp.prod(x_shape, dtype=onp.int32) if axis is None else x_shape[axis]\n i = rng(i_shape, onp.int32) % (2 * n - 1) - (n - 1)\n return x, i\n\n jnp_op = lambda x, i: jnp.take_along_axis(x, i, axis=axis)\n\n if hasattr(onp, \"take_along_axis\"):\n onp_op = lambda x, i: onp.take_along_axis(x, i, axis=axis)\n self._CheckAgainstNumpy(jnp_op, onp_op, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_n={}_increasing={}\".format(\n jtu.format_shape_dtype_string([shape], dtype),\n n, increasing),\n \"dtype\": dtype, \"shape\": shape, \"n\": n, \"increasing\": increasing,\n \"rng_factory\": jtu.rand_default}\n for dtype in inexact_dtypes\n for shape in [0, 5]\n for n in [2, 4]\n for increasing in [False, True]))\n def testVander(self, shape, dtype, n, increasing, rng_factory):\n rng = rng_factory()\n def onp_fun(arg):\n arg = arg.astype(onp.float32) if dtype == jnp.bfloat16 else arg\n return onp.vander(arg, N=n, increasing=increasing)\n jnp_fun = lambda arg: jnp.vander(arg, N=n, increasing=increasing)\n args_maker = lambda: [rng([shape], dtype)]\n # np.vander seems to return float64 for all floating types. We could obey\n # those semantics, but they seem like a bug.\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False,\n tol={onp.float32: 1e-3})\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=False)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": jtu.format_test_name_suffix(\"nan_to_num\", [shape],\n [dtype]),\n \"rng_factory\": jtu.rand_some_inf_and_nan, \"shape\": shape,\n \"dtype\": dtype}\n for shape in all_shapes\n for dtype in inexact_dtypes))\n def testNanToNum(self, rng_factory, shape, dtype):\n rng = rng_factory()\n dtype = onp.dtype(dtypes.canonicalize_dtype(dtype)).type\n def onp_fun(x):\n if dtype == jnp.bfloat16:\n x = onp.where(onp.isnan(x), dtype(0), x)\n x = onp.where(onp.isposinf(x), jnp.finfo(dtype).max, x)\n x = onp.where(onp.isneginf(x), jnp.finfo(dtype).min, x)\n return x\n else:\n return onp.nan_to_num(x).astype(dtype)\n\n args_maker = lambda: [rng(shape, dtype)]\n check_dtypes = shape is not jtu.PYTHON_SCALAR_SHAPE\n self._CheckAgainstNumpy(onp_fun, jnp.nan_to_num, args_maker,\n check_dtypes=check_dtypes)\n self._CompileAndCheck(jnp.nan_to_num, args_maker,\n check_dtypes=check_dtypes)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": jtu.format_test_name_suffix(\"ix_\", shapes, dtypes),\n \"rng_factory\": jtu.rand_default, \"shapes\": shapes, \"dtypes\": dtypes}\n for shapes, dtypes in (\n ((), ()),\n (((7,),), (onp.int32,)),\n (((3,), (4,)), (onp.int32, onp.int32)),\n (((3,), (1,), (4,)), (onp.int32, onp.int32, onp.int32)),\n )))\n def testIx_(self, rng_factory, shapes, dtypes):\n rng = rng_factory()\n args_maker = lambda: [rng(shape, dtype)\n for shape, dtype in zip(shapes, dtypes)]\n self._CheckAgainstNumpy(onp.ix_, jnp.ix_, args_maker,\n check_dtypes=True)\n self._CompileAndCheck(jnp.ix_, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\":\n \"_op={}_a_shape={}_q_shape={}_axis={}_keepdims={}_interpolation={}\".format(\n op,\n jtu.format_shape_dtype_string(a_shape, a_dtype),\n jtu.format_shape_dtype_string(q_shape, q_dtype),\n axis, keepdims, interpolation),\n \"a_rng\": jtu.rand_default(), \"q_rng\": q_rng, \"op\": op,\n \"a_shape\": a_shape, \"a_dtype\": a_dtype,\n \"q_shape\": q_shape, \"q_dtype\": q_dtype, \"axis\": axis,\n \"keepdims\": keepdims,\n \"interpolation\": interpolation}\n for (op, q_rng) in (\n (\"percentile\", jtu.rand_uniform(low=0., high=100.)),\n (\"quantile\", jtu.rand_uniform(low=0., high=1.)),\n )\n for a_dtype in float_dtypes\n for a_shape, axis in (\n ((7,), None),\n ((47, 7), 0),\n ((4, 101), 1),\n )\n for q_dtype in [onp.float32]\n for q_shape in scalar_shapes + [(4,)]\n for keepdims in [False, True]\n for interpolation in ['linear', 'lower', 'higher', 'nearest', 'midpoint']))\n def testQuantile(self, op, a_rng, q_rng, a_shape, a_dtype, q_shape, q_dtype,\n axis, keepdims, interpolation):\n if op == \"quantile\" and numpy_version < (1, 15):\n raise SkipTest(\"Numpy < 1.15 does not have np.quantile\")\n args_maker = lambda: [a_rng(a_shape, a_dtype), q_rng(q_shape, q_dtype)]\n def onp_fun(*args):\n args = [x if jnp.result_type(x) != jnp.bfloat16 else\n onp.asarray(x, onp.float32) for x in args]\n return getattr(onp, op)(*args, axis=axis, keepdims=keepdims,\n interpolation=interpolation)\n jnp_fun = partial(getattr(jnp, op), axis=axis, keepdims=keepdims,\n interpolation=interpolation)\n # TODO(phawkins): we currently set dtype=False because we aren't as\n # aggressive about promoting to float64. It's not clear we want to mimic\n # Numpy here.\n tol_spec = {onp.float32: 2e-4, onp.float64: 5e-6}\n tol = max(jtu.tolerance(a_dtype, tol_spec),\n jtu.tolerance(q_dtype, tol_spec))\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False,\n tol=tol)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True, rtol=tol)\n\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\":\n \"_a_shape={}_axis={}_keepdims={}\".format(\n jtu.format_shape_dtype_string(a_shape, a_dtype),\n axis, keepdims),\n \"a_rng\": jtu.rand_default(),\n \"a_shape\": a_shape, \"a_dtype\": a_dtype,\n \"axis\": axis,\n \"keepdims\": keepdims}\n for a_dtype in float_dtypes\n for a_shape, axis in (\n ((7,), None),\n ((47, 7), 0),\n ((4, 101), 1),\n )\n for keepdims in [False, True]))\n def testMedian(self, a_rng, a_shape, a_dtype, axis, keepdims):\n args_maker = lambda: [a_rng(a_shape, a_dtype)]\n def onp_fun(*args):\n args = [x if jnp.result_type(x) != jnp.bfloat16 else\n onp.asarray(x, onp.float32) for x in args]\n return onp.median(*args, axis=axis, keepdims=keepdims)\n jnp_fun = partial(jnp.median, axis=axis, keepdims=keepdims)\n # TODO(phawkins): we currently set dtype=False because we aren't as\n # aggressive about promoting to float64. It's not clear we want to mimic\n # Numpy here.\n tol_spec = {onp.float32: 2e-4, onp.float64: 5e-6}\n tol = jtu.tolerance(a_dtype, tol_spec)\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False,\n tol=tol)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True, rtol=tol)\n\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}\".format(\n jtu.format_shape_dtype_string(shape, dtype)),\n \"shape\": shape, \"dtype\": dtype}\n for shape in all_shapes for dtype in all_dtypes))\n def testWhereOneArgument(self, shape, dtype):\n rng = jtu.rand_some_zero()\n onp_fun = lambda x: onp.where(x)\n onp_fun = jtu.ignore_warning(\n category=DeprecationWarning,\n message=\"Calling nonzero on 0d arrays.*\")(onp_fun)\n jnp_fun = lambda x: jnp.where(x)\n args_maker = lambda: [rng(shape, dtype)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_{}\".format(\"_\".join(\n jtu.format_shape_dtype_string(shape, dtype)\n for shape, dtype in zip(shapes, dtypes))),\n \"rng_factory\": jtu.rand_default, \"shapes\": shapes, \"dtypes\": dtypes}\n for shapes in filter(_shapes_are_broadcast_compatible,\n CombosWithReplacement(all_shapes, 3))\n for dtypes in CombosWithReplacement(all_dtypes, 3)))\n def testWhereThreeArgument(self, rng_factory, shapes, dtypes):\n rng = rng_factory()\n args_maker = self._GetArgsMaker(rng_factory(), shapes, dtypes)\n def onp_fun(cond, x, y):\n return _promote_like_jnp(partial(onp.where, cond))(x, y)\n self._CheckAgainstNumpy(onp_fun, jnp.where, args_maker,\n check_dtypes=True)\n self._CompileAndCheck(jnp.where, args_maker, check_dtypes=True)\n\n def testWhereScalarPromotion(self):\n x = jnp.where(jnp.array([True, False]), 3,\n jnp.ones((2,), dtype=jnp.float32))\n self.assertEqual(x.dtype, onp.dtype(onp.float32))\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": jtu.format_test_name_suffix(\"\", shapes,\n (onp.bool_,) * n + dtypes),\n \"rng_factory\": jtu.rand_default, \"shapes\": shapes, \"dtypes\": dtypes}\n for n in range(0, 3)\n for shapes in filter(\n _shapes_are_broadcast_compatible,\n CombosWithReplacement(all_shapes, 2 * n + 1))\n for dtypes in CombosWithReplacement(all_dtypes, n + 1)))\n def testSelect(self, rng_factory, shapes, dtypes):\n rng = rng_factory()\n n = len(dtypes) - 1\n def args_maker():\n condlist = [rng(shape, onp.bool_) for shape in shapes[:n]]\n choicelist = [rng(shape, dtype)\n for shape, dtype in zip(shapes[n:-1], dtypes[:n])]\n default = rng(shapes[-1], dtypes[-1])\n return condlist, choicelist, default\n # TODO(phawkins): float32/float64 type mismatches\n def onp_fun(condlist, choicelist, default):\n choicelist = [x if jnp.result_type(x) != jnp.bfloat16\n else x.astype(onp.float32) for x in choicelist]\n dtype = jnp.result_type(default, *choicelist)\n return onp.select(condlist,\n [onp.asarray(x, dtype=dtype) for x in choicelist],\n onp.asarray(default, dtype=dtype))\n self._CheckAgainstNumpy(onp_fun, jnp.select, args_maker,\n check_dtypes=False)\n self._CompileAndCheck(jnp.select, args_maker, check_dtypes=True,\n rtol={onp.float64: 1e-7, onp.complex128: 1e-7})\n\n\n def testIssue330(self):\n x = jnp.full((1, 1), jnp.array([1])[0]) # doesn't crash\n self.assertEqual(x[0, 0], 1)\n\n def testScalarDtypePromotion(self):\n orig_numpy_result = (1 + onp.eye(1, dtype=onp.float32)).dtype\n jax_numpy_result = (1 + jnp.eye(1, dtype=jnp.float32)).dtype\n self.assertEqual(orig_numpy_result, jax_numpy_result)\n\n def testSymmetrizeDtypePromotion(self):\n x = onp.eye(3, dtype=onp.float32)\n orig_numpy_result = ((x + x.T) / 2).dtype\n\n x = jnp.eye(3, dtype=jnp.float32)\n jax_numpy_result = ((x + x.T) / 2).dtype\n self.assertEqual(orig_numpy_result, jax_numpy_result)\n\n # NOTE(mattjj): I disabled this test when removing lax._safe_mul because\n # introducing the convention 0 * inf = 0 leads to silently wrong results in\n # some cases. See this comment for details:\n # https://github.com/google/jax/issues/1052#issuecomment-514083352\n # def testIssue347(self):\n # # https://github.com/google/jax/issues/347\n # def test_fail(x):\n # x = jnp.sqrt(jnp.sum(x ** 2, axis=1))\n # ones = jnp.ones_like(x)\n # x = jnp.where(x > 0.5, x, ones)\n # return jnp.sum(x)\n # x = jnp.array([[1, 2], [3, 4], [0, 0]], dtype=jnp.float64)\n # result = api.grad(test_fail)(x)\n # assert not onp.any(onp.isnan(result))\n\n def testIssue453(self):\n # https://github.com/google/jax/issues/453\n a = onp.arange(6) + 1\n ans = jnp.reshape(a, (3, 2), order='F')\n expected = onp.reshape(a, (3, 2), order='F')\n self.assertAllClose(ans, expected, check_dtypes=True)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_op={}_dtype={}\".format(op, pytype.__name__),\n \"pytype\": pytype, \"dtype\": dtype, \"op\": op}\n for pytype, dtype in [(int, jnp.int_), (float, jnp.float_),\n (bool, jnp.bool_), (complex, jnp.complex_)]\n for op in [\"atleast_1d\", \"atleast_2d\", \"atleast_3d\"]))\n def testAtLeastNdLiterals(self, pytype, dtype, op):\n # Fixes: https://github.com/google/jax/issues/634\n onp_fun = lambda arg: getattr(onp, op)(arg).astype(dtype)\n jnp_fun = lambda arg: getattr(jnp, op)(arg)\n args_maker = lambda: [pytype(2)]\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(*jtu.cases_from_list(\n {\"testcase_name\": \"_case={}\".format(i),\n \"input\": input}\n for i, input in enumerate([\n 3,\n [3],\n [onp.array(3)],\n [onp.array([3])],\n [[onp.array(3)]],\n [[onp.array([3])]],\n [3, 4, 5],\n [\n [onp.eye(2, dtype=onp.int32) * 2, onp.zeros((2, 3), dtype=onp.int32)],\n [onp.ones((3, 2), dtype=onp.int32), onp.eye(3, dtype=onp.int32) * 3],\n ],\n [onp.array([1, 2, 3]), onp.array([2, 3, 4]), 10],\n [onp.ones((2, 2), dtype=onp.int32), onp.zeros((2, 2), dtype=onp.int32)],\n [[onp.array([1, 2, 3])], [onp.array([2, 3, 4])]],\n ])))\n def testBlock(self, input):\n args_maker = lambda: [input]\n self._CheckAgainstNumpy(onp.block, jnp.block, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp.block, args_maker, check_dtypes=True)\n\n def testLongLong(self):\n self.assertAllClose(onp.int64(7), api.jit(lambda x: x)(onp.longlong(7)),\n check_dtypes=True)\n\n def testArange(self):\n # test cases inspired by dask tests at\n # https://github.com/dask/dask/blob/master/dask/array/tests/test_creation.py#L92\n self.assertAllClose(jnp.arange(77),\n onp.arange(77, dtype=jnp.int_), check_dtypes=True)\n self.assertAllClose(jnp.arange(2, 13),\n onp.arange(2, 13, dtype=jnp.int_), check_dtypes=True)\n self.assertAllClose(jnp.arange(4, 21, 9),\n onp.arange(4, 21, 9, dtype=jnp.int_), check_dtypes=True)\n self.assertAllClose(jnp.arange(53, 5, -3),\n onp.arange(53, 5, -3, dtype=jnp.int_),\n check_dtypes=True)\n self.assertAllClose(jnp.arange(77, dtype=float),\n onp.arange(77, dtype=float), check_dtypes=True)\n self.assertAllClose(jnp.arange(2, 13, dtype=int),\n onp.arange(2, 13, dtype=int), check_dtypes=True)\n self.assertAllClose(jnp.arange(0, 1, -0.5),\n onp.arange(0, 1, -0.5, dtype=jnp.float_),\n check_dtypes=True)\n\n self.assertRaises(TypeError, lambda: jnp.arange())\n\n # test that jnp.arange(N) doesn't instantiate an ndarray\n self.assertNotEqual(type(jnp.arange(77)), type(onp.arange(77)))\n self.assertEqual(type(jnp.arange(77)), type(lax.iota(onp.int32, 77)))\n\n # test that jnp.arange(N, dtype=int32) doesn't instantiate an ndarray\n self.assertNotEqual(type(jnp.arange(77, dtype=jnp.int32)),\n type(onp.arange(77, dtype=onp.int32)))\n self.assertEqual(type(jnp.arange(77, dtype=jnp.int32)),\n type(lax.iota(onp.int32, 77)))\n\n # test laziness for int dtypes\n self.assertTrue(xla.is_device_constant(jnp.arange(77)))\n self.assertTrue(xla.is_device_constant(jnp.arange(77, dtype=jnp.int32)))\n\n def testIssue830(self):\n a = jnp.arange(4, dtype=jnp.complex64)\n self.assertEqual(a.dtype, jnp.complex64)\n\n def testIssue728(self):\n assert jnp.allclose(jnp.eye(5000), onp.eye(5000))\n self.assertEqual(0, onp.sum(jnp.eye(1050) - onp.eye(1050)))\n\n def testIssue746(self):\n jnp.arange(12).reshape(3, 4) # doesn't crash\n\n def testIssue764(self):\n x = jnp.linspace(190, 200, 4)\n f = api.grad(lambda x: jnp.sum(jnp.tanh(x)))\n # Expected values computed with autograd in float64 precision.\n expected = onp.array([3.71669453e-165, 4.72999108e-168, 6.01954653e-171,\n 7.66067839e-174], onp.float64)\n self.assertAllClose(f(x), expected, check_dtypes=False)\n\n def testIssue776(self):\n \"\"\"Tests that the scatter-add transpose rule instantiates symbolic zeros.\"\"\"\n def f(u):\n y = jax.ops.index_add(onp.ones(10,), [2, 4, 5], u)\n # The transpose rule for lax.tie_in returns a symbolic zero for its first\n # argument.\n return lax.tie_in(y, 7.)\n\n self.assertAllClose(onp.zeros(3,), api.grad(f)(onp.ones(3,)),\n check_dtypes=True)\n\n # NOTE(mattjj): I disabled this test when removing lax._safe_mul because this\n # is a numerical stability issue that should be solved with a custom jvp rule\n # of the sigmoid function being differentiated here, not by safe_mul.\n # def testIssue777(self):\n # x = jnp.linspace(-200, 0, 4, dtype=onp.float32)\n # f = api.grad(lambda x: jnp.sum(1 / (1 + jnp.exp(-x))))\n # self.assertAllClose(f(x), onp.array([0., 0., 0., 0.25], dtype=onp.float32),\n # check_dtypes=True)\n\n @parameterized.named_parameters(\n jtu.cases_from_list(\n {\"testcase_name\": jtu.format_test_name_suffix(op, [()], [dtype]),\n \"dtype\": dtype, \"op\": op}\n for dtype in float_dtypes\n for op in (\"sqrt\", \"arccos\", \"arcsin\", \"arctan\", \"sin\", \"cos\", \"tan\",\n \"sinh\", \"cosh\", \"tanh\", \"arccosh\", \"arcsinh\", \"arctanh\", \"exp\",\n \"log\", \"expm1\", \"log1p\")))\n def testMathSpecialFloatValues(self, op, dtype):\n onp_op = getattr(onp, op)\n onp_op = jtu.ignore_warning(category=RuntimeWarning,\n message=\"invalid value.*\")(onp_op)\n onp_op = jtu.ignore_warning(category=RuntimeWarning,\n message=\"divide by zero.*\")(onp_op)\n onp_op = jtu.ignore_warning(category=RuntimeWarning,\n message=\"overflow.*\")(onp_op)\n\n jnp_op = getattr(jnp, op)\n dtype = onp.dtype(dtypes.canonicalize_dtype(dtype)).type\n for x in (onp.nan, -onp.inf, -100., -2., -1., 0., 1., 2., 100., onp.inf,\n jnp.finfo(dtype).max, onp.sqrt(jnp.finfo(dtype).max),\n onp.sqrt(jnp.finfo(dtype).max) * 2.):\n if onp.isnan(x) and op in (\"sinh\", \"cosh\", \"expm1\", \"exp\"):\n # TODO(b/133842876, b/133842870): these return wrong outputs on CPU for\n # NaN inputs.\n continue\n if (op in (\"sin\", \"cos\", \"tan\", \"arctan\") and\n jtu.device_under_test() == \"tpu\"):\n continue # TODO(b/132196789, b/134175194): fix and reenable.\n x = dtype(x)\n expected = onp_op(x)\n actual = jnp_op(x)\n tol = jtu.tolerance(dtype, {onp.float32: 1e-3, onp.float64: 1e-7})\n self.assertAllClose(expected, actual, check_dtypes=True, atol=tol,\n rtol=tol)\n\n def testIssue883(self):\n # from https://github.com/google/jax/issues/883\n\n @partial(api.jit, static_argnums=(1,))\n def f(x, v):\n return x\n\n x = jnp.ones((10, 10))\n v = jnp.array([1, 2, 3])\n first_call = f(x, v)\n second_call = f(x, v) # doesn't crash\n\n def testReductionOfOutOfBoundsAxis(self): # Issue 888\n x = jnp.ones((3, 4))\n self.assertRaises(ValueError, lambda: jnp.sum(x, axis=2))\n\n def testIssue956(self):\n self.assertRaises(TypeError, lambda: jnp.ndarray((1, 1)))\n\n @parameterized.named_parameters(\n jtu.cases_from_list(\n {\"testcase_name\":\n \"_shape={}_dtype={}_out_dtype={}_axis={}_ddof={}_keepdims={}\"\n .format(shape, dtype, out_dtype, axis, ddof, keepdims),\n \"shape\": shape, \"dtype\": dtype, \"out_dtype\": out_dtype, \"axis\": axis,\n \"ddof\": ddof, \"keepdims\": keepdims, \"rng_factory\": rng_factory}\n for shape in [(5,), (10, 5)]\n for dtype in all_dtypes\n for out_dtype in inexact_dtypes\n for axis in [None, 0, -1]\n for ddof in [0, 1, 2]\n for keepdims in [False, True]\n for rng_factory in [jtu.rand_default]))\n def testVar(self, shape, dtype, out_dtype, axis, ddof, keepdims, rng_factory):\n rng = rng_factory()\n args_maker = self._GetArgsMaker(rng, [shape], [dtype])\n def onp_fun(x):\n out = onp.var(x.astype(jnp.promote_types(onp.float32, dtype)),\n axis=axis, ddof=ddof, keepdims=keepdims)\n return out.astype(out_dtype)\n jnp_fun = partial(jnp.var, dtype=out_dtype, axis=axis, ddof=ddof, keepdims=keepdims)\n tol = jtu.tolerance(out_dtype, {onp.float16: 1e-1, onp.float32: 1e-3,\n onp.float64: 1e-3, onp.complex128: 1e-6})\n self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True,\n tol=tol)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True, rtol=tol,\n atol=tol)\n\n @parameterized.named_parameters(\n jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_dtype={}_rowvar={}_ddof={}_bias={}\".format(\n shape, dtype, rowvar, ddof, bias),\n \"shape\": shape, \"dtype\": dtype, \"rowvar\": rowvar, \"ddof\": ddof,\n \"bias\": bias, \"rng_factory\": rng_factory}\n for shape in [(5,), (10, 5), (5, 10)]\n for dtype in all_dtypes\n for rowvar in [True, False]\n for bias in [True, False]\n for ddof in [None, 2, 3]\n for rng_factory in [jtu.rand_default]))\n @jtu.skip_on_devices(\"gpu\") # TODO(b/138003641): test fails on GPU.\n def testCov(self, shape, dtype, rowvar, ddof, bias, rng_factory):\n rng = rng_factory()\n args_maker = self._GetArgsMaker(rng, [shape], [dtype])\n onp_fun = partial(onp.cov, rowvar=rowvar, ddof=ddof, bias=bias)\n jnp_fun = partial(jnp.cov, rowvar=rowvar, ddof=ddof, bias=bias)\n tol = {onp.float32: 1e-5, onp.float64: 1e-13, onp.complex128: 1e-13}\n tol = 7e-2 if jtu.device_under_test() == \"tpu\" else tol\n tol = jtu.join_tolerance(tol, jtu.tolerance(dtype))\n self._CheckAgainstNumpy(\n onp_fun, jnp_fun, args_maker, check_dtypes=False, tol=tol)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True, atol=tol,\n rtol=tol)\n\n def testIssue967(self):\n self.assertRaises(TypeError, lambda: jnp.zeros(1.5))\n\n @parameterized.named_parameters(\n jtu.cases_from_list(\n {\"testcase_name\": \"_shape={}_dtype={}_rowvar={}\".format(\n shape, dtype, rowvar),\n \"shape\": shape, \"dtype\": dtype, \"rowvar\": rowvar,\n \"rng_factory\": rng_factory}\n for shape in [(5,), (10, 5), (3, 10)]\n for dtype in number_dtypes\n for rowvar in [True, False]\n for rng_factory in [jtu.rand_default]))\n def testCorrCoef(self, shape, dtype, rowvar, rng_factory):\n rng = rng_factory()\n args_maker = self._GetArgsMaker(rng, [shape], [dtype])\n mat = onp.asarray([rng(shape, dtype)])\n onp_fun = partial(onp.corrcoef, rowvar=rowvar)\n jnp_fun = partial(jnp.corrcoef, rowvar=rowvar)\n if not onp.any(onp.isclose(onp.std(mat), 0.0)):\n self._CheckAgainstNumpy(\n onp_fun, jnp_fun, args_maker, check_dtypes=False,\n tol=1e-2 if jtu.device_under_test() == \"tpu\" else None)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(\n jtu.cases_from_list(\n {\"testcase_name\": \"_shapes={}_dtype={}_indexing={}_sparse={}\".format(\n shapes, dtype, indexing, sparse),\n \"shapes\": shapes, \"dtype\": dtype, \"indexing\": indexing,\n \"sparse\": sparse, \"rng_factory\": rng_factory}\n for shapes in [(), (5,), (5, 3)]\n for dtype in number_dtypes\n for indexing in ['xy', 'ij']\n for sparse in [True, False]\n for rng_factory in [jtu.rand_default]))\n def testMeshGrid(self, shapes, dtype, indexing, sparse, rng_factory):\n rng = rng_factory()\n args_maker = self._GetArgsMaker(rng, [(x,) for x in shapes],\n [dtype] * len(shapes))\n onp_fun = partial(onp.meshgrid, indexing=indexing, sparse=sparse)\n jnp_fun = partial(jnp.meshgrid, indexing=indexing, sparse=sparse)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n @parameterized.named_parameters(\n jtu.cases_from_list(\n {\"testcase_name\": (\"_start_shape={}_stop_shape={}_num={}_endpoint={}\"\n \"_retstep={}_dtype={}\").format(\n start_shape, stop_shape, num, endpoint, retstep, dtype),\n \"start_shape\": start_shape, \"stop_shape\": stop_shape,\n \"num\": num, \"endpoint\": endpoint, \"retstep\": retstep,\n \"dtype\": dtype, \"rng_factory\": rng_factory}\n for start_shape in [(), (2,), (2, 2)]\n for stop_shape in [(), (2,), (2, 2)]\n for num in [0, 1, 2, 5, 20]\n for endpoint in [True, False]\n for retstep in [True, False]\n for dtype in number_dtypes + [None,]\n for rng_factory in [jtu.rand_default]))\n def testLinspace(self, start_shape, stop_shape, num, endpoint,\n retstep, dtype, rng_factory):\n if num == 1 and not endpoint and numpy_version < (1, 17, 5):\n raise SkipTest(\"Numpy < 1.17.5 has a linspace bug.\")\n rng = rng_factory()\n # relax default tolerances slightly\n tol = jtu.tolerance(dtype if dtype else onp.float32) * 10\n args_maker = self._GetArgsMaker(rng,\n [start_shape, stop_shape],\n [dtype, dtype])\n start, stop = args_maker()\n ndim = len(onp.shape(start + stop))\n for axis in range(-ndim, ndim):\n jnp_op = lambda start, stop: jnp.linspace(\n start, stop, num,\n endpoint=endpoint, retstep=retstep, dtype=dtype, axis=axis)\n onp_op = lambda start, stop: onp.linspace(\n start, stop, num,\n endpoint=endpoint, retstep=retstep, dtype=dtype, axis=axis)\n self._CheckAgainstNumpy(onp_op, jnp_op, args_maker,\n check_dtypes=False, tol=tol)\n # floating-point compute between jitted platforms and non-jit + rounding\n # cause unavoidable variation in integer truncation for some inputs.\n if dtype in (inexact_dtypes + [None,]):\n self._CompileAndCheck(jnp_op, args_maker,\n check_dtypes=False, atol=tol, rtol=tol)\n\n @parameterized.named_parameters(\n jtu.cases_from_list(\n {\"testcase_name\": (\"_start_shape={}_stop_shape={}_num={}_endpoint={}\"\n \"_base={}_dtype={}\").format(\n start_shape, stop_shape, num, endpoint, base,\n dtype.__name__ if dtype else \"None\"),\n \"start_shape\": start_shape,\n \"stop_shape\": stop_shape,\n \"num\": num, \"endpoint\": endpoint, \"base\": base,\n \"dtype\": dtype, \"rng_factory\": rng_factory}\n for start_shape in [(), (2,), (2, 2)]\n for stop_shape in [(), (2,), (2, 2)]\n for num in [0, 1, 2, 5, 20]\n for endpoint in [True, False]\n for base in [10.0, 2, onp.e]\n for dtype in inexact_dtypes + [None,]\n for rng_factory in [jtu.rand_default]))\n def testLogspace(self, start_shape, stop_shape, num,\n endpoint, base, dtype, rng_factory):\n if (dtype in int_dtypes and\n jtu.device_under_test() in (\"gpu\", \"tpu\") and\n not FLAGS.jax_enable_x64):\n raise unittest.SkipTest(\"GPUx32 truncated exponentiation\"\n \" doesn't exactly match other platforms.\")\n rng = rng_factory()\n # relax default tolerances slightly\n tol = {onp.float16: 2e-2, onp.float32: 1e-2, onp.float64: 1e-6,\n onp.complex64: 1e-3, onp.complex128: 1e-6}\n args_maker = self._GetArgsMaker(rng,\n [start_shape, stop_shape],\n [dtype, dtype])\n start, stop = args_maker()\n ndim = len(onp.shape(start + stop))\n for axis in range(-ndim, ndim):\n jnp_op = lambda start, stop: jnp.logspace(\n start, stop, num, endpoint=endpoint, base=base, dtype=dtype, axis=axis)\n onp_op = lambda start, stop: onp.logspace(\n start, stop, num, endpoint=endpoint, base=base, dtype=dtype, axis=axis)\n self._CheckAgainstNumpy(onp_op, jnp_op, args_maker,\n check_dtypes=False, tol=tol)\n if dtype in (inexact_dtypes + [None,]):\n # Why do compiled and op-by-op float16 np.power numbers differ\n # slightly more than expected?\n atol = {onp.float16: 1e-2}\n self._CompileAndCheck(jnp_op, args_maker,\n check_dtypes=False, atol=atol, rtol=tol)\n\n @parameterized.named_parameters(\n jtu.cases_from_list(\n {\"testcase_name\": (\"_start_shape={}_stop_shape={}_num={}_endpoint={}\"\n \"_dtype={}\").format(\n start_shape, stop_shape, num, endpoint, dtype),\n \"start_shape\": start_shape,\n \"stop_shape\": stop_shape,\n \"num\": num, \"endpoint\": endpoint,\n \"dtype\": dtype, \"rng_factory\": rng_factory}\n for start_shape in [(), (2,), (2, 2)]\n for stop_shape in [(), (2,), (2, 2)]\n for num in [0, 1, 2, 5, 20]\n for endpoint in [True, False]\n # NB: numpy's geomspace gives nonsense results on integer types\n for dtype in inexact_dtypes + [None,]\n for rng_factory in [jtu.rand_default]))\n def testGeomspace(self, start_shape, stop_shape, num,\n endpoint, dtype, rng_factory):\n rng = rng_factory()\n # relax default tolerances slightly\n tol = {onp.float16: 4e-3, onp.float32: 2e-3, onp.complex128: 1e-14}\n def args_maker():\n \"\"\"Test the set of inputs onp.geomspace is well-defined on.\"\"\"\n start, stop = self._GetArgsMaker(rng,\n [start_shape, stop_shape],\n [dtype, dtype])()\n # onp.geomspace can't handle differently ranked tensors\n # w. negative numbers!\n start, stop = jnp.broadcast_arrays(start, stop)\n if dtype in complex_dtypes:\n return start, stop\n # to avoid NaNs, non-complex start and stop cannot\n # differ in sign, elementwise\n start = start * jnp.sign(start) * jnp.sign(stop)\n return start, stop\n start, stop = args_maker()\n ndim = len(onp.shape(start + stop))\n for axis in range(-ndim, ndim):\n def jnp_op(start, stop):\n return jnp.geomspace(start, stop, num, endpoint=endpoint, dtype=dtype,\n axis=axis)\n def onp_op(start, stop):\n start = start.astype(onp.float32) if dtype == jnp.bfloat16 else start\n stop = stop.astype(onp.float32) if dtype == jnp.bfloat16 else stop\n return onp.geomspace(\n start, stop, num, endpoint=endpoint,\n dtype=dtype if dtype != jnp.bfloat16 else onp.float32,\n axis=axis).astype(dtype)\n self._CheckAgainstNumpy(onp_op, jnp_op, args_maker,\n check_dtypes=False, tol=tol)\n if dtype in (inexact_dtypes + [None,]):\n self._CompileAndCheck(jnp_op, args_maker,\n check_dtypes=False, atol=tol, rtol=tol)\n\n def testDisableNumpyRankPromotionBroadcasting(self):\n try:\n prev_flag = FLAGS.jax_numpy_rank_promotion\n FLAGS.jax_numpy_rank_promotion = \"allow\"\n jnp.ones(2) + jnp.ones((1, 2)) # works just fine\n finally:\n FLAGS.jax_numpy_rank_promotion = prev_flag\n\n try:\n prev_flag = FLAGS.jax_numpy_rank_promotion\n FLAGS.jax_numpy_rank_promotion = \"raise\"\n self.assertRaises(ValueError, lambda: jnp.ones(2) + jnp.ones((1, 2)))\n finally:\n FLAGS.jax_numpy_rank_promotion = prev_flag\n\n try:\n prev_flag = FLAGS.jax_numpy_rank_promotion\n FLAGS.jax_numpy_rank_promotion = \"warn\"\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n jnp.ones(2) + jnp.ones((1, 2))\n assert len(w) > 0\n msg = str(w[-1].message)\n expected_msg = (\"Following NumPy automatic rank promotion for add on \"\n \"shapes (2,) (1, 2).\")\n self.assertEqual(msg[:len(expected_msg)], expected_msg)\n\n prev_len = len(w)\n jnp.ones(2) + 3\n self.assertEqual(len(w), prev_len) # don't want to warn for scalars\n finally:\n FLAGS.jax_numpy_rank_promotion = prev_flag\n\n def testStackArrayArgument(self):\n # tests https://github.com/google/jax/issues/1271\n @api.jit\n def foo(x):\n return jnp.stack(x)\n foo(onp.zeros(2)) # doesn't crash\n\n @api.jit\n def foo(x):\n return jnp.concatenate(x)\n foo(onp.zeros((2, 2))) # doesn't crash\n\n def testReluGradientConstants(self):\n # This is a regression test that verifies that constants associated with the\n # gradient of np.maximum (from lax._balanced_eq) aren't hoisted into the\n # outermost jaxpr. This was producing some large materialized constants for\n # every relu activation in a model.\n def body(i, xy):\n x, y = xy\n y = y + jax.grad(lambda z: jnp.sum(jnp.maximum(z, 0.)))(x)\n return x, y\n\n f = lambda y: lax.fori_loop(0, 5, body, (y, y))\n wrapped = linear_util.wrap_init(f)\n pv = partial_eval.PartialVal.unknown(jax.ShapedArray((3, 4), onp.float32))\n _, _, consts = partial_eval.trace_to_jaxpr(wrapped, [pv])\n self.assertFalse(\n any(onp.array_equal(x, onp.full((3, 4), 2., dtype=onp.float32))\n for x in consts))\n\n @parameterized.named_parameters(\n {\"testcase_name\": \"_from={}_to={}\".format(from_shape, to_shape),\n \"rng_factory\": rng_factory, \"from_shape\": from_shape, \"to_shape\": to_shape}\n for from_shape, to_shape in [\n [(1, 3), (4, 3)],\n [(3,), (2, 1, 3)],\n [(3,), (3, 3)],\n [(1,), (3,)],\n ]\n for rng_factory in [jtu.rand_default])\n def testBroadcastTo(self, from_shape, to_shape, rng_factory):\n rng = rng_factory()\n args_maker = self._GetArgsMaker(rng, [from_shape], [onp.float32])\n onp_op = lambda x: onp.broadcast_to(x, to_shape)\n jnp_op = lambda x: jnp.broadcast_to(x, to_shape)\n self._CheckAgainstNumpy(onp_op, jnp_op, args_maker, check_dtypes=True)\n self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)\n\n def testBroadcastToIssue1522(self):\n self.assertRaisesRegex(\n ValueError, \"Incompatible shapes for broadcasting: .*\",\n lambda: jnp.broadcast_to(onp.ones((2, 3)), (1, 3)))\n\n def testBroadcastToIntIssue1548(self):\n self.assertAllClose(jnp.broadcast_to(1, (3, 2)), onp.ones((3, 2)),\n check_dtypes=False)\n\n def testBroadcastToOnScalar(self):\n self.assertIsInstance(jnp.broadcast_to(10.0, ()), jnp.ndarray)\n self.assertIsInstance(onp.broadcast_to(10.0, ()), onp.ndarray)\n\n def testPrecision(self):\n\n ones_1d = onp.ones((2,))\n ones_2d = onp.ones((2, 2))\n ones_3d = onp.ones((2, 2, 2))\n HIGHEST = lax.Precision.HIGHEST\n\n jtu.assert_dot_precision(None, jnp.dot, ones_1d, ones_1d)\n jtu.assert_dot_precision(\n HIGHEST,\n partial(jnp.dot, precision=HIGHEST),\n ones_1d, ones_1d)\n jtu.assert_dot_precision(\n HIGHEST,\n partial(jnp.dot, precision=HIGHEST),\n ones_3d, ones_3d)\n jtu.assert_dot_precision(\n HIGHEST,\n partial(jnp.matmul, precision=HIGHEST),\n ones_2d, ones_2d)\n jtu.assert_dot_precision(\n HIGHEST,\n partial(jnp.vdot, precision=HIGHEST),\n ones_1d, ones_1d)\n jtu.assert_dot_precision(\n HIGHEST,\n partial(jnp.tensordot, axes=2, precision=HIGHEST),\n ones_2d, ones_2d)\n jtu.assert_dot_precision(\n HIGHEST,\n partial(jnp.tensordot, axes=(0, 0), precision=HIGHEST),\n ones_1d, ones_1d)\n jtu.assert_dot_precision(\n HIGHEST,\n partial(jnp.tensordot, axes=((0,), (0,)), precision=HIGHEST),\n ones_1d, ones_1d)\n jtu.assert_dot_precision(\n HIGHEST,\n partial(jnp.einsum, 'i,i', precision=HIGHEST),\n ones_1d, ones_1d)\n jtu.assert_dot_precision(\n HIGHEST,\n partial(jnp.einsum, 'ij,ij', precision=HIGHEST),\n ones_2d, ones_2d)\n jtu.assert_dot_precision(\n HIGHEST,\n partial(jnp.inner, precision=HIGHEST),\n ones_1d, ones_1d)\n\n @parameterized.named_parameters(\n jtu.cases_from_list(\n {\"testcase_name\": (\"_shape={}_axis={}_dtype={}\").format(shape, axis, dtype),\n \"shape\": shape,\n \"axis\": axis,\n \"dtype\": dtype, \"rng_factory\": rng_factory}\n for shape in [(10,), (10, 15), (10, 15, 20)]\n for _num_axes in range(len(shape))\n for axis in itertools.combinations(range(len(shape)), _num_axes)\n for dtype in inexact_dtypes\n for rng_factory in [jtu.rand_default]))\n def testGradient(self, shape, axis, dtype, rng_factory):\n rng = rng_factory()\n args_maker = self._GetArgsMaker(rng, [shape], [dtype])\n jnp_fun = lambda y: jnp.gradient(y, axis=axis)\n onp_fun = lambda y: onp.gradient(y, axis=axis)\n self._CheckAgainstNumpy(\n onp_fun, jnp_fun, args_maker, check_dtypes=False)\n self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n\n def testZerosShapeErrors(self):\n # see https://github.com/google/jax/issues/1822\n self.assertRaisesRegex(\n TypeError,\n \"Shapes must be 1D sequences of concrete values of integer type.*\",\n lambda: jnp.zeros(1.))\n self.assertRaisesRegex(\n TypeError,\n \"Shapes must be 1D sequences of concrete values of integer type.*\\n\"\n \"If using `jit`, try using `static_argnums` or applying `jit` to smaller subfunctions.\",\n lambda: api.jit(jnp.zeros)(2))\n\n def testTraceMethod(self):\n x = onp.random.randn(3, 4).astype(jnp.float_)\n self.assertAllClose(x.trace(), jnp.array(x).trace(), check_dtypes=True)\n self.assertAllClose(x.trace(), api.jit(lambda y: y.trace())(x),\n check_dtypes=True)\n\n# Most grad tests are at the lax level (see lax_test.py), but we add some here\n# as needed for e.g. particular compound ops of interest.\n\nGradTestSpec = collections.namedtuple(\n \"GradTestSpec\",\n [\"op\", \"nargs\", \"order\", \"rng_factory\", \"dtypes\", \"name\", \"tol\"])\ndef grad_test_spec(op, nargs, order, rng_factory, dtypes, name=None, tol=None):\n return GradTestSpec(\n op, nargs, order, rng_factory, dtypes, name or op.__name__, tol)\n\nGRAD_TEST_RECORDS = [\n grad_test_spec(jnp.arcsinh, nargs=1, order=2,\n rng_factory=jtu.rand_positive,\n dtypes=[onp.float64, onp.complex64], tol=1e-4),\n grad_test_spec(jnp.arccosh, nargs=1, order=2,\n rng_factory=jtu.rand_positive,\n dtypes=[onp.float64, onp.complex64], tol=1e-4),\n grad_test_spec(jnp.arctanh, nargs=1, order=2,\n rng_factory=partial(jtu.rand_uniform, -0.9, 0.9),\n dtypes=[onp.float64, onp.complex64], tol=1e-4),\n grad_test_spec(jnp.logaddexp, nargs=2, order=1,\n rng_factory=partial(jtu.rand_uniform, -0.9, 0.9),\n dtypes=[onp.float64], tol=1e-4),\n grad_test_spec(jnp.logaddexp2, nargs=2, order=2,\n rng_factory=partial(jtu.rand_uniform, -0.9, 0.9),\n dtypes=[onp.float64], tol=1e-4),\n]\n\nGradSpecialValuesTestSpec = collections.namedtuple(\n \"GradSpecialValuesTestSpec\", [\"op\", \"values\", \"order\"])\n\nGRAD_SPECIAL_VALUE_TEST_RECORDS = [\n GradSpecialValuesTestSpec(jnp.arcsinh, [0., 1000.], 2),\n GradSpecialValuesTestSpec(jnp.arccosh, [1000.], 2),\n GradSpecialValuesTestSpec(jnp.arctanh, [0.], 2),\n GradSpecialValuesTestSpec(jnp.sinc, [0.], 1),\n]\n\ndef num_float_bits(dtype):\n return jnp.finfo(dtypes.canonicalize_dtype(dtype)).bits\n\nclass NumpyGradTests(jtu.JaxTestCase):\n @parameterized.named_parameters(itertools.chain.from_iterable(\n jtu.cases_from_list(\n {\"testcase_name\": jtu.format_test_name_suffix(\n rec.name, shapes, itertools.repeat(dtype)),\n \"op\": rec.op, \"rng_factory\": rec.rng_factory, \"shapes\": shapes, \"dtype\": dtype,\n \"order\": rec.order, \"tol\": rec.tol}\n for shapes in CombosWithReplacement(nonempty_shapes, rec.nargs)\n for dtype in rec.dtypes)\n for rec in GRAD_TEST_RECORDS))\n def testOpGrad(self, op, rng_factory, shapes, dtype, order, tol):\n rng = rng_factory()\n tol = {onp.float32: 1e-1, onp.complex64: 1e-1}\n args = tuple(rng(shape, dtype) for shape in shapes)\n check_grads(op, args, order, [\"fwd\", \"rev\"], tol, tol)\n\n @parameterized.named_parameters(itertools.chain.from_iterable(\n jtu.cases_from_list(\n {\"testcase_name\": \"_{}_{}\".format(rec.op.__name__, special_value),\n \"op\": rec.op, \"special_value\": special_value, \"order\": rec.order}\n for special_value in rec.values)\n for rec in GRAD_SPECIAL_VALUE_TEST_RECORDS))\n def testOpGradSpecialValue(self, op, special_value, order):\n check_grads(op, (special_value,), order, [\"fwd\", \"rev\"],\n atol={onp.float32: 3e-3})\n\n def testTakeAlongAxisIssue1521(self):\n # https://github.com/google/jax/issues/1521\n idx = jnp.repeat(jnp.arange(3), 10).reshape((30, 1))\n\n def f(x):\n y = x * jnp.arange(3.).reshape((1, 3))\n return jnp.take_along_axis(y, idx, -1).sum()\n\n check_grads(f, (1.,), order=1)\n\n\nif __name__ == \"__main__\":\n absltest.main()\n" ]
[ [ "numpy.diag", "numpy.take_along_axis", "numpy.split", "numpy.expand_dims", "numpy.dot", "numpy.take", "numpy.linspace", "numpy.asarray", "numpy.squeeze", "numpy.flipud", "numpy.nan_to_num", "numpy.dtype", "numpy.round", "numpy.concatenate", "numpy.isneginf", "numpy.mean", "numpy.tri", "numpy.random.randn", "numpy.cross", "numpy.where", "numpy.trace", "numpy.random.randint", "numpy.frexp", "numpy.swapaxes", "numpy.vander", "numpy.pad", "numpy.clip", "numpy.reshape", "numpy.arange", "numpy.eye", "numpy.fliplr", "numpy.version.version.split", "numpy.matmul", "numpy.full", "numpy.std", "numpy.tensordot", "numpy.count_nonzero", "numpy.float32", "numpy.repeat", "numpy.zeros", "numpy.isclose", "numpy.rot90", "numpy.msort", "numpy.nonzero", "numpy.isnan", "numpy.logspace", "numpy.median", "numpy.full_like", "numpy.int64", "numpy.append", "numpy.ndim", "numpy.identity", "numpy.argsort", "numpy.array", "numpy.random.RandomState", "numpy.diagonal", "numpy.flip", "numpy.random.random", "numpy.inner", "numpy.gradient", "numpy.isposinf", "numpy.tile", "numpy.ones", "numpy.geomspace", "numpy.ldexp", "numpy.longlong", "numpy.shape", "numpy.broadcast_to", "numpy.prod", "numpy.diag_indices", "numpy.average" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wongwsvincent/pennylane-cirq
[ "14f421a31016949ec6f3172f90e7f06a6674e913" ]
[ "tests/test_expval.py" ]
[ "# Copyright 2018 Xanadu Quantum Technologies 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\"\"\"Tests that exectation values are correctly computed in the plugin devices\"\"\"\nimport pytest\n\nimport numpy as np\nimport pennylane as qml\nfrom contextlib import contextmanager\n\nfrom conftest import U, U2, A, B\n\n\nnp.random.seed(42)\n\n\n@contextmanager\ndef mimic_execution_for_expval(device):\n device.reset()\n\n with device.execution_context():\n yield\n\n if not device.shots is None:\n device._samples = device.generate_samples()\n\n\[email protected](\"shots\", [None, 8192])\nclass TestExpval:\n \"\"\"Test expectation values\"\"\"\n\n def test_identity_expectation(self, device, shots, tol):\n \"\"\"Test that identity expectation value (i.e. the trace) is 1\"\"\"\n theta = 0.432\n phi = 0.123\n\n dev = device(2)\n\n with mimic_execution_for_expval(dev):\n dev.apply(\n [qml.RX(theta, wires=[0]), qml.RX(phi, wires=[1]), qml.CNOT(wires=[0, 1]),]\n )\n\n O = qml.Identity\n name = \"Identity\"\n\n dev._obs_queue = [O(wires=[0], do_queue=False), O(wires=[1], do_queue=False)]\n\n res = np.array(\n [dev.expval(O(wires=[0], do_queue=False)), dev.expval(O(wires=[1], do_queue=False)),]\n )\n\n assert np.allclose(res, np.array([1, 1]), **tol)\n\n def test_pauliz_expectation(self, device, shots, tol):\n \"\"\"Test that PauliZ expectation value is correct\"\"\"\n theta = 0.432\n phi = 0.123\n\n dev = device(2)\n\n with mimic_execution_for_expval(dev):\n dev.apply(\n [qml.RX(theta, wires=[0]), qml.RX(phi, wires=[1]), qml.CNOT(wires=[0, 1]),]\n )\n\n O = qml.PauliZ\n name = \"PauliZ\"\n\n dev._obs_queue = [O(wires=[0], do_queue=False), O(wires=[1], do_queue=False)]\n\n res = np.array(\n [dev.expval(O(wires=[0], do_queue=False)), dev.expval(O(wires=[1], do_queue=False)),]\n )\n\n assert np.allclose(res, np.array([np.cos(theta), np.cos(theta) * np.cos(phi)]), **tol)\n\n def test_paulix_expectation(self, device, shots, tol):\n \"\"\"Test that PauliX expectation value is correct\"\"\"\n theta = 0.432\n phi = 0.123\n\n dev = device(2)\n O = qml.PauliX\n\n with mimic_execution_for_expval(dev):\n dev.apply(\n [qml.RY(theta, wires=[0]), qml.RY(phi, wires=[1]), qml.CNOT(wires=[0, 1]),],\n rotations=O(wires=[0], do_queue=False).diagonalizing_gates()\n + O(wires=[1], do_queue=False).diagonalizing_gates(),\n )\n\n dev._obs_queue = [O(wires=[0], do_queue=False), O(wires=[1], do_queue=False)]\n\n res = np.array(\n [dev.expval(O(wires=[0], do_queue=False)), dev.expval(O(wires=[1], do_queue=False)),]\n )\n assert np.allclose(res, np.array([np.sin(theta) * np.sin(phi), np.sin(phi)]), **tol)\n\n def test_pauliy_expectation(self, device, shots, tol):\n \"\"\"Test that PauliY expectation value is correct\"\"\"\n theta = 0.432\n phi = 0.123\n\n dev = device(2)\n O = qml.PauliY\n\n with mimic_execution_for_expval(dev):\n dev.apply(\n [qml.RX(theta, wires=[0]), qml.RX(phi, wires=[1]), qml.CNOT(wires=[0, 1]),],\n rotations=O(wires=[0], do_queue=False).diagonalizing_gates()\n + O(wires=[1], do_queue=False).diagonalizing_gates(),\n )\n\n dev._obs_queue = [O(wires=[0], do_queue=False), O(wires=[1], do_queue=False)]\n\n res = np.array(\n [dev.expval(O(wires=[0], do_queue=False)), dev.expval(O(wires=[1], do_queue=False)),]\n )\n assert np.allclose(res, np.array([0, -(np.cos(theta)) * np.sin(phi)]), **tol)\n\n def test_hadamard_expectation(self, device, shots, tol):\n \"\"\"Test that Hadamard expectation value is correct\"\"\"\n theta = 0.432\n phi = 0.123\n\n dev = device(2)\n O = qml.Hadamard\n\n with mimic_execution_for_expval(dev):\n dev.apply(\n [qml.RY(theta, wires=[0]), qml.RY(phi, wires=[1]), qml.CNOT(wires=[0, 1]),],\n rotations=O(wires=[0], do_queue=False).diagonalizing_gates()\n + O(wires=[1], do_queue=False).diagonalizing_gates(),\n )\n\n dev._obs_queue = [O(wires=[0], do_queue=False), O(wires=[1], do_queue=False)]\n\n res = np.array(\n [dev.expval(O(wires=[0], do_queue=False)), dev.expval(O(wires=[1], do_queue=False)),]\n )\n expected = np.array(\n [\n np.sin(theta) * np.sin(phi) + np.cos(theta),\n np.cos(theta) * np.cos(phi) + np.sin(phi),\n ]\n ) / np.sqrt(2)\n assert np.allclose(res, expected, **tol)\n\n def test_hermitian_expectation(self, device, shots, tol):\n \"\"\"Test that arbitrary Hermitian expectation values are correct\"\"\"\n theta = 0.432\n phi = 0.123\n\n dev = device(2)\n O = qml.Hermitian\n\n with mimic_execution_for_expval(dev):\n dev.apply(\n [qml.RY(theta, wires=[0]), qml.RY(phi, wires=[1]), qml.CNOT(wires=[0, 1]),],\n rotations=O(A, wires=[0], do_queue=False).diagonalizing_gates()\n + O(A, wires=[1], do_queue=False).diagonalizing_gates(),\n )\n\n dev._obs_queue = [\n O(A, wires=[0], do_queue=False),\n O(A, wires=[1], do_queue=False),\n ]\n\n res = np.array(\n [\n dev.expval(O(A, wires=[0], do_queue=False)),\n dev.expval(O(A, wires=[1], do_queue=False)),\n ]\n )\n\n a = A[0, 0]\n re_b = A[0, 1].real\n d = A[1, 1]\n ev1 = ((a - d) * np.cos(theta) + 2 * re_b * np.sin(theta) * np.sin(phi) + a + d) / 2\n ev2 = ((a - d) * np.cos(theta) * np.cos(phi) + 2 * re_b * np.sin(phi) + a + d) / 2\n expected = np.array([ev1, ev2])\n\n assert np.allclose(res, expected, **tol)\n\n def test_multi_mode_hermitian_expectation(self, device, shots, tol):\n \"\"\"Test that arbitrary multi-mode Hermitian expectation values are correct\"\"\"\n theta = 0.432\n phi = 0.123\n\n dev = device(2)\n O = qml.Hermitian\n\n with mimic_execution_for_expval(dev):\n dev.apply(\n [qml.RY(theta, wires=[0]), qml.RY(phi, wires=[1]), qml.CNOT(wires=[0, 1]),],\n rotations=O(B, wires=[0, 1], do_queue=False).diagonalizing_gates(),\n )\n\n dev._obs_queue = [O(B, wires=[0, 1], do_queue=False)]\n\n res = np.array([dev.expval(O(B, wires=[0, 1], do_queue=False))])\n\n # below is the analytic expectation value for this circuit with arbitrary\n # Hermitian observable B\n expected = 0.5 * (\n 6 * np.cos(theta) * np.sin(phi)\n - np.sin(theta) * (8 * np.sin(phi) + 7 * np.cos(phi) + 3)\n - 2 * np.sin(phi)\n - 6 * np.cos(phi)\n - 6\n )\n\n assert np.allclose(res, expected, **tol)\n\n\[email protected](\"shots\", [None, 8192])\nclass TestTensorExpval:\n \"\"\"Test tensor expectation values\"\"\"\n\n def test_paulix_pauliy(self, device, shots, tol):\n \"\"\"Test that a tensor product involving PauliX and PauliY works correctly\"\"\"\n theta = 0.432\n phi = 0.123\n varphi = -0.543\n\n dev = device(3)\n\n obs = qml.PauliX(wires=[0], do_queue=False) @ qml.PauliY(wires=[2], do_queue=False)\n\n with mimic_execution_for_expval(dev):\n dev.apply(\n [\n qml.RX(theta, wires=[0]),\n qml.RX(phi, wires=[1]),\n qml.RX(varphi, wires=[2]),\n qml.CNOT(wires=[0, 1]),\n qml.CNOT(wires=[1, 2]),\n ],\n rotations=obs.diagonalizing_gates(),\n )\n\n res = dev.expval(obs)\n expected = np.sin(theta) * np.sin(phi) * np.sin(varphi)\n\n assert np.allclose(res, expected, **tol)\n\n def test_pauliz_hadamard(self, device, shots, tol):\n \"\"\"Test that a tensor product involving PauliZ and PauliY and hadamard works correctly\"\"\"\n theta = 0.432\n phi = 0.123\n varphi = -0.543\n\n dev = device(3)\n\n obs = (\n qml.PauliZ(wires=[0], do_queue=False)\n @ qml.Hadamard(wires=[1], do_queue=False)\n @ qml.PauliY(wires=[2], do_queue=False)\n )\n\n with mimic_execution_for_expval(dev):\n dev.apply(\n [\n qml.RX(theta, wires=[0]),\n qml.RX(phi, wires=[1]),\n qml.RX(varphi, wires=[2]),\n qml.CNOT(wires=[0, 1]),\n qml.CNOT(wires=[1, 2]),\n ],\n rotations=obs.diagonalizing_gates(),\n )\n\n res = dev.expval(obs)\n expected = -(np.cos(varphi) * np.sin(phi) + np.sin(varphi) * np.cos(theta)) / np.sqrt(2)\n\n assert np.allclose(res, expected, **tol)\n\n def test_hermitian(self, device, shots, tol):\n \"\"\"Test that a tensor product involving qml.Hermitian works correctly\"\"\"\n theta = 0.432\n phi = 0.123\n varphi = -0.543\n\n dev = device(3)\n\n A = np.array(\n [\n [-6, 2 + 1j, -3, -5 + 2j],\n [2 - 1j, 0, 2 - 1j, -5 + 4j],\n [-3, 2 + 1j, 0, -4 + 3j],\n [-5 - 2j, -5 - 4j, -4 - 3j, -6],\n ]\n )\n obs = qml.PauliZ(wires=[0], do_queue=False) @ qml.Hermitian(A, wires=[1, 2], do_queue=False)\n\n with mimic_execution_for_expval(dev):\n dev.apply(\n [\n qml.RX(theta, wires=[0]),\n qml.RX(phi, wires=[1]),\n qml.RX(varphi, wires=[2]),\n qml.CNOT(wires=[0, 1]),\n qml.CNOT(wires=[1, 2]),\n ],\n rotations=obs.diagonalizing_gates(),\n )\n\n res = dev.expval(obs)\n\n expected = 0.5 * (\n -6 * np.cos(theta) * (np.cos(varphi) + 1)\n - 2 * np.sin(varphi) * (np.cos(theta) + np.sin(phi) - 2 * np.cos(phi))\n + 3 * np.cos(varphi) * np.sin(phi)\n + np.sin(phi)\n )\n\n assert np.allclose(res, expected, **tol)\n" ]
[ [ "numpy.sqrt", "numpy.allclose", "numpy.random.seed", "numpy.cos", "numpy.sin", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Atul-Anand-Jha/reading_comprehension_tf
[ "9d45ff62aa4004c466e4fe6b6639cec754199b2b" ]
[ "reading_comprehension/reading_comprehension_run.py" ]
[ "import argparse\nimport os.path\nimport time\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.python import debug as tf_debug\n\nfrom util.default_util import *\nfrom util.param_util import *\nfrom util.model_util import *\nfrom util.eval_util import *\nfrom util.debug_logger import *\nfrom util.train_logger import *\nfrom util.eval_logger import *\nfrom util.summary_writer import *\n\ndef add_arguments(parser):\n parser.add_argument(\"--mode\", help=\"mode to run\", required=True)\n parser.add_argument(\"--config\", help=\"path to json config\", required=True)\n\ndef sample_predict(sess,\n model,\n batch_size,\n ckpt_file,\n eval_mode):\n load_model(sess, model, ckpt_file, eval_mode)\n \n data_size = len(model.input_data)\n feed_dict, data_dict = generate_feed_dict(model, data_size, batch_size)\n sess.run(model.data_pipeline.initializer, feed_dict=feed_dict)\n \n predict_span = []\n while True:\n try:\n infer_result = model.model.infer(sess, model.word_embedding)\n predict_span.extend(infer_result.predict)\n except tf.errors.OutOfRangeError:\n break\n \n predict_size = len(predict_span)\n if data_size != predict_size:\n raise ValueError(\"input data size {0} and output data size {1} is not the same\".format(data_size, predict_size))\n \n sample_result = []\n for i in range(data_size):\n sample_id = data_dict[\"input_data\"][i][\"id\"]\n context = data_dict[\"input_context\"][i]\n context_tokens = context.split(\" \")\n \n predict_start = int(predict_span[i][0])\n predict_end = int(predict_span[i][1])\n predict = \" \".join(context_tokens[predict_start:predict_end+1])\n \n sample_result.append({\n \"id\": sample_id,\n \"context\": context,\n \"predict\": {\n \"text\": predict,\n \"start\": predict_start,\n \"end\": predict_end\n },\n \"answers\": []\n })\n \n for answer in data_dict[\"input_data\"][i][\"answers\"]:\n label_start = int(answer[\"start\"])\n label_end = int(answer[\"end\"])\n label = \" \".join(context_tokens[label_start:label_end+1])\n \n sample_result[-1][\"answers\"].append({\n \"text\": label,\n \"start\": label_start,\n \"end\": label_end\n })\n \n return sample_result\n\ndef extrinsic_eval(logger,\n summary_writer,\n sample_result,\n metric_list,\n detail_type,\n global_step,\n epoch):\n predict_text = []\n label_text = []\n for sample in sample_result:\n predict_text.append(sample[\"predict\"][\"text\"])\n label_text.append([])\n \n for answer in sample[\"answers\"]:\n label_text[-1].append(answer[\"text\"])\n \n eval_result_list = []\n sample_output = sample_result\n for metric in metric_list:\n score = evaluate_from_data(predict_text, label_text, metric)\n summary_writer.add_value_summary(metric, score, global_step)\n eval_result = ExtrinsicEvalLog(metric=metric,\n score=score, sample_output=None, sample_size=len(sample_output))\n eval_result_list.append(eval_result)\n \n if detail_type == \"simplified\":\n sample_output = { sample[\"id\"]: sample[\"predict\"][\"text\"] for sample in sample_output }\n \n eval_result_detail = ExtrinsicEvalLog(metric=\"detail\",\n score=0.0, sample_output=sample_output, sample_size=len(sample_output))\n basic_info = BasicInfoEvalLog(epoch=epoch, global_step=global_step)\n \n logger.update_extrinsic_eval(eval_result_list, basic_info)\n logger.update_extrinsic_eval_detail(eval_result_detail, basic_info)\n logger.check_extrinsic_eval()\n logger.check_extrinsic_eval_detail()\n\ndef decoding_eval(logger,\n sample_result,\n sample_size,\n random_seed,\n global_step,\n epoch):\n np.random.seed(random_seed)\n sample_ids = np.random.randint(0, len(sample_result)-1, size=sample_size)\n sample_data = [sample_result[sample_id] for sample_id in sample_ids]\n \n eval_result_list = []\n for sample in sample_data:\n sample_input = sample\n sample_output = sample[\"predict\"][\"text\"]\n sample_reference_list = []\n for answer in sample[\"answers\"]:\n sample_reference = answer[\"text\"]\n sample_reference_list.append(sample_reference)\n \n eval_result = DecodingEvalLog(sample_input=sample_input,\n sample_output=sample_output, sample_reference=sample_reference_list)\n eval_result_list.append(eval_result)\n \n basic_info = BasicInfoEvalLog(epoch=epoch, global_step=global_step)\n \n logger.update_decoding_eval(eval_result_list, basic_info)\n logger.check_decoding_eval()\n\ndef generate_feed_dict(model,\n data_size,\n batch_size):\n data_size = min(data_size, len(model.input_data))\n input_data = model.input_data[:data_size]\n input_answer = model.input_answer[:data_size]\n \n input_question = model.input_question[:data_size]\n input_question_word = model.input_question_word[:data_size] if model.input_question_word is not None else None\n input_question_subword = model.input_question_subword[:data_size] if model.input_question_subword is not None else None\n input_question_char = model.input_question_char[:data_size] if model.input_question_char is not None else None\n \n input_context = model.input_context[:data_size]\n input_context_word = model.input_context_word[:data_size] if model.input_context_word is not None else None\n input_context_subword = model.input_context_subword[:data_size] if model.input_context_subword is not None else None\n input_context_char = model.input_context_char[:data_size] if model.input_context_char is not None else None\n \n data_dict = {\n \"data_size\": data_size,\n \"input_data\": input_data,\n \"input_answer\": input_answer,\n \"input_question\": input_question,\n \"input_question_word\": input_question_word,\n \"input_question_subword\": input_question_subword,\n \"input_question_char\": input_question_char,\n \"input_context\": input_context,\n \"input_context_word\": input_context_word,\n \"input_context_subword\": input_context_subword,\n \"input_context_char\": input_context_char\n }\n \n feed_dict = {\n model.data_pipeline.data_size_placeholder: data_size,\n model.data_pipeline.batch_size_placeholder: batch_size\n }\n\n if model.data_pipeline.input_answer_placeholder is not None and input_answer is not None:\n feed_dict[model.data_pipeline.input_answer_placeholder] = input_answer\n\n if model.data_pipeline.input_question_placeholder is not None and input_question is not None:\n feed_dict[model.data_pipeline.input_question_placeholder] = input_question\n if model.data_pipeline.input_question_word_placeholder is not None and input_question_word is not None:\n feed_dict[model.data_pipeline.input_question_word_placeholder] = input_question_word\n if model.data_pipeline.input_question_subword_placeholder is not None and input_question_subword is not None:\n feed_dict[model.data_pipeline.input_question_subword_placeholder] = input_question_subword\n if model.data_pipeline.input_question_char_placeholder is not None and input_question_char is not None:\n feed_dict[model.data_pipeline.input_question_char_placeholder] = input_question_char\n \n if model.data_pipeline.input_context_placeholder is not None and input_context is not None:\n feed_dict[model.data_pipeline.input_context_placeholder] = input_context\n if model.data_pipeline.input_context_word_placeholder is not None and input_context_word is not None:\n feed_dict[model.data_pipeline.input_context_word_placeholder] = input_context_word\n if model.data_pipeline.input_context_subword_placeholder is not None and input_context_subword is not None:\n feed_dict[model.data_pipeline.input_context_subword_placeholder] = input_context_subword\n if model.data_pipeline.input_context_char_placeholder is not None and input_context_char is not None:\n feed_dict[model.data_pipeline.input_context_char_placeholder] = input_context_char\n \n return feed_dict, data_dict\n\ndef train(logger,\n hyperparams,\n enable_eval=True,\n enable_debug=False):\n config_proto = get_config_proto(hyperparams.device_log_device_placement,\n hyperparams.device_allow_soft_placement, hyperparams.device_allow_growth,\n hyperparams.device_per_process_gpu_memory_fraction)\n \n summary_output_dir = hyperparams.train_summary_output_dir\n if not tf.gfile.Exists(summary_output_dir):\n tf.gfile.MakeDirs(summary_output_dir)\n \n logger.log_print(\"##### create train model #####\")\n train_model = create_train_model(logger, hyperparams)\n train_sess = tf.Session(config=config_proto, graph=train_model.graph)\n if enable_debug == True:\n train_sess = tf_debug.LocalCLIDebugWrapperSession(train_sess)\n \n train_summary_writer = SummaryWriter(train_model.graph, os.path.join(summary_output_dir, \"train\"))\n init_model(train_sess, train_model)\n train_logger = TrainLogger(hyperparams.data_log_output_dir)\n \n if enable_eval == True:\n logger.log_print(\"##### create infer model #####\")\n infer_model = create_infer_model(logger, hyperparams)\n infer_sess = tf.Session(config=config_proto, graph=infer_model.graph)\n if enable_debug == True:\n infer_sess = tf_debug.LocalCLIDebugWrapperSession(infer_sess)\n \n infer_summary_writer = SummaryWriter(infer_model.graph, os.path.join(summary_output_dir, \"infer\"))\n init_model(infer_sess, infer_model)\n eval_logger = EvalLogger(hyperparams.data_log_output_dir)\n \n logger.log_print(\"##### start training #####\")\n global_step = 0\n for epoch in range(hyperparams.train_num_epoch):\n feed_dict, data_dict = generate_feed_dict(train_model, len(train_model.input_answer), hyperparams.train_batch_size)\n train_sess.run(train_model.data_pipeline.initializer, feed_dict=feed_dict)\n \n step_in_epoch = 0\n while True:\n try:\n start_time = time.time()\n train_result = train_model.model.train(train_sess, train_model.word_embedding)\n end_time = time.time()\n \n global_step = train_result.global_step\n step_in_epoch += 1\n train_logger.update(train_result, epoch, step_in_epoch, end_time-start_time)\n \n if step_in_epoch % hyperparams.train_step_per_stat == 0:\n train_logger.check()\n train_summary_writer.add_summary(train_result.summary, global_step)\n if step_in_epoch % hyperparams.train_step_per_ckpt == 0:\n train_model.model.save(train_sess, global_step, \"debug\")\n if step_in_epoch % hyperparams.train_step_per_eval == 0 and enable_eval == True:\n ckpt_file = infer_model.model.get_latest_ckpt(\"debug\")\n sample_result = sample_predict(infer_sess, infer_model, hyperparams.train_eval_batch_size, ckpt_file, \"debug\")\n extrinsic_eval(eval_logger, infer_summary_writer, sample_result,\n hyperparams.train_eval_metric, hyperparams.train_eval_detail_type, global_step, epoch)\n decoding_eval(eval_logger, sample_result, hyperparams.train_decoding_sample_size, \n hyperparams.train_random_seed + global_step, global_step, epoch)\n except tf.errors.OutOfRangeError:\n train_logger.check()\n train_summary_writer.add_summary(train_result.summary, global_step)\n train_model.model.save(train_sess, global_step, \"epoch\")\n if enable_eval == True:\n ckpt_file = infer_model.model.get_latest_ckpt(\"epoch\")\n sample_result = sample_predict(infer_sess, infer_model, hyperparams.train_eval_batch_size, ckpt_file, \"epoch\")\n extrinsic_eval(eval_logger, infer_summary_writer, sample_result,\n hyperparams.train_eval_metric, hyperparams.train_eval_detail_type, global_step, epoch)\n decoding_eval(eval_logger, sample_result, hyperparams.train_decoding_sample_size, \n hyperparams.train_random_seed + global_step, global_step, epoch)\n break\n\n train_summary_writer.close_writer()\n if enable_eval == True:\n infer_summary_writer.close_writer()\n \n logger.log_print(\"##### finish training #####\")\n\ndef evaluate(logger,\n hyperparams,\n enable_debug=False): \n config_proto = get_config_proto(hyperparams.device_log_device_placement,\n hyperparams.device_allow_soft_placement, hyperparams.device_allow_growth,\n hyperparams.device_per_process_gpu_memory_fraction)\n \n summary_output_dir = hyperparams.train_summary_output_dir\n if not tf.gfile.Exists(summary_output_dir):\n tf.gfile.MakeDirs(summary_output_dir)\n \n logger.log_print(\"##### create infer model #####\")\n infer_model = create_infer_model(logger, hyperparams)\n infer_sess = tf.Session(config=config_proto, graph=infer_model.graph)\n if enable_debug == True:\n infer_sess = tf_debug.LocalCLIDebugWrapperSession(infer_sess)\n \n infer_summary_writer = SummaryWriter(infer_model.graph, os.path.join(summary_output_dir, \"infer\"))\n init_model(infer_sess, infer_model)\n eval_logger = EvalLogger(hyperparams.data_log_output_dir)\n \n logger.log_print(\"##### start evaluation #####\")\n global_step = 0\n eval_mode = \"debug\" if enable_debug == True else \"epoch\"\n ckpt_file_list = infer_model.model.get_ckpt_list(eval_mode)\n for i, ckpt_file in enumerate(ckpt_file_list):\n sample_result = sample_predict(infer_sess, infer_model, hyperparams.train_eval_batch_size, ckpt_file, eval_mode)\n extrinsic_eval(eval_logger, infer_summary_writer, sample_result,\n hyperparams.train_eval_metric, hyperparams.train_eval_detail_type, global_step, i)\n decoding_eval(eval_logger, sample_result,\n hyperparams.train_decoding_sample_size, hyperparams.train_random_seed, global_step, i)\n \n infer_summary_writer.close_writer()\n logger.log_print(\"##### finish evaluation #####\")\n\ndef main(args):\n hyperparams = load_hyperparams(args.config)\n logger = DebugLogger(hyperparams.data_log_output_dir)\n \n tf_version = check_tensorflow_version()\n logger.log_print(\"# tensorflow verison is {0}\".format(tf_version))\n \n if (args.mode == 'train'):\n train(logger, hyperparams, enable_eval=False, enable_debug=False)\n elif (args.mode == 'train_eval'):\n train(logger, hyperparams, enable_eval=True, enable_debug=False)\n elif (args.mode == 'train_debug'):\n train(logger, hyperparams, enable_eval=False, enable_debug=True)\n elif (args.mode == 'eval'):\n evaluate(logger, hyperparams, enable_debug=False)\n elif (args.mode == 'eval_debug'):\n evaluate(logger, hyperparams, enable_debug=True)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n add_arguments(parser)\n args = parser.parse_args()\n main(args)\n" ]
[ [ "numpy.random.seed", "tensorflow.gfile.Exists", "tensorflow.gfile.MakeDirs", "tensorflow.Session", "tensorflow.python.debug.LocalCLIDebugWrapperSession" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
nilswagner/glue
[ "1e16776f557482cc8444d2b8ecbb813ce691a70d" ]
[ "glue/viewers/matplotlib/state.py" ]
[ "from echo import CallbackProperty, SelectionCallbackProperty, keep_in_sync, delay_callback\n\nfrom matplotlib.colors import to_rgba\n\nfrom glue.core.message import LayerArtistUpdatedMessage\n\nfrom glue.core.state_objects import State\nfrom glue.viewers.common.state import ViewerState, LayerState\n\nfrom glue.utils import defer_draw, avoid_circular\n\n__all__ = ['DeferredDrawSelectionCallbackProperty', 'DeferredDrawCallbackProperty',\n 'MatplotlibDataViewerState', 'MatplotlibLayerState']\n\n\nclass DeferredDrawCallbackProperty(CallbackProperty):\n \"\"\"\n A callback property where drawing is deferred until\n after notify has called all callback functions.\n \"\"\"\n\n @defer_draw\n def notify(self, *args, **kwargs):\n super(DeferredDrawCallbackProperty, self).notify(*args, **kwargs)\n\n\nclass DeferredDrawSelectionCallbackProperty(SelectionCallbackProperty):\n \"\"\"\n A callback property where drawing is deferred until\n after notify has called all callback functions.\n \"\"\"\n\n @defer_draw\n def notify(self, *args, **kwargs):\n super(DeferredDrawSelectionCallbackProperty, self).notify(*args, **kwargs)\n\n\nVALID_WEIGHTS = ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']\n\n\nVALID_LOCATIONS = ['draggable', 'best',\n 'upper right', 'upper left',\n 'lower left', 'lower right',\n 'center left', 'center right',\n 'lower center', 'upper center']\n\n\nclass MatplotlibLegendState(State):\n \"\"\"The legend state\"\"\"\n\n visible = DeferredDrawCallbackProperty(False, docstring=\"Whether to show the legend\")\n\n location = DeferredDrawSelectionCallbackProperty(0, docstring=\"The location of the legend in the axis\")\n\n title = DeferredDrawCallbackProperty(\"\", docstring='The title of the legend')\n fontsize = DeferredDrawCallbackProperty(10, docstring='The font size of the title')\n\n alpha = DeferredDrawCallbackProperty(0.6, docstring='Transparency of the legend frame')\n frame_color = DeferredDrawCallbackProperty(\"#ffffff\", docstring='Frame color of the legend')\n show_edge = DeferredDrawCallbackProperty(True, docstring=\"Whether to show the edge of the frame \")\n text_color = DeferredDrawCallbackProperty(\"#000000\", docstring='Text color of the legend')\n\n def __init__(self, *args, **kwargs):\n MatplotlibLegendState.location.set_choices(self, VALID_LOCATIONS)\n\n super().__init__(*args, **kwargs)\n self._set_color_choices()\n\n def _set_color_choices(self):\n from glue.config import settings\n\n self.frame_color = settings.BACKGROUND_COLOR\n self.text_color = settings.FOREGROUND_COLOR\n\n @property\n def edge_color(self):\n if self.show_edge:\n return to_rgba(self.text_color, self.alpha)\n else:\n return None\n\n @property\n def draggable(self):\n return self.location == 'draggable'\n\n @property\n def mpl_location(self):\n if self.location == 'draggable':\n return 'best'\n else:\n return self.location\n\n def update_axes_settings_from(self, state):\n self.visible = state.show_legend\n self.loc_and_drag = state.loc_and_drag\n self.alpha = state.alpha\n self.title = state.title\n self.fontsize = state.fontsize\n self.frame_color = state.frame_color\n self.show_edge = state.show_edge\n self.text_color = state.text_color\n\n\nclass MatplotlibDataViewerState(ViewerState):\n \"\"\"\n A base class that includes common attributes for viewers based on\n Matplotlib.\n \"\"\"\n\n x_min = DeferredDrawCallbackProperty(docstring='Lower limit of the visible x range')\n x_max = DeferredDrawCallbackProperty(docstring='Upper limit of the visible x range')\n\n y_min = DeferredDrawCallbackProperty(docstring='Lower limit of the visible y range')\n y_max = DeferredDrawCallbackProperty(docstring='Upper limit of the visible y range')\n\n x_log = DeferredDrawCallbackProperty(False, docstring='Whether the x axis is logarithmic')\n y_log = DeferredDrawCallbackProperty(False, docstring='Whether the y axis is logarithmic')\n\n aspect = DeferredDrawCallbackProperty('auto', docstring='Aspect ratio for the axes')\n\n show_axes = DeferredDrawCallbackProperty(True, docstring='Whether the axes are shown')\n\n x_axislabel = DeferredDrawCallbackProperty('', docstring='Label for the x-axis')\n y_axislabel = DeferredDrawCallbackProperty('', docstring='Label for the y-axis')\n\n x_axislabel_size = DeferredDrawCallbackProperty(10, docstring='Size of the x-axis label')\n y_axislabel_size = DeferredDrawCallbackProperty(10, docstring='Size of the y-axis label')\n\n x_axislabel_weight = DeferredDrawSelectionCallbackProperty(1, docstring='Weight of the x-axis label')\n y_axislabel_weight = DeferredDrawSelectionCallbackProperty(1, docstring='Weight of the y-axis label')\n\n x_ticklabel_size = DeferredDrawCallbackProperty(8, docstring='Size of the x-axis tick labels')\n y_ticklabel_size = DeferredDrawCallbackProperty(8, docstring='Size of the y-axis tick labels')\n\n def __init__(self, *args, **kwargs):\n\n self._axes_aspect_ratio = None\n\n MatplotlibDataViewerState.x_axislabel_weight.set_choices(self, VALID_WEIGHTS)\n MatplotlibDataViewerState.y_axislabel_weight.set_choices(self, VALID_WEIGHTS)\n\n super(MatplotlibDataViewerState, self).__init__(*args, **kwargs)\n self.legend = MatplotlibLegendState(*args, **kwargs)\n\n self.add_callback('aspect', self._adjust_limits_aspect, priority=10000)\n self.add_callback('x_min', self._adjust_limits_aspect_x, priority=10000)\n self.add_callback('x_max', self._adjust_limits_aspect_x, priority=10000)\n self.add_callback('y_min', self._adjust_limits_aspect_y, priority=10000)\n self.add_callback('y_max', self._adjust_limits_aspect_y, priority=10000)\n\n def _set_axes_aspect_ratio(self, value):\n \"\"\"\n Set the aspect ratio of the axes in which the visualization is shown.\n This is a private method that is intended only for internal use, and it\n allows this viewer state class to adjust the limits accordingly when\n the aspect callback property is set to 'equal'\n \"\"\"\n self._axes_aspect_ratio = value\n self._adjust_limits_aspect(aspect_adjustable='both')\n\n def _adjust_limits_aspect_x(self, *args):\n self._adjust_limits_aspect(aspect_adjustable='y')\n\n def _adjust_limits_aspect_y(self, *args):\n self._adjust_limits_aspect(aspect_adjustable='x')\n\n @avoid_circular\n def _adjust_limits_aspect(self, *args, **kwargs):\n \"\"\"\n Adjust the limits of the visualization to take into account the aspect\n ratio. This only works if `_set_axes_aspect_ratio` has been called\n previously.\n \"\"\"\n\n if self.aspect == 'auto' or self._axes_aspect_ratio is None:\n return\n\n if self.x_min is None or self.x_max is None or self.y_min is None or self.y_max is None:\n return\n\n aspect_adjustable = kwargs.pop('aspect_adjustable', 'auto')\n\n changed = None\n\n # Find axes aspect ratio\n axes_ratio = self._axes_aspect_ratio\n\n # Put the limits in temporary variables so that we only actually change\n # them in one go at the end.\n x_min, x_max = self.x_min, self.x_max\n y_min, y_max = self.y_min, self.y_max\n\n # Find current data ratio\n data_ratio = abs(y_max - y_min) / abs(x_max - x_min)\n\n # Only do something if the data ratio is sufficiently different\n # from the axes ratio.\n if abs(data_ratio - axes_ratio) / (0.5 * (data_ratio + axes_ratio)) > 0.01:\n\n # We now adjust the limits - which ones we adjust depends on\n # the adjust keyword. We also make sure we preserve the\n # mid-point of the current coordinates.\n\n if aspect_adjustable == 'both':\n\n # We need to adjust both at the same time\n\n x_mid = 0.5 * (x_min + x_max)\n x_width = abs(x_max - x_min) * (data_ratio / axes_ratio) ** 0.5\n\n y_mid = 0.5 * (y_min + y_max)\n y_width = abs(y_max - y_min) / (data_ratio / axes_ratio) ** 0.5\n\n x_min = x_mid - x_width / 2.\n x_max = x_mid + x_width / 2.\n\n y_min = y_mid - y_width / 2.\n y_max = y_mid + y_width / 2.\n\n elif (aspect_adjustable == 'auto' and data_ratio > axes_ratio) or aspect_adjustable == 'x':\n x_mid = 0.5 * (x_min + x_max)\n x_width = abs(y_max - y_min) / axes_ratio\n x_min = x_mid - x_width / 2.\n x_max = x_mid + x_width / 2.\n else:\n y_mid = 0.5 * (y_min + y_max)\n y_width = abs(x_max - x_min) * axes_ratio\n y_min = y_mid - y_width / 2.\n y_max = y_mid + y_width / 2.\n\n with delay_callback(self, 'x_min', 'x_max', 'y_min', 'y_max'):\n self.x_min = x_min\n self.x_max = x_max\n self.y_min = y_min\n self.y_max = y_max\n\n def update_axes_settings_from(self, state):\n # axis\n self.x_axislabel_size = state.x_axislabel_size\n self.y_axislabel_size = state.y_axislabel_size\n self.x_axislabel_weight = state.x_axislabel_weight\n self.y_axislabel_weight = state.y_axislabel_weight\n self.x_ticklabel_size = state.x_ticklabel_size\n self.y_ticklabel_size = state.y_ticklabel_size\n # legend\n self.legend.update_axes_settings_from(state.legend)\n\n @defer_draw\n def _notify_global(self, *args, **kwargs):\n super(MatplotlibDataViewerState, self)._notify_global(*args, **kwargs)\n\n def _update_priority(self, name):\n if name == 'layers':\n return 2\n elif name.endswith('_log'):\n return 0.5\n elif name.endswith(('_min', '_max')):\n return 0\n else:\n return 1\n\n\nclass MatplotlibLayerState(LayerState):\n \"\"\"\n A base class that includes common attributes for all layers in viewers based\n on Matplotlib.\n \"\"\"\n\n color = DeferredDrawCallbackProperty(docstring='The color used to display '\n 'the data')\n alpha = DeferredDrawCallbackProperty(docstring='The transparency used to '\n 'display the data')\n\n def __init__(self, viewer_state=None, **kwargs):\n\n super(MatplotlibLayerState, self).__init__(viewer_state=viewer_state, **kwargs)\n\n self.color = self.layer.style.color\n self.alpha = self.layer.style.alpha\n\n self._sync_color = keep_in_sync(self, 'color', self.layer.style, 'color')\n self._sync_alpha = keep_in_sync(self, 'alpha', self.layer.style, 'alpha')\n\n self.add_global_callback(self._notify_layer_update)\n\n def _notify_layer_update(self, **kwargs):\n message = LayerArtistUpdatedMessage(self)\n if self.layer is not None and self.layer.hub is not None:\n self.layer.hub.broadcast(message)\n\n @defer_draw\n def _notify_global(self, *args, **kwargs):\n super(MatplotlibLayerState, self)._notify_global(*args, **kwargs)\n" ]
[ [ "matplotlib.colors.to_rgba" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
OsciiArt/Cookpad
[ "b2245f84db0650d6282c97c98600de825c6ed6e0", "b2245f84db0650d6282c97c98600de825c6ed6e0" ]
[ "train_180131_2.py", "train_180215_1_Dense_6th_training.py" ]
[ "import numpy as np # linear algebra\nnp.random.seed(42)\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom sklearn.model_selection import train_test_split\nfrom matplotlib import pyplot\nimport time\nimport os, glob\nimport cv2\n\n# parameters\nformat = \"%H%M\"\nts = time.strftime(format)\nbase_name = os.path.splitext(__file__)[0] + \"_ts\" + ts\ninput_size = 128\n\n\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Input, Flatten, GaussianNoise\nfrom keras.layers import GlobalMaxPooling2D, Reshape, UpSampling3D, Activation\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.merge import Concatenate\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, Callback, EarlyStopping, CSVLogger, ReduceLROnPlateau\nfrom keras import backend as K\n\n\ndef get_callbacks(save_path, lr=0.001, patience=64):\n csv_logger = CSVLogger(save_path + '_log.csv', append=True)\n # check_path = save_path + '_e{epoch:02d}_vl{val_loss:.5f}.hdf5'\n check_path = save_path\n save_checkpoint = ModelCheckpoint(filepath=check_path, monitor='val_loss', save_best_only=True)\n lerning_rate_schedular = ReduceLROnPlateau(patience=8, min_lr=lr * 0.00001)\n early_stopping = EarlyStopping(monitor='val_loss',\n patience=16,\n verbose=1,\n min_delta=1e-4,\n mode='min')\n Callbacks = [csv_logger,\n save_checkpoint,\n # lerning_rate_schedular,\n early_stopping\n ]\n return Callbacks\n\n\n\ndef swish(x):\n return x * K.sigmoid(x)\n\n\nfrom keras.applications.vgg16 import VGG16\nfrom keras.optimizers import SGD\n\ndef get_model(num_class):\n base_model = VGG16(weights='imagenet', include_top=False,\n input_shape=[input_size,input_size,3], classes=1)\n x = base_model.get_layer('block5_pool').output\n\n x = GlobalMaxPooling2D()(x)\n x = Dense(512, activation='relu', name='fc2')(x)\n x = Dropout(0.3)(x)\n x = Dense(512, activation='relu', name='fc3')(x)\n x = Dropout(0.3)(x)\n\n predictions = Dense(num_class, activation='softmax')(x)\n\n model = Model(inputs=base_model.input, outputs=predictions)\n\n sgd = SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True)\n model.compile(loss='categorical_crossentropy',\n optimizer=sgd,\n metrics=['accuracy'])\n return model\n\n\ndef randomHueSaturationValue(image, hue_shift_limit=(-180, 180),\n sat_shift_limit=(-255, 255),\n val_shift_limit=(-255, 255), u=0.5):\n if np.random.random() < u:\n image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n h, s, v = cv2.split(image) # sikisou, saido, meido\n hue_shift = np.random.uniform(hue_shift_limit[0], hue_shift_limit[1])\n h = cv2.add(h, hue_shift)\n sat_shift = np.random.uniform(sat_shift_limit[0], sat_shift_limit[1])\n s = cv2.add(s, sat_shift)\n val_shift = np.random.uniform(val_shift_limit[0], val_shift_limit[1])\n v = cv2.add(v, val_shift)\n image = cv2.merge((h, s, v))\n image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)\n\n return image\n\n\n\n\ndef randomShiftScaleRotate(image,\n shift_limit=(-0.0625, 0.0625),\n scale_limit=(-0.1, 0.1),\n rotate_limit=(-45, 45), aspect_limit=(0, 0),\n borderMode=cv2.BORDER_CONSTANT, u=0.5):\n if np.random.random() < u:\n height, width, channel = image.shape\n\n angle = np.random.uniform(rotate_limit[0], rotate_limit[1]) # degree\n scale = np.random.uniform(1 + scale_limit[0], 1 + scale_limit[1])\n aspect = np.random.uniform(1 + aspect_limit[0], 1 + aspect_limit[1])\n sx = scale * aspect / (aspect ** 0.5)\n sy = scale / (aspect ** 0.5)\n dx = round(np.random.uniform(shift_limit[0], shift_limit[1]) * width)\n dy = round(np.random.uniform(shift_limit[0], shift_limit[1]) * height)\n\n cc = np.math.cos(angle / 180 * np.math.pi) * sx\n ss = np.math.sin(angle / 180 * np.math.pi) * sy\n rotate_matrix = np.array([[cc, -ss], [ss, cc]])\n\n box0 = np.array([[0, 0], [width, 0], [width, height], [0, height], ])\n box1 = box0 - np.array([width / 2, height / 2])\n box1 = np.dot(box1, rotate_matrix.T) + np.array([width / 2 + dx, height / 2 + dy])\n\n box0 = box0.astype(np.float32)\n box1 = box1.astype(np.float32)\n mat = cv2.getPerspectiveTransform(box0, box1)\n image = cv2.warpPerspective(image, mat, (width, height), flags=cv2.INTER_LINEAR, borderMode=borderMode,\n borderValue=(\n 0, 0,\n 0,))\n\n return image\n\ndef randomHorizontalFlip(image, u=0.5):\n if np.random.random() < u:\n image = cv2.flip(image, 1)\n\n return image\n\ndef randomVerticalFlip(image, u=0.5):\n if np.random.random() < u:\n image = cv2.flip(image, 0)\n\n return image\n\n\ndef get_random_eraser(p=0.5, s_l=0.02, s_h=0.4, r_1=0.3, r_2=1/0.3, v_l=0, v_h=255, pixel_level=False):\n def eraser(input_img):\n img_h, img_w, img_c = input_img.shape\n p_1 = np.random.rand()\n\n if p_1 > p:\n return input_img\n\n while True:\n s = np.random.uniform(s_l, s_h) * img_h * img_w\n r = np.random.uniform(r_1, r_2)\n w = int(np.sqrt(s / r))\n h = int(np.sqrt(s * r))\n left = np.random.randint(0, img_w)\n top = np.random.randint(0, img_h)\n\n if left + w <= img_w and top + h <= img_h:\n break\n\n if pixel_level:\n c = np.random.uniform(v_l, v_h, (h, w, img_c))\n else:\n c = np.random.uniform(v_l, v_h)\n\n input_img[top:top + h, left:left + w, :] = c\n\n return input_img\n\n return eraser\n\n\nfrom multiprocessing import Pool\n\ndef load_img(args):\n img_path = args\n img = cv2.imread(img_path)\n # print(\"img shape\", img.shape)\n img = cv2.resize(img, (input_size, input_size))\n img = randomHueSaturationValue(img,\n hue_shift_limit=(-5, 5),\n sat_shift_limit=(-1, 1),\n val_shift_limit=(-2, 2),\n u=0.5)\n img = randomShiftScaleRotate(img,\n shift_limit=(-0.2, 0.2),\n scale_limit=(-0.2, 0.5),\n rotate_limit=(-30, 30),\n aspect_limit=(-0.2, 0.2),\n u=0.5)\n img = randomHorizontalFlip(img)\n img = randomVerticalFlip(img)\n return img\n\ndef train_generator(x_train, y_train, img_dir, batch_size, shuffle=True):\n # x_train = x_train.as_matrix()\n # y_train = y_train.as_matrix()\n y_train = np.eye(55)[y_train]\n batch_index = 0\n n = x_train.shape[0]\n # print(\"n\", n)\n eraser = get_random_eraser(v_h=0.)\n pool = Pool()\n while 1:\n if batch_index == 0:\n index_array = np.arange(n)\n if shuffle:\n index_array = np.random.permutation(n)\n\n current_index = (batch_index * batch_size) % n\n if n >= current_index + batch_size:\n current_batch_size = batch_size\n batch_index += 1\n else:\n current_batch_size = n - current_index\n batch_index = 0\n\n batch_id = index_array[current_index: current_index + current_batch_size]\n\n batch_x = pool.map(load_img,\n [img_dir + '/{}'.format(x_train[id])\n for id in batch_id])\n for id in range(len(batch_x)):\n img = batch_x[id]\n img =eraser(img)\n # img =eraser(img)\n # img =eraser(img)\n # img =eraser(img)\n # img =eraser(img)\n batch_x[id] = img\n batch_x = np.array(batch_x, np.float32) / 255\n\n batch_y = y_train[index_array[current_index: current_index + current_batch_size]]\n\n # print(\"batch shape\", batch_x.shape, batch_y.shape)\n\n yield (batch_x, batch_y)\n\n\ndef get_mixer(p=0.5, s_l=0.02, s_h=0.4, r_1=0.3, r_2=1/0.3):\n def mixer(img1, img2, mask1, mask2):\n img_h, img_w, img_c = img1.shape\n p_1 = np.random.rand()\n\n if p_1 > p:\n return img1, mask1\n\n while True:\n s = np.random.uniform(s_l, s_h) * img_h * img_w\n r = np.random.uniform(r_1, r_2)\n w = int(np.sqrt(s / r))\n h = int(np.sqrt(s * r))\n left = np.random.randint(0, img_w)\n top = np.random.randint(0, img_h)\n\n if left + w <= img_w and top + h <= img_h:\n break\n\n img1[top:top + h, left:left + w, :] = img2[top:top + h, left:left + w, :]\n mask1[top:top + h, left:left + w, :] = mask2[top:top + h, left:left + w, :]\n\n return img1, mask1\n\n return mixer\n\ndef mix_generator(X_train, Y_train, img_dir, batch_size, shuffle=True):\n alpha = 0.2\n gen1 = train_generator(X_train, Y_train, img_dir, batch_size, shuffle)\n gen2 = train_generator(X_train, Y_train, img_dir, batch_size, shuffle)\n while True:\n batch1 = next(gen1)\n batch2 = next(gen2)\n current_batch_size = batch1[0].shape[0]\n l = np.random.beta(alpha, alpha, current_batch_size)\n X_l = l.reshape(current_batch_size, 1, 1, 1)\n Y_l = l.reshape(current_batch_size, 1)\n\n batch_x = batch1[0] * X_l + batch2[0] * (1 - X_l)\n batch_y = batch1[1] * Y_l + batch2[1] * (1 - Y_l)\n\n yield (batch_x, batch_y)\n\n\n\n\ndef test_generator(x_train, img_dir, batch_size, shuffle=True):\n # x_train = x_train.as_matrix()\n # y_train = y_train.as_matrix()\n batch_index = 0\n n = x_train.shape[0]\n # print(\"n\", n)\n eraser = get_random_eraser(v_h=0.)\n while 1:\n if batch_index == 0:\n index_array = np.arange(n)\n if shuffle:\n index_array = np.random.permutation(n)\n\n current_index = (batch_index * batch_size) % n\n if n >= current_index + batch_size:\n current_batch_size = batch_size\n batch_index += 1\n else:\n current_batch_size = n - current_index\n batch_index = 0\n\n batch_x = []\n batch_id = index_array[current_index: current_index + current_batch_size]\n # print(batch_x_base)\n for id in batch_id:\n # print(x_train[0])\n # print(x_train[id])\n # print(img_dir + '/{}'.format(x_train[id]))\n\n img = cv2.imread(img_dir + '/{}'.format(x_train[id]))\n # print(\"img shape\", img.shape)\n img = cv2.resize(img, (input_size, input_size))\n img = randomHueSaturationValue(img,\n hue_shift_limit=(-5, 5),\n sat_shift_limit=(-1, 1),\n val_shift_limit=(-2, 2),\n u=0.5)\n img = randomShiftScaleRotate(img,\n shift_limit=(-0.2, 0.2),\n scale_limit=(-0.2, 0.2),\n rotate_limit=(-30, 30),\n aspect_limit = (-0.2, 0.2),\n u=0.5)\n img = randomHorizontalFlip(img)\n # img =eraser(img)\n batch_x.append(img)\n batch_x = np.array(batch_x, np.float32) / 255\n\n # batch_y = y_train[index_array[current_index: current_index + current_batch_size]]\n\n # print(\"batch shape\", batch_x.shape, batch_y.shape)\n\n yield batch_x\n\n\n\ndef load_data(train_path=\"input/train_master.tsv\", test_path=\"input/sample_submit.tsv\"):\n train = pd.read_csv(train_path, delimiter=\"\\t\", index_col=False)\n test = pd.read_csv(test_path, delimiter=\"\\t\", index_col=False, header=None)\n print(\"train shape\", train.shape)\n print(train.head())\n X_train = train['file_name'].as_matrix()\n y_train = train['category_id'].as_matrix()\n # y_train = np.eye(55)[y_train]\n # print(y_train[:5])\n # print(y_train.shape)\n X_test = test.iloc[:,0]\n\n return X_train, y_train, X_test\n\n\nfrom sklearn.model_selection import StratifiedKFold, StratifiedShuffleSplit\nfrom sklearn.metrics import log_loss\n\n\ndef train(epochs, seed):\n # parameter\n batch_size = 128\n num_class = 55\n save_path = base_name + \"_seed\" + str(seed)\n model_path = \"_\"\n\n # Load data\n X_train, y_train, X_test = load_data()\n\n # CV\n ids_train_split, ids_valid_split = train_test_split(np.arange(X_train.shape[0]),\n random_state=42, test_size=0.05,\n stratify=y_train)\n\n\n # data process\n X_train_cv = X_train[ids_train_split]\n y_train_cv = y_train[ids_train_split]\n X_holdout = X_train[ids_valid_split]\n Y_holdout = y_train[ids_valid_split]\n # print(X_train_cv.head())\n\n\n # define file path and get callbacks\n weight_path = \"model/\" + save_path + '.hdf5'\n callbacks = get_callbacks(weight_path, patience=16)\n gen = mix_generator(X_train_cv, y_train_cv, \"input/train\", batch_size)\n gen_val = train_generator(X_holdout, Y_holdout, \"input/train\", batch_size, shuffle=False)\n gen_val_pred = test_generator(X_holdout, \"input/train\", batch_size, shuffle=False)\n gen_tst_pred = test_generator(X_test, \"input/test\", batch_size, shuffle=False)\n model = get_model(num_class)\n model.fit_generator(generator=gen,\n steps_per_epoch=np.ceil(X_train_cv.shape[0] / batch_size),\n epochs=epochs,\n verbose=1,\n callbacks=callbacks,\n validation_data=gen_val,\n validation_steps=np.ceil(X_holdout.shape[0] / batch_size),\n )\n\n # Getting the Best Model\n model.load_weights(filepath=weight_path)\n\n # Getting Training Score\n # score = model.evaluate_generator(generator=gen_trn_eval,\n # steps=np.ceil(X_train.shape[0]/batch_size))\n # print('Train loss:', score[0])\n # print('Train accuracy:', score[1])\n\n # Getting Valid Score\n score = model.evaluate_generator(generator=gen_val,\n steps=np.ceil(X_holdout.shape[0]/batch_size))\n print('Valid loss:', score[0])\n print('Valid accuracy:', score[1])\n\n # Getting validation prediction\n pred_valid = model.predict_generator(generator=gen_val_pred,\n steps=np.ceil(X_holdout.shape[0]/batch_size))\n\n # Getting Test prediction\n pred_test = model.predict_generator(generator=gen_tst_pred,\n steps=np.ceil(X_test.shape[0]/batch_size))\n\n submission = pd.DataFrame({'id': X_test, 'predict': np.argmax(pred_test, axis=1)})\n submit_path = \"output/submission\" + save_path + \"_val_loss\" + str(score[0]) + \"_val_acc\" + str(score[1]) + \".tsv\"\n submission.to_csv(submit_path, index=False, header=False, sep='\\t')\n\n np.save(\"input/\" + base_name + \"_valid.npy\", pred_valid)\n np.save(\"input/\" + base_name + \"_test.npy\", pred_test)\n\n\ndef main():\n train(epochs=250, seed=0)\n\n\nif __name__ == \"__main__\": main()\n\n", "import numpy as np # linear algebra\nnp.random.seed(42)\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom sklearn.model_selection import train_test_split\nfrom matplotlib import pyplot\nimport time\nimport os, glob\nimport cv2\n\n# parameters\nformat = \"%H%M\"\nts = time.strftime(format)\nbase_name = os.path.splitext(__file__)[0] + \"_ts\" + ts\ninput_size = 221\n\n\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Input, Flatten, GaussianNoise\nfrom keras.layers import GlobalMaxPooling2D, Reshape, UpSampling3D, Activation\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.merge import Concatenate\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, Callback, EarlyStopping, CSVLogger, ReduceLROnPlateau, LearningRateScheduler\nfrom keras import backend as K\n\n\ndef get_callbacks(save_path, lr=0.001, patience=64):\n csv_logger = CSVLogger(save_path + '_log.csv', append=True)\n # check_path = save_path + '_e{epoch:02d}_vl{val_loss:.5f}.hdf5'\n check_path = save_path\n save_checkpoint = ModelCheckpoint(filepath=check_path, monitor='val_loss', save_best_only=True)\n lerning_rate_schedular = ReduceLROnPlateau(patience=8, min_lr=lr * 0.00001)\n def lrs(epoch):\n if epoch<100:\n return 1e-6\n elif epoch<200:\n return 1e-7\n else:\n return 1e-8\n\n learning_rate_Schedular = LearningRateScheduler(lambda epoch: lrs(epoch))\n early_stopping = EarlyStopping(monitor='val_loss',\n patience=16,\n verbose=1,\n min_delta=1e-4,\n mode='min')\n Callbacks = [csv_logger,\n save_checkpoint,\n learning_rate_Schedular,\n # early_stopping\n ]\n return Callbacks\n\n\n\ndef swish(x):\n return x * K.sigmoid(x)\n\n\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.densenet import DenseNet121\nfrom keras.optimizers import SGD, Adam\nfrom keras.layers import GlobalAveragePooling2D\n\ndef get_model(num_class):\n base_model = DenseNet121(weights=None, include_top=False,\n input_shape=[input_size,input_size,3], classes=1)\n # print(base_model.summary())\n x = base_model.get_layer(\"bn\").output\n # x = base_model.get_layer(\"block5_pool\").output\n\n x = GlobalAveragePooling2D()(x)\n predictions = Dense(num_class, activation='softmax')(x)\n\n model = Model(inputs=base_model.input, outputs=predictions)\n\n sgd = SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True)\n optimizer = Adam(lr=0.0001)\n model.compile(loss='categorical_crossentropy',\n optimizer=optimizer,\n metrics=['accuracy'])\n return model\n\n\ndef randomHueSaturationValue(image, hue_shift_limit=(-180, 180),\n sat_shift_limit=(-255, 255),\n val_shift_limit=(-255, 255), u=0.5):\n if np.random.random() < u:\n image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n h, s, v = cv2.split(image) # sikisou, saido, meido\n hue_shift = np.random.uniform(hue_shift_limit[0], hue_shift_limit[1])\n h = cv2.add(h, hue_shift)\n sat_shift = np.random.uniform(sat_shift_limit[0], sat_shift_limit[1])\n s = cv2.add(s, sat_shift)\n val_shift = np.random.uniform(val_shift_limit[0], val_shift_limit[1])\n v = cv2.add(v, val_shift)\n image = cv2.merge((h, s, v))\n image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)\n\n return image\n\n\n\n\ndef randomShiftScaleRotate(image,\n shift_limit=(-0.0625, 0.0625),\n scale_limit=(-0.1, 0.1),\n rotate_limit=(-45, 45), aspect_limit=(0, 0),\n borderMode=cv2.BORDER_CONSTANT, u=0.5):\n if np.random.random() < u:\n height, width, channel = image.shape\n\n angle = np.random.uniform(rotate_limit[0], rotate_limit[1]) # degree\n scale = np.random.uniform(1 + scale_limit[0], 1 + scale_limit[1])\n aspect = np.random.uniform(1 + aspect_limit[0], 1 + aspect_limit[1])\n sx = scale * aspect / (aspect ** 0.5)\n sy = scale / (aspect ** 0.5)\n dx = round(np.random.uniform(shift_limit[0], shift_limit[1]) * width)\n dy = round(np.random.uniform(shift_limit[0], shift_limit[1]) * height)\n\n cc = np.math.cos(angle / 180 * np.math.pi) * sx\n ss = np.math.sin(angle / 180 * np.math.pi) * sy\n rotate_matrix = np.array([[cc, -ss], [ss, cc]])\n\n box0 = np.array([[0, 0], [width, 0], [width, height], [0, height], ])\n box1 = box0 - np.array([width / 2, height / 2])\n box1 = np.dot(box1, rotate_matrix.T) + np.array([width / 2 + dx, height / 2 + dy])\n\n box0 = box0.astype(np.float32)\n box1 = box1.astype(np.float32)\n mat = cv2.getPerspectiveTransform(box0, box1)\n image = cv2.warpPerspective(image, mat, (width, height), flags=cv2.INTER_LINEAR, borderMode=borderMode,\n borderValue=(\n 0, 0,\n 0,))\n\n return image\n\ndef randomHorizontalFlip(image, u=0.5):\n if np.random.random() < u:\n image = cv2.flip(image, 1)\n\n return image\n\ndef randomVerticalFlip(image, u=0.5):\n if np.random.random() < u:\n image = cv2.flip(image, 0)\n\n return image\n\n\ndef get_mixer(p=0.5, s_l=0.02, s_h=0.4, r_1=0.3, r_2=1/0.3):\n def mixer(img1, img2, y1, y2):\n img_h, img_w, img_c = img1.shape\n p_1 = np.random.rand()\n\n if p_1 > p:\n return img1, y1\n\n while True:\n s = np.random.uniform(s_l, s_h) * img_h * img_w\n r = np.random.uniform(r_1, r_2)\n w = int(np.sqrt(s / r))\n h = int(np.sqrt(s * r))\n left = np.random.randint(0, img_w)\n top = np.random.randint(0, img_h)\n\n if left + w <= img_w and top + h <= img_h:\n break\n\n img1[top:top + h, left:left + w, :] = img2[top:top + h, left:left + w, :]\n\n\n return img1, mask1\n\n return mixer\n\n\n\ndef get_random_eraser(p=0.5, s_l=0.02, s_h=0.4, r_1=0.3, r_2=1/0.3, v_l=0, v_h=255, pixel_level=False):\n def eraser(input_img):\n img_h, img_w, img_c = input_img.shape\n p_1 = np.random.rand()\n\n if p_1 > p:\n return input_img\n\n while True:\n s = np.random.uniform(s_l, s_h) * img_h * img_w\n r = np.random.uniform(r_1, r_2)\n w = int(np.sqrt(s / r))\n h = int(np.sqrt(s * r))\n left = np.random.randint(0, img_w)\n top = np.random.randint(0, img_h)\n\n if left + w <= img_w and top + h <= img_h:\n break\n\n if pixel_level:\n c = np.random.uniform(v_l, v_h, (h, w, img_c))\n else:\n c = np.random.uniform(v_l, v_h)\n\n input_img[top:top + h, left:left + w, :] = c\n\n return input_img\n\n return eraser\n\n\nfrom multiprocessing import Pool\n\ndef load_img(args):\n img_path = args\n img = cv2.imread(img_path)\n # print(\"img shape\", img.shape)\n img = cv2.resize(img, (input_size, input_size))\n img = randomHueSaturationValue(img,\n hue_shift_limit=(-50, 50),\n sat_shift_limit=(-5, 5),\n val_shift_limit=(-15, 15),\n u=0.25)\n img = randomShiftScaleRotate(img,\n shift_limit=(-0.2, 0.2),\n scale_limit=(-0.2, 0.5),\n rotate_limit=(-30, 30),\n aspect_limit=(-0.2, 0.2),\n u=0.25)\n img = randomHorizontalFlip(img)\n # img = randomVerticalFlip(img)\n return img\n\n\ndef load_img_valid(args):\n img_path = args\n img = cv2.imread(img_path)\n img = cv2.resize(img, (input_size, input_size))\n return img\n\ndef train_generator(x_train, y_train, img_dir, batch_size, shuffle=True):\n # x_train = x_train.as_matrix()\n # y_train = y_train.as_matrix()\n y_train = np.eye(55)[y_train]\n batch_index = 0\n n = x_train.shape[0]\n # print(\"n\", n)\n eraser = get_random_eraser(v_h=0.)\n pool = Pool(8)\n while 1:\n if batch_index == 0:\n index_array = np.arange(n)\n if shuffle:\n index_array = np.random.permutation(n)\n\n current_index = (batch_index * batch_size) % n\n if n >= current_index + batch_size:\n current_batch_size = batch_size\n batch_index += 1\n else:\n current_batch_size = n - current_index\n batch_index = 0\n\n batch_id = index_array[current_index: current_index + current_batch_size]\n\n batch_x = pool.map(load_img,\n ['{}'.format(x_train[id])\n for id in batch_id])\n for id in range(len(batch_x)):\n img = batch_x[id]\n # img =eraser(img)\n # img =eraser(img)\n # img =eraser(img)\n # img =eraser(img)\n # img =eraser(img)\n batch_x[id] = img\n batch_x = np.array(batch_x, np.float32) / 255\n\n batch_y = y_train[index_array[current_index: current_index + current_batch_size]]\n\n # print(\"batch shape\", batch_x.shape, batch_y.shape)\n\n yield (batch_x, batch_y)\n\n\ndef valid_generator(x_train, y_train, img_dir, batch_size, shuffle=True):\n # x_train = x_train.as_matrix()\n # y_train = y_train.as_matrix()\n y_train = np.eye(55)[y_train]\n batch_index = 0\n n = x_train.shape[0]\n # print(\"n\", n)\n eraser = get_random_eraser(v_h=0.)\n pool = Pool(4)\n while 1:\n if batch_index == 0:\n index_array = np.arange(n)\n if shuffle:\n index_array = np.random.permutation(n)\n\n current_index = (batch_index * batch_size) % n\n if n >= current_index + batch_size:\n current_batch_size = batch_size\n batch_index += 1\n else:\n current_batch_size = n - current_index\n batch_index = 0\n\n batch_id = index_array[current_index: current_index + current_batch_size]\n\n batch_x = pool.map(load_img_valid,\n ['{}'.format(x_train[id])\n for id in batch_id])\n for id in range(len(batch_x)):\n img = batch_x[id]\n # img =eraser(img)\n # img =eraser(img)\n # img =eraser(img)\n # img =eraser(img)\n # img =eraser(img)\n batch_x[id] = img\n batch_x = np.array(batch_x, np.float32) / 255\n\n batch_y = y_train[index_array[current_index: current_index + current_batch_size]]\n\n # print(\"batch shape\", batch_x.shape, batch_y.shape)\n\n yield (batch_x, batch_y)\n\n\ndef get_mixer(p=1, s_l=0.02, s_h=0.4, r_1=0.3, r_2=1/0.3):\n def mixer(img1, img2, y1, y2):\n img_h, img_w, img_c = img1.shape\n p_1 = np.random.rand()\n\n if p_1 > p:\n return img1, y1\n\n while True:\n s = np.random.uniform(s_l, s_h) * img_h * img_w\n r = np.random.uniform(r_1, r_2)\n w = int(np.sqrt(s / r))\n h = int(np.sqrt(s * r))\n left = np.random.randint(0, img_w)\n top = np.random.randint(0, img_h)\n\n if left + w <= img_w and top + h <= img_h:\n break\n\n img1[top:top + h, left:left + w, :] = img2[top:top + h, left:left + w, :]\n y = (1- h/img_h*w/img_w) * y1 + h/img_h*w/img_w * y2\n\n return img1, y\n\n return mixer\n\ndef mix_generator(X_train, Y_train, img_dir, batch_size, shuffle=True):\n alpha = 1\n gen1 = train_generator(X_train, Y_train, img_dir, batch_size, shuffle)\n gen2 = train_generator(X_train, Y_train, img_dir, batch_size, shuffle)\n while True:\n batch1 = next(gen1)\n batch2 = next(gen2)\n current_batch_size = batch1[0].shape[0]\n l = np.random.beta(alpha, alpha, current_batch_size)\n X_l = l.reshape(current_batch_size, 1, 1, 1)\n Y_l = l.reshape(current_batch_size, 1)\n\n batch_x = batch1[0] * X_l + batch2[0] * (1 - X_l)\n batch_y = batch1[1] * Y_l + batch2[1] * (1 - Y_l)\n\n yield (batch_x, batch_y)\n\n\n\ndef mix_generator2(X_train, Y_train, img_dir, batch_size, shuffle=True):\n alpha = 0.2\n gen1 = mix_generator(X_train, Y_train, img_dir, batch_size, shuffle)\n gen2 = mix_generator(X_train, Y_train, img_dir, batch_size, shuffle)\n mixer =get_mixer()\n while True:\n batch1 = next(gen1)\n batch2 = next(gen2)\n batch_x = []\n batch_y = []\n for i in range(batch1[0].shape[0]):\n x1, y1 = batch1[0][i], batch1[1][i]\n x2, y2 = batch2[0][i], batch2[1][i]\n new_x, new_y = mixer(x1, x2, y1, y2)\n batch_x.append(new_x)\n batch_y.append(new_y)\n batch_x = np.array(batch_x)\n batch_y = np.array(batch_y)\n batch = (batch_x, batch_y)\n\n yield batch\n\n\n\ndef test_generator(x_train, img_dir, batch_size, shuffle=True):\n # x_train = x_train.as_matrix()\n # y_train = y_train.as_matrix()\n batch_index = 0\n n = x_train.shape[0]\n # print(\"n\", n)\n eraser = get_random_eraser(v_h=0.)\n while 1:\n if batch_index == 0:\n index_array = np.arange(n)\n if shuffle:\n index_array = np.random.permutation(n)\n\n current_index = (batch_index * batch_size) % n\n if n >= current_index + batch_size:\n current_batch_size = batch_size\n batch_index += 1\n else:\n current_batch_size = n - current_index\n batch_index = 0\n\n batch_x = []\n batch_id = index_array[current_index: current_index + current_batch_size]\n # print(batch_x_base)\n for id in batch_id:\n # print(x_train[0])\n # print(x_train[id])\n # print(img_dir + '/{}'.format(x_train[id]))\n\n img = cv2.imread('{}'.format(x_train[id]))\n # print(\"img shape\", img.shape)\n img = cv2.resize(img, (input_size, input_size))\n # img =eraser(img)\n batch_x.append(img)\n batch_x = np.array(batch_x, np.float32) / 255\n\n # batch_y = y_train[index_array[current_index: current_index + current_batch_size]]\n\n # print(\"batch shape\", batch_x.shape, batch_y.shape)\n\n yield batch_x\n\n\n\ndef load_data(train_path=\"input/train_master.tsv\", test_path=\"input/sample_submit.tsv\"):\n train = pd.read_csv(train_path, delimiter=\"\\t\", index_col=False)\n test = pd.read_csv(test_path, delimiter=\"\\t\", index_col=False, header=None)\n print(\"train shape\", train.shape)\n print(train.head())\n X_train = train['file_name'].as_matrix()\n y_train = train['category_id'].as_matrix()\n # y_train = np.eye(55)[y_train]\n # print(y_train[:5])\n # print(y_train.shape)\n X_test = test.iloc[:,0]\n\n return X_train, y_train, X_test\n\n\nfrom sklearn.model_selection import StratifiedKFold, StratifiedShuffleSplit\nfrom sklearn.metrics import log_loss\n\n\ndef train(epochs, seed):\n # parameter\n batch_size = 64\n num_class = 55\n save_path = base_name\n model_path = \"_\"\n\n # Load data\n X_train, y_train, X_test = load_data()\n y_test = pd.read_csv(\"output/submissionevaluate_180210_1_Dense_5th_training_ts1213_seed0testaugx8rot90_val_loss0.23128337343533834_val_acc0.9183333333333333.tsv\",\n delimiter=\"\\t\", index_col=False, header=None)\n y_test = y_test.as_matrix()[:,1].astype(np.uint8)\n X_train = \"input/train/\" + X_train\n X_test = \"input/test/\" + X_test\n print(X_train[:10])\n print(X_train.shape, y_train.shape)\n print(X_test.shape, y_test.shape)\n\n # CV\n ids_train_split, ids_valid_split = train_test_split(np.arange(X_train.shape[0]),\n random_state=42, test_size=0.05,\n stratify=y_train)\n\n\n # data process\n X_train_cv = X_train[ids_train_split]\n y_train_cv = y_train[ids_train_split]\n X_train_cv = np.concatenate([X_train_cv, X_test])\n y_train_cv = np.concatenate([y_train_cv, y_test])\n X_holdout = X_train[ids_valid_split]\n Y_holdout = y_train[ids_valid_split]\n # print(X_train_cv.head())\n\n\n # define file path and get callbacks\n weight_path = \"model/\" + save_path + '.hdf5'\n callbacks = get_callbacks(weight_path, patience=16)\n gen = train_generator(X_train_cv, y_train_cv, \"input/train\", batch_size)\n gen_val = valid_generator(X_holdout, Y_holdout, \"input/train\", batch_size, shuffle=False)\n gen_val_pred = test_generator(X_holdout, \"input/train\", batch_size, shuffle=False)\n gen_tst_pred = test_generator(X_test, \"input/test\", batch_size, shuffle=False)\n model = get_model(num_class)\n\n model.load_weights(filepath=\"model/train_180201_2_Dense_4th_training_ts2017.hdf5\")\n model.fit_generator(generator=gen,\n steps_per_epoch=np.ceil(X_train_cv.shape[0] / batch_size),\n epochs=epochs,\n verbose=1,\n callbacks=callbacks,\n validation_data=gen_val,\n validation_steps=np.ceil(X_holdout.shape[0] / batch_size),\n )\n\n # Getting the Best Model\n model.save_weights(filepath=weight_path[:-4] + \"_nostop.hdf5\")\n model.load_weights(filepath=weight_path)\n\n # Getting Training Score\n # score = model.evaluate_generator(generator=gen_trn_eval,\n # steps=np.ceil(X_train.shape[0]/batch_size))\n # print('Train loss:', score[0])\n # print('Train accuracy:', score[1])\n\n # Getting Valid Score\n score = model.evaluate_generator(generator=gen_val,\n steps=np.ceil(X_holdout.shape[0]/batch_size))\n print('Valid loss:', score[0])\n print('Valid accuracy:', score[1])\n\n # Getting validation prediction\n pred_valid = model.predict_generator(generator=gen_val_pred,\n steps=np.ceil(X_holdout.shape[0]/batch_size))\n\n # Getting Test prediction\n pred_test = model.predict_generator(generator=gen_tst_pred,\n steps=np.ceil(X_test.shape[0]/batch_size))\n\n submission = pd.DataFrame({'id': X_test, 'predict': np.argmax(pred_test, axis=1)})\n submit_path = \"output/submission\" + save_path + \"_val_loss\" + str(score[0]) + \"_val_acc\" + str(score[1]) + \".tsv\"\n submission.to_csv(submit_path, index=False, header=False, sep='\\t')\n\n np.save(\"input/\" + base_name + \"_valid.npy\", pred_valid)\n np.save(\"input/\" + base_name + \"_test.npy\", pred_test)\n\n\ndef main():\n train(epochs=250, seed=0)\n\n\nif __name__ == \"__main__\": main()\n\n" ]
[ [ "numpy.dot", "pandas.read_csv", "numpy.random.random", "numpy.random.beta", "numpy.random.seed", "numpy.math.cos", "numpy.sqrt", "numpy.arange", "numpy.eye", "numpy.save", "numpy.ceil", "numpy.argmax", "numpy.random.permutation", "numpy.random.rand", "numpy.math.sin", "numpy.random.uniform", "numpy.array", "numpy.random.randint" ], [ "numpy.dot", "numpy.sqrt", "numpy.concatenate", "numpy.random.randint", "pandas.read_csv", "numpy.random.beta", "numpy.math.cos", "numpy.arange", "numpy.eye", "numpy.save", "numpy.ceil", "numpy.argmax", "numpy.random.rand", "numpy.array", "numpy.random.random", "numpy.random.seed", "numpy.random.permutation", "numpy.math.sin", "numpy.random.uniform" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
fcr/featuremapper
[ "b999110dce9bbbdf4b6dbd2d13bfca1596064c6a", "b999110dce9bbbdf4b6dbd2d13bfca1596064c6a" ]
[ "featuremapper/distribution.py", "featuremapper/analysis/raster.py" ]
[ "\"\"\"\nDistribution class\n\"\"\"\n# To do:\n#\n# - wrap bins for cyclic histograms\n# - check use of float() in count_mag() etc\n# - clarify comment about negative selectivity\n#\n# - function to return value in a range (like a real histogram)\n# - cache values\n# - assumes cyclic axes start at 0: include a shift based on range\n#\n# - is there a way to make this work for arrays without mentioning\n# \"array\" anywhere in here?\n# - should this be two classes: one for the core (which would be\n# small though) and another for statistics?\n\nimport numpy as np\n\nimport param\nimport cmath\nimport math\n\nunavailable_scipy_optimize = False\ntry:\n from scipy import optimize\nexcept ImportError:\n param.Parameterized().debug(\"scipy.optimize not available, dummy von Mises fit\")\n unavailable_scipy_optimize = True\n\ndef wrap(lower, upper, x):\n \"\"\"\n Circularly alias the numeric value x into the range [lower,upper).\n\n Valid for cyclic quantities like orientations or hues.\n \"\"\"\n #I have no idea how I came up with this algorithm; it should be simplified.\n #\n # Note that Python's % operator works on floats and arrays;\n # usually one can simply use that instead. E.g. to wrap array or\n # scalar x into 0,2*pi, just use \"x % (2*pi)\".\n axis_range = upper - lower\n return lower + (x - lower + 2.0 * axis_range * (1.0 - math.floor(x / (2.0 * axis_range)))) % axis_range\n\ndef calc_theta(bins, axis_range):\n \"\"\"\n Convert a bin number to a direction in radians.\n\n Works for NumPy arrays of bin numbers, returning\n an array of directions.\n \"\"\"\n return np.exp( (2.0 * np.pi) * bins / axis_range * 1.0j )\n\n\nclass Distribution(object):\n \"\"\"\n Holds a distribution of the values f(x) associated with a variable x.\n\n A Distribution is a histogram-like object that is a dictionary of\n samples. Each sample is an x:f(x) pair, where x is called the feature_bin\n and f(x) is called the value(). Each feature_bin's value is typically\n maintained as the sum of all the values that have been placed into\n it.\n\n The feature_bin axis is continuous, and can represent a continuous\n quantity without discretization. Alternatively, this class can be\n used as a traditional histogram by either discretizing the feature_bin\n number before adding each sample, or by binning the values in the\n final Distribution.\n\n Distributions are bounded by the specified axis_bounds, and can\n either be cyclic (like directions or hues) or non-cyclic. For\n cyclic distributions, samples provided outside the axis_bounds\n will be wrapped back into the bound range, as is appropriate for\n quantities like directions. For non-cyclic distributions,\n providing samples outside the axis_bounds will result in a\n ValueError.\n\n In addition to the values, can also return the counts, i.e., the\n number of times that a sample has been added with the given feature_bin.\n\n Not all instances of this class will be a true distribution in the\n mathematical sense; e.g. the values will have to be normalized\n before they can be considered a probability distribution.\n\n If keep_peak=True, the value stored in each feature_bin will be the\n maximum of all values ever added, instead of the sum. The\n distribution will thus be a record of the maximum value\n seen at each feature_bin, also known as an envelope.\n \"\"\"\n\n # Holds the number of times that undefined values have been\n # returned from calculations for any instance of this class,\n # e.g. calls to vector_direction() or vector_selectivity() when no\n # value is non-zero. Useful for warning users when the values are\n # not meaningful.\n undefined_vals = 0\n\n def __init__(self, axis_bounds, axis_range, cyclic, data, counts, total_count, total_value, theta):\n self._data = data\n self._counts = counts\n\n # total_count and total_value hold the total number and sum\n # (respectively) of values that have ever been provided for\n # each feature_bin. For a simple distribution these will be the same as\n # sum_counts() and sum_values().\n self.total_count = total_count\n self.total_value = total_value\n \n self.axis_bounds = axis_bounds\n self.axis_range = axis_range\n self.cyclic = cyclic\n \n self._pop_store = None\n\n # Cache busy data\n self._keys = list(data.keys())\n self._values = list(data.values())\n self._theta = theta\n \n if self.cyclic:\n # Cache the vector sum\n self._vector_sum = self._fast_vector_sum(self._values, theta)\n else:\n self._vector_sum = None\n \n def data(self):\n \"\"\"\n Answer a dictionary with bins as keys.\n \"\"\"\n return self._data\n \n def pop(self, feature_bin):\n \"\"\"\n Remove the entry with bin from the distribution.\n \"\"\"\n if self._pop_store is not None:\n raise Exception(\"Distribution: attempt to pop value before outstanding restore\")\n self._pop_store = self._data.pop(feature_bin)\n \n self._keys = list(self._data.keys())\n self._values = list(self._data.values())\n\n def restore(self, feature_bin):\n \"\"\"\n Restore the entry with bin from the distribution.\n Only valid if called after a pop.\n \"\"\"\n if self._pop_store is None:\n raise Exception(\"Distribution: attempt to restore value before pop\")\n self._data[feature_bin] = self._pop_store\n self._pop_store = None\n \n self._keys = list(self._data.keys())\n self._values = list(self._data.values())\n\n def vector_sum(self):\n \"\"\"\n Return the vector sum of the distribution as a tuple (magnitude, avgbinnum).\n\n Each feature_bin contributes a vector of length equal to its value, at\n a direction corresponding to the feature_bin number. Specifically,\n the total feature_bin number range is mapped into a direction range\n [0,2pi].\n\n For a cyclic distribution, the avgbinnum will be a continuous\n measure analogous to the max_value_bin() of the distribution.\n But this quantity has more precision than max_value_bin()\n because it is computed from the entire distribution instead of\n just the peak feature_bin. However, it is likely to be useful only\n for uniform or very dense sampling; with sparse, non-uniform\n sampling the estimates will be biased significantly by the\n particular samples chosen.\n\n The avgbinnum is not meaningful when the magnitude is 0,\n because a zero-length vector has no direction. To find out\n whether such cases occurred, you can compare the value of\n undefined_vals before and after a series of calls to this\n function.\n \n This tries to use cached values of this.\n\n \"\"\"\n if self._vector_sum is None:\n # There is a non cyclic distribution that is using this.\n # Calculate and then cache it\n \n # First check if there is a cached theta. If not derive it.\n if self._theta is None: \n self._theta = calc_theta(np.array(self._keys), self.axis_range)\n\n self._vector_sum = self._fast_vector_sum(self._values, self._theta)\n \n return self._vector_sum\n \n def _fast_vector_sum(self, values, theta):\n \"\"\"\n Return the vector sum of the distribution as a tuple (magnitude, avgbinnum).\n \n This implementation assumes that the values of the distribution needed for the \n vector sum will not be changed and depends on cached values.\n \n \"\"\"\n # vectors are represented in polar form as complex numbers\n v_sum = np.inner(values, theta)\n\n magnitude = abs(v_sum)\n direction = cmath.phase(v_sum)\n\n if v_sum == 0:\n self.undefined_vals += 1\n\n direction_radians = self._radians_to_bins(direction)\n\n # wrap the direction because arctan2 returns principal values\n wrapped_direction = wrap(self.axis_bounds[0], self.axis_bounds[1], direction_radians)\n\n return (magnitude, wrapped_direction)\n\n\n def get_value(self, feature_bin):\n \"\"\"\n Return the value of the specified feature_bin.\n\n (Return None if there is no such feature_bin.)\n \"\"\"\n return self._data.get(feature_bin)\n\n\n def get_count(self, feature_bin):\n \"\"\"\n Return the count from the specified feature_bin.\n\n (Return None if there is no such feature_bin.)\n \"\"\"\n return self._counts.get(feature_bin)\n\n\n def values(self):\n \"\"\"\n Return a list of values.\n\n Various statistics can then be calculated if desired:\n\n sum(vals) (total of all values)\n max(vals) (highest value in any feature_bin)\n\n Note that the feature_bin-order of values returned does not necessarily\n match that returned by counts().\n \"\"\"\n return self._values\n\n\n def counts(self):\n \"\"\"\n Return a list of values.\n\n Various statistics can then be calculated if desired:\n\n sum(counts) (total of all counts)\n max(counts) (highest count in any feature_bin)\n\n Note that the feature_bin-order of values returned does not necessarily\n match that returned by values().\n \"\"\"\n return list(self._counts.values())\n\n\n def bins(self):\n \"\"\"\n Return a list of bins that have been populated.\n \"\"\"\n return self._keys\n\n\n def sub_distr( self, distr ):\n \"\"\"\n Subtract the given distribution from the current one.\n Only existing bins are modified, new bins in the given\n distribution are discarded without raising errors.\n\n Note that total_value and total_count are not affected, and\n keep_peak is ignored, therefore analysis relying on these\n values should not call this method.\n \"\"\"\n for b in distr.bins():\n if b in self.bins():\n v = distr._data.get(b)\n if v is not None: self._data[b] -= v\n\n\n def max_value_bin(self):\n \"\"\"\n Return the feature_bin with the largest value.\n \n Note that uses cached values so that pop and restore\n need to be used if want with altered distribution.\n \"\"\"\n return self._keys[np.argmax(self._values)]\n\n\n def weighted_sum(self):\n \"\"\"Return the sum of each value times its feature_bin.\"\"\"\n return np.inner(self._keys, self._values)\n\n\n def value_mag(self, feature_bin):\n \"\"\"Return the value of a single feature_bin as a proportion of total_value.\"\"\"\n return self._safe_divide(self._data.get(feature_bin), self.total_value)\n\n\n def count_mag(self, feature_bin):\n \"\"\"Return the count of a single feature_bin as a proportion of total_count.\"\"\"\n return self._safe_divide(float(self._counts.get(feature_bin)), float(self.total_count))\n # use of float()\n\n\n def _bins_to_radians(self, bin):\n \"\"\"\n Convert a bin number to a direction in radians.\n\n Works for NumPy arrays of bin numbers, returning\n an array of directions.\n \"\"\"\n return (2*np.pi)*bin/self.axis_range\n\n\n def _radians_to_bins(self, direction):\n \"\"\"\n Convert a direction in radians into a feature_bin number.\n\n Works for NumPy arrays of direction, returning\n an array of feature_bin numbers.\n \"\"\"\n return direction * self.axis_range / (2 * np.pi)\n\n\n def _safe_divide(self, numerator, denominator):\n \"\"\"\n Division routine that avoids division-by-zero errors\n (returning zero in such cases) but keeps track of them\n for undefined_values().\n \"\"\"\n if denominator == 0:\n self.undefined_vals += 1\n return 0\n else:\n return numerator/denominator\n\n\nclass Pref(dict):\n \"\"\"\n This class simply collects named arguments into a dictionary\n\n the main purpose is to make pretty readable the output of DistributionStatisticFn\n functions.\n In addition, trap missing keys\n \"\"\"\n\n def __init__(self, **args):\n dict.__init__(self, **args)\n\n def __getitem__(self, key):\n try:\n return dict.__getitem__(self, key)\n except KeyError:\n return None\n\n\n\nclass DistributionStatisticFn(param.Parameterized):\n \"\"\"\n Base class for various functions performing statistics on a distribution.\n \"\"\"\n\n value_scale = param.NumericTuple((0.0, 1.0), doc=\"\"\"\n Scaling of the resulting value of the distribution statistics,\n typically the preference of a unit to feature values. The tuple\n specifies (offset, multiplier) of the output scaling\"\"\")\n\n# APNOTE: previously selectivity_scale[ 1 ] used to be 17, a value suitable\n# for combining preference and selectivity in HSV plots. Users wishing to keep\n# this value should now set it when creating SheetViews, in commands like that\n# in command/analysis.py\n selectivity_scale = param.NumericTuple((0.0, 1.0), doc=\"\"\"\n Scaling of the resulting measure of the distribution peakedness,\n typically the selectivity of a unit to its preferred feature value.\n The tuple specifies (offset, multiplier) of the output scaling\"\"\")\n\n __abstract = True\n\n def __call__(self, distribution):\n \"\"\"\n Apply the distribution statistic function; must be implemented by subclasses.\n\n Subclasses sould be called with a Distribution as argument, return will be a\n dictionary, with Pref objects as values\n \"\"\"\n raise NotImplementedError\n\n\nclass DescriptiveStatisticFn(DistributionStatisticFn):\n \"\"\"\n Abstract class for basic descriptive statistics\n \"\"\"\n\n def vector_sum(self, d):\n \"\"\"\n Return the vector sum of the distribution as a tuple (magnitude, avgbinnum).\n\n Each bin contributes a vector of length equal to its value, at\n a direction corresponding to the bin number. Specifically,\n the total bin number range is mapped into a direction range\n [0,2pi].\n\n For a cyclic distribution, the avgbinnum will be a continuous\n measure analogous to the max_value_bin() of the distribution.\n But this quantity has more precision than max_value_bin()\n because it is computed from the entire distribution instead of\n just the peak bin. However, it is likely to be useful only\n for uniform or very dense sampling; with sparse, non-uniform\n sampling the estimates will be biased significantly by the\n particular samples chosen.\n\n The avgbinnum is not meaningful when the magnitude is 0,\n because a zero-length vector has no direction. To find out\n whether such cases occurred, you can compare the value of\n undefined_vals before and after a series of calls to this\n function.\n \n This is a slow algorithm and should only be used if the\n contents of the distribution have been changed by the statistical \n function.\n If not, then the cached value in the distribution should be used.\n\n \"\"\"\n # vectors are represented in polar form as complex numbers\n h = d.data()\n theta = calc_theta(np.array(list(h.keys())), d.axis_range)\n return d._fast_vector_sum(list(h.values()), theta)\n\n\n def _weighted_average(self, d ):\n \"\"\"\n Return the weighted_sum divided by the sum of the values\n \"\"\"\n return d._safe_divide(d.weighted_sum(), sum(d.values()))\n\n\n def selectivity(self, d):\n \"\"\"\n Return a measure of the peakedness of the distribution. The\n calculation differs depending on whether this is a cyclic\n variable. For a cyclic variable, returns the magnitude of the\n vector_sum() divided by the sum_value() (see\n _vector_selectivity for more details). For a non-cyclic\n variable, returns the max_value_bin()) as a proportion of the\n sum_value() (see _relative_selectivity for more details).\n \"\"\"\n if d.cyclic == True:\n return self._vector_selectivity(d)\n else:\n return self._relative_selectivity(d)\n\n\n # CEBHACKALERT: the definition of selectivity for non-cyclic\n # quantities probably needs some more thought.\n # Additionally, this fails the test in testfeaturemap\n # (see the comment there).\n def _relative_selectivity(self, d):\n \"\"\"\n Return max_value_bin()) as a proportion of the sum_value().\n\n This quantity is a measure of how strongly the distribution is\n biased towards the max_value_bin(). For a smooth,\n single-lobed distribution with an inclusive, non-cyclic range,\n this quantity is an analog to vector_selectivity. To be a\n precise analog for arbitrary distributions, it would need to\n compute some measure of the selectivity that works like the\n weighted_average() instead of the max_value_bin(). The result\n is scaled such that if all bins are identical, the selectivity\n is 0.0, and if all bins but one are zero, the selectivity is\n 1.0.\n \"\"\"\n # A single feature_bin is considered fully selective (but could also\n # arguably be considered fully unselective)\n if len(d.data()) <= 1:\n return 1.0\n\n proportion = d._safe_divide(max(d.values()), sum(d.values()))\n offset = 1.0/len(d.values())\n scaled = (proportion-offset) / (1.0-offset)\n\n # negative scaled is possible\n # e.g. 2 bins, with values that sum to less than 0.5\n # this probably isn't what should be done in those cases\n if scaled >= 0.0:\n return scaled\n else:\n return 0.0\n\n\n def _vector_selectivity(self, d):\n \"\"\"\n Return the magnitude of the vector_sum() divided by the sum_value().\n\n This quantity is a vector-based measure of the peakedness of\n the distribution. If only a single feature_bin has a non-zero value(),\n the selectivity will be 1.0, and if all bins have the same\n value() then the selectivity will be 0.0. Other distributions\n will result in intermediate values.\n\n For a distribution with a sum_value() of zero (i.e. all bins\n empty), the selectivity is undefined. Assuming that one will\n usually be looking for high selectivity, we return zero in such\n a case so that high selectivity will not mistakenly be claimed.\n To find out whether such cases occurred, you can compare the\n value of undefined_values() before and after a series of\n calls to this function.\n \"\"\"\n return d._safe_divide(d.vector_sum()[0], sum(d.values()))\n\n\n __abstract = True\n\n\n\nclass DescriptiveBimodalStatisticFn(DescriptiveStatisticFn):\n \"\"\"\n Abstract class for descriptive statistics of two-modes distributions\n\n \"\"\"\n\n def second_max_value_bin(self, d):\n \"\"\"\n Return the feature_bin with the second largest value.\n If there is one feature_bin only, return it. This is not a correct result,\n however it is practical for plotting compatibility, and it will not\n mistakenly be claimed as secondary maximum, by forcing its selectivity\n to 0.0\n \"\"\"\n if len(d.bins()) <= 1:\n return d.bins()[0]\n\n k = d.max_value_bin()\n d.pop(k)\n m = d.max_value_bin()\n d.restore(k)\n\n return m\n\n\n def second_selectivity(self, d):\n \"\"\"\n Return the selectivity of the second largest value in the distribution.\n If there is one feature_bin only, the selectivity is 0, since there is no second\n peack at all, and this value is also used to discriminate the validity\n of second_max_value_bin()\n Selectivity is computed in two ways depending on whether the variable is\n a cyclic, as in selectivity()\n \"\"\"\n if len( d._data ) <= 1:\n return 0.0\n if d.cyclic == True:\n return self._vector_second_selectivity(d)\n else:\n return self._relative_second_selectivity(d)\n\n\n def _relative_second_selectivity(self, d):\n \"\"\"\n Return the value of the second maximum as a proportion of the sum_value()\n see _relative_selectivity() for further details\n \"\"\"\n k = d.max_value_bin()\n d.pop(k)\n m = max(d.values())\n d.restore(k)\n\n proportion = d._safe_divide(m, sum(d.values()))\n offset = 1.0 / len(d.data())\n scaled = (proportion - offset) / (1.0 - offset)\n\n return max(scaled, 0.0)\n\n\n def _vector_second_selectivity(self, d):\n \"\"\"\n Return the magnitude of the vector_sum() of all bins excluding the\n maximum one, divided by the sum_value().\n see _vector_selectivity() for further details\n \"\"\"\n k = d.max_value_bin()\n d.pop(k)\n s = self.vector_sum(d)[0]\n d.restore(k)\n\n return self._safe_divide(s, sum(d.values()))\n\n\n def second_peak_bin(self, d):\n \"\"\"\n Return the feature_bin with the second peak in the distribution.\n Unlike second_max_value_bin(), it does not return a feature_bin which is the\n second largest value, if laying on a wing of the first peak, the second\n peak is returned only if the distribution is truly multimodal. If it isn't,\n return the first peak (for compatibility with numpy array type, and\n plotting compatibility), however the corresponding selectivity will be\n forced to 0.0\n \"\"\"\n h = d.data()\n l = len(h)\n if l <= 1:\n return d.keys()[0]\n\n ks = list(h.keys())\n ks.sort()\n ik0 = ks.index(d.keys()[np.argmax(d.values())])\n k0 = ks[ik0]\n v0 = h[k0]\n\n v = v0\n k = k0\n ik = ik0\n while h[k] <= v:\n ik += 1\n if ik >= l:\n ik = 0\n if ik == ik0:\n return k0\n v = h[k]\n k = ks[ik]\n ik1 = ik\n\n v = v0\n k = k0\n ik = ik0\n while h[k] <= v:\n ik -= 1\n if ik < 0:\n ik = l - 1\n if ik == ik0:\n return k0\n v = h[k]\n k = ks[ik]\n ik2 = ik\n\n if ik1 == ik2:\n return ks[ik1]\n\n ik = ik1\n m = 0\n while ik != ik2:\n k = ks[ik]\n if h[k] > m:\n m = h[k]\n im = ik\n ik += 1\n if ik >= l:\n ik = 0\n\n return ks[im]\n\n\n def second_peak_selectivity(self, d):\n \"\"\"\n Return the selectivity of the second peak in the distribution.\n\n If the distribution has only one peak, return 0.0, and this value is\n also usefl to discriminate the validity of second_peak_bin()\n \"\"\"\n l = len(d.keys())\n if l <= 1:\n return 0.0\n\n p1 = d.max_value_bin()\n p2 = self.second_peak_bin(d)\n if p1 == p2:\n return 0.0\n\n m = d.get_value(p2)\n proportion = d._safe_divide(m, sum(d.values()))\n offset = 1.0 / l\n scaled = (proportion - offset) / (1.0 - offset)\n\n return max(scaled, 0.0)\n\n\n def second_peak(self, d):\n \"\"\"\n Return preference and selectivity of the second peak in the distribution.\n\n It is just the combination of second_peak_bin() and\n second_peak_selectivity(), with the advantage of avoiding a duplicate\n call of second_peak_bin(), if the user is interested in both preference\n and selectivity, as often is the case.\n \"\"\"\n l = len(d.keys())\n if l <= 1:\n return (d.keys()[0], 0.0)\n\n p1 = d.max_value_bin()\n p2 = self.second_peak_bin(d)\n if p1 == p2:\n return (p1, 0.0)\n\n m = d.get_value(p2)\n proportion = d._safe_divide(m, sum(d.values()))\n offset = 1.0 / l\n scaled = (proportion - offset) / (1.0 - offset)\n\n return (p2, max(scaled, 0.0))\n\n\n __abstract = True\n\n\nclass DSF_MaxValue(DescriptiveStatisticFn):\n \"\"\"\n Return the peak value of the given distribution\n\n \"\"\"\n\n\n def __call__(self, d):\n p = self.value_scale[1] * (d.max_value_bin() + self.value_scale[0])\n s = self.selectivity_scale[1] * (self.selectivity(d)+self.selectivity_scale[0])\n\n return {\"\": Pref(preference=p, selectivity=s)}\n\n\n\nclass DSF_WeightedAverage(DescriptiveStatisticFn):\n \"\"\"\n Return the main mode of the given distribution\n\n The prefence value ia a continuous, interpolated equivalent of the max_value_bin().\n For a cyclic distribution, this is the direction of the vector\n sum (see vector_sum()).\n For a non-cyclic distribution, this is the arithmetic average\n of the data on the bin_axis, where each feature_bin is weighted by its\n value.\n Such a computation will generally produce much more precise maps using\n fewer test stimuli than the discrete method. However, weighted_average\n methods generally require uniform and full-range sampling, which is not\n always feasible.\n For measurements at evenly-spaced intervals over the full range of\n possible parameter values, weighted_averages are a good measure of the\n underlying continuous-valued parameter preference, assuming that neurons\n are tuned broadly enough (and/or sampled finely enough) that they\n respond to at least two of the tested parameter values. This method\n will not usually give good results when those criteria are not met, i.e.\n if the sampling is too sparse, not at evenly-spaced intervals, or does\n not cover the full range of possible values. In such cases\n max_value_bin should be used, and the number of test patterns will\n usually need to be increased instead.\n \"\"\"\n\n def __call__(self, d):\n p = d.vector_sum()[1] if d.cyclic else self._weighted_average(d)\n p = self.value_scale[1] * (p + self.value_scale[0])\n s = self.selectivity_scale[1] * (self.selectivity(d) + self.selectivity_scale[0])\n\n return {\"\": Pref(preference=p, selectivity=s)}\n\n\n\nclass DSF_TopTwoValues(DescriptiveBimodalStatisticFn):\n \"\"\"\n Return the two max values of distributions in the given matrix\n\n \"\"\"\n\n\n def __call__(self, d):\n r = {}\n p = self.value_scale[1] * (d.max_value_bin() + self.value_scale[0])\n s = self.selectivity_scale[1] * (self.selectivity(d) + self.selectivity_scale[0])\n r[\"\"] = Pref(preference=p, selectivity=s)\n p = self.second_max_value_bin(d)\n s = self.second_selectivity(d)\n p = self.value_scale[1] * (p + self.value_scale[0])\n s = self.selectivity_scale[1] * (s + self.selectivity_scale[0])\n r[\"Mode2\"] = Pref(preference=p, selectivity=s)\n\n return r\n\n\nclass DSF_BimodalPeaks(DescriptiveBimodalStatisticFn):\n \"\"\"\n Return the two peak values of distributions in the given matrix\n \"\"\"\n\n def __call__(self, d):\n r = {}\n p = self.value_scale[1] * (d.max_value_bin() + self.value_scale[0])\n s = self.selectivity_scale[1] * (self.selectivity(d) + self.selectivity_scale[0])\n r[\"\"] = Pref(preference=p, selectivity=s)\n p, s = self.second_peak(d)\n p = self.value_scale[1] * (p + self.value_scale[0])\n s = self.selectivity_scale[1] * (s + self.selectivity_scale[0])\n r[\"Mode2\"] = Pref(preference=p, selectivity=s)\n\n return r\n\n\n\nclass VonMisesStatisticFn(DistributionStatisticFn):\n \"\"\"\n Base class for von Mises statistics\n \"\"\"\n\n # values to fit the maximum value of k parameter in von Mises distribution,\n # as a function of the number of bins in the distribution. Useful for\n # keeping selectivity in range 0..1. Values derived offline from distribution\n # with a single active feature_bin, and total bins from 8 to 32\n vm_kappa_fit = (0.206, 0.614)\n\n # level of activity in units confoundable with noise. Used in von Mises fit,\n # for two purposes: if the standard deviation of a distribution is below this\n # value, the distribution is assumed to lack any mode; it is the maximum level\n # of random noise added to a distribution before the fit optimization, for\n # stability reasons\n noise_level = 0.001\n\n # exit code of the distribution fit function. Codes are function-specific and\n # each fit function, if provide exit codes, should have corresponding string translation\n fit_exit_code = 0\n\n user_warned_if_unavailable = False\n\n __abstract = True\n\n def _orth(self, t):\n \"\"\"\n Return the orthogonal orientation\n \"\"\"\n if t < 0.5 * np.pi:\n return t + 0.5 * np.pi\n return t - 0.5 * np.pi\n\n\n def _in_pi(self, t):\n \"\"\"\n Reduce orientation from -pi..2pi to 0..pi\n \"\"\"\n if t > np.pi:\n return t - np.pi\n if t < 0:\n return t + np.pi\n return t\n\n\n def von_mises(self, pars, x):\n \"\"\"\n Compute a simplified von Mises function.\n\n Original formulation in Richard von Mises, \"Wahrscheinlichkeitsrechnung\n und ihre Anwendungen in der Statistik und theoretischen Physik\", 1931,\n Deuticke, Leipzig; see also Mardia, K.V. and Jupp, P.E., \" Directional\n Statistics\", 1999, J. Wiley, p.36;\n http://en.wikipedia.org/wiki/Von_Mises_distribution\n The two differences are that this function is a continuous probability\n distribution on a semi-circle, while von Mises is on the full circle,\n and that the normalization factor, which is the inverse of the modified\n Bessel function of first kind and 0 degree in the original, is here a fit parameter.\n \"\"\"\n a, k, t = pars\n return a * np.exp(k * (np.cos(2 * (x - t)) - 1))\n\n\n def von2_mises(self, pars, x):\n \"\"\"\n Compute a simplified bimodal von Mises function\n\n Two superposed von Mises functions, with different peak and bandwith values\n \"\"\"\n p1 = pars[: 3]\n p2 = pars[3:]\n return self.von_mises(p1, x) + self.von_mises(p2, x)\n\n\n def von_mises_res(self, pars, x, y):\n return y - self.von_mises(pars, x)\n\n\n def von2_mises_res(self, pars, x, y):\n return y - self.von2_mises(pars, x)\n\n\n def norm_sel(self, k, n):\n m = (self.vm_kappa_fit[0] + n * self.vm_kappa_fit[1])**2\n return np.log(1 + k) / np.log(1 + m)\n\n\n def fit_vm(self, distribution):\n \"\"\"\n computes the best fit of the monovariate von Mises function in the\n semi-circle.\n Return a tuple with the orientation preference, in the same range of\n axis_bounds, the orientation selectivity, and an estimate of the\n goodness-of-fit, as the variance of the predicted orientation\n preference. The selectivity is given by the bandwith parameter of the\n von Mises function, modified for compatibility with other selectivity\n computations in this class. The bandwith parameter is transposed in\n logaritmic scale, and is normalized by the maximum value for the number\n of bins in the distribution, in order to give roughly 1.0 for a\n distribution with one feature_bin at 1.0 an all the other at 0.0, and 0.0 for\n uniform distributions. The normalizing factor of the selectivity is fit\n for the total number of bins, using fit parameters computed offline.\n There are conditions that prevents apriori the possibility to fit the\n distribution:\n * not enough bins, at least 4 are necessary\n * the distribution is too flat, below the noise level\n and conditions of aposteriori failures:\n * \"ier\" flag returned by leastsq out of ( 1, 2, 3, 4 )\n * no estimated Jacobian around the solution\n * negative bandwith (the peak of the distribution is convex)\n Note that these are the minimal conditions, their fulfillment does not\n warrant unimodality, is up to the user to check the goodness-of-fit value\n for an accurate acceptance of the fit.\n \"\"\"\n if unavailable_scipy_optimize:\n if not VonMisesStatisticFn.user_warned_if_unavailable:\n param.Parameterized().warning(\"scipy.optimize not available, dummy von Mises fit\")\n VonMisesStatisticFn.user_warned_if_unavailable=True\n self.fit_exit_code = 3\n return 0, 0, 0\n\n to_pi = np.pi / distribution.axis_range\n x = to_pi * np.array(distribution.bins())\n n = len(x)\n if n < 5:\n param.Parameterized().warning(\"No von Mises fit possible with less than 4 bins\")\n self.fit_exit_code = -1\n return 0, 0, 0\n\n y = np.array(distribution.values())\n if y.std() < self.noise_level:\n self.fit_exit_code = 1\n return 0, 0, 0\n\n rn = self.noise_level * np.random.random_sample(y.shape)\n p0 = (1.0, 1.0, distribution.max_value_bin())\n r = optimize.leastsq(self.von_mises_res, p0, args=(x, y + rn),\n full_output=True)\n\n if not r[-1] in ( 1, 2, 3, 4 ):\n self.fit_exit_code = 100 + r[-1]\n return 0, 0, 0\n\n residuals = r[2]['fvec']\n jacobian = r[1]\n bandwith = r[0][1]\n tuning = r[0][2]\n\n if bandwith < 0:\n self.fit_exit_code = 1\n return 0, 0, 0\n\n if jacobian is None:\n self.fit_exit_code = 2\n return 0, 0, 0\n\n error = (residuals**2).sum() / (n - len(p0))\n covariance = jacobian * error\n g = covariance[2, 2]\n p = self._in_pi(tuning) / to_pi\n s = self.norm_sel(bandwith, n)\n self.fit_exit_code = 0\n return p, s, g\n\n\n def vm_fit_exit_codes(self):\n if self.fit_exit_code == 0:\n return \"succesfull exit\"\n if self.fit_exit_code == -1:\n return \"not enough bins for this fit\"\n if self.fit_exit_code == 1:\n return \"flat distribution\"\n if self.fit_exit_code == 2:\n return \"flat distribution\"\n if self.fit_exit_code == 3:\n return \"missing scipy.optimize import\"\n if self.fit_exit_code > 110:\n return \"unknown exit code\"\n if self.fit_exit_code > 100:\n return \"error \" + str(self.fit_exit_code - 100) + \" in scipy.optimize.leastsq\"\n\n return \"unknown exit code\"\n\n\n def fit_v2m(self, distribution):\n \"\"\"\n computes the best fit of the bivariate von Mises function in the\n semi-circle.\n Return the tuple:\n (\n orientation1_preference, orientation1_selectivity, goodness_of_fit1,\n orientation2_preference, orientation2_selectivity, goodness_of_fit2\n )\n See fit_vm() for considerations about selectivity and goodness_of_fit\n \"\"\"\n null = 0, 0, 0, 0, 0, 0\n if unavailable_scipy_optimize:\n if not VonMisesStatisticFn.user_warned_if_unavailable:\n param.Parameterized().warning(\"scipy.optimize not available, dummy von Mises fit\")\n VonMisesStatisticFn.user_warned_if_unavailable=True\n self.fit_exit_code = 3\n return null\n\n to_pi = np.pi / distribution.axis_range\n x = to_pi * np.array(distribution.bins())\n n = len(x)\n if n < 9:\n param.Parameterized().warning( \"no bimodal von Mises fit possible with less than 8 bins\" )\n self.fit_exit_code = -1\n return null\n y = np.array(distribution.values())\n if y.std() < self.noise_level:\n self.fit_exit_code = 1\n return null\n\n rn = self.noise_level * np.random.random_sample(y.shape)\n t0 = distribution.max_value_bin()\n p0 = (1.0, 1.0, t0, 1.0, 1.0, self._orth(t0))\n r = optimize.leastsq(self.von2_mises_res, p0, args=(x, y + rn),\n full_output=True)\n if not r[-1] in ( 1, 2, 3, 4 ):\n self.fit_exit_code = 100 + r[-1]\n return null\n residuals = r[2]['fvec']\n jacobian = r[1]\n bandwith_1 = r[0][1]\n tuning_1 = r[0][2]\n bandwith_2 = r[0][4]\n tuning_2 = r[0][5]\n if jacobian is None:\n self.fit_exit_code = 2\n return null\n if bandwith_1 < 0:\n self.fit_exit_code = 1\n return null\n if bandwith_2 < 0:\n self.fit_exit_code = 1\n return null\n\n error = (residuals ** 2).sum() / (n - len(p0))\n covariance = jacobian * error\n g1 = covariance[2, 2]\n g2 = covariance[5, 5]\n p1 = self._in_pi(tuning_1) / to_pi\n p2 = self._in_pi(tuning_2) / to_pi\n s1 = self.norm_sel(bandwith_1, n)\n s2 = self.norm_sel(bandwith_2, n)\n self.fit_exit_code = 0\n return p1, s1, g1, p2, s2, g2\n\n\n def __call__(self, distribution):\n \"\"\"\n Apply the distribution statistic function; must be implemented by subclasses.\n\n \"\"\"\n raise NotImplementedError\n\n\n\nclass DSF_VonMisesFit(VonMisesStatisticFn):\n \"\"\"\n Return the main mode of distribution in the given matrix, by fit with von Mises function.\n \"\"\"\n\n worst_fit = param.Number(default=0.5, bounds=(0.0, None), softbounds=(0.0, 1.0), doc=\"\"\"\n worst good-of-fitness value for accepting the distribution as monomodal\"\"\")\n\n # default result in case of failure of the fit\n null_result = {\"\": Pref(preference=0, selectivity=0, goodness_of_fit=0),\n \"Modes\": Pref(number=0)}\n\n def __call__(self, distribution):\n f = self.fit_vm(distribution)\n if self.fit_exit_code != 0 or f[-1] > self.worst_fit:\n return self.null_result\n results = {}\n p, s, g = f\n p = self.value_scale[1] * (p + self.value_scale[0])\n s = self.selectivity_scale[1] * (s + self.selectivity_scale[0])\n results[\"\"] = Pref(preference=p, selectivity=s, goodness_of_fit=g)\n results[\"Modes\"] = Pref(number=1)\n\n return results\n\n\n\nclass DSF_BimodalVonMisesFit(VonMisesStatisticFn):\n \"\"\"\n Return the two modes of distributions in the given matrix, by fit with von Mises function\n\n The results of the main mode are available in\n self.{preference,selectivity,good_of_fit}, while the second mode results are\n in the first element of the self.more_modes list, as a dictionary with keys\n preference,selectivity,good_of_fit.\n \"\"\"\n\n worst_fit = param.Number(default=0.5, bounds=(0.0, None), softbounds=(0.0, 1.0), doc=\"\"\"\n Worst good-of-fitness value for accepting the distribution as mono- or bi-modal\"\"\")\n\n # default result in case of failure of the fit\n null_result = {\n \"\": Pref(preference=0, selectivity=0, goodness_of_fit=0),\n \"Mode2\": Pref(preference=0, selectivity=0, goodness_of_fit=0),\n \"Modes\": Pref(number=0)\n }\n\n\n def _analyze_distr(self, d):\n \"\"\"\n Analyze the given distribution with von Mises bimodal fit.\n\n The distribution is analyzed with both unimodal and bimodal fits, and a\n decision about the number of modes is made by comparing the goodness of\n fit. It is a quick but inaccurate way of estimating the number of modes.\n Return preference, selectivity, goodness of fit for both modes, and the\n estimated numer of modes, None if even the unimodal fit failed. If the\n distribution is unimodal, values of the second mode are set to 0. The main\n mode is always the one with the largest selectivity (von Mises bandwith).\n \"\"\"\n no1 = False\n f = self.fit_vm(d)\n if self.fit_exit_code != 0:\n no1 = True\n p, s, g = f\n f2 = self.fit_v2m(d)\n if self.fit_exit_code != 0 or f2[2] > self.worst_fit:\n if no1 or f[-1] > self.worst_fit:\n return None\n return p, s, g, 0, 0, 0, 1\n p1, s1, g1, p2, s2, g2 = f2\n if g1 > g:\n return p, s, g, 0, 0, 0, 1\n\n if s2 > s1:\n return p2, s2, g2, p1, s1, g1, 2\n\n return p1, s1, g1, p2, s2, g2, 2\n\n\n def __call__(self, distribution):\n f = self._analyze_distr(distribution)\n if f is None:\n return self.null_result\n\n results = {}\n p, s, g = f[: 3]\n p = self.value_scale[1] * (p + self.value_scale[0])\n s = self.selectivity_scale[1] * (s + self.selectivity_scale[0])\n results[\"\"] = Pref(preference=p, selectivity=s, goodness_of_fit=g)\n p, s, g, n = f[3:]\n p = self.value_scale[1] * (p + self.value_scale[0])\n s = self.selectivity_scale[1] * (s + self.selectivity_scale[0])\n results[\"Mode2\"] = Pref(preference=p, selectivity=s, goodness_of_fit=g)\n results[\"Modes\"] = Pref(number=n)\n\n return results\n", "\"\"\"\nUseful Operations over Raster elements.\n\"\"\"\n\nimport numpy as np\n\nimport param\nfrom holoviews import CompositeOverlay, BoundingBox, Dimension\nfrom holoviews import Image, Curve, VectorField\nfrom holoviews.core import Operation\nfrom holoviews.operation.normalization import raster_normalization\n\n\nclass fft_power(Operation):\n \"\"\"\n Given a Image element, compute the power of the 2D Fast Fourier\n Transform (FFT).\n \"\"\"\n\n output_type = Curve\n\n max_power = param.Number(default=1.0, doc=\"\"\"\n The maximum power value of the output power spectrum.\"\"\")\n\n group = param.String(default='FFT Power', doc=\"\"\"\n The group assigned to the output power spectrum.\"\"\")\n\n\n def _process(self, matrix, key=None):\n normfn = raster_normalization.instance()\n if self.p.input_ranges:\n matrix = normfn.process_element(matrix, key, *self.p.input_ranges)\n else:\n matrix = normfn.process_element(matrix, key)\n\n fft_spectrum = abs(np.fft.fftshift(np.fft.fft2(matrix.data - 0.5, s=None, axes=(-2, -1))))\n fft_spectrum = 1 - fft_spectrum # Inverted spectrum by convention\n zero_min_spectrum = fft_spectrum - fft_spectrum.min()\n spectrum_range = fft_spectrum.max() - fft_spectrum.min()\n spectrum = (self.p.max_power * zero_min_spectrum) / spectrum_range\n\n l, b, r, t = matrix.bounds.lbrt()\n density = matrix.xdensity\n bounds = BoundingBox(radius=(density/2)/(r-l))\n\n return Image(spectrum, bounds=bounds, label=matrix.label, group=self.p.group)\n\n\n\nclass vectorfield(Operation):\n \"\"\"\n Given a Image with a single channel, convert it to a VectorField\n object at a given spatial sampling interval. The values in the\n Image are assumed to correspond to the vector angle in radians\n and the value is assumed to be cyclic.\n\n If supplied with an Overlay, the second sheetview in the overlay\n will be interpreted as the third vector dimension.\n \"\"\"\n\n output_type = VectorField\n\n rows = param.Integer(default=10, doc=\"\"\"\n The number of rows in the vector field.\"\"\")\n\n cols = param.Integer(default=10, doc=\"\"\"\n The number of columns in the vector field.\"\"\")\n\n group = param.String(default='Vectors', doc=\"\"\"\n The group assigned to the output vector field.\"\"\")\n\n\n def _process(self, view, key=None):\n\n if isinstance(view, CompositeOverlay) and len(view) >= 2:\n radians, lengths = view[0], view[1]\n else:\n radians, lengths = view, None\n\n cyclic_dim = radians.vdims[0]\n if not cyclic_dim.cyclic:\n raise Exception(\"First input Image must be declared cyclic\")\n\n l, b, r, t = radians.bounds.lbrt()\n X, Y = np.meshgrid(np.linspace(l, r, self.p.cols+2)[1:-1],\n np.linspace(b, t, self.p.rows+2)[1:-1])\n\n vector_data = []\n for x, y in zip(X.flat, Y.flat):\n components = (x,y, radians[x,y])\n if lengths is not None:\n components += (lengths[x,y],)\n\n vector_data.append(components)\n\n vdims = [Dimension('Angle', cyclic=True, range=cyclic_dim.range)]\n if lengths is not None:\n vdims.append(Dimension('Magnitude'))\n return VectorField(np.array(vector_data), label=radians.label, group=self.p.group,\n vdims=vdims)\n\n" ]
[ [ "numpy.log", "numpy.inner", "numpy.random.random_sample", "numpy.cos", "scipy.optimize.leastsq", "numpy.argmax", "numpy.array", "numpy.exp" ], [ "numpy.fft.fft2", "numpy.array", "numpy.linspace" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
KodeWorker/tensorflow
[ "a7f91fd5ce53253ab4bfd6448886028a085e0ddf", "a7f91fd5ce53253ab4bfd6448886028a085e0ddf" ]
[ "tensorflow/python/training/checkpoint_utils.py", "tensorflow/python/training/tracking/base.py" ]
[ "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tools to work with checkpoints.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time\nimport six\n\nfrom tensorflow.core.protobuf import saver_pb2\nfrom tensorflow.python.distribute import distribution_strategy_context\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import io_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import variable_scope as vs\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training import checkpoint_management\nfrom tensorflow.python.training import py_checkpoint_reader\nfrom tensorflow.python.training.saving import saveable_object_util\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n__all__ = [\n \"load_checkpoint\", \"load_variable\", \"list_variables\",\n \"checkpoints_iterator\", \"init_from_checkpoint\"\n]\n\n\n@tf_export(\"train.load_checkpoint\")\ndef load_checkpoint(ckpt_dir_or_file):\n \"\"\"Returns `CheckpointReader` for checkpoint found in `ckpt_dir_or_file`.\n\n If `ckpt_dir_or_file` resolves to a directory with multiple checkpoints,\n reader for the latest checkpoint is returned.\n\n Args:\n ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint\n file.\n\n Returns:\n `CheckpointReader` object.\n\n Raises:\n ValueError: If `ckpt_dir_or_file` resolves to a directory with no\n checkpoints.\n \"\"\"\n filename = _get_checkpoint_filename(ckpt_dir_or_file)\n if filename is None:\n raise ValueError(\"Couldn't find 'checkpoint' file or checkpoints in \"\n \"given directory %s\" % ckpt_dir_or_file)\n return py_checkpoint_reader.NewCheckpointReader(filename)\n\n\n@tf_export(\"train.load_variable\")\ndef load_variable(ckpt_dir_or_file, name):\n \"\"\"Returns the tensor value of the given variable in the checkpoint.\n\n Args:\n ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint.\n name: Name of the variable to return.\n\n Returns:\n A numpy `ndarray` with a copy of the value of this variable.\n \"\"\"\n # TODO(b/29227106): Fix this in the right place and remove this.\n if name.endswith(\":0\"):\n name = name[:-2]\n reader = load_checkpoint(ckpt_dir_or_file)\n return reader.get_tensor(name)\n\n\n@tf_export(\"train.list_variables\")\ndef list_variables(ckpt_dir_or_file):\n \"\"\"Returns list of all variables in the checkpoint.\n\n Args:\n ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint.\n\n Returns:\n List of tuples `(name, shape)`.\n \"\"\"\n reader = load_checkpoint(ckpt_dir_or_file)\n variable_map = reader.get_variable_to_shape_map()\n names = sorted(variable_map.keys())\n result = []\n for name in names:\n result.append((name, variable_map[name]))\n return result\n\n\ndef wait_for_new_checkpoint(checkpoint_dir,\n last_checkpoint=None,\n seconds_to_sleep=1,\n timeout=None):\n \"\"\"Waits until a new checkpoint file is found.\n\n Args:\n checkpoint_dir: The directory in which checkpoints are saved.\n last_checkpoint: The last checkpoint path used or `None` if we're expecting\n a checkpoint for the first time.\n seconds_to_sleep: The number of seconds to sleep for before looking for a\n new checkpoint.\n timeout: The maximum number of seconds to wait. If left as `None`, then the\n process will wait indefinitely.\n\n Returns:\n a new checkpoint path, or None if the timeout was reached.\n \"\"\"\n logging.info(\"Waiting for new checkpoint at %s\", checkpoint_dir)\n stop_time = time.time() + timeout if timeout is not None else None\n while True:\n checkpoint_path = checkpoint_management.latest_checkpoint(checkpoint_dir)\n if checkpoint_path is None or checkpoint_path == last_checkpoint:\n if stop_time is not None and time.time() + seconds_to_sleep > stop_time:\n return None\n time.sleep(seconds_to_sleep)\n else:\n logging.info(\"Found new checkpoint at %s\", checkpoint_path)\n return checkpoint_path\n\n\n@tf_export(\"train.checkpoints_iterator\")\ndef checkpoints_iterator(checkpoint_dir,\n min_interval_secs=0,\n timeout=None,\n timeout_fn=None):\n \"\"\"Continuously yield new checkpoint files as they appear.\n\n The iterator only checks for new checkpoints when control flow has been\n reverted to it. This means it can miss checkpoints if your code takes longer\n to run between iterations than `min_interval_secs` or the interval at which\n new checkpoints are written.\n\n The `timeout` argument is the maximum number of seconds to block waiting for\n a new checkpoint. It is used in combination with the `timeout_fn` as\n follows:\n\n * If the timeout expires and no `timeout_fn` was specified, the iterator\n stops yielding.\n * If a `timeout_fn` was specified, that function is called and if it returns\n a true boolean value the iterator stops yielding.\n * If the function returns a false boolean value then the iterator resumes the\n wait for new checkpoints. At this point the timeout logic applies again.\n\n This behavior gives control to callers on what to do if checkpoints do not\n come fast enough or stop being generated. For example, if callers have a way\n to detect that the training has stopped and know that no new checkpoints\n will be generated, they can provide a `timeout_fn` that returns `True` when\n the training has stopped. If they know that the training is still going on\n they return `False` instead.\n\n Args:\n checkpoint_dir: The directory in which checkpoints are saved.\n min_interval_secs: The minimum number of seconds between yielding\n checkpoints.\n timeout: The maximum number of seconds to wait between checkpoints. If left\n as `None`, then the process will wait indefinitely.\n timeout_fn: Optional function to call after a timeout. If the function\n returns True, then it means that no new checkpoints will be generated and\n the iterator will exit. The function is called with no arguments.\n\n Yields:\n String paths to latest checkpoint files as they arrive.\n \"\"\"\n checkpoint_path = None\n while True:\n new_checkpoint_path = wait_for_new_checkpoint(\n checkpoint_dir, checkpoint_path, timeout=timeout)\n if new_checkpoint_path is None:\n if not timeout_fn:\n # timed out\n logging.info(\"Timed-out waiting for a checkpoint.\")\n return\n if timeout_fn():\n # The timeout_fn indicated that we are truly done.\n return\n else:\n # The timeout_fn indicated that more checkpoints may come.\n continue\n start = time.time()\n checkpoint_path = new_checkpoint_path\n yield checkpoint_path\n time_to_next_eval = start + min_interval_secs - time.time()\n if time_to_next_eval > 0:\n time.sleep(time_to_next_eval)\n\n\n@tf_export(v1=[\"train.init_from_checkpoint\"])\ndef init_from_checkpoint(ckpt_dir_or_file, assignment_map):\n \"\"\"Replaces `tf.Variable` initializers so they load from a checkpoint file.\n\n Values are not loaded immediately, but when the initializer is run\n (typically by running a `tf.compat.v1.global_variables_initializer` op).\n\n Note: This overrides default initialization ops of specified variables and\n redefines dtype.\n\n Assignment map supports following syntax:\n\n * `'checkpoint_scope_name/': 'scope_name/'` - will load all variables in\n current `scope_name` from `checkpoint_scope_name` with matching tensor\n names.\n * `'checkpoint_scope_name/some_other_variable': 'scope_name/variable_name'` -\n will initialize `scope_name/variable_name` variable\n from `checkpoint_scope_name/some_other_variable`.\n * `'scope_variable_name': variable` - will initialize given `tf.Variable`\n object with tensor 'scope_variable_name' from the checkpoint.\n * `'scope_variable_name': list(variable)` - will initialize list of\n partitioned variables with tensor 'scope_variable_name' from the checkpoint.\n * `'/': 'scope_name/'` - will load all variables in current `scope_name` from\n checkpoint's root (e.g. no scope).\n\n Supports loading into partitioned variables, which are represented as\n `'<variable>/part_<part #>'`.\n\n Example:\n\n ```python\n\n # Say, '/tmp/model.ckpt' has the following tensors:\n # -- name='old_scope_1/var1', shape=[20, 2]\n # -- name='old_scope_1/var2', shape=[50, 4]\n # -- name='old_scope_2/var3', shape=[100, 100]\n\n # Create new model's variables\n with tf.compat.v1.variable_scope('new_scope_1'):\n var1 = tf.compat.v1.get_variable('var1', shape=[20, 2],\n initializer=tf.compat.v1.zeros_initializer())\n with tf.compat.v1.variable_scope('new_scope_2'):\n var2 = tf.compat.v1.get_variable('var2', shape=[50, 4],\n initializer=tf.compat.v1.zeros_initializer())\n # Partition into 5 variables along the first axis.\n var3 = tf.compat.v1.get_variable(name='var3', shape=[100, 100],\n initializer=tf.compat.v1.zeros_initializer(),\n partitioner=lambda shape, dtype: [5, 1])\n\n # Initialize all variables in `new_scope_1` from `old_scope_1`.\n init_from_checkpoint('/tmp/model.ckpt', {'old_scope_1/': 'new_scope_1'})\n\n # Use names to specify which variables to initialize from checkpoint.\n init_from_checkpoint('/tmp/model.ckpt',\n {'old_scope_1/var1': 'new_scope_1/var1',\n 'old_scope_1/var2': 'new_scope_2/var2'})\n\n # Or use tf.Variable objects to identify what to initialize.\n init_from_checkpoint('/tmp/model.ckpt',\n {'old_scope_1/var1': var1,\n 'old_scope_1/var2': var2})\n\n # Initialize partitioned variables using variable's name\n init_from_checkpoint('/tmp/model.ckpt',\n {'old_scope_2/var3': 'new_scope_2/var3'})\n\n # Or specify the list of tf.Variable objects.\n init_from_checkpoint('/tmp/model.ckpt',\n {'old_scope_2/var3': var3._get_variable_list()})\n\n ```\n\n Args:\n ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint.\n assignment_map: Dict, where keys are names of the variables in the\n checkpoint and values are current variables or names of current variables\n (in default graph).\n\n Raises:\n ValueError: If missing variables in current graph, or if missing\n checkpoints or tensors in checkpoints.\n \"\"\"\n init_from_checkpoint_fn = lambda _: _init_from_checkpoint(\n ckpt_dir_or_file, assignment_map)\n if distribution_strategy_context.get_cross_replica_context():\n init_from_checkpoint_fn(None)\n else:\n distribution_strategy_context.get_replica_context().merge_call(\n init_from_checkpoint_fn)\n\n\ndef _init_from_checkpoint(ckpt_dir_or_file, assignment_map):\n \"\"\"See `init_from_checkpoint` for documentation.\"\"\"\n ckpt_file = _get_checkpoint_filename(ckpt_dir_or_file)\n reader = load_checkpoint(ckpt_dir_or_file)\n variable_map = reader.get_variable_to_shape_map()\n for tensor_name_in_ckpt, current_var_or_name in sorted(\n six.iteritems(assignment_map)):\n var = None\n # Check if this is Variable object or list of Variable objects (in case of\n # partitioned variables).\n if _is_variable(current_var_or_name) or (\n isinstance(current_var_or_name, list)\n and all(_is_variable(v) for v in current_var_or_name)):\n var = current_var_or_name\n else:\n store_vars = vs._get_default_variable_store()._vars # pylint:disable=protected-access\n # Check if this variable is in var_store.\n var = store_vars.get(current_var_or_name, None)\n # Also check if variable is partitioned as list.\n if var is None:\n var = _collect_partitioned_variable(current_var_or_name, store_vars)\n if var is not None:\n # If 1 to 1 mapping was provided, find variable in the checkpoint.\n if tensor_name_in_ckpt not in variable_map:\n raise ValueError(\"Tensor %s is not found in %s checkpoint %s\" % (\n tensor_name_in_ckpt, ckpt_dir_or_file, variable_map\n ))\n if _is_variable(var):\n # Additional at-call-time checks.\n if not var.get_shape().is_compatible_with(\n variable_map[tensor_name_in_ckpt]):\n raise ValueError(\n \"Shape of variable %s (%s) doesn't match with shape of \"\n \"tensor %s (%s) from checkpoint reader.\" % (\n var.name, str(var.get_shape()),\n tensor_name_in_ckpt, str(variable_map[tensor_name_in_ckpt])\n ))\n var_name = var.name\n else:\n var_name = \",\".join([v.name for v in var])\n _set_variable_or_list_initializer(var, ckpt_file, tensor_name_in_ckpt)\n logging.debug(\"Initialize variable %s from checkpoint %s with %s\",\n var_name, ckpt_dir_or_file, tensor_name_in_ckpt)\n else:\n scopes = \"\"\n # TODO(vihanjain): Support list of 'current_var_or_name' here.\n if \"/\" in current_var_or_name:\n scopes = current_var_or_name[:current_var_or_name.rindex(\"/\")]\n if not tensor_name_in_ckpt.endswith(\"/\"):\n raise ValueError(\n \"Assignment map with scope only name {} should map to scope only \"\n \"{}. Should be 'scope/': 'other_scope/'.\".format(\n scopes, tensor_name_in_ckpt))\n # If scope to scope mapping was provided, find all variables in the scope\n # and create variable to variable mapping.\n scope_variables = set()\n for var_name in store_vars:\n if not scopes or var_name.startswith(scopes + \"/\"):\n # Consume /part_ if partitioned variable.\n if \"/part_\" in var_name:\n var_name = var_name[:var_name.index(\"/part_\")]\n scope_variables.add(var_name)\n for var_name in sorted(scope_variables):\n # Lookup name with specified prefix and suffix from current variable.\n # If tensor_name given is '/' (root), don't use it for full name.\n full_tensor_name = var_name[len(scopes):]\n if current_var_or_name != \"/\":\n full_tensor_name = full_tensor_name[1:]\n if tensor_name_in_ckpt != \"/\":\n full_tensor_name = tensor_name_in_ckpt + full_tensor_name\n # Remove trailing '/', if any, in the full_tensor_name\n if full_tensor_name.endswith(\"/\"):\n full_tensor_name = full_tensor_name[:-1]\n if full_tensor_name not in variable_map:\n raise ValueError(\n \"Tensor %s (%s in %s) is not found in %s checkpoint\" % (\n full_tensor_name, var_name[len(scopes) + 1:],\n tensor_name_in_ckpt, ckpt_dir_or_file\n ))\n var = store_vars.get(var_name, None)\n if var is None:\n var = _collect_partitioned_variable(var_name, store_vars)\n _set_variable_or_list_initializer(var, ckpt_file, full_tensor_name)\n logging.debug(\"Initialize variable %s from checkpoint %s with %s\",\n var_name, ckpt_dir_or_file, full_tensor_name)\n\n\ndef _get_checkpoint_filename(ckpt_dir_or_file):\n \"\"\"Returns checkpoint filename given directory or specific checkpoint file.\"\"\"\n if gfile.IsDirectory(ckpt_dir_or_file):\n return checkpoint_management.latest_checkpoint(ckpt_dir_or_file)\n return ckpt_dir_or_file\n\n\ndef _set_checkpoint_initializer(variable,\n ckpt_file,\n tensor_name,\n slice_spec,\n name=\"checkpoint_initializer\",\n # +++ DIT: default write_version=saver_pb2.SaverDef.DIT\n write_version=saver_pb2.SaverDef.DIT):\n # --- DIT: default write_version=saver_pb2.SaverDef.DIT\n \"\"\"Overrides given variable's initialization op.\n\n Sets variable initializer to assign op that initializes variable from tensor's\n value in the checkpoint.\n\n Args:\n variable: `tf.Variable` object.\n ckpt_file: string, full path of the checkpoint.\n tensor_name: Name of the tensor to load from the checkpoint.\n slice_spec: Slice specification for loading partitioned tensors.\n name: Name of the operation.\n \"\"\"\n base_type = variable.dtype.base_dtype\n # Do not colocate with variable since RestoreV2 op only runs on CPU and\n # colocation will force variable (and other ops that colocate with variable)\n # to be on CPU as well. It is okay to place the variable's initializer op on\n # CPU since it will only be run once at the start.\n with ops.device(variable.device), ops.device(\"/cpu:0\"):\n \n #restore_op = io_ops.restore_v2(\n # ckpt_file, [tensor_name], [slice_spec], [base_type], name=name)[0]\n # +++ DIT: check for restore_dit\n if self._write_version == saver_pb2.SaverDef.V1 or self._write_version == saver_pb2.SaverDef.V2:\n restore_op = io_ops.restore_v2(ckpt_file, [tensor_name], [slice_spec], [base_type], name=name)[0]\n elif self._write_version == saver_pb2.SaverDef.DIT:\n restore_op = io_ops.restore_dit(ckpt_file, [tensor_name], [slice_spec], [base_type], name=name)[0]\n else:\n raise RuntimeError(\"Unexpected write_version: \" + self._write_version)\n # --- DIT: check for restore_dit\n names_to_saveables = saveable_object_util.op_list_to_dict([variable])\n saveable_objects = []\n for name, op in names_to_saveables.items():\n for s in saveable_object_util.saveable_objects_for_op(op, name):\n saveable_objects.append(s)\n\n assert len(saveable_objects) == 1 # Should be only one variable.\n init_op = saveable_objects[0].restore([restore_op], restored_shapes=None)\n\n # pylint:disable=protected-access\n variable._initializer_op = init_op\n restore_op.set_shape(variable.shape)\n variable._initial_value = restore_op\n # pylint:enable=protected-access\n\n\ndef _set_variable_or_list_initializer(variable_or_list, ckpt_file,\n tensor_name):\n \"\"\"Overrides initialization op of given variable or list of variables.\n\n Calls `_set_checkpoint_initializer` for each variable in the given list of\n variables.\n\n Args:\n variable_or_list: `tf.Variable` object or a list of `tf.Variable` objects.\n ckpt_file: string, full path of the checkpoint.\n tensor_name: Name of the tensor to load from the checkpoint.\n\n Raises:\n ValueError: if all objects in `variable_or_list` are not partitions of the\n same large variable.\n \"\"\"\n if isinstance(variable_or_list, (list, tuple)):\n # A set of slices.\n slice_name = None\n for v in variable_or_list:\n slice_info = v._save_slice_info # pylint:disable=protected-access\n if slice_name is None:\n slice_name = slice_info.full_name\n elif slice_name != slice_info.full_name:\n raise ValueError(\"Slices must all be from the same tensor: %s != %s\" %\n (slice_name, slice_info.full_name))\n _set_checkpoint_initializer(v, ckpt_file, tensor_name, slice_info.spec)\n else:\n _set_checkpoint_initializer(variable_or_list, ckpt_file, tensor_name, \"\")\n\n\ndef _is_variable(x):\n return (isinstance(x, variables.Variable) or\n resource_variable_ops.is_resource_variable(x))\n\n\ndef _collect_partitioned_variable(name, all_vars):\n \"\"\"Returns list of `tf.Variable` that comprise the partitioned variable.\"\"\"\n if name + \"/part_0\" in all_vars:\n var = []\n i = 0\n while name + \"/part_%d\" % i in all_vars:\n var.append(all_vars[name + \"/part_%d\" % i])\n i += 1\n return var\n return None\n", "\"\"\"An object-local variable management scheme.\"\"\"\n# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\nimport collections\n\nimport six\n\nfrom tensorflow.core.protobuf import saver_pb2\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.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import gen_io_ops as io_ops\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training.saving import saveable_object\nfrom tensorflow.python.util import tf_contextlib\nfrom tensorflow.python.util import tf_decorator\n\n# Key where the object graph proto is saved in a TensorBundle\nOBJECT_GRAPH_PROTO_KEY = \"_CHECKPOINTABLE_OBJECT_GRAPH\"\n\n# A key indicating a variable's value in an object's checkpointed Tensors\n# (Trackable._gather_saveables_for_checkpoint). If this is the only key and\n# the object has no dependencies, then its value may be restored on object\n# creation (avoiding double assignment when executing eagerly).\nVARIABLE_VALUE_KEY = \"VARIABLE_VALUE\"\nOBJECT_CONFIG_JSON_KEY = \"OBJECT_CONFIG_JSON\"\n\nTrackableReference = collections.namedtuple(\n \"TrackableReference\",\n [\n # The local name for this dependency.\n \"name\",\n # The Trackable object being referenced.\n \"ref\"\n ])\n\n\nclass CheckpointInitialValue(ops.Tensor):\n \"\"\"Tensor wrapper for managing update UIDs in `Variables`.\n\n When supplied as an initial value, objects of this type let a `Variable`\n (`Variable`, `ResourceVariable`, etc.) know the UID of the restore the initial\n value came from. This allows deferred restorations to be sequenced in the\n order the user specified them, and lets us fall back on assignment if an\n initial value is not set (e.g. due to a custom getter interfering).\n\n See comments in _add_variable_with_custom_getter for more information about\n how `CheckpointInitialValue` is used.\n \"\"\"\n\n def __init__(self, checkpoint_position, shape=None):\n self.wrapped_value = checkpoint_position.value_tensors()[VARIABLE_VALUE_KEY]\n if shape:\n # We need to set the static shape information on the initializer if\n # possible so we don't get a variable with an unknown shape.\n self.wrapped_value.set_shape(shape)\n self._checkpoint_position = checkpoint_position\n\n def __getattr__(self, attr):\n try:\n return getattr(self.wrapped_value, attr)\n except AttributeError:\n return self.__getattribute__(attr)\n\n @property\n def checkpoint_position(self):\n return self._checkpoint_position\n\n\nclass NoRestoreSaveable(saveable_object.SaveableObject):\n \"\"\"Embeds a tensor in a checkpoint with no restore ops.\"\"\"\n\n def __init__(self, tensor, name, dtype=None, device=None):\n spec = saveable_object.SaveSpec(\n tensor, \"\", name, dtype=dtype, device=device)\n super(NoRestoreSaveable, self).__init__(tensor, [spec], name)\n\n def restore(self, restored_tensors, restored_shapes):\n return control_flow_ops.no_op()\n\n\[email protected]_metaclass(abc.ABCMeta)\nclass PythonStateSaveable(saveable_object.SaveableObject):\n \"\"\"An interface for saving/restoring volatile Python state.\"\"\"\n\n @abc.abstractmethod\n def feed_dict_additions(self):\n \"\"\"When running a graph, indicates fresh state to feed.\n\n Returns:\n A dictionary mapping `Tensor`s to current Python state.\n \"\"\"\n pass\n\n @abc.abstractmethod\n def freeze(self):\n \"\"\"Create a new `SaveableObject` which freezes current state as a constant.\n\n Used when executing eagerly to embed the current state as a constant, or\n when creating a static tf.compat.v1.train.Saver with the frozen current\n Python state.\n\n Returns:\n A `SaveableObject` which is not a `PythonStateSaveable` instance (i.e. has\n no Python state associated with it).\n \"\"\"\n pass\n\n\nclass PythonStringStateSaveable(PythonStateSaveable):\n \"\"\"Saves Python state in a checkpoint.\"\"\"\n\n def __init__(self, name, state_callback, restore_callback=None):\n \"\"\"Configure saving.\n\n Args:\n name: The checkpoint key to write to.\n state_callback: A function taking no arguments which returns a string.\n This function is run every time a checkpoint is written.\n restore_callback: A function taking a Python string, used to restore\n state. Optional; defaults to doing nothing, in which case it is ignored\n by status assertions such as assert_consumed().\n \"\"\"\n self._has_trivial_state_callback = (restore_callback is None)\n\n def _state_callback_wrapper():\n with ops.init_scope():\n return state_callback()\n\n self._state_callback = _state_callback_wrapper\n self._restore_callback = restore_callback\n with ops.device(\"/cpu:0\"):\n self._save_string = constant_op.constant(\"\", dtype=dtypes.string)\n spec = saveable_object.SaveSpec(\n self._save_string, \"\", name, dtype=dtypes.string)\n super(PythonStringStateSaveable, self).__init__(self._save_string, [spec],\n name)\n\n @property\n def optional_restore(self):\n \"\"\"For values with no restore, relaxes assert_consumed().\"\"\"\n return self._has_trivial_state_callback\n\n def feed_dict_additions(self):\n \"\"\"When running a graph, indicates fresh state to feed.\"\"\"\n return {self._save_string: self._state_callback()}\n\n def freeze(self):\n \"\"\"Create a frozen `SaveableObject` which saves the current state.\"\"\"\n\n def _constant_state():\n return constant_op.constant(self._state_callback(), dtype=dtypes.string)\n\n return NoRestoreSaveable(\n tensor=_constant_state,\n dtype=dtypes.string,\n name=self.name,\n device=\"cpu:0\")\n\n def python_restore(self, restored_strings):\n \"\"\"Called to restore Python state.\"\"\"\n if self._restore_callback:\n restored, = restored_strings\n self._restore_callback(restored)\n\n def restore(self, restored_tensors, restored_shapes):\n \"\"\"Called to restore TensorFlow state (nothing to do).\"\"\"\n return control_flow_ops.no_op()\n\n\nclass CheckpointPosition(object):\n \"\"\"Indicates a position within a `_CheckpointRestoreCoordinator`.\"\"\"\n # +++ DIT: default write_version=saver_pb2.SaverDef.DIT\n def __init__(self, checkpoint, proto_id, write_version=saver_pb2.SaverDef.DIT):\n # --- DIT: default write_version=saver_pb2.SaverDef.DIT\n \"\"\"Specify an object within a checkpoint.\n\n Args:\n checkpoint: A _CheckpointRestoreCoordinator object.\n proto_id: The index of this object in TrackableObjectGraph.nodes.\n \"\"\"\n self._checkpoint = checkpoint\n self._proto_id = proto_id\n self._write_version = write_version\n \n def restore(self, trackable):\n \"\"\"Restore this value into `trackable`.\"\"\"\n with ops.init_scope():\n if self.bind_object(trackable):\n # This object's correspondence with a checkpointed object is new, so\n # process deferred restorations for it and its dependencies.\n restore_ops = trackable._restore_from_checkpoint_position(self) # pylint: disable=protected-access\n if restore_ops:\n self._checkpoint.new_restore_ops(restore_ops)\n\n def bind_object(self, trackable):\n \"\"\"Set a checkpoint<->object correspondence and process slot variables.\n\n Args:\n trackable: The object to record a correspondence for.\n\n Returns:\n True if this is a new assignment, False if this object has already been\n mapped to a checkpointed `Object` proto.\n Raises:\n AssertionError: If another object is already bound to the `Object` proto.\n \"\"\"\n checkpoint = self.checkpoint\n checkpoint.all_python_objects.add(trackable)\n current_assignment = checkpoint.object_by_proto_id.get(self._proto_id, None)\n checkpoint.matched_proto_ids.add(self._proto_id)\n if current_assignment is None:\n checkpoint.object_by_proto_id[self._proto_id] = trackable\n for deferred_slot_restoration in (\n checkpoint.deferred_slot_restorations.pop(self._proto_id, ())):\n trackable._create_or_restore_slot_variable( # pylint: disable=protected-access\n slot_variable_position=CheckpointPosition(\n checkpoint=checkpoint,\n proto_id=deferred_slot_restoration.slot_variable_id),\n variable=deferred_slot_restoration.original_variable,\n slot_name=deferred_slot_restoration.slot_name)\n for slot_restoration in checkpoint.slot_restorations.pop(\n self._proto_id, ()):\n optimizer_object = checkpoint.object_by_proto_id.get(\n slot_restoration.optimizer_id, None)\n if optimizer_object is None:\n # The optimizer has not yet been created or tracked. Record in the\n # checkpoint that the slot variables need to be restored when it is.\n checkpoint.deferred_slot_restorations.setdefault(\n slot_restoration.optimizer_id, []).append(\n _DeferredSlotVariableRestoration(\n original_variable=trackable,\n slot_variable_id=slot_restoration.slot_variable_id,\n slot_name=slot_restoration.slot_name))\n else:\n optimizer_object._create_or_restore_slot_variable( # pylint: disable=protected-access\n slot_variable_position=CheckpointPosition(\n checkpoint=checkpoint,\n proto_id=slot_restoration.slot_variable_id),\n variable=trackable,\n slot_name=slot_restoration.slot_name)\n return True # New assignment\n else:\n # The object was already mapped for this checkpoint load, which means\n # we don't need to do anything besides check that the mapping is\n # consistent (if the dependency DAG is not a tree then there are\n # multiple paths to the same object).\n if current_assignment is not trackable:\n logging.warning((\n \"Inconsistent references when loading the checkpoint into this \"\n \"object graph. Either the Trackable object references in the \"\n \"Python program have changed in an incompatible way, or the \"\n \"checkpoint was generated in an incompatible program.\\n\\nTwo \"\n \"checkpoint references resolved to different objects (%s and %s).\"),\n current_assignment, trackable)\n return False # Not a new assignment\n\n def is_simple_variable(self):\n \"\"\"Determine whether this value is restorable with a Tensor initializer.\"\"\"\n attributes = self.object_proto.attributes\n return (len(attributes) == 1 and\n attributes[0].name == VARIABLE_VALUE_KEY and\n not self.object_proto.children)\n\n def value_tensors(self):\n \"\"\"Create value `Tensor`s for this object's attributes.\n\n Does not require that the Python object has been created. Used for\n restore-on-create when executing eagerly.\n\n Returns:\n A dictionary mapping from object attribute names to `Tensor`s.\n \"\"\"\n value_tensors = {}\n for serialized_tensor in self.object_proto.attributes:\n checkpoint_key = serialized_tensor.checkpoint_key\n dtype = self._checkpoint.dtype_map[checkpoint_key]\n base_type = dtype.base_dtype\n with ops.init_scope():\n with ops.device(\"/cpu:0\"):\n # Run the restore itself on the CPU.\n #value, = io_ops.restore_v2(\n # prefix=self._checkpoint.save_path_tensor,\n # tensor_names=[checkpoint_key],\n # shape_and_slices=[\"\"],\n # dtypes=[base_type],\n # name=\"%s_checkpoint_read\" % (serialized_tensor.name,))\n \n # +++ DIT: check for restore_dit\n if self._write_version == saver_pb2.SaverDef.V1 or self._write_version == saver_pb2.SaverDef.V2:\n value, = io_ops.restore_v2(\n prefix=self._checkpoint.save_path_tensor,\n tensor_names=[checkpoint_key],\n shape_and_slices=[\"\"],\n dtypes=[base_type],\n name=\"%s_checkpoint_read\" % (serialized_tensor.name,))\n elif self._write_version == saver_pb2.SaverDef.DIT:\n value, = io_ops.restore_dit(\n prefix=self._checkpoint.save_path_tensor,\n tensor_names=[checkpoint_key],\n shape_and_slices=[\"\"],\n dtypes=[base_type],\n name=\"%s_checkpoint_read\" % (serialized_tensor.name,))\n else:\n raise RuntimeError(\"Unexpected write_version: \" + self._write_version)\n # --- DIT: check for restore_dit\n \n # Copy the value to the current device if necessary.\n value_tensors[serialized_tensor.name] = array_ops.identity(value)\n return value_tensors\n\n def gather_ops_or_named_saveables(self):\n \"\"\"Looks up or creates SaveableObjects which don't have cached ops.\"\"\"\n saveables = self.trackable._gather_saveables_for_checkpoint() # pylint: disable=protected-access\n # Name saveables based on the name this object had when it was checkpointed.\n named_saveables = {}\n python_saveables = []\n existing_restore_ops = []\n for serialized_tensor in self.object_proto.attributes:\n if context.executing_eagerly():\n existing_op = None\n else:\n existing_op = self._checkpoint.restore_ops_by_name.get(\n serialized_tensor.checkpoint_key, None)\n if existing_op is not None:\n existing_restore_ops.append(existing_op)\n continue\n\n # Only if we don't have cached ops for this SaveableObject, we'll see if\n # the SaveableObject itself has been cached. If not, we'll make it, and\n # either way we'll extract new ops from it (or if it has Python state to\n # restore, we'll run that).\n saveables_cache = self._checkpoint.graph_view.saveables_cache\n if saveables_cache is None:\n # No SaveableObject caching when executing eagerly.\n saveable = None\n else:\n # If we've already created and cached a SaveableObject for this\n # attribute, we can re-use it to avoid re-creating some ops when graph\n # building.\n saveable_list = saveables_cache.get(self.trackable,\n {}).get(serialized_tensor.name,\n (None,))\n if len(saveable_list) == 1:\n # Almost every attribute will have exactly one SaveableObject.\n saveable, = saveable_list\n else:\n # Don't use cached SaveableObjects for partitioned variables, which is\n # the only case where we'd have a list of SaveableObjects. Op caching\n # will catch them.\n saveable = None\n if saveable is not None:\n # The name of this attribute has changed, so we need to re-generate\n # the SaveableObject.\n if serialized_tensor.checkpoint_key not in saveable.name:\n saveable = None\n del saveables_cache[self.trackable]\n break\n if saveable is None:\n # If there was no cached SaveableObject, we should check if the Python\n # object has the attribute.\n saveable_factory = saveables.get(serialized_tensor.name, None)\n if saveable_factory is None:\n # Purposefully does not throw an exception if attributes have been\n # added or deleted. Stores unused attributes so an exception can be\n # raised if the user decides to check that everything in the\n # checkpoint was loaded.\n if not serialized_tensor.optional_restore:\n self._checkpoint.unused_attributes.setdefault(\n self._proto_id, []).append(serialized_tensor.name)\n continue\n if callable(saveable_factory):\n saveable = saveable_factory(name=serialized_tensor.checkpoint_key)\n else:\n saveable = saveable_factory\n if saveables_cache is not None:\n saveables_cache.setdefault(self.trackable,\n {})[serialized_tensor.name] = [saveable]\n if isinstance(saveable, PythonStateSaveable):\n python_saveables.append(saveable)\n else:\n named_saveables[serialized_tensor.checkpoint_key] = saveable\n return existing_restore_ops, named_saveables, python_saveables\n\n def restore_ops(self):\n \"\"\"Create or fetch restore ops for this object's attributes.\n\n Requires that the `Trackable` Python object has been bound to an object\n ID in the checkpoint.\n\n Returns:\n A list of operations when graph building, or an empty list when executing\n eagerly.\n \"\"\"\n (restore_ops, tensor_saveables,\n python_saveables) = self.gather_ops_or_named_saveables()\n restore_ops.extend(\n self._checkpoint.restore_saveables(tensor_saveables, python_saveables))\n return restore_ops\n\n @property\n def checkpoint(self):\n return self._checkpoint\n\n @property\n def trackable(self):\n return self._checkpoint.object_by_proto_id[self._proto_id]\n\n @property\n def object_proto(self):\n return self._checkpoint.object_graph_proto.nodes[self._proto_id]\n\n @property\n def restore_uid(self):\n return self._checkpoint.restore_uid\n\n def __repr__(self):\n return repr(self.object_proto)\n\n\n_DeferredSlotVariableRestoration = collections.namedtuple(\n \"_DeferredSlotVariableRestoration\", [\n \"original_variable\",\n \"slot_variable_id\",\n \"slot_name\",\n ])\n\n_SlotVariableRestoration = collections.namedtuple(\n \"_SlotVariableRestoration\",\n [\n # The checkpoint proto id of the optimizer object.\n \"optimizer_id\",\n # The checkpoint proto id of the slot variable.\n \"slot_variable_id\",\n \"slot_name\",\n ])\n\n\ndef no_automatic_dependency_tracking(method):\n \"\"\"Disables automatic dependency tracking on attribute assignment.\n\n Use to decorate any method of a Trackable object. Attribute assignment in\n that method will not add dependencies (also respected in Model). Harmless if\n used in a class which does not do automatic dependency tracking (which means\n it's safe to use in base classes which may have subclasses which also inherit\n from Trackable).\n\n Args:\n method: The method to decorate.\n\n Returns:\n A decorated method which sets and un-sets automatic dependency tracking for\n the object the method is called on (not thread safe).\n \"\"\"\n\n def _method_wrapper(self, *args, **kwargs):\n previous_value = getattr(self, \"_self_setattr_tracking\", True)\n self._self_setattr_tracking = False # pylint: disable=protected-access\n try:\n result = method(self, *args, **kwargs)\n finally:\n self._self_setattr_tracking = previous_value # pylint: disable=protected-access\n return result\n\n return tf_decorator.make_decorator(\n target=method, decorator_func=_method_wrapper)\n\n\n@tf_contextlib.contextmanager\ndef no_manual_dependency_tracking_scope(obj):\n \"\"\"A context that disables manual dependency tracking for the given `obj`.\n\n Sometimes library methods might track objects on their own and we might want\n to disable that and do the tracking on our own. One can then use this context\n manager to disable the tracking the library method does and do your own\n tracking.\n\n For example:\n\n class TestLayer(tf.keras.Layer):\n def build():\n with no_manual_dependency_tracking_scope(self):\n var = self.add_variable(\"name1\") # Creates a var and doesn't track it\n self._track_trackable(\"name2\", var) # We track variable with name `name2`\n\n Args:\n obj: A trackable object.\n\n Yields:\n a scope in which the object doesn't track dependencies manually.\n \"\"\"\n # pylint: disable=protected-access\n previous_value = getattr(obj, \"_manual_tracking\", True)\n obj._manual_tracking = False\n try:\n yield\n finally:\n obj._manual_tracking = previous_value\n\n\n@tf_contextlib.contextmanager\ndef no_automatic_dependency_tracking_scope(obj):\n \"\"\"A context that disables automatic dependency tracking when assigning attrs.\n\n Objects that inherit from Autotrackable automatically creates dependencies\n to trackable objects through attribute assignments, and wraps data structures\n (lists or dicts) with trackable classes. This scope may be used to temporarily\n disable this behavior. This works similar to the decorator\n `no_automatic_dependency_tracking`.\n\n Example usage:\n ```\n model = tf.keras.Model()\n model.arr1 = [] # Creates a ListWrapper object\n with no_automatic_dependency_tracking_scope(model):\n model.arr2 = [] # Creates a regular, untracked python list\n ```\n\n Args:\n obj: A trackable object.\n\n Yields:\n a scope in which the object doesn't track dependencies.\n \"\"\"\n previous_value = getattr(obj, \"_setattr_tracking\", True)\n obj._setattr_tracking = False # pylint: disable=protected-access\n try:\n yield\n finally:\n obj._setattr_tracking = previous_value # pylint: disable=protected-access\n\n\nclass Trackable(object):\n \"\"\"Base class for `Trackable` objects without automatic dependencies.\n\n This class has no __setattr__ override for performance reasons. Dependencies\n must be added explicitly. Unless attribute assignment is performance-critical,\n use `AutoTrackable` instead. Use `Trackable` for `isinstance`\n checks.\n \"\"\"\n\n # For compatibility with wrapt.ObjectProxy, attributes are all prefixed with\n # _self_. We have some properties to forward semi-public attributes to their\n # _self_ equivalents.\n\n @property\n def _setattr_tracking(self):\n if not hasattr(self, \"_self_setattr_tracking\"):\n self._self_setattr_tracking = True\n return self._self_setattr_tracking\n\n @_setattr_tracking.setter\n def _setattr_tracking(self, value):\n self._self_setattr_tracking = value\n\n @property\n def _update_uid(self):\n return self._self_update_uid\n\n @_update_uid.setter\n def _update_uid(self, value):\n self._self_update_uid = value\n\n @property\n def _unconditional_checkpoint_dependencies(self):\n return self._self_unconditional_checkpoint_dependencies\n\n @property\n def _unconditional_dependency_names(self):\n return self._self_unconditional_dependency_names\n\n @property\n def _name_based_restores(self):\n return self._self_name_based_restores\n\n # Trackable does not do automatic dependency tracking, but uses the\n # no_automatic_dependency_tracking decorator so it can avoid adding\n # dependencies if a subclass is Trackable / inherits from Model (both of\n # which have __setattr__ overrides).\n @no_automatic_dependency_tracking\n def _maybe_initialize_trackable(self):\n \"\"\"Initialize dependency management.\n\n Not __init__, since most objects will forget to call it.\n \"\"\"\n if hasattr(self, \"_self_unconditional_checkpoint_dependencies\"):\n # __init__ already called. This check means that we don't need\n # Trackable.__init__() in the constructor of every TensorFlow object.\n return\n # A list of TrackableReference objects. Some classes implementing\n # `Trackable`, notably `Optimizer`s, may override the\n # _checkpoint_dependencies property with conditional dependencies\n # (e.g. based on the current graph when saving).\n self._self_unconditional_checkpoint_dependencies = []\n # Maps names -> Trackable objects\n self._self_unconditional_dependency_names = {}\n # Restorations for other Trackable objects on which this object may\n # eventually depend. Maps local name -> CheckpointPosition list. Optimizers\n # tack on conditional dependencies, and so need separate management of\n # deferred dependencies too.\n self._self_unconditional_deferred_dependencies = {}\n # The UID of the highest assignment to this object. Used to ensure that the\n # last requested assignment determines the final value of an object.\n if hasattr(self, \"_self_update_uid\"):\n raise AssertionError(\n \"Internal error: the object had an update UID set before its \"\n \"initialization code was run.\")\n self._self_update_uid = -1\n # When executing eagerly, holds a collection of _NameBasedRestoreCoordinator\n # instances, which should be checked when creating variables or other\n # saveables. These are passed on recursively to all dependencies, since\n # unlike object-based checkpoint restores we don't know which subgraph is\n # being restored in advance. This mechanism is only necessary for\n # restore-on-create when executing eagerly, and so is unused when graph\n # building.\n self._self_name_based_restores = set()\n\n @property\n def _object_identifier(self):\n \"\"\"String used to identify this object in a SavedModel.\n\n Generally, the object identifier is constant across objects of the same\n class, while the metadata field is used for instance-specific data.\n\n Returns:\n String object identifier.\n \"\"\"\n return \"_generic_user_object\"\n\n @property\n def _tracking_metadata(self):\n \"\"\"String containing object metadata, which is saved to the SavedModel.\"\"\"\n return \"\"\n\n def _no_dependency(self, value):\n \"\"\"If automatic dependency tracking is enabled, ignores `value`.\"\"\"\n return value\n\n def _name_based_attribute_restore(self, checkpoint):\n \"\"\"Restore the object's attributes from a name-based checkpoint.\"\"\"\n self._self_name_based_restores.add(checkpoint)\n if self._self_update_uid < checkpoint.restore_uid:\n checkpoint.eager_restore(self)\n self._self_update_uid = checkpoint.restore_uid\n\n @property\n def _checkpoint_dependencies(self):\n \"\"\"All dependencies of this object.\n\n May be overridden to include conditional dependencies.\n\n Returns:\n A list of `TrackableReference` objects indicating named\n `Trackable` dependencies which should be saved along with this\n object.\n \"\"\"\n return self._self_unconditional_checkpoint_dependencies\n\n @property\n def _deferred_dependencies(self):\n \"\"\"A dictionary with deferred dependencies.\n\n Stores restorations for other Trackable objects on which this object\n may eventually depend. May be overridden by sub-classes (e.g. Optimizers use\n conditional dependencies based the current graph, and so need separate\n management of deferred dependencies too).\n\n Returns:\n A dictionary mapping from local name to a list of CheckpointPosition\n objects.\n \"\"\"\n return self._self_unconditional_deferred_dependencies\n\n def _lookup_dependency(self, name):\n \"\"\"Look up a dependency by name.\n\n May be overridden to include conditional dependencies.\n\n Args:\n name: The local name of the dependency.\n\n Returns:\n A `Trackable` object, or `None` if no dependency by this name was\n found.\n \"\"\"\n return self._self_unconditional_dependency_names.get(name, None)\n\n def _add_variable_with_custom_getter(self,\n name,\n shape=None,\n dtype=dtypes.float32,\n initializer=None,\n getter=None,\n overwrite=False,\n **kwargs_for_getter):\n \"\"\"Restore-on-create for a variable be saved with this `Trackable`.\n\n If the user has requested that this object or another `Trackable` which\n depends on this object be restored from a checkpoint (deferred loading\n before variable object creation), `initializer` may be ignored and the value\n from the checkpoint used instead.\n\n Args:\n name: A name for the variable. Must be unique within this object.\n shape: The shape of the variable.\n dtype: The data type of the variable.\n initializer: The initializer to use. Ignored if there is a deferred\n restoration left over from a call to\n `_restore_from_checkpoint_position`.\n getter: The getter to wrap which actually fetches the variable.\n overwrite: If True, disables unique name and type checks.\n **kwargs_for_getter: Passed to the getter.\n\n Returns:\n The new variable object.\n\n Raises:\n ValueError: If the variable name is not unique.\n \"\"\"\n self._maybe_initialize_trackable()\n with ops.init_scope():\n if context.executing_eagerly():\n # If this is a variable with a single Tensor stored in the checkpoint,\n # we can set that value as an initializer rather than initializing and\n # then assigning (when executing eagerly). This call returns None if\n # there is nothing to restore.\n checkpoint_initializer = self._preload_simple_restoration(\n name=name, shape=shape)\n else:\n checkpoint_initializer = None\n if (checkpoint_initializer is not None and\n not (isinstance(initializer, CheckpointInitialValue) and\n (initializer.restore_uid > checkpoint_initializer.restore_uid))):\n # If multiple Trackable objects are \"creating\" the same variable\n # via the magic of custom getters, the one with the highest restore UID\n # (the one called last) has to make the final initializer. If another\n # custom getter interrupts this process by overwriting the initializer,\n # then we'll catch that when we call _track_trackable. So this is\n # \"best effort\" to set the initializer with the highest restore UID.\n initializer = checkpoint_initializer\n shape = None\n new_variable = getter(\n name=name,\n shape=shape,\n dtype=dtype,\n initializer=initializer,\n **kwargs_for_getter)\n\n # If we set an initializer and the variable processed it, tracking will not\n # assign again. It will add this variable to our dependencies, and if there\n # is a non-trivial restoration queued, it will handle that. This also\n # handles slot variables.\n if not overwrite or isinstance(new_variable, Trackable):\n return self._track_trackable(new_variable, name=name, overwrite=overwrite)\n else:\n # TODO(allenl): Some variable types are not yet supported. Remove this\n # fallback once all get_variable() return types are Trackable.\n return new_variable\n\n def _preload_simple_restoration(self, name, shape):\n \"\"\"Return a dependency's value for restore-on-create.\n\n Note the restoration is not deleted; if for some reason preload is called\n and then not assigned to the variable (for example because a custom getter\n overrides the initializer), the assignment will still happen once the\n variable is tracked (determined based on checkpoint.restore_uid).\n\n Args:\n name: The object-local name of the dependency holding the variable's\n value.\n shape: The shape of the variable being loaded into.\n\n Returns:\n An callable for use as a variable's initializer/initial_value, or None if\n one should not be set (either because there was no variable with this name\n in the checkpoint or because it needs more complex deserialization). Any\n non-trivial deserialization will happen when the variable object is\n tracked.\n \"\"\"\n deferred_dependencies_list = self._deferred_dependencies.get(name, ())\n if not deferred_dependencies_list:\n # Nothing to do; we don't have a restore for this dependency queued up.\n return\n for checkpoint_position in deferred_dependencies_list:\n if not checkpoint_position.is_simple_variable():\n # If _any_ pending restoration is too complicated to fit in an\n # initializer (because it has dependencies, or because there are\n # multiple Tensors to restore), bail and let the general tracking code\n # handle it.\n return None\n checkpoint_position = max(\n deferred_dependencies_list,\n key=lambda restore: restore.checkpoint.restore_uid)\n return CheckpointInitialValue(\n checkpoint_position=checkpoint_position, shape=shape)\n\n def _track_trackable(self, trackable, name, overwrite=False):\n \"\"\"Declare a dependency on another `Trackable` object.\n\n Indicates that checkpoints for this object should include variables from\n `trackable`.\n\n Variables in a checkpoint are mapped to `Trackable`s based on the names\n provided when the checkpoint was written. To avoid breaking existing\n checkpoints when modifying a class, neither variable names nor dependency\n names (the names passed to `_track_trackable`) may change.\n\n Args:\n trackable: A `Trackable` which this object depends on.\n name: A local name for `trackable`, used for loading checkpoints into the\n correct objects.\n overwrite: Boolean, whether silently replacing dependencies is OK. Used\n for __setattr__, where throwing an error on attribute reassignment would\n be inappropriate.\n\n Returns:\n `trackable`, for convenience when declaring a dependency and\n assigning to a member variable in one statement.\n\n Raises:\n TypeError: If `trackable` does not inherit from `Trackable`.\n ValueError: If another object is already tracked by this name.\n \"\"\"\n self._maybe_initialize_trackable()\n if not isinstance(trackable, Trackable):\n raise TypeError((\"Trackable._track_trackable() passed type %s, not a \"\n \"Trackable.\") % (type(trackable),))\n if not getattr(self, \"_manual_tracking\", True):\n return trackable\n new_reference = TrackableReference(name=name, ref=trackable)\n current_object = self._lookup_dependency(name)\n if (current_object is not None and current_object is not trackable):\n if not overwrite:\n raise ValueError(\n (\"Called Trackable._track_trackable() with name='%s', \"\n \"but a Trackable with this name is already declared as a \"\n \"dependency. Names must be unique (or overwrite=True).\") % (name,))\n # This is a weird thing to do, but we're not going to stop people from\n # using __setattr__.\n for index, (old_name, _) in enumerate(\n self._self_unconditional_checkpoint_dependencies):\n if name == old_name:\n self._self_unconditional_checkpoint_dependencies[\n index] = new_reference\n elif current_object is None:\n self._self_unconditional_checkpoint_dependencies.append(new_reference)\n self._handle_deferred_dependencies(name=name, trackable=trackable)\n self._self_unconditional_dependency_names[name] = trackable\n return trackable\n\n def _handle_deferred_dependencies(self, name, trackable):\n \"\"\"Pop and load any deferred checkpoint restores into `trackable`.\n\n This method does not add a new dependency on `trackable`, but it does\n check if any outstanding/deferred dependencies have been queued waiting for\n this dependency to be added (matched based on `name`). If so,\n `trackable` and its dependencies are restored. The restorations are\n considered fulfilled and so are deleted.\n\n `_track_trackable` is more appropriate for adding a\n normal/unconditional dependency, and includes handling for deferred\n restorations. This method allows objects such as `Optimizer` to use the same\n restoration logic while managing conditional dependencies themselves, by\n overriding `_checkpoint_dependencies` and `_lookup_dependency` to change the\n object's dependencies based on the context it is saved/restored in (a single\n optimizer instance can have state associated with multiple graphs).\n\n Args:\n name: The name of the dependency within this object (`self`), used to\n match `trackable` with values saved in a checkpoint.\n trackable: The Trackable object to restore (inheriting from `Trackable`).\n \"\"\"\n self._maybe_initialize_trackable()\n trackable._maybe_initialize_trackable() # pylint: disable=protected-access\n deferred_dependencies_list = self._deferred_dependencies.pop(name, ())\n for checkpoint_position in sorted(\n deferred_dependencies_list,\n key=lambda restore: restore.checkpoint.restore_uid,\n reverse=True):\n checkpoint_position.restore(trackable)\n\n # Pass on any name-based restores queued in this object.\n for name_based_restore in sorted(\n self._self_name_based_restores,\n key=lambda checkpoint: checkpoint.restore_uid,\n reverse=True):\n trackable._name_based_attribute_restore(name_based_restore) # pylint: disable=protected-access\n\n def _restore_from_checkpoint_position(self, checkpoint_position):\n \"\"\"Restore this object and its dependencies (may be deferred).\"\"\"\n # Attempt a breadth-first traversal, since presumably the user has more\n # control over shorter paths. If we don't have all of the dependencies at\n # this point, the end result is not breadth-first (since other deferred\n # traversals will happen later).\n visit_queue = collections.deque([checkpoint_position])\n restore_ops = []\n tensor_saveables = {}\n python_saveables = []\n while visit_queue:\n current_position = visit_queue.popleft()\n new_restore_ops, new_tensor_saveables, new_python_saveables = (\n current_position.trackable # pylint: disable=protected-access\n ._single_restoration_from_checkpoint_position(\n checkpoint_position=current_position,\n visit_queue=visit_queue))\n restore_ops.extend(new_restore_ops)\n tensor_saveables.update(new_tensor_saveables)\n python_saveables.extend(new_python_saveables)\n restore_ops.extend(\n current_position.checkpoint.restore_saveables(\n tensor_saveables, python_saveables))\n return restore_ops\n\n def _single_restoration_from_checkpoint_position(self, checkpoint_position,\n visit_queue):\n \"\"\"Restore this object, and either queue its dependencies or defer them.\"\"\"\n self._maybe_initialize_trackable()\n checkpoint = checkpoint_position.checkpoint\n # If the UID of this restore is lower than our current update UID, we don't\n # need to actually restore the object. However, we should pass the\n # restoration on to our dependencies.\n if checkpoint.restore_uid > self._self_update_uid:\n restore_ops, tensor_saveables, python_saveables = (\n checkpoint_position.gather_ops_or_named_saveables())\n self._self_update_uid = checkpoint.restore_uid\n else:\n restore_ops = ()\n tensor_saveables = {}\n python_saveables = ()\n for child in checkpoint_position.object_proto.children:\n child_position = CheckpointPosition(\n checkpoint=checkpoint, proto_id=child.node_id)\n local_object = self._lookup_dependency(child.local_name)\n if local_object is None:\n # We don't yet have a dependency registered with this name. Save it\n # in case we do.\n self._deferred_dependencies.setdefault(child.local_name,\n []).append(child_position)\n else:\n if child_position.bind_object(trackable=local_object):\n # This object's correspondence is new, so dependencies need to be\n # visited. Delay doing it so that we get a breadth-first dependency\n # resolution order (shallowest paths first). The caller is responsible\n # for emptying visit_queue.\n visit_queue.append(child_position)\n return restore_ops, tensor_saveables, python_saveables\n\n def _gather_saveables_for_checkpoint(self):\n \"\"\"Returns a dictionary of values to checkpoint with this object.\n\n Keys in the returned dictionary are local to this object and in a separate\n namespace from dependencies. Values may either be `SaveableObject` factories\n or variables easily converted to `SaveableObject`s (as in\n `tf.compat.v1.train.Saver`'s\n `var_list` constructor argument).\n\n `SaveableObjects` have a name set, which Trackable needs to generate\n itself. So rather than returning `SaveableObjects` directly, this method\n should return a dictionary of callables which take `name` arguments and\n return `SaveableObjects` with that name.\n\n If this object may also be passed to the global-name-based\n `tf.compat.v1.train.Saver`,\n the returned callables should have a default value for their name argument\n (i.e. be callable with no arguments).\n\n Returned values must be saved only by this object; if any value may be\n shared, it should instead be a dependency. For example, variable objects\n save their own values with the key `VARIABLE_VALUE_KEY`, but objects which\n reference variables simply add a dependency.\n\n Returns:\n The dictionary mapping attribute names to `SaveableObject` factories\n described above. For example:\n {VARIABLE_VALUE_KEY:\n lambda name=\"global_name_for_this_object\":\n SaveableObject(name=name, ...)}\n \"\"\"\n return {}\n\n def _list_extra_dependencies_for_serialization(self, serialization_cache):\n \"\"\"Lists extra dependencies to serialize.\n\n Internal sub-classes can override this method to return extra dependencies\n that should be saved with the object during SavedModel serialization. For\n example, this is used to save `trainable_variables` in Keras models. The\n python property `trainable_variables` contains logic to iterate through the\n weights from the model and its sublayers. The serialized Keras model saves\n `trainable_weights` as a trackable list of variables.\n\n PLEASE NOTE when overriding this method:\n 1. This function may only generate new trackable objects the first time it\n is called.\n 2. The returned dictionary must not have naming conflicts with\n dependencies tracked by the root. In other words, if the root is\n tracking `object_1` with name 'x', and this functions returns\n `{'x': object_2}`, an error is raised when saving.\n\n Args:\n serialization_cache: A dictionary shared between all objects in the same\n object graph. This object is passed to both\n `_list_extra_dependencies_for_serialization` and\n `_list_functions_for_serialization`.\n\n Returns:\n A dictionary mapping attribute names to trackable objects.\n \"\"\"\n del serialization_cache\n return dict()\n\n def _list_functions_for_serialization(self, serialization_cache):\n \"\"\"Lists the functions of this trackable to serialize.\n\n Internal sub-classes can override this with specific logic. E.g.\n `AutoTrackable` provides an implementation that returns the `attr`\n that return functions.\n\n Args:\n serialization_cache: Dictionary passed to all objects in the same object\n graph during serialization.\n\n Returns:\n A dictionary mapping attribute names to `Function` or\n `ConcreteFunction`.\n \"\"\"\n del serialization_cache\n return dict()\n" ]
[ [ "tensorflow.python.framework.ops.device", "tensorflow.python.ops.io_ops.restore_dit", "tensorflow.python.platform.tf_logging.debug", "tensorflow.python.ops.io_ops.restore_v2", "tensorflow.python.distribute.distribution_strategy_context.get_cross_replica_context", "tensorflow.python.training.saving.saveable_object_util.saveable_objects_for_op", "tensorflow.python.platform.tf_logging.info", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.ops.variable_scope._get_default_variable_store", "tensorflow.python.training.checkpoint_management.latest_checkpoint", "tensorflow.python.training.py_checkpoint_reader.NewCheckpointReader", "tensorflow.python.platform.gfile.IsDirectory", "tensorflow.python.ops.resource_variable_ops.is_resource_variable", "tensorflow.python.distribute.distribution_strategy_context.get_replica_context", "tensorflow.python.training.saving.saveable_object_util.op_list_to_dict" ], [ "tensorflow.python.ops.array_ops.identity", "tensorflow.python.ops.gen_io_ops.restore_v2", "tensorflow.python.platform.tf_logging.warning", "tensorflow.python.framework.ops.init_scope", "tensorflow.python.ops.gen_io_ops.restore_dit", "tensorflow.python.util.tf_decorator.make_decorator", "tensorflow.python.training.saving.saveable_object.SaveSpec", "tensorflow.python.framework.ops.device", "tensorflow.python.ops.control_flow_ops.no_op", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.framework.constant_op.constant" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "1.13", "2.3", "2.4", "2.9", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "1.13", "2.3", "2.4", "2.9", "2.5", "2.2", "2.10" ] } ]
IssamLaradji/SSR
[ "90623188abb4dd9f30566faa2f170a76db9e1846" ]
[ "src/datasets.py" ]
[ "import os\n\nimport soft_renderer.functional as srf\nimport torch, random\nimport numpy as np\nimport tqdm\nfrom haven import haven_utils as hu\nfrom PIL import Image, ImageOps, ImageFilter\nimport torchvision.transforms as transforms\n\nclass_ids_map = {\n '02691156': 'Airplane',\n '02828884': 'Bench',\n '02933112': 'Cabinet',\n '02958343': 'Car',\n '03001627': 'Chair',\n '03211117': 'Display',\n '03636649': 'Lamp',\n '03691459': 'Loudspeaker',\n '04090263': 'Rifle',\n '04256520': 'Sofa',\n '04379243': 'Table',\n '04401088': 'Telephone',\n '04530566': 'Watercraft',\n}\n\nCLASS_IDS = sorted(list(class_ids_map.keys()))\nclass ShapeNet(object):\n def __init__(self, directory=None, split=None, exp_dict=None):\n self.class_ids = CLASS_IDS\n n_classes = exp_dict.get('n_classes')\n if n_classes:\n self.class_ids = CLASS_IDS[:n_classes]\n\n classes = exp_dict.get('classes')\n if classes:\n classes_map = {key: value for (value, key) in class_ids_map.items()}\n self.class_ids = sorted([classes_map[k] for k in classes])\n \n self.split = split\n self.elevation = 30.\n self.distance = 2.732\n self.exp_dict = exp_dict\n self.class_ids_map = class_ids_map\n \n\n self.images = []\n self.voxels = []\n self.labels = []\n self.class_ids_pair = list(zip(self.class_ids, [self.class_ids_map[i] for i in self.class_ids]))\n\n self.num_data = {}\n self.pos = {}\n count = 0\n # ind2class = {key: value for (value, key) in enumerate(self.class_ids)}\n loop = tqdm.tqdm(self.class_ids)\n loop.set_description(f'Loading {split} Dataset')\n n_train_objects = exp_dict.get('n_train_objects')\n n_ratio_val = exp_dict.get('n_val_ratio')\n # assert n_ratio_val is not None\n if n_train_objects is None and split == 'unlabeled':\n return \n \n if split in ['train', 'unlabeled']:\n set_name = 'train'\n elif split in ['val', 'test']:\n set_name = 'val'\n if n_ratio_val is None:\n set_name = split\n for ci, class_id in enumerate(loop):\n i = list(np.load(os.path.join(directory, '%s_%s_images.npz' % (class_id, set_name))).items())[0][1]\n v = list(np.load(os.path.join(directory, '%s_%s_voxels.npz' % (class_id, set_name))).items())[0][1]\n \n \n # train get only first n\n if split == 'train' and n_train_objects is not None:\n n = n_train_objects\n\n i = i[:n]\n v = v[:n]\n\n # unlabeled get only first n\n if split == 'unlabeled' and n_train_objects is not None:\n n = n_train_objects\n\n i = i[n:]\n v = v[n:]\n\n elif split == 'val' and n_ratio_val is not None:\n n = int(i.shape[0]*n_ratio_val)\n\n i = i[:n]\n v = v[:n]\n \n elif split == 'test' and n_ratio_val is not None:\n n = int(i.shape[0]*n_ratio_val)\n\n i = i[n:]\n v = v[n:]\n\n self.images += [i]\n self.voxels += [v]\n self.labels += [torch.ones(i.shape[0]) * ci]\n self.images = np.concatenate(self.images, axis=0) \n self.images = torch.from_numpy(self.images.astype('float32') / 255.)\n\n self.voxels = np.concatenate(self.voxels, axis=0) \n self.voxels = torch.from_numpy(self.voxels.astype('float32'))\n\n self.labels = torch.cat(self.labels, dim=0)\n # positible view points\n distances = torch.ones(24).float() * self.distance\n elevations = torch.ones(24).float() * self.elevation\n self.possible_viewpoints = srf.get_points_from_angles(distances, elevations, -torch.arange(24) * 15)\n\n print(f'{split} samples: {len(self)}')\n\n def __len__(self):\n if isinstance(self.images, list):\n return len(self.images)\n return self.images.shape[0]\n\n def __getitem__(self, idx, vp_idx=None, vp_idx_b=None):\n # image A\n images_a, viewpoints_a, viewpoint_id_a = self.get_random_viewpoint(idx, vp_idx)\n\n # image B\n images_b, viewpoints_b, viewpoint_id_b = self.get_random_viewpoint(idx, vp_idx_b)\n\n return {'images_a':images_a, \n 'viewpoints_a': viewpoints_a, \n 'object_id_a':idx,\n 'viewpoint_id_a':viewpoint_id_a,\n\n 'images_b':images_b, \n 'viewpoints_b': viewpoints_b,\n 'object_id_b':idx,\n 'viewpoint_id_b':viewpoint_id_b}\n\n def insert_images(self, images):\n self.images = torch.cat([self.images, images], dim=0)\n\n def pop_indices(self, ind_list):\n selected_images = self.images[ind_list]\n keep_idx = np.delete(np.arange(self.images.shape[0]), ind_list)\n self.images = self.images[keep_idx]\n # return list(np.delete(arr, id_to_del))\n return selected_images\n\n def get_random_viewpoint(self, idx, vp_idx=None):\n if vp_idx is None:\n viewpoint_id = np.random.randint(0, 24)\n else:\n viewpoint_id = vp_idx\n # get image and viewpoint\n images = self.images[idx][viewpoint_id]\n \n # get viewpoint\n viewpoints = srf.get_points_from_angles(self.distance, self.elevation, -viewpoint_id * 15)\n\n return images, torch.as_tensor(viewpoints), viewpoint_id\n\n def get_all_batches_for_evaluation(self, batch_size, class_id):\n assert self.images.shape[0] == self.voxels.shape[0]\n\n ci = self.class_ids.index(class_id)\n ind_ci = self.labels == ci\n im_cls = self.images[ind_ci]\n vx_cls = self.voxels[ind_ci]\n\n data_ids = np.arange(im_cls.shape[0])\n viewpoint_ids = np.tile(np.arange(24), data_ids.size)\n data_ids = np.repeat(data_ids, 24) * 24 + viewpoint_ids\n\n distances = torch.ones(data_ids.size).float() * self.distance\n elevations = torch.ones(data_ids.size).float() * self.elevation\n viewpoints_all = srf.get_points_from_angles(distances, elevations, -torch.from_numpy(viewpoint_ids).float() * 15)\n\n shape = im_cls.shape[-3:]\n images = im_cls.view(-1, *shape)\n\n shape = vx_cls.shape[-3:]\n voxels = vx_cls.view(-1, *shape)\n\n for i in range((data_ids.size - 1) // batch_size + 1):\n im = images[data_ids[i * batch_size:(i + 1) * batch_size]]\n vx = voxels[data_ids[i * batch_size:(i + 1) * batch_size] // 24]\n yield im, vx\n\n\n\nclass Transform:\n def __init__(self):\n self.transform = transforms.Compose([\n transforms.ToPILImage(),\n transforms.RandomResizedCrop(224, interpolation=Image.BICUBIC),\n transforms.RandomHorizontalFlip(p=0.5),\n transforms.RandomApply(\n [transforms.ColorJitter(brightness=0.4, contrast=0.4,\n saturation=0.2, hue=0.1)],\n p=0.8\n ),\n transforms.RandomGrayscale(p=0.2),\n GaussianBlur(p=1.0),\n Solarization(p=0.0),\n transforms.ToTensor(),\n # transforms.Normalize(mean=[0.485, 0.456, 0.406],\n # std=[0.229, 0.224, 0.225])\n ])\n self.transform_prime = transforms.Compose([\n transforms.ToPILImage(),\n transforms.RandomResizedCrop(224, interpolation=Image.BICUBIC),\n transforms.RandomHorizontalFlip(p=0.5),\n transforms.RandomApply(\n [transforms.ColorJitter(brightness=0.4, contrast=0.4,\n saturation=0.2, hue=0.1)],\n p=0.8\n ),\n transforms.RandomGrayscale(p=0.2),\n GaussianBlur(p=0.1),\n Solarization(p=0.2),\n transforms.ToTensor(),\n # transforms.Normalize(mean=[0.485, 0.456, 0.406],\n # std=[0.229, 0.224, 0.225])\n ])\n\n def __call__(self, x):\n y1 = self.transform(x)\n y2 = self.transform_prime(x)\n return y1, y2\n\nclass GaussianBlur(object):\n def __init__(self, p):\n self.p = p\n\n def __call__(self, img):\n if random.random() < self.p:\n sigma = random.random() * 1.9 + 0.1\n return img.filter(ImageFilter.GaussianBlur(sigma))\n else:\n return img\n\n\nclass Solarization(object):\n def __init__(self, p):\n self.p = p\n\n def __call__(self, img):\n if random.random() < self.p:\n return ImageOps.solarize(img)\n else:\n return img\n" ]
[ [ "torch.ones", "torch.cat", "numpy.arange", "torch.from_numpy", "numpy.concatenate", "numpy.random.randint", "torch.arange", "numpy.repeat", "torch.as_tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tedunderwood/biographies
[ "b79dbd054fca10860d2c5a89d9c5ab1df8a93642", "aba7b7180aea944bdc4fa163b0008eca34fe73cc" ]
[ "code/extract_balanced.py", "topicmodel/dataprep/tabletomallet_biofic.py" ]
[ "#!/usr/bin/python3\n\nimport sys\nimport os\nimport shutil\nimport csv\nimport zipfile\nimport pandas as pd\nimport glob\n\ninfile = sys.argv[1]\noutfile = sys.argv[2]\n\n# remove holding_folder if it exists, and create new folder\n# use 'rm -r /holding_folder/* in shell script instead?'\nholding_path = '/media/secure_volume/holding_folder'\nif os.path.isdir(holding_path):\n shutil.rmtree(holding_path)\nos.mkdir(holding_path) \n\ndef extract(infile):\n '''\n Merges bioindex.tsv with the infile (balanced data),\n finds the volsplit.zip location for each bio file and \n extracts the files into secure_volume/holding_folder.\n '''\n \n bioindex = pd.read_csv('/media/secure_volume/index/bioindex.tsv', sep='\\t')\n balanced_bioindex = pd.read_table(infile)\n\n for suffix in balanced_bioindex.filesuffix.unique():\n volsplit_file = 'volsplit'+str(suffix)+'.zip'\n volsplit_df = balanced_bioindex.loc[balanced_bioindex.filesuffix == suffix,:]\n try:\n with zipfile.ZipFile('/media/secure_volume/'+volsplit_file, 'r') as myzip:\n for idx, row in volsplit_df.iterrows():\n filename = row['mainid']+'.zip'\n myzip.extract(filename, '/media/secure_volume/holding_folder')\n\n except Exception as e:\n print('ERROR:',filename,'not found in',volsplit_file,'!', e)\n \ndef slicer(outfile):\n idx_file_path = '/media/secure_volume/index/bioindex.tsv'\n holding_folder_path = '/media/secure_volume/holding_folder/'\n bio_idx_df = pd.read_table(idx_file_path)\n bio_idx_df.set_index('mainid', inplace = True)\n mainid_list = [vol for vol in os.listdir(holding_folder_path) if vol.endswith('.zip')]\n # remove '.zip' from file names\n mainid_list_clean = [item[0:-4] for item in mainid_list]\n\n #subset bioindex on holding_folder IDs\n htid_series = bio_idx_df.htid[mainid_list_clean]\n file_path_list = glob.glob(holding_folder_path+'*.zip')\n # print('file path list has: ',len(file_path_list))\n # print('htid_list has', len(htid_list))\n \n slice_df = pd.DataFrame(htid_series)\n slice_df['path'] = file_path_list\n slice_df['c'] = 0\n slice_df['d'] = 1001\n\n with open(outfile, 'w') as outf:\n slice_df.to_csv(outfile, sep='\\t', header=False, index=False)\n\n print(\"Wrote\", len(slice_df), \"rows to\", outfile)\n\nextract(infile)\nslicer(outfile)\n", "#!/usr/bin/env python3\n\n# tabletomallet_firstfic.py\n\n# This script selects & prepares data for use by MALLET. It starts from the\n# tabular data produced by jsontotable5.py, and slightly changes format.\n# More importantly, it selects volumes distributed as evenly as possible across\n# time, and ensures that the volumes for all our preregistered hypotheses\n# will be present.\n\nimport csv, random, sys\nimport pandas as pd\n\n# Our general strategy is to take 1000 books from each decade between the 1780s\n# and the 2000s (where 1000 books are available, which they aren't until the 1850s).\n# So we start by organizing books by decade:\n\ndecades = dict()\nfor floor in range(1780, 2010, 10):\n decades[floor] = set()\n\nwith open('../../metadata/filtered_fiction_plus_18c.tsv', encoding = 'utf-8') as f:\n reader = csv.DictReader(f, delimiter = '\\t')\n for row in reader:\n # there are two different forms of id volumes can have,\n # because 19c stories are often multi-volume\n # and so I assigned them new docids\n\n inferreddate = int(row['inferreddate'])\n decfloor = 10 * (inferreddate // 10)\n docid = row['docid']\n\n if decfloor in decades:\n decades[decfloor].add(docid)\n\n# Then sample 1000 from each decade.\n\nrandomsample = set()\n\nfor floor, available in decades.items():\n if len(available) < 500:\n k = len(available)\n print(floor, k)\n else:\n k = 500\n selected = random.sample(available, k)\n randomsample = randomsample.union(selected)\n\n# We also want to ensure that we have all the books needed to test preregistered hypotheses.\n# So let's add those too.\n\ndef getdoc(anid):\n '''\n Gets the docid part of a character id\n '''\n\n if '|' in anid:\n thedoc = anid.split('|')[0]\n elif '_' in anid:\n thedoc = anid.split('_')[0]\n else:\n print('error', anid)\n thedoc = anid\n\n return thedoc\n\nspecialids = set()\n\nwith open('../../evaluation/hypotheses.tsv', encoding = 'utf-8') as f:\n reader = csv.DictReader(f, delimiter = '\\t')\n for row in reader:\n ids = [row['firstsim'], row['secondsim'], row['distractor']]\n for anid in ids:\n docid = getdoc(anid)\n specialids.add(docid)\n\n# In addition, there are a few characters who are known to be split across a couple\n# different names. We're going to unify these in data prep.\n\n# Our strategy is to create a dictionary that translates the supplemental character\n# ids into main character ids. This is only necessary in 15 cases.\n\nchar_translator = dict()\nto_supplement = set()\n\nwith open('../../evaluation/newcharacters.tsv', encoding = 'utf-8') as f:\n reader = csv.DictReader(f, delimiter = '\\t')\n for row in reader:\n supp = row['supplementalcharid']\n if len(supp) > 1:\n char_translator[supp] = row['charid']\n to_supplement.add(row['charid'])\n\nprint('Translator for ', len(char_translator))\n\nsources = ['/Users/tunder/data/character_table_18c19c.tsv',\n '/Users/tunder/data/character_table_post1900.tsv']\n\nmalletout = '/Users/tunder/data/bioficchars.txt'\n\nerrors = 0\nerrorset = {}\n\nlines = []\nspecial_lines = []\n\nwordholding = dict()\nlabelholding = dict()\n\nfor s in sources:\n with open(s, encoding = 'utf-8') as f:\n for line in f:\n fields = line.strip().split('\\t')\n docid = fields[0]\n if docid in randomsample or docid in specialids:\n charid = fields[2]\n date = fields[4]\n gender = fields[3]\n words = fields[5]\n label = 'fic' + date + gender\n\n if charid in char_translator or charid in to_supplement:\n words = fields[5].split()\n\n if charid in char_translator:\n hold_id = char_translator[charid]\n else:\n hold_id = charid\n\n if hold_id not in wordholding:\n wordholding[hold_id] = []\n wordholding[hold_id].extend(words)\n labelholding[hold_id] = label\n\n else:\n outline = ' '.join([charid, label, words]) + '\\n'\n if docid in specialids:\n special_lines.append(outline)\n else:\n lines.append(outline)\n\n if len(lines) > 1000:\n with open(malletout, mode = 'a', encoding = 'utf-8') as f:\n for l in lines:\n f.write(l)\n lines = []\n\nwith open(malletout, mode = 'a', encoding = 'utf-8') as f:\n for l in lines:\n f.write(l)\n\nfor anid in to_supplement:\n outline = ' '.join([anid, labelholding[anid], ' '.join(wordholding[anid])]) + '\\n'\n special_lines.append(outline)\n\nwith open(malletout, mode = 'a', encoding = 'utf-8') as f:\n for l in special_lines:\n f.write(l)\n\nprint(\"Total volumes: \", len(randomsample) + len(specialids))\n\nprint()\nprint('Starting to get biographies.')\n\nbiosources = ['../../data/all_post23bio_Sep11.tsv',\n '../../data/all_pre23bio_new.tsv']\n\nbiometa = pd.read_csv('../../metadata/allparsedbio.tsv', sep = '\\t', index_col = 'docid')\n\ndef getdecade(date):\n return 10 * (date // 10)\n\nbiometa = biometa.assign(decade = biometa.inferreddate.map(getdecade))\n\ndecadegrouping = biometa.groupby('decade')\nbiosample = set()\n\nfor dec, group in decadegrouping:\n if dec < 1780 or dec > 2000:\n continue\n\n available = group.index.tolist()\n\n if len(available) < 500:\n k = len(available)\n print(floor, k)\n else:\n k = 500\n selected = random.sample(available, k)\n biosample = biosample.union(selected)\n\nlines = []\n\nfor s in biosources:\n with open(s, encoding = 'utf-8') as f:\n for line in f:\n fields = line.strip().split('\\t')\n docid = fields[0]\n if docid in biosample:\n charid = fields[2]\n date = fields[5]\n gender = fields[3]\n words = fields[6]\n label = 'bio' + date + gender\n\n outline = ' '.join([charid, label, words]) + '\\n'\n lines.append(outline)\n\n if len(lines) > 1000:\n with open(malletout, mode = 'a', encoding = 'utf-8') as f:\n for l in lines:\n f.write(l)\n lines = []\n\nwith open(malletout, mode = 'a', encoding = 'utf-8') as f:\n for l in lines:\n f.write(l)\n\n\n\n" ]
[ [ "pandas.read_table", "pandas.read_csv", "pandas.DataFrame" ], [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
KnightOfTheMoonlight/visdom4detectron2
[ "2455e4790f470bba54299c049410fc0713ae7529" ]
[ "detectron2/modeling/mmdet_wrapper.py" ]
[ "# -*- coding: utf-8 -*-\n\nimport itertools\nimport logging\nimport numpy as np\nfrom collections import OrderedDict\nfrom collections.abc import Mapping\nfrom typing import Dict, List, Optional, Tuple, Union\nimport torch\nfrom omegaconf import DictConfig, OmegaConf\nfrom torch import Tensor, nn\n\nfrom detectron2.layers import ShapeSpec\nfrom detectron2.structures import BitMasks, Boxes, ImageList, Instances\nfrom detectron2.utils.events import get_event_storage\n\nfrom .backbone import Backbone\n\nlogger = logging.getLogger(__name__)\n\n\ndef _to_container(cfg):\n \"\"\"\n mmdet will assert the type of dict/list.\n So convert omegaconf objects to dict/list.\n \"\"\"\n if isinstance(cfg, DictConfig):\n cfg = OmegaConf.to_container(cfg, resolve=True)\n from mmcv.utils import ConfigDict\n\n return ConfigDict(cfg)\n\n\nclass MMDetBackbone(Backbone):\n \"\"\"\n Wrapper of mmdetection backbones to use in detectron2.\n\n mmdet backbones produce list/tuple of tensors, while detectron2 backbones\n produce a dict of tensors. This class wraps the given backbone to produce\n output in detectron2's convention, so it can be used in place of detectron2\n backbones.\n \"\"\"\n\n def __init__(\n self,\n backbone: Union[nn.Module, Mapping],\n neck: Union[nn.Module, Mapping, None] = None,\n *,\n pretrained_backbone: Optional[str] = None,\n output_shapes: List[ShapeSpec],\n output_names: Optional[List[str]] = None,\n ):\n \"\"\"\n Args:\n backbone: either a backbone module or a mmdet config dict that defines a\n backbone. The backbone takes a 4D image tensor and returns a\n sequence of tensors.\n neck: either a backbone module or a mmdet config dict that defines a\n neck. The neck takes outputs of backbone and returns a\n sequence of tensors. If None, no neck is used.\n pretrained_backbone: defines the backbone weights that can be loaded by\n mmdet, such as \"torchvision://resnet50\".\n output_shapes: shape for every output of the backbone (or neck, if given).\n stride and channels are often needed.\n output_names: names for every output of the backbone (or neck, if given).\n By default, will use \"out0\", \"out1\", ...\n \"\"\"\n super().__init__()\n if isinstance(backbone, Mapping):\n from mmdet.models import build_backbone\n\n backbone = build_backbone(_to_container(backbone))\n self.backbone = backbone\n\n if isinstance(neck, Mapping):\n from mmdet.models import build_neck\n\n neck = build_neck(_to_container(neck))\n self.neck = neck\n\n # It's confusing that backbone weights are given as a separate argument,\n # but \"neck\" weights, if any, are part of neck itself. This is the interface\n # of mmdet so we follow it. Reference:\n # https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/detectors/two_stage.py\n logger.info(f\"Initializing mmdet backbone weights: {pretrained_backbone} ...\")\n self.backbone.init_weights(pretrained_backbone)\n # train() in mmdet modules is non-trivial, and has to be explicitly\n # called. Reference:\n # https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/backbones/resnet.py\n self.backbone.train()\n if self.neck is not None:\n logger.info(\"Initializing mmdet neck weights ...\")\n if isinstance(self.neck, nn.Sequential):\n for m in self.neck:\n m.init_weights()\n else:\n self.neck.init_weights()\n self.neck.train()\n\n self._output_shapes = output_shapes\n if not output_names:\n output_names = [f\"out{i}\" for i in range(len(output_shapes))]\n self._output_names = output_names\n\n def forward(self, x) -> Dict[str, Tensor]:\n outs = self.backbone(x)\n if self.neck is not None:\n outs = self.neck(outs)\n assert isinstance(\n outs, (list, tuple)\n ), \"mmdet backbone should return a list/tuple of tensors!\"\n if len(outs) != len(self._output_shapes):\n raise ValueError(\n \"Length of output_shapes does not match outputs from the mmdet backbone: \"\n f\"{len(outs)} != {len(self._output_shapes)}\"\n )\n return {k: v for k, v in zip(self._output_names, outs)}\n\n def output_shape(self) -> Dict[str, ShapeSpec]:\n return {k: v for k, v in zip(self._output_names, self._output_shapes)}\n\n\nclass MMDetDetector(nn.Module):\n \"\"\"\n Wrapper of a mmdetection detector model, for detection and instance segmentation.\n Input/output formats of this class follow detectron2's convention, so a\n mmdetection model can be trained and evaluated in detectron2.\n \"\"\"\n\n def __init__(\n self,\n detector: Union[nn.Module, Mapping],\n *,\n # Default is 32 regardless of model:\n # https://github.com/open-mmlab/mmdetection/tree/master/configs/_base_/datasets\n size_divisibility=32,\n pixel_mean: Tuple[float],\n pixel_std: Tuple[float],\n ):\n \"\"\"\n Args:\n detector: a mmdet detector, or a mmdet config dict that defines a detector.\n size_divisibility: pad input images to multiple of this number\n pixel_mean: per-channel mean to normalize input image\n pixel_std: per-channel stddev to normalize input image\n \"\"\"\n super().__init__()\n if isinstance(detector, Mapping):\n from mmdet.models import build_detector\n\n detector = build_detector(_to_container(detector))\n self.detector = detector\n self.size_divisibility = size_divisibility\n\n self.register_buffer(\"pixel_mean\", torch.tensor(pixel_mean).view(-1, 1, 1), False)\n self.register_buffer(\"pixel_std\", torch.tensor(pixel_std).view(-1, 1, 1), False)\n assert (\n self.pixel_mean.shape == self.pixel_std.shape\n ), f\"{self.pixel_mean} and {self.pixel_std} have different shapes!\"\n\n def forward(self, batched_inputs: Tuple[Dict[str, torch.Tensor]]):\n images = [x[\"image\"].to(self.device) for x in batched_inputs]\n images = [(x - self.pixel_mean) / self.pixel_std for x in images]\n images = ImageList.from_tensors(images, size_divisibility=self.size_divisibility).tensor\n metas = []\n rescale = {\"height\" in x for x in batched_inputs}\n if len(rescale) != 1:\n raise ValueError(\"Some inputs have original height/width, but some don't!\")\n rescale = list(rescale)[0]\n output_shapes = []\n for input in batched_inputs:\n meta = {}\n c, h, w = input[\"image\"].shape\n meta[\"img_shape\"] = meta[\"ori_shape\"] = (h, w, c)\n if rescale:\n scale_factor = np.sqrt(h * w / (input[\"height\"] * input[\"width\"]))\n ori_shape = (input[\"height\"], input[\"width\"])\n output_shapes.append(ori_shape)\n meta[\"ori_shape\"] = ori_shape + (c,)\n else:\n scale_factor = 1.0\n output_shapes.append((h, w))\n meta[\"scale_factor\"] = scale_factor\n meta[\"flip\"] = False\n padh, padw = images.shape[-2:]\n meta[\"pad_shape\"] = (padh, padw, c)\n metas.append(meta)\n\n if self.training:\n gt_instances = [x[\"instances\"].to(self.device) for x in batched_inputs]\n if gt_instances[0].has(\"gt_masks\"):\n from mmdet.core import PolygonMasks as mm_PolygonMasks, BitmapMasks as mm_BitMasks\n\n def convert_mask(m, shape):\n # mmdet mask format\n if isinstance(m, BitMasks):\n return mm_BitMasks(m.tensor.cpu().numpy(), shape[0], shape[1])\n else:\n return mm_PolygonMasks(m.polygons, shape[0], shape[1])\n\n gt_masks = [convert_mask(x.gt_masks, x.image_size) for x in gt_instances]\n else:\n gt_masks = None\n losses_and_metrics = self.detector.forward_train(\n images,\n metas,\n [x.gt_boxes.tensor for x in gt_instances],\n [x.gt_classes for x in gt_instances],\n gt_masks=gt_masks,\n )\n return _parse_losses(losses_and_metrics)\n else:\n results = self.detector.simple_test(images, metas, rescale=rescale)\n results = [\n {\"instances\": _convert_mmdet_result(r, shape)}\n for r, shape in zip(results, output_shapes)\n ]\n return results\n\n @property\n def device(self):\n return self.pixel_mean.device\n\n\n# Reference: show_result() in\n# https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/detectors/base.py\ndef _convert_mmdet_result(result, shape: Tuple[int, int]) -> Instances:\n if isinstance(result, tuple):\n bbox_result, segm_result = result\n if isinstance(segm_result, tuple):\n segm_result = segm_result[0]\n else:\n bbox_result, segm_result = result, None\n\n bboxes = torch.from_numpy(np.vstack(bbox_result)) # Nx5\n bboxes, scores = bboxes[:, :4], bboxes[:, -1]\n labels = [\n torch.full((bbox.shape[0],), i, dtype=torch.int32) for i, bbox in enumerate(bbox_result)\n ]\n labels = torch.cat(labels)\n inst = Instances(shape)\n inst.pred_boxes = Boxes(bboxes)\n inst.scores = scores\n inst.pred_classes = labels\n\n if segm_result is not None and len(labels) > 0:\n segm_result = list(itertools.chain(*segm_result))\n segm_result = [torch.from_numpy(x) if isinstance(x, np.ndarray) else x for x in segm_result]\n segm_result = torch.stack(segm_result, dim=0)\n inst.pred_masks = segm_result\n return inst\n\n\n# reference: https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/detectors/base.py\ndef _parse_losses(losses: Dict[str, Tensor]) -> Dict[str, Tensor]:\n log_vars = OrderedDict()\n for loss_name, loss_value in losses.items():\n if isinstance(loss_value, torch.Tensor):\n log_vars[loss_name] = loss_value.mean()\n elif isinstance(loss_value, list):\n log_vars[loss_name] = sum(_loss.mean() for _loss in loss_value)\n else:\n raise TypeError(f\"{loss_name} is not a tensor or list of tensors\")\n\n if \"loss\" not in loss_name:\n # put metrics to storage; don't return them\n storage = get_event_storage()\n value = log_vars.pop(loss_name).cpu().item()\n storage.put_scalar(loss_name, value)\n return log_vars\n" ]
[ [ "numpy.sqrt", "torch.full", "torch.cat", "torch.from_numpy", "torch.tensor", "torch.stack", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tomjur/TF2.0DQN
[ "4813d40ffaa455e4b70459a6db0a996d73b760d9" ]
[ "main.py" ]
[ "from config_utils import read_main_config\nfrom deep_q_network import DeepQNetwork\nfrom gym_wrapper import GymWrapper\n\n\nfrom tensorflow.python.framework.ops import disable_eager_execution\ndisable_eager_execution()\n\nconfig = read_main_config()\ngym_wrapper = GymWrapper(config['general']['scenario'])\ndeep_q_network = DeepQNetwork(config, gym_wrapper)\ndeep_q_network.train()\ndeep_q_network.test(episodes=3)" ]
[ [ "tensorflow.python.framework.ops.disable_eager_execution" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "1.13", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] } ]
pyiron/pyiron_atomistic
[ "0cd4c910806f44dfc829ddd642e323efcf7e36d5", "0cd4c910806f44dfc829ddd642e323efcf7e36d5" ]
[ "pyiron_atomistics/vasp/outcar.py", "tests/atomistics/job/test_atomistic.py" ]
[ "# coding: utf-8\n# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department\n# Distributed under the terms of \"New BSD License\", see the LICENSE file.\n\nfrom collections import OrderedDict\nimport numpy as np\nimport warnings\nimport scipy.constants\nimport re\n\n__author__ = \"Sudarsan Surendralal\"\n__copyright__ = (\n \"Copyright 2021, Max-Planck-Institut für Eisenforschung GmbH - \"\n \"Computational Materials Design (CM) Department\"\n)\n__version__ = \"1.0\"\n__maintainer__ = \"Sudarsan Surendralal\"\n__email__ = \"[email protected]\"\n__status__ = \"production\"\n__date__ = \"Sep 1, 2017\"\n\nKBAR_TO_EVA = (\n scipy.constants.physical_constants[\"joule-electron volt relationship\"][0] / 1e22\n)\n\n\nclass Outcar(object):\n \"\"\"\n This module is used to parse VASP OUTCAR files.\n\n Attributes:\n\n parse_dict (dict): A dictionary with all the useful quantities parsed from an OUTCAR file after from_file() is\n executed\n\n \"\"\"\n\n def __init__(self):\n self.parse_dict = dict()\n\n def from_file(self, filename=\"OUTCAR\"):\n \"\"\"\n Parse and store relevant quantities from the OUTCAR file into parse_dict.\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n\n \"\"\"\n with open(filename, \"r\") as f:\n lines = f.readlines()\n energies = self.get_total_energies(filename=filename, lines=lines)\n energies_int = self.get_energy_without_entropy(filename=filename, lines=lines)\n energies_zero = self.get_energy_sigma_0(filename=filename, lines=lines)\n scf_energies = self.get_all_total_energies(filename=filename, lines=lines)\n n_atoms = self.get_number_of_atoms(filename=filename, lines=lines)\n forces = self.get_forces(filename=filename, lines=lines, n_atoms=n_atoms)\n positions = self.get_positions(filename=filename, lines=lines, n_atoms=n_atoms)\n cells = self.get_cells(filename=filename, lines=lines)\n steps = self.get_steps(filename=filename, lines=lines)\n temperatures = self.get_temperatures(filename=filename, lines=lines)\n time = self.get_time(filename=filename, lines=lines)\n fermi_level = self.get_fermi_level(filename=filename, lines=lines)\n scf_moments = self.get_dipole_moments(filename=filename, lines=lines)\n kin_energy_error = self.get_kinetic_energy_error(filename=filename, lines=lines)\n stresses = self.get_stresses(filename=filename, si_unit=False, lines=lines)\n n_elect = self.get_nelect(filename=filename, lines=lines)\n e_fermi_list, vbm_list, cbm_list = self.get_band_properties(filename=filename, lines=lines)\n elastic_constants = self.get_elastic_constants(filename=filename, lines=lines)\n try:\n irreducible_kpoints = self.get_irreducible_kpoints(\n filename=filename, lines=lines\n )\n except ValueError:\n print(\"irreducible kpoints not parsed !\")\n irreducible_kpoints = None\n magnetization, final_magmom_lst = self.get_magnetization(\n filename=filename, lines=lines\n )\n broyden_mixing = self.get_broyden_mixing_mesh(filename=filename, lines=lines)\n\n self.parse_dict[\"energies\"] = energies\n self.parse_dict[\"energies_int\"] = energies_int\n self.parse_dict[\"energies_zero\"] = energies_zero\n self.parse_dict[\"scf_energies\"] = scf_energies\n self.parse_dict[\"forces\"] = forces\n self.parse_dict[\"positions\"] = positions\n self.parse_dict[\"cells\"] = cells\n self.parse_dict[\"steps\"] = steps\n self.parse_dict[\"temperatures\"] = temperatures\n self.parse_dict[\"time\"] = time\n self.parse_dict[\"fermi_level\"] = fermi_level\n self.parse_dict[\"scf_dipole_moments\"] = scf_moments\n self.parse_dict[\"kin_energy_error\"] = kin_energy_error\n self.parse_dict[\"stresses\"] = stresses\n self.parse_dict[\"irreducible_kpoints\"] = irreducible_kpoints\n self.parse_dict[\"magnetization\"] = magnetization\n self.parse_dict[\"final_magmoms\"] = final_magmom_lst\n self.parse_dict[\"broyden_mixing\"] = broyden_mixing\n self.parse_dict[\"n_elect\"] = n_elect\n self.parse_dict[\"e_fermi_list\"] = e_fermi_list\n self.parse_dict[\"vbm_list\"] = vbm_list\n self.parse_dict[\"cbm_list\"] = cbm_list\n self.parse_dict[\"elastic_constants\"] = elastic_constants\n try:\n self.parse_dict[\"pressures\"] = (\n np.average(stresses[:, 0:3], axis=1) * KBAR_TO_EVA\n )\n except IndexError:\n self.parse_dict[\"pressures\"] = np.zeros(len(steps))\n\n def to_hdf(self, hdf, group_name=\"outcar\"):\n \"\"\"\n Store output in an HDF5 file\n\n Args:\n hdf (pyiron_base.generic.hdfio.FileHDFio): HDF5 group or file\n group_name (str): Name of the HDF5 group\n \"\"\"\n with hdf.open(group_name) as hdf5_output:\n for key in self.parse_dict.keys():\n hdf5_output[key] = self.parse_dict[key]\n\n def to_hdf_minimal(self, hdf, group_name=\"outcar\"):\n \"\"\"\n Store minimal output in an HDF5 file (output unique to OUTCAR)\n\n Args:\n hdf (pyiron_base.generic.hdfio.FileHDFio): HDF5 group or file\n group_name (str): Name of the HDF5 group\n \"\"\"\n unique_quantities = [\n \"kin_energy_error\",\n \"broyden_mixing\",\n \"stresses\",\n \"irreducible_kpoints\",\n ]\n with hdf.open(group_name) as hdf5_output:\n for key in self.parse_dict.keys():\n if key in unique_quantities:\n hdf5_output[key] = self.parse_dict[key]\n\n def from_hdf(self, hdf, group_name=\"outcar\"):\n \"\"\"\n Load output from an HDF5 file\n\n Args:\n hdf (pyiron_base.generic.hdfio.FileHDFio): HDF5 group or file\n group_name (str): Name of the HDF5 group\n \"\"\"\n with hdf.open(group_name) as hdf5_output:\n for key in hdf5_output.list_nodes():\n self.parse_dict[key] = hdf5_output[key]\n\n def get_positions_and_forces(self, filename=\"OUTCAR\", lines=None, n_atoms=None):\n \"\"\"\n Gets the forces and positions for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n n_atoms (int/None): number of ions in OUTCAR\n\n Returns:\n [positions, forces] (sequence)\n numpy.ndarray: A Nx3xM array of positions in $\\AA$\n numpy.ndarray: A Nx3xM array of forces in $eV / \\AA$\n\n where N is the number of atoms and M is the number of time steps\n \"\"\"\n if n_atoms is None:\n n_atoms = self.get_number_of_atoms(filename=filename, lines=lines)\n trigger_indices, lines = _get_trigger(\n lines=lines, filename=filename, trigger=\"TOTAL-FORCE (eV/Angst)\"\n )\n return self._get_positions_and_forces_parser(\n lines=lines,\n trigger_indices=trigger_indices,\n n_atoms=n_atoms,\n pos_flag=True,\n force_flag=True,\n )\n\n def get_positions(self, filename=\"OUTCAR\", lines=None, n_atoms=None):\n\n \"\"\"\n Gets the positions for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n n_atoms (int/None): number of ions in OUTCAR\n\n Returns:\n numpy.ndarray: A Nx3xM array of positions in $\\AA$\n\n where N is the number of atoms and M is the number of time steps\n \"\"\"\n if n_atoms is None:\n n_atoms = self.get_number_of_atoms(filename=filename, lines=lines)\n trigger_indices, lines = _get_trigger(\n lines=lines, filename=filename, trigger=\"TOTAL-FORCE (eV/Angst)\"\n )\n return self._get_positions_and_forces_parser(\n lines=lines,\n trigger_indices=trigger_indices,\n n_atoms=n_atoms,\n pos_flag=True,\n force_flag=False,\n )\n\n def get_forces(self, filename=\"OUTCAR\", lines=None, n_atoms=None):\n \"\"\"\n Gets the forces for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n n_atoms (int/None): number of ions in OUTCAR\n\n Returns:\n\n numpy.ndarray: A Nx3xM array of forces in $eV / \\AA$\n\n where N is the number of atoms and M is the number of time steps\n \"\"\"\n if n_atoms is None:\n n_atoms = self.get_number_of_atoms(filename=filename, lines=lines)\n trigger_indices, lines = _get_trigger(\n lines=lines, filename=filename, trigger=\"TOTAL-FORCE (eV/Angst)\"\n )\n return self._get_positions_and_forces_parser(\n lines=lines,\n trigger_indices=trigger_indices,\n n_atoms=n_atoms,\n pos_flag=False,\n force_flag=True,\n )\n\n def get_cells(self, filename=\"OUTCAR\", lines=None):\n \"\"\"\n Gets the cell size and shape for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: A 3x3xM array of the cell shape in $\\AA$\n\n where M is the number of time steps\n \"\"\"\n trigger_indices, lines = _get_trigger(\n lines=lines, filename=filename, trigger=\"VOLUME and BASIS-vectors are now :\"\n )\n return self._get_cells_praser(lines=lines, trigger_indices=trigger_indices)\n\n @staticmethod\n def get_stresses(filename=\"OUTCAR\", lines=None, si_unit=True):\n \"\"\"\n\n Args:\n filename (str): Input filename\n lines (list/None): lines read from the file\n si_unit (bool): True SI units are used\n\n Returns:\n numpy.ndarray: An array of stress values\n\n \"\"\"\n trigger_indices, lines = _get_trigger(\n lines=lines,\n filename=filename,\n trigger=\"FORCE on cell =-STRESS in cart. coord. units (eV):\",\n )\n pullay_stress_lst = []\n for j in trigger_indices:\n try:\n if si_unit:\n pullay_stress_lst.append(\n [float(l) for l in lines[j + 13].split()[1:7]]\n )\n else:\n pullay_stress_lst.append(\n [float(l) for l in lines[j + 14].split()[2:8]]\n )\n except ValueError:\n if si_unit:\n pullay_stress_lst.append([float(\"NaN\")] * 6)\n else:\n pullay_stress_lst.append([float(\"NaN\")] * 6)\n return np.array(pullay_stress_lst)\n\n @staticmethod\n def get_irreducible_kpoints(\n filename=\"OUTCAR\", reciprocal=True, weight=True, planewaves=True, lines=None\n ):\n \"\"\"\n Function to extract the irreducible kpoints from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n reciprocal (bool): Get either the reciprocal or the cartesian coordinates\n weight (bool): Get the weight assigned to the irreducible kpoints\n planewaves (bool): Get the planewaves assigned to the irreducible kpoints\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: An array of k-points\n \"\"\"\n kpoint_lst = []\n weight_lst = []\n planewaves_lst = []\n trigger_number_str = \"Subroutine IBZKPT returns following result:\"\n trigger_plane_waves_str = \"k-point 1 :\"\n trigger_number = 0\n trigger_plane_waves = 0\n lines = _get_lines_from_file(filename=filename, lines=lines)\n for i, line in enumerate(lines):\n line = line.strip()\n if trigger_number_str in line:\n trigger_number = int(i)\n elif planewaves:\n if trigger_plane_waves_str in line:\n trigger_plane_waves = int(i)\n number_irr_kpoints = int(lines[trigger_number + 3].split()[1])\n if reciprocal:\n trigger_start = trigger_number + 7\n else:\n trigger_start = trigger_number + 10 + number_irr_kpoints\n for line in lines[trigger_start : trigger_start + number_irr_kpoints]:\n line = line.strip()\n line = _clean_line(line)\n kpoint_lst.append([float(l) for l in line.split()[0:3]])\n if weight:\n weight_lst.append(float(line.split()[3]))\n if planewaves and trigger_plane_waves != 0:\n for line in lines[\n trigger_plane_waves : trigger_plane_waves + number_irr_kpoints\n ]:\n line = line.strip()\n line = _clean_line(line)\n planewaves_lst.append(float(line.split()[-1]))\n if weight and planewaves:\n return np.array(kpoint_lst), np.array(weight_lst), np.array(planewaves_lst)\n elif weight:\n return np.array(kpoint_lst), np.array(weight_lst)\n elif planewaves:\n return np.array(kpoint_lst), np.array(planewaves_lst)\n else:\n return np.array(kpoint_lst)\n\n @staticmethod\n def get_total_energies(filename=\"OUTCAR\", lines=None):\n \"\"\"\n Gets the total energy for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: A 1xM array of the total energies in $eV$\n\n where M is the number of time steps\n \"\"\"\n\n def get_total_energies_from_line(line):\n return float(_clean_line(line.strip()).split()[-2])\n\n trigger_indices, lines = _get_trigger(\n lines=lines,\n filename=filename,\n trigger=\"FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)\",\n )\n return np.array(\n [get_total_energies_from_line(lines[j + 2]) for j in trigger_indices]\n )\n\n @staticmethod\n def get_energy_without_entropy(filename=\"OUTCAR\", lines=None):\n \"\"\"\n Gets the total energy for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: A 1xM array of the total energies in $eV$\n\n where M is the number of time steps\n \"\"\"\n\n def get_energy_without_entropy_from_line(line):\n return float(_clean_line(line.strip()).split()[3])\n\n trigger_indices, lines = _get_trigger(\n lines=lines,\n filename=filename,\n trigger=\"FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)\",\n )\n return np.array(\n [\n get_energy_without_entropy_from_line(lines[j + 4])\n for j in trigger_indices\n ]\n )\n\n @staticmethod\n def get_energy_sigma_0(filename=\"OUTCAR\", lines=None):\n \"\"\"\n Gets the total energy for every ionic step from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: A 1xM array of the total energies in $eV$\n\n where M is the number of time steps\n \"\"\"\n\n def get_energy_sigma_0_from_line(line):\n return float(_clean_line(line.strip()).split()[-1])\n\n trigger_indices, lines = _get_trigger(\n lines=lines,\n filename=filename,\n trigger=\"FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)\",\n )\n return np.array(\n [get_energy_sigma_0_from_line(lines[j + 4]) for j in trigger_indices]\n )\n\n @staticmethod\n def get_all_total_energies(filename=\"OUTCAR\", lines=None):\n \"\"\"\n Gets the energy at every electronic step\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n list: A list of energie for every electronic step at every ionic step\n \"\"\"\n ionic_trigger = \"FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)\"\n electronic_trigger = \"free energy TOTEN =\"\n scf_energies = list()\n lines = _get_lines_from_file(filename=filename, lines=lines)\n istep_energies = list()\n for i, line in enumerate(lines):\n line = line.strip()\n if ionic_trigger in line:\n scf_energies.append(np.array(istep_energies))\n istep_energies = list()\n if electronic_trigger in line:\n line = _clean_line(line)\n ene = float(line.split()[-2])\n istep_energies.append(ene)\n return scf_energies\n\n @staticmethod\n def get_magnetization(filename=\"OUTCAR\", lines=None):\n \"\"\"\n Gets the magnetization\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n list: A list with the mgnetization values\n \"\"\"\n ionic_trigger = \"FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)\"\n electronic_trigger = \"eigenvalue-minimisations\"\n nion_trigger = \"NIONS =\"\n mag_lst = list()\n local_spin_trigger = False\n n_atoms = None\n mag_dict = dict()\n mag_dict[\"x\"] = list()\n mag_dict[\"y\"] = list()\n mag_dict[\"z\"] = list()\n lines = _get_lines_from_file(filename=filename, lines=lines)\n istep_energies = list()\n final_magmom_lst = list()\n for i, line in enumerate(lines):\n line = line.strip()\n if ionic_trigger in line:\n mag_lst.append(np.array(istep_energies))\n istep_energies = list()\n if \"Atomic Wigner-Seitz radii\" in line:\n local_spin_trigger = True\n\n if electronic_trigger in line:\n try:\n line = lines[i + 2].split(\"magnetization\")[-1]\n if line != \" \\n\":\n spin_str_lst = line.split()\n spin_str_len = len(spin_str_lst)\n if spin_str_len == 1:\n ene = float(line)\n elif spin_str_len == 3:\n ene = [\n float(spin_str_lst[0]),\n float(spin_str_lst[1]),\n float(spin_str_lst[2]),\n ]\n else:\n warnings.warn(\"Unrecognized spin configuration.\")\n return mag_lst, final_magmom_lst\n istep_energies.append(ene)\n except ValueError:\n warnings.warn(\"Something went wrong in parsing the magnetization\")\n if n_atoms is None:\n if nion_trigger in line:\n n_atoms = int(line.split(nion_trigger)[-1])\n if local_spin_trigger:\n try:\n for ind_dir, direc in enumerate([\"x\", \"y\", \"z\"]):\n if \"magnetization ({})\".format(direc) in line:\n mag_dict[direc].append(\n [\n float(lines[i + 4 + atom_index].split()[-1])\n for atom_index in range(n_atoms)\n ]\n )\n except ValueError:\n warnings.warn(\n \"Something went wrong in parsing the magnetic moments\"\n )\n if len(mag_dict[\"x\"]) > 0:\n if len(mag_dict[\"y\"]) == 0:\n final_mag = np.array(mag_dict[\"x\"])\n else:\n n_ionic_steps = np.array(mag_dict[\"x\"]).shape[0]\n final_mag = np.abs(np.zeros((n_ionic_steps, n_atoms, 3)))\n final_mag[:, :, 0] = np.array(mag_dict[\"x\"])\n final_mag[:, :, 1] = np.array(mag_dict[\"y\"])\n final_mag[:, :, 2] = np.array(mag_dict[\"z\"])\n final_magmom_lst = final_mag.tolist()\n return mag_lst, final_magmom_lst\n\n @staticmethod\n def get_broyden_mixing_mesh(filename=\"OUTCAR\", lines=None):\n \"\"\"\n Gets the Broyden mixing mesh size\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n int: Mesh size\n \"\"\"\n trigger_indices, lines = _get_trigger(\n lines=lines, filename=filename, trigger=\"gives a total of \"\n )\n if len(trigger_indices) > 0:\n line_ngx = lines[trigger_indices[0] - 2]\n else:\n warnings.warn(\n \"Unable to parse the Broyden mixing mesh. Returning 0 instead\"\n )\n return 0\n # Exclude all alphabets, and spaces. Then split based on '='\n str_list = re.sub(\n r\"[a-zA-Z]\", r\"\", line_ngx.replace(\" \", \"\").replace(\"\\n\", \"\")\n ).split(\"=\")\n return np.prod([int(val) for val in str_list[1:]])\n\n @staticmethod\n def get_temperatures(filename=\"OUTCAR\", lines=None):\n \"\"\"\n Gets the temperature at each ionic step (applicable for MD)\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: An array of temperatures in Kelvin\n \"\"\"\n trigger_indices, lines = _get_trigger(\n lines=lines, filename=filename, trigger=\"kin. lattice EKIN_LAT= \"\n )\n temperatures = []\n if len(trigger_indices) > 0:\n for j in trigger_indices:\n line = lines[j].strip()\n line = _clean_line(line)\n temperatures.append(float(line.split()[-2]))\n else:\n temperatures = np.zeros(\n len(\n _get_trigger(\n lines=lines,\n trigger=\"FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)\",\n return_lines=False,\n )\n )\n )\n return np.array(temperatures)\n\n @staticmethod\n def get_steps(filename=\"OUTCAR\", lines=None):\n \"\"\"\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: Steps during the simulation\n \"\"\"\n nblock_trigger = \"NBLOCK =\"\n trigger = \"FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)\"\n trigger_indices = list()\n read_nblock = True\n n_block = 1\n lines = _get_lines_from_file(filename=filename, lines=lines)\n for i, line in enumerate(lines):\n line = line.strip()\n if trigger in line:\n trigger_indices.append(i)\n if read_nblock is None:\n if nblock_trigger in line:\n line = _clean_line(line)\n n_block = int(line.split(nblock_trigger)[-1])\n return n_block * np.linspace(0, len(trigger_indices))\n\n def get_time(self, filename=\"OUTCAR\", lines=None):\n \"\"\"\n Time after each simulation step (for MD)\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n numpy.ndarray: An array of time values in fs\n\n \"\"\"\n potim_trigger = \"POTIM =\"\n read_potim = True\n potim = 1.0\n lines = _get_lines_from_file(filename=filename, lines=lines)\n for i, line in enumerate(lines):\n line = line.strip()\n if read_potim is None:\n if potim_trigger in line:\n line = _clean_line(line)\n potim = float(line.split(potim_trigger)[0])\n return potim * self.get_steps(filename)\n\n @staticmethod\n def get_kinetic_energy_error(filename=\"OUTCAR\", lines=None):\n \"\"\"\n Get the kinetic energy error\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n float: The kinetic energy error in eV\n \"\"\"\n trigger = \"kinetic energy error for atom=\"\n e_kin_err = list()\n n_species_list = list()\n nion_trigger = \"ions per type =\"\n tot_kin_error = 0.0\n lines = _get_lines_from_file(filename=filename, lines=lines)\n for i, line in enumerate(lines):\n line = line.strip()\n if trigger in line:\n e_kin_err.append(float(line.split()[5]))\n if nion_trigger in line:\n n_species_list = [\n float(val) for val in line.split(nion_trigger)[-1].strip().split()\n ]\n if len(n_species_list) > 0 and len(n_species_list) == len(e_kin_err):\n tot_kin_error = np.sum(np.array(n_species_list) * np.array(e_kin_err))\n return tot_kin_error\n\n @staticmethod\n def get_fermi_level(filename=\"OUTCAR\", lines=None):\n \"\"\"\n Getting the Fermi-level (Kohn_Sham) from the OUTCAR file\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n float: The Kohn-Sham Fermi level in eV\n \"\"\"\n trigger = \"E-fermi :\"\n trigger_indices, lines = _get_trigger(\n lines=lines, filename=filename, trigger=trigger\n )\n if len(trigger_indices) != 0:\n try:\n return float(lines[trigger_indices[-1]].split(trigger)[-1].split()[0])\n except ValueError:\n return\n else:\n return\n\n @staticmethod\n def get_dipole_moments(filename=\"OUTCAR\", lines=None):\n \"\"\"\n Get the electric dipole moment at every electronic step\n\n Args:\n filename (str): Filename of the OUTCAR file to parse\n lines (list/None): lines read from the file\n\n Returns:\n list: A list of dipole moments in (eA) for each electronic step\n\n \"\"\"\n moment_trigger = \"dipolmoment\"\n istep_trigger = \"FREE ENERGIE OF THE ION-ELECTRON SYSTEM (eV)\"\n dip_moms = list()\n lines = _get_lines_from_file(filename=filename, lines=lines)\n istep_mom = list()\n for i, line in enumerate(lines):\n line = line.strip()\n if istep_trigger in line:\n dip_moms.append(np.array(istep_mom))\n istep_mom = list()\n if moment_trigger in line:\n line = _clean_line(line)\n mom = np.array([float(val) for val in line.split()[1:4]])\n istep_mom.append(mom)\n return dip_moms\n\n @staticmethod\n def get_nelect(filename=\"OUTCAR\", lines=None):\n \"\"\"\n Returns the number of electrons in the simulation\n\n Args:\n filename (str): OUTCAR filename\n lines (list/None): lines read from the file\n\n Returns:\n float: The number of electrons in the simulation\n\n \"\"\"\n nelect_trigger = \"NELECT\"\n lines = _get_lines_from_file(filename=filename, lines=lines)\n for i, line in enumerate(lines):\n line = line.strip()\n if nelect_trigger in line:\n return float(line.split()[2])\n\n @staticmethod\n def get_number_of_atoms(filename=\"OUTCAR\", lines=None):\n \"\"\"\n Returns the number of ions in the simulation\n\n Args:\n filename (str): OUTCAR filename\n lines (list/None): lines read from the file\n\n Returns:\n int: The number of ions in the simulation\n\n \"\"\"\n ions_trigger = \"NIONS =\"\n trigger_indices, lines = _get_trigger(\n lines=lines, filename=filename, trigger=ions_trigger\n )\n if len(trigger_indices) != 0:\n return int(lines[trigger_indices[0]].split(ions_trigger)[-1])\n else:\n raise ValueError()\n\n @staticmethod\n def get_band_properties(filename=\"OUTCAR\", lines=None):\n fermi_trigger = \"E-fermi\"\n fermi_trigger_indices, lines = _get_trigger(\n lines=lines, filename=filename, trigger=fermi_trigger\n )\n fermi_level_list = list()\n vbm_level_dict = OrderedDict()\n cbm_level_dict = OrderedDict()\n for ind in fermi_trigger_indices:\n fermi_level_list.append(float(lines[ind].strip().split()[2]))\n band_trigger = \"band No. band energies occupation\"\n is_spin_polarized = False\n for n, ind in enumerate(fermi_trigger_indices):\n if n == len(fermi_trigger_indices) - 1:\n trigger_indices, lines_new = _get_trigger(\n lines=lines[ind:-1], filename=filename, trigger=band_trigger\n )\n else:\n trigger_indices, lines_new = _get_trigger(\n lines=lines[ind:fermi_trigger_indices[n+1]], filename=filename, trigger=band_trigger\n )\n band_data = list()\n for ind in trigger_indices:\n if \"spin component\" in lines_new[ind-3]:\n is_spin_polarized = True\n for line in lines_new[ind+1:]:\n data = line.strip().split()\n if len(data) != 3:\n break\n band_data.append([float(d) for d in data[1:]])\n if is_spin_polarized:\n band_data_per_spin = [np.array(band_data[0:int(len(band_data)/2)]).tolist(),\n np.array(band_data[int(len(band_data)/2):]).tolist()]\n else:\n band_data_per_spin = [band_data]\n for spin, band_data in enumerate(band_data_per_spin):\n if spin in cbm_level_dict.keys():\n pass\n else:\n cbm_level_dict[spin] = list()\n if spin in vbm_level_dict.keys():\n pass\n else:\n vbm_level_dict[spin] = list()\n if len(band_data) > 0:\n band_energy, band_occ = [np.array(band_data)[:, i] for i in range(2)]\n args = np.argsort(band_energy)\n band_occ = band_occ[args]\n band_energy = band_energy[args]\n cbm_bool = np.abs(band_occ) < 1e-6\n if any(cbm_bool):\n cbm_level_dict[spin].append(band_energy[np.abs(band_occ) < 1e-6][0])\n else:\n cbm_level_dict[spin].append(band_energy[-1])\n # If spin channel is completely empty, setting vbm=cbm\n if all(cbm_bool):\n vbm_level_dict[spin].append(cbm_level_dict[spin][-1])\n else:\n vbm_level_dict[spin].append(band_energy[~cbm_bool][-1])\n return np.array(fermi_level_list), np.array([val for val\n in vbm_level_dict.values()]), np.array([val\n for val in\n cbm_level_dict.values()])\n\n @staticmethod\n def get_elastic_constants(filename=\"OUTCAR\", lines=None):\n lines = _get_lines_from_file(filename=filename, lines=lines)\n trigger_indices = _get_trigger(lines=lines, filename=filename, trigger=\"TOTAL ELASTIC MODULI (kBar)\", return_lines=False)\n if len(trigger_indices) != 1:\n return None\n else:\n start_index = trigger_indices[0] + 3\n end_index = start_index + 6\n elastic_constants = []\n for line in lines[start_index:end_index]:\n elastic_constants.append(line.split()[1:])\n elastic_GPa = np.array(elastic_constants, dtype=float) / 10\n return elastic_GPa\n\n @staticmethod\n def _get_positions_and_forces_parser(\n lines, trigger_indices, n_atoms, pos_flag=True, force_flag=True\n ):\n \"\"\"\n Parser to get the forces and or positions for every ionic step from the OUTCAR file\n\n Args:\n lines (list): lines read from the file\n trigger_indices (list): list of line indices where the trigger was found.\n n_atoms (int): number of atoms\n pos_flag (bool): parse position\n force_flag (bool): parse forces\n\n Returns:\n [positions, forces] (sequence)\n numpy.ndarray: A Nx3xM array of positions in $\\AA$\n numpy.ndarray: A Nx3xM array of forces in $eV / \\AA$\n\n where N is the number of atoms and M is the number of time steps\n\n \"\"\"\n positions = []\n forces = []\n for j in trigger_indices:\n pos = []\n force = []\n for line in lines[j + 2 : j + n_atoms + 2]:\n line = line.strip()\n line = _clean_line(line)\n if pos_flag:\n pos.append([float(l) for l in line.split()[0:3]])\n if force_flag:\n force.append([float(l) for l in line.split()[3:]])\n forces.append(force)\n positions.append(pos)\n if pos_flag and force_flag:\n return np.array(positions), np.array(forces)\n elif pos_flag:\n return np.array(positions)\n elif force_flag:\n return np.array(forces)\n\n @staticmethod\n def _get_cells_praser(lines, trigger_indices):\n \"\"\"\n Parser to get the cell size and shape for every ionic step from the OUTCAR file\n\n Args:\n lines (list): lines read from the file\n trigger_indices (list): list of line indices where the trigger was found.\n n_atoms (int): number of atoms\n\n Returns:\n numpy.ndarray: A 3x3xM array of the cell shape in $\\AA$\n\n where M is the number of time steps\n\n \"\"\"\n cells = []\n try:\n for j in trigger_indices:\n cell = []\n for line in lines[j + 5: j + 8]:\n line = line.strip()\n line = _clean_line(line)\n cell.append([float(l) for l in line.split()[0:3]])\n cells.append(cell)\n return np.array(cells)\n except ValueError:\n warnings.warn(\"Unable to parse the cells from the OUTCAR file\")\n return\n\n\ndef _clean_line(line):\n return line.replace(\"-\", \" -\")\n\n\ndef _get_trigger(trigger, filename=None, lines=None, return_lines=True):\n \"\"\"\n Find the lines where a specific trigger appears.\n\n Args:\n trigger (str): string pattern to search for\n lines (list/None): list of lines\n filename (str/None): file to read lines from\n\n Returns:\n list: indicies of the lines where the trigger string was found and list of lines\n \"\"\"\n lines = _get_lines_from_file(filename=filename, lines=lines)\n trigger_indicies = [i for i, line in enumerate(lines) if trigger in line.strip()]\n if return_lines:\n return trigger_indicies, lines\n else:\n return trigger_indicies\n\n\ndef _get_lines_from_file(filename, lines=None):\n \"\"\"\n If lines is None read the lines from the file with the filename filename.\n\n Args:\n filename (str): file to read lines from\n lines (list/ None): list of lines\n\n Returns:\n list: list of lines\n \"\"\"\n if lines is None:\n with open(filename, \"r\") as f:\n lines = f.readlines()\n return lines\n", "# coding: utf-8\n# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department\n# Distributed under the terms of \"New BSD License\", see the LICENSE file.\n\nimport unittest\nimport numpy as np\nimport os\nimport shutil\nfrom pyiron_atomistics.project import Project\nfrom pyiron_base import ProjectHDFio\nfrom pyiron_atomistics.atomistics.job.atomistic import AtomisticGenericJob\nfrom pyiron_atomistics.atomistics.structure.atoms import Atoms, CrystalStructure\nimport warnings\n\n\nclass TestAtomisticGenericJob(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.execution_path = os.path.dirname(os.path.abspath(__file__))\n cls.project = Project(os.path.join(cls.execution_path, \"test_job\"))\n cls.job = AtomisticGenericJob(\n project=ProjectHDFio(project=cls.project, file_name=\"test_job\"),\n job_name=\"test_job\",\n )\n cls.job.structure = CrystalStructure(\n element=\"Al\", bravais_basis=\"fcc\", lattice_constants=4\n ).repeat(4)\n\n @classmethod\n def tearDownClass(cls):\n cls.execution_path = os.path.dirname(os.path.abspath(__file__))\n project = Project(os.path.join(cls.execution_path, \"test_job\"))\n project.remove_jobs_silently(recursive=True)\n project.remove(enable=True)\n\n def test_attributes(self):\n self.assertIsInstance(self.job.structure, Atoms)\n\n def test_get_displacements(self):\n n_steps = 10\n # increasing each position by 0.5 at each step\n positions = np.array([self.job.structure.positions + 0.5 * i for i in range(n_steps)])\n # constant cell\n cells = np.array([self.job.structure.cell] * n_steps)\n disp = self.job.output.get_displacements(self.job.structure, positions=positions, cells=cells)\n disp_ref = np.ones_like(positions) * 0.5\n disp_ref[0] *= 0.0\n self.assertTrue(np.allclose(disp, disp_ref))\n # varying cell\n cells = np.array([self.job.structure.cell * ((i+1) / 10) for i in range(n_steps)])\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n disp = self.job.output.get_displacements(self.job.structure,\n positions=positions, cells=cells)\n self.assertEqual(len(w), 1)\n self.assertIsInstance(w[-1].message, UserWarning)\n self.assertFalse(np.allclose(disp, disp_ref))\n dummy_struct = self.job.structure.copy()\n disp_ref = list()\n for pos, cell in zip(positions, cells):\n pos_init = dummy_struct.get_scaled_positions().copy()\n dummy_struct.set_cell(cell, scale_atoms=False)\n dummy_struct.positions = pos\n dummy_struct.center_coordinates_in_unit_cell()\n diff = dummy_struct.get_scaled_positions()-pos_init\n diff[diff >= 0.5] -= 1.0\n diff[diff <= -0.5] += 1.0\n disp_ref.append(np.dot(diff, cell))\n self.assertTrue(np.allclose(disp, disp_ref))\n\n @unittest.skipIf(os.name == 'nt', \"Runs forever on Windows\")\n def test_get_structure(self):\n \"\"\"get_structure() should return structures with the exact values from the HDF files even if the size of\n structures changes.\"\"\"\n\n # tested here with lammps as a concrete instantiation of AtomisticGenericJob\n # have to do extra tango because Project.unpack is weird right now\n cwd = os.curdir\n to_dir = os.path.join(self.project.path, \"..\")\n shutil.copy(\"tests/static/lammps_test_files/get_structure_test.tar.gz\", to_dir)\n shutil.copy(\"tests/static/lammps_test_files/export.csv\", to_dir)\n os.chdir(to_dir)\n self.project.unpack(\"get_structure_test\")\n job = self.project.load(\"inter_calculator\")\n os.chdir(cwd)\n\n for i, struct in enumerate(job.iter_structures()):\n # breakpoint()\n self.assertTrue(np.allclose(job.output.positions[i], struct.positions))\n self.assertTrue(np.allclose(job.output.cells[i], struct.cell.array))\n self.assertTrue(np.allclose(job.output.indices[i], struct.indices))\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.abs", "numpy.average", "numpy.argsort", "numpy.array", "numpy.zeros" ], [ "numpy.dot", "numpy.array", "numpy.ones_like", "numpy.allclose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
manhph2211/Pytorch-Fb-Classification
[ "cf5f9c0b356635020ff245c255d971e450d203fb" ]
[ "dataloader.py" ]
[ "import torch\nimport torchvision\nfrom torchvision import transforms, utils, datasets\nfrom torch.utils.data import Dataset, DataLoader, SubsetRandomSampler\nfrom sklearn.metrics import classification_report, confusion_matrix\n\n\ndef makeDataSet(IMAGE_SHAPE = 300,DATA_PATH = './data_after_splitting/'):\n\n\timage_transforms = {\n\t \"train\": transforms.Compose([\n\t transforms.Resize((IMAGE_SHAPE, IMAGE_SHAPE)),\n\t transforms.ToTensor(),\n\t transforms.Normalize([0.5, 0.5, 0.5],\n\t [0.5, 0.5, 0.5])\n\t ]),\n\t \"val\": transforms.Compose([\n\t transforms.Resize((IMAGE_SHAPE, IMAGE_SHAPE)),\n\t transforms.ToTensor(),\n\t transforms.Normalize([0.5, 0.5, 0.5],\n\t [0.5, 0.5, 0.5])\n\t ])\n\t}\n\n\ttrain_dataset = datasets.ImageFolder(root = DATA_PATH + \"train\",\n\t transform = image_transforms[\"train\"]\n\t )\n\n\tval_dataset = datasets.ImageFolder(root = DATA_PATH + \"val\",\n\t transform = image_transforms[\"val\"]\n\t )\n\ttrain_dataloader = DataLoader(train_dataset, batch_size=4, num_workers=2, shuffle=True)\n\tval_dataloader = DataLoader(val_dataset, batch_size=4, num_workers=2, shuffle=True)\n\n\treturn train_dataloader,val_dataloader\n" ]
[ [ "torch.utils.data.DataLoader" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
LucaZancato/stric
[ "8daeeca48b8d0b2db8156e7f1c66c0956c133353" ]
[ "main.py" ]
[ "import hydra\nimport os\n\nimport logging\nimport json\n\nimport numpy as np\nimport torch\nimport matplotlib.pyplot as plt\nfrom collections import defaultdict\nimport json\n\nfrom IPython import embed\n# from AD_models import AD_Time_Series\n# from AD_utils import AD_report, AD_dataset, plot_AD_dataset, AD_preprocessing\n# import T_models, A_models\n\n\nimport stric.datasets as datasets\nimport stric.detection_models.time_series_models as models\nimport stric.detection_models.detector_models as detectors\n\nfrom stric.detection_models.time_series_models.stric import InterpretableTCNFading\nimport stric.detection_models.detector_models.likelihood_ratio_estimators as likelihood_ratio_estimators\nfrom stric.detection_models.detector_models.base_detector import Detector\n\[email protected](config_name=\"config/config_interpretable_model\")\ndef main(cfg):\n data_path = os.path.join(hydra.utils.get_original_cwd(), 'data')\n\n dataset = datasets.__dict__[cfg.dataset.info.name](\n past_len=cfg.t_model.info.memory_length,\n fut_len=cfg.t_model.info.pred_length,\n data_path=data_path,\n dataset_subset=cfg.dataset.info.subname,\n dataset_index=cfg.dataset.info.index,\n normalize=cfg.dataset.preprocessing.normalize,\n )\n\n linear_kernel_sizes = cfg.t_model.info.linear_kernel_sizes\n interpretable_kernel_sizes = cfg.t_model.info.memory_length if linear_kernel_sizes is None else linear_kernel_sizes\n\n ############# Trend parameters ################\n HP_lams = np.logspace(8, 10, cfg.t_model.info.num_trends_filters) # Range of values of regularization parameter for HP filter (regulates the regularity of the trend component)\n HP_Ts = [interpretable_kernel_sizes] * cfg.t_model.info.num_trends_filters # Lenght of the HP filter (here we could choose large numbers if we want to increase the memory of the HP filter)\n\n ############# Periodic part parameters ################\n theta = np.random.uniform(2 * np.pi / 20, 2 * np.pi / 10, cfg.t_model.info.n_periodic_poles).reshape(-1, 1)\n r = np.random.uniform(1, 1, cfg.t_model.info.n_periodic_poles).reshape(-1, 1)\n purely_periodic_poles = np.concatenate((r, theta), 1)\n\n ############# Linear part parameters ################\n real_poles = np.random.uniform(-1, 1, cfg.t_model.info.n_complex_poles).reshape(-1, 1)\n theta = np.random.uniform(2 * np.pi / 20, 2 * np.pi / 10, cfg.t_model.info.n_complex_poles).reshape(-1, 1)\n r = np.random.uniform(0, 1, cfg.t_model.info.n_complex_poles).reshape(-1, 1)\n complex_poles = np.concatenate((r, theta), 1)\n\n model = InterpretableTCNFading(data=dataset, test_portion=cfg.t_model.info.test_portion,\n memory_length=cfg.t_model.info.memory_length, pred_length=cfg.t_model.info.pred_length,\n input_channels=dataset.n_timeseries, output_channels=dataset.n_timeseries,\n\n linear_kernel_sizes=interpretable_kernel_sizes,\n\n HP_lams=HP_lams, HP_Ts=HP_Ts,\n\n purely_periodic_poles=purely_periodic_poles,\n\n real_poles=real_poles,\n complex_poles=complex_poles,\n\n num_channels_TCN=cfg.t_model.info.num_channels_TCN,\n kernel_size_TCN=cfg.t_model.info.kernel_size_TCN,\n dropout_TCN=cfg.t_model.info.dropout_TCN,\n learnable_filters=False, random_init=False,\n ).to(cfg.device)\n\n model.train_model(bs=cfg.t_model.info.bs, lr=cfg.t_model.info.lr, epochs=cfg.t_model.info.epochs)\n\n # To visualize predictions per time-series (this plots all the available time-series)\n model.visualize(save=cfg.save_images)\n\n # Test predictive performance of the trained_model: see prediction errors across time-series for training and test\n ind = 4\n train_residuals, test_residuals = model.get_residuals(ind=ind)\n\n # Save results\n predictions_logs = defaultdict(list)\n predictions_logs['train_residuals'] = train_residuals.tolist()\n predictions_logs['test_residuals'] = test_residuals.tolist()\n predictions_logs['train_residuals_stds'] = train_residuals.std(0).tolist()\n predictions_logs['test_residuals_stds'] = test_residuals.std(0).tolist()\n predictions_logs['train_residuals_stds_mean'] = train_residuals.std(0).mean().item()\n predictions_logs['test_residuals_stds_mean'] = test_residuals.std(0).mean().item()\n\n with open('predictions_logs.json', 'w') as file:\n json.dump(predictions_logs, file)\n\n # Plot Interepretable decomposition\n _ = model.get_components(ind=None, save=cfg.save_images)\n\n # Anomaly detection\n ####### Detector' HPs ########\n kernel_length_scale = cfg.a_model.info.kernel_length_scale * test_residuals.std()\n kernel_type = cfg.a_model.info.kernel_type\n kernel_hps = {'length_scales': torch.tensor(kernel_length_scale), 'train_length_scales': False,\n 'scale_factor': torch.tensor(1.), 'train_scale_factor': False}\n ones = np.ones(dataset.n_timeseries)\n ####### Detector' HPs ########\n a_model = Detector(test_residuals, detectors.__dict__[cfg.a_model.type],\n cfg.a_model.info.kernel_type, kernel_hps, win_length=cfg.a_model.info.k, n=cfg.a_model.info.n,\n device=cfg.device)\n a_model.fit()\n\n log_lik = a_model.get_future_log_lik()\n a_labels = a_model.get_anomaly_labels(cfg.a_model.info.threshold * ones)\n\n a_model.visualize_anomaly_scores(save=cfg.save_images)\n a_model.visualize_anomaly_labels(thresholds=cfg.a_model.info.threshold * ones, save=cfg.save_images)\n\n # Save results\n anomaly_logs = defaultdict(list)\n anomaly_logs['log_lik'] = log_lik.tolist()\n anomaly_logs['a_labels'] = a_labels.tolist()\n\n with open('anomaly_logs.json', 'w') as file:\n json.dump(anomaly_logs, file)\n\n\nif __name__ == \"__main__\":\n main()" ]
[ [ "numpy.logspace", "torch.tensor", "numpy.concatenate", "numpy.ones", "numpy.random.uniform" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dave-cz/esp32_power_meter
[ "649c2020be587b2d57d40dd3c201feec3596c2a0" ]
[ "server/server.py" ]
[ "import logging\nimport pandas as pd\nfrom flask import Flask, request\nfrom gevent.pywsgi import WSGIServer\nfrom time import sleep\n\nfrom func import rms, meas_to_influx, rms_to_influx, config\n\nlogger = logging.getLogger(config['log_name'])\nlogger.setLevel(logging.INFO)\nh_stream = logging.StreamHandler()\nh_stream.setLevel(logging.INFO)\nlogger.addHandler(h_stream)\n\napp = Flask(__name__)\n\n\[email protected]('/save')\ndef save():\n headers = request.headers\n if 'X-API-KEY' not in headers or headers['X-API-KEY'] != config['api_key']:\n sleep(5)\n return '', 401\n\n data = request.json\n dt = pd.Timestamp(data['dt'])\n s_data, power = rms(data['payload'], data['ticks'], dt)\n\n if power < 0:\n logger.error(data)\n return '', 204\n\n if power < 100:\n return str(power)\n\n # print(s_data)\n # print(power)\n rms_to_influx(power, dt)\n meas_to_influx(s_data)\n\n return str(power)\n\n\nif __name__ == '__main__':\n # app.run(host=config['url'], port=config['port'])\n WSGIServer((config['url'], config['port']), app).serve_forever()\n" ]
[ [ "pandas.Timestamp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]